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
b4120ec570624ae4c66269ae2a8f916ec55734e9
ipywidgets/widgets/valuewidget.py
ipywidgets/widgets/valuewidget.py
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. """Contains the ValueWidget class""" from .widget import Widget class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. """Contains the ValueWidget class""" from .widget import Widget from traitlets import Any class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" value = Any(help="The value of the widget.") def get_interact_value(self): """Return the value for this widget which should be passed to interactive functions. Custom widgets can change this method to process the raw value ``self.value``. """ return self.value
Add a value trait to Value widgets.
Add a value trait to Value widgets.
Python
bsd-3-clause
ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets
--- +++ @@ -4,10 +4,13 @@ """Contains the ValueWidget class""" from .widget import Widget +from traitlets import Any class ValueWidget(Widget): """Widget that can be used for the input of an interactive function""" + + value = Any(help="The value of the widget.") def get_interact_value(self): """Return the value for this widget which should be passed to
7dbe03fcbbbf57ec9380eb9a1c24b5fd9f6594e2
zinnia/tests/utils.py
zinnia/tests/utils.py
"""Utils for Zinnia's tests""" import cStringIO from xmlrpclib import Transport from django.test.client import Client class TestTransport(Transport): """Handles connections to XML-RPC server through Django test client.""" def __init__(self, *args, **kwargs): Transport.__init__(self, *args, **kwargs) self.client = Client() def request(self, host, handler, request_body, verbose=0): self.verbose = verbose response = self.client.post(handler, request_body, content_type="text/xml") res = cStringIO.StringIO(response.content) res.seek(0) return self.parse_response(res)
"""Utils for Zinnia's tests""" import StringIO from xmlrpclib import Transport from django.test.client import Client class TestTransport(Transport): """Handles connections to XML-RPC server through Django test client.""" def __init__(self, *args, **kwargs): Transport.__init__(self, *args, **kwargs) self.client = Client() def request(self, host, handler, request_body, verbose=0): self.verbose = verbose response = self.client.post(handler, request_body, content_type="text/xml") res = StringIO.StringIO(response.content) setattr(res, 'getheader', lambda *args: '') # For Python >= 2.7 res.seek(0) return self.parse_response(res)
Fix tests on Python2.7 xmlrpclib.Transport.parse_response calls 'getheader' on its response input
Fix tests on Python2.7 xmlrpclib.Transport.parse_response calls 'getheader' on its response input
Python
bsd-3-clause
1844144/django-blog-zinnia,petecummings/django-blog-zinnia,jfdsmit/django-blog-zinnia,Maplecroft/django-blog-zinnia,marctc/django-blog-zinnia,Zopieux/django-blog-zinnia,1844144/django-blog-zinnia,petecummings/django-blog-zinnia,bywbilly/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,extertioner/django-blog-zinnia,aorzh/django-blog-zinnia,Fantomas42/django-blog-zinnia,aorzh/django-blog-zinnia,Maplecroft/django-blog-zinnia,ghachey/django-blog-zinnia,ghachey/django-blog-zinnia,jfdsmit/django-blog-zinnia,marctc/django-blog-zinnia,marctc/django-blog-zinnia,Zopieux/django-blog-zinnia,dapeng0802/django-blog-zinnia,jfdsmit/django-blog-zinnia,ZuluPro/django-blog-zinnia,bywbilly/django-blog-zinnia,jfdsmit/django-blog-zinnia,extertioner/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,dapeng0802/django-blog-zinnia,Fantomas42/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,ZuluPro/django-blog-zinnia,aorzh/django-blog-zinnia,1844144/django-blog-zinnia,dapeng0802/django-blog-zinnia,petecummings/django-blog-zinnia
--- +++ @@ -1,5 +1,5 @@ """Utils for Zinnia's tests""" -import cStringIO +import StringIO from xmlrpclib import Transport from django.test.client import Client @@ -18,6 +18,7 @@ response = self.client.post(handler, request_body, content_type="text/xml") - res = cStringIO.StringIO(response.content) + res = StringIO.StringIO(response.content) + setattr(res, 'getheader', lambda *args: '') # For Python >= 2.7 res.seek(0) return self.parse_response(res)
1ecc81d47cb8a9b07e5b37f382f1145c5232359d
docs/conf.py
docs/conf.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'amqp', __file__, project='py-amqp', description='Python Promises', version_dev='2.0', version_stable='1.4', canonical_url='https://amqp.readthedocs.io', webdomain='celeryproject.org', github_project='celery/py-amqp', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2016', publisher='Celery Project', html_logo='images/celery_128.png', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=[], include_intersphinx={'python', 'sphinx'}, apicheck_package='amqp', apicheck_ignore_modules=['amqp'], ))
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from sphinx_celery import conf globals().update(conf.build_config( 'amqp', __file__, project='py-amqp', description='Python Promises', version_dev='2.1', version_stable='2.0', canonical_url='https://amqp.readthedocs.io', webdomain='celeryproject.org', github_project='celery/py-amqp', author='Ask Solem & contributors', author_name='Ask Solem', copyright='2016', publisher='Celery Project', html_logo='images/celery_128.png', html_favicon='images/favicon.ico', html_prepend_sidebars=['sidebardonations.html'], extra_extensions=[], include_intersphinx={'python', 'sphinx'}, apicheck_package='amqp', apicheck_ignore_modules=['amqp'], ))
Set stable version to 2.x
Docs: Set stable version to 2.x
Python
lgpl-2.1
smurfix/aio-py-amqp,smurfix/aio-py-amqp
--- +++ @@ -7,8 +7,8 @@ 'amqp', __file__, project='py-amqp', description='Python Promises', - version_dev='2.0', - version_stable='1.4', + version_dev='2.1', + version_stable='2.0', canonical_url='https://amqp.readthedocs.io', webdomain='celeryproject.org', github_project='celery/py-amqp',
2355b13c180bfb065cf5826f5e1e48079822da16
dimod/package_info.py
dimod/package_info.py
__version__ = '1.0.0.dev4' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
__version__ = '1.0.0.dev5' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
Update version 1.0.0.dev4 -> 1.0.0.dev5
Update version 1.0.0.dev4 -> 1.0.0.dev5
Python
apache-2.0
oneklc/dimod,oneklc/dimod
--- +++ @@ -1,4 +1,4 @@ -__version__ = '1.0.0.dev4' +__version__ = '1.0.0.dev5' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
fa89ac95954502c14105857dfbb8dece271408e0
fiesta/fiesta.py
fiesta/fiesta.py
import base64, json, urllib2 api_client_id = "To3-IKknn36qAAAA" api_client_secret = "46d028xWl8zXGa3GCOYJMeXlr5pUebCNZcz3SCJj" basic_auth = base64.b64encode("%s:%s" % (api_client_id, api_client_secret)) def _create_and_send_request(uri, api_inputs): request = urllib2.Request(uri) request.add_header("Authorization", "Basic %s" % (basic_auth)) request.add_header("Content-Type", "application/json") request.add_data(json.dumps(api_inputs)) return urllib2.urlopen(request) def create_group_trusted(): create_group_uri = "https://api.fiesta.cc/group" api_inputs = {} response = _create_and_send_request(create_group_uri, api_inputs) json_response = json.loads(response.read()) group_id = json_response['data']['group_id'] def add_member_trusted(group_id, member_email, group_name): add_member_uri = "https://api.fiesta.cc/membership/%s" api_inputs = {'group_name': group_name, 'address': member_email} _create_and_send_request(add_member_uri % group_id, api_inputs)
import base64, json, urllib2 api_client_id = "" api_client_secret = "" basic_auth = base64.b64encode("%s:%s" % (api_client_id, api_client_secret)) def _create_and_send_request(uri, api_inputs): request = urllib2.Request(uri) request.add_header("Authorization", "Basic %s" % (basic_auth)) request.add_header("Content-Type", "application/json") request.add_data(json.dumps(api_inputs)) return urllib2.urlopen(request) def create_group_trusted(): create_group_uri = "https://api.fiesta.cc/group" api_inputs = {} response = _create_and_send_request(create_group_uri, api_inputs) json_response = json.loads(response.read()) group_id = json_response['data']['group_id'] def add_member_trusted(group_id, member_email, group_name): add_member_uri = "https://api.fiesta.cc/membership/%s" api_inputs = {'group_name': group_name, 'address': member_email} _create_and_send_request(add_member_uri % group_id, api_inputs)
Remove accidental commit of credentials
Remove accidental commit of credentials
Python
apache-2.0
fiesta/fiesta-python
--- +++ @@ -1,7 +1,7 @@ import base64, json, urllib2 -api_client_id = "To3-IKknn36qAAAA" -api_client_secret = "46d028xWl8zXGa3GCOYJMeXlr5pUebCNZcz3SCJj" +api_client_id = "" +api_client_secret = "" basic_auth = base64.b64encode("%s:%s" % (api_client_id, api_client_secret)) def _create_and_send_request(uri, api_inputs):
a98f1291df2a9d7a232e96f6b65369c03b5f8e12
dmoj/executors/ZIG.py
dmoj/executors/ZIG.py
from dmoj.executors.compiled_executor import CompiledExecutor class Executor(CompiledExecutor): ext = 'zig' name = 'ZIG' command = 'zig' test_program = ''' const std = @import("std"); pub fn main() !void { const io = std.io; const stdin = std.io.getStdIn().inStream(); const stdout = std.io.getStdOut().outStream(); var line_buf: [50]u8 = undefined; while (try stdin.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { if (line.len == 0) break; try stdout.print("{}", .{line}); } }''' def __init__(self, problem_id, source_code, **kwargs): # this clean needs to happen because zig refuses to compile carriage returns # https://github.com/ziglang/zig/issues/544 code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n') super().__init__(problem_id, code, **kwargs) def get_compile_args(self): return [ self.get_command(), 'build-exe', self._code, '--release-safe', '--name', self.problem, ] @classmethod def get_version_flags(cls, command): return ['version']
from dmoj.executors.compiled_executor import CompiledExecutor class Executor(CompiledExecutor): ext = 'zig' name = 'ZIG' command = 'zig' test_program = ''' const std = @import("std"); pub fn main() !void { const io = std.io; const stdin = std.io.getStdIn().inStream(); const stdout = std.io.getStdOut().outStream(); var line_buf: [50]u8 = undefined; while (try stdin.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { if (line.len == 0) break; try stdout.print("{}", .{line}); } }''' def create_files(self, problem_id, source_code, *args, **kwargs): # This cleanup needs to happen because Zig refuses to compile carriage returns. # See <https://github.com/ziglang/zig/issues/544>. source_code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n') super().create_files(problem_id, source_code, *args, **kwargs) def get_compile_args(self): return [ self.get_command(), 'build-exe', self._code, '--release-safe', '--name', self.problem, ] @classmethod def get_version_flags(cls, command): return ['version']
Move Zig source normalization to `create_files`
Move Zig source normalization to `create_files` This actually works, even if I don't know why.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
--- +++ @@ -20,11 +20,11 @@ } }''' - def __init__(self, problem_id, source_code, **kwargs): - # this clean needs to happen because zig refuses to compile carriage returns - # https://github.com/ziglang/zig/issues/544 - code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n') - super().__init__(problem_id, code, **kwargs) + def create_files(self, problem_id, source_code, *args, **kwargs): + # This cleanup needs to happen because Zig refuses to compile carriage returns. + # See <https://github.com/ziglang/zig/issues/544>. + source_code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n') + super().create_files(problem_id, source_code, *args, **kwargs) def get_compile_args(self): return [
a426a460555e17d6969444f6dea2ef4e131d6eaf
iatidataquality/registry.py
iatidataquality/registry.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from flask import Flask, render_template, flash, request, Markup, \ session, redirect, url_for, escape, Response, abort, send_file from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import func from datetime import datetime from iatidataquality import app from iatidataquality import db from iatidq import dqdownload, dqregistry, dqindicators, dqorganisations, dqpackages import usermanagement @app.route("/registry/refresh/") @usermanagement.perms_required() def registry_refresh(): dqregistry.refresh_packages() return "Refreshed" @app.route("/registry/download/") @usermanagement.perms_required() def registry_download(): dqdownload.run() return "Downloading"
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 from flask import Flask, render_template, flash, request, Markup, \ session, redirect, url_for, escape, Response, abort, send_file from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import func from datetime import datetime from iatidataquality import app from iatidataquality import db from iatidq import dqdownload, dqregistry, dqindicators, dqorganisations, dqpackages import usermanagement @app.route("/registry/refresh/") @usermanagement.perms_required() def registry_refresh(): dqregistry.refresh_packages() return "Refreshed" @app.route("/registry/download/") @usermanagement.perms_required() def registry_download(): dqdownload.run() return "Downloading" @app.route("/registry/deleted/") @usermanagement.perms_required() def registry_deleted(): num_deleted = dqregistry.check_deleted_packages() if num_deleted >0: msg = '%s packages were set to deleted' % num_deleted else: msg = "No packages were set to deleted" flash(msg, '') return redirect(url_for('packages_manage'))
Add URL for checking for deleted packages
Add URL for checking for deleted packages
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
--- +++ @@ -30,3 +30,15 @@ def registry_download(): dqdownload.run() return "Downloading" + +@app.route("/registry/deleted/") +@usermanagement.perms_required() +def registry_deleted(): + num_deleted = dqregistry.check_deleted_packages() + if num_deleted >0: + msg = '%s packages were set to deleted' % num_deleted + else: + msg = "No packages were set to deleted" + + flash(msg, '') + return redirect(url_for('packages_manage'))
9109d7d148abd8764b750becced3487f6d9ea8fc
rpcdaemon/lib/pidfile.py
rpcdaemon/lib/pidfile.py
import os class PIDFile(): def __init__(self, path): if not path: raise IOError('File not found. Please specify PID file path.') self.path = path def __enter__(self): if not os.path.exists(self.path): # Create it with open(self.path, 'w') as pidfile: pidfile.write(str(os.getpid()) + '\n') else: # Open for read/write, so we can do either with open(self.path, 'rw+') as pidfile: # Get PID from file, stripping whitespace and leading 0s pid = str(int(pidfile.readline().strip())) # pidfile and process exist if pid and os.path.exists('/proc/' + pid): raise SystemExit('Daemon already running.') else: # Clear and write our PID pidfile.seek(0) pidfile.write(str(os.getpid()) + '\n') pidfile.truncate() return self def __exit__(self, exc_type, exc_val, exc_tb): # If pidfile exists here we wrote it; kill it if os.path.exists(self.path): os.remove(self.path) # Succeeded at exiting; don't suppress any bubbled exceptions return False
import os class PIDFile(): def __init__(self, path): if not path: raise IOError('File not found. Please specify PID file path.') self.path = path def __enter__(self): if not os.path.exists(self.path): # Create it with open(self.path, 'w') as pidfile: pidfile.write(str(os.getpid()) + '\n') else: # Open for read/write, so we can do either with open(self.path, 'rw+') as pidfile: # Get PID from file, stripping whitespace and leading 0s pid = str(int(pidfile.readline().strip())) # pidfile and process exist if pid and os.path.exists('/proc/' + pid): raise SystemExit('Daemon already running.') else: # Clear and write our PID pidfile.seek(0) pidfile.write(str(os.getpid()) + '\n') pidfile.truncate() return self def __exit__(self, *args, **kwargs): # If pidfile exists here we wrote it; kill it if os.path.exists(self.path): os.remove(self.path) # Succeeded at exiting; don't suppress any bubbled exceptions return False
Fix change in args between versions of python-daemon
Fix change in args between versions of python-daemon Newer version call __exit__ with exception data, old versions merely call __exit__().
Python
apache-2.0
Apsu/rpcdaemon
--- +++ @@ -29,7 +29,7 @@ return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__(self, *args, **kwargs): # If pidfile exists here we wrote it; kill it if os.path.exists(self.path): os.remove(self.path)
3ec6dda43e617ddf6ad6b755cbcf2e93d5ff0983
feebb/preprocessor.py
feebb/preprocessor.py
import json class Preprocessor: def __init__(self): self.reset() def reset(self): self.number_elements = 0 self.length_elements = [] self.E_elements = [] self.I_elements = [] self.loads = [] self.supports = [] def load_json(self, infile): self.reset() with open(infile) as json_model: model = json.load(json_model) self.number_elements = len(model['elements']) self.length_elements = [element['length'] for element in model['elements']] self.E_elements = [element['youngs_mod'] for element in model['elements']] self.I_elements = [element['moment_of_inertia'] for element in model['elements']] # for element in model['elements']: # for load in element['loads']: # load["element"] = element["element"] # self.loads.append(load) self.loads = [element['loads'] for element in model['elements']] self.supports = model['supports']
import json class Preprocessor: def __init__(self): self.reset() def __str__(self): return json.dumps(self.__dict__, indent=2, separators=(',', ': ')) def reset(self): self.number_elements = 0 self.length_elements = [] self.E_elements = [] self.I_elements = [] self.loads = [] self.supports = [] def load_json(self, infile): self.reset() with open(infile) as json_model: model = json.load(json_model) self.number_elements = len(model['elements']) self.length_elements = [element['length'] for element in model['elements']] self.E_elements = [element['youngs_mod'] for element in model['elements']] self.I_elements = [element['moment_of_inertia'] for element in model['elements']] # for element in model['elements']: # for load in element['loads']: # load["element"] = element["element"] # self.loads.append(load) self.loads = [element['loads'] for element in model['elements']] self.supports = model['supports']
Add __str__ to Preprocessor class
Add __str__ to Preprocessor class
Python
mit
rbn920/feebb
--- +++ @@ -4,6 +4,9 @@ class Preprocessor: def __init__(self): self.reset() + + def __str__(self): + return json.dumps(self.__dict__, indent=2, separators=(',', ': ')) def reset(self): self.number_elements = 0
2409dfabbd53aaa9e21d8b93485cff0dd2db308c
wooey/migrations/0012_wooeyjob_uuid.py
wooey/migrations/0012_wooeyjob_uuid.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid, os def gen_uuid(apps, schema_editor): WooeyJob = apps.get_model('wooey', 'WooeyJob') for obj in WooeyJob.objects.all(): obj.uuid = uuid.uuid4() obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0011_script_versioning_cleanup'), ] operations = [ # Add the uuid field with unique=False for existing entries # due to a bug in migrations this will set all to the same uuid migrations.AddField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=False, max_length=255), ), # Set the uuids for existing records migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), # Set to unique=True migrations.AlterField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=True, max_length=255), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import uuid, os def gen_uuid(apps, schema_editor): WooeyJob = apps.get_model('wooey', 'WooeyJob') for obj in WooeyJob.objects.all(): obj.uuid = uuid.uuid4() obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0011_script_versioning_cleanup'), ] operations = [ # Add the uuid field with unique=False for existing entries # due to a bug in migrations this will set all to the same uuid migrations.AddField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=False, max_length=255), ), # Set the uuids for existing records migrations.RunPython(gen_uuid), # Set to unique=True migrations.AlterField( model_name='wooeyjob', name='uuid', field=models.CharField(default=uuid.uuid4, unique=True, max_length=255), ), ]
Remove migrations.RunPython.noop from reverse for Django<1.8
Remove migrations.RunPython.noop from reverse for Django<1.8
Python
bsd-3-clause
waytai/Wooey,wooey/Wooey,alexkolar/Wooey,wooey/Wooey,hottwaj/Wooey,wooey/Wooey,hottwaj/Wooey,wooey/Wooey,waytai/Wooey,hottwaj/Wooey,alexkolar/Wooey,waytai/Wooey,alexkolar/Wooey
--- +++ @@ -26,7 +26,7 @@ field=models.CharField(default=uuid.uuid4, unique=False, max_length=255), ), # Set the uuids for existing records - migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), + migrations.RunPython(gen_uuid), # Set to unique=True migrations.AlterField( model_name='wooeyjob',
8182b0b053d45252c7800aa1bf1f750fdfa7f876
examples/jumbo_fields.py
examples/jumbo_fields.py
from __future__ import print_function import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
from __future__ import print_function import os from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') def repeat50k(s): return s * 50000 @activity.with_attributes(task_list='quickstart', version='example') def length(x): return len(x) class JumboFieldsWorkflow(Workflow): """ This workflow demonstrates how you can use simpleflow jumbo fields, e.g. how simpleflow can automatically store input/results on S3 if their length crosses the SWF limits (32KB for input/results). """ name = 'basic' version = 'example' task_list = 'example' def run(self, string): if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format( string, string_length.result))
Make JumboFieldsWorkflow fail if no env var
Make JumboFieldsWorkflow fail if no env var If SIMPLEFLOW_JUMBO_FIELDS_BUCKET is not set, the example doesn't work; make this clear. Signed-off-by: Yves Bastide <3b1fe340dba76bf37270abad774f327f50b5e1d8@botify.com>
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
--- +++ @@ -1,12 +1,8 @@ from __future__ import print_function -import time +import os -from simpleflow import ( - activity, - Workflow, - futures, -) +from simpleflow import Workflow, activity @activity.with_attributes(task_list='quickstart', version='example') @@ -30,6 +26,9 @@ task_list = 'example' def run(self, string): + if 'SIMPLEFLOW_JUMBO_FIELDS_BUCKET' not in os.environ: + print("Please define SIMPLEFLOW_JUMBO_FIELDS_BUCKET to run this example (see README.rst).") + raise ValueError() long_string = self.submit(repeat50k, str(string)) string_length = self.submit(length, long_string) print('{} * 50k has a length of: {}'.format(
09bf3b9883096e7a433508a6d6e03efad2a137df
httpavail.py
httpavail.py
import sys, requests, argparse from retrying import retry argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argument('url') argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available') argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry') args = argparser.parse_args() @retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000) def check(): print('Checking', args.url) sys.stdout.flush() response = requests.get(args.url, timeout = 1) response.raise_for_status() return response.status_code if check() == 200: sys.exit(0) else: sys.exit(1)
import sys, requests, argparse from retrying import retry argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argument('url') argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available') argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry') argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code') args = argparser.parse_args() @retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000) def check(): print('Checking', args.url, 'for HTTP code', args.status_code) sys.stdout.flush() response = requests.get(args.url, timeout = 1) if response.status_code != args.status_code: raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code)) try: check() sys.exit(0) except Exception as e: print(str(e)) sys.exit(1)
Make the expected HTTP status code configurable
Make the expected HTTP status code configurable
Python
mit
ulich/docker-httpavail
--- +++ @@ -5,19 +5,23 @@ argparser.add_argument('url') argparser.add_argument('-t', '--timeout', type=int, default=120, help='total timeout in seconds to wait for the url to be available') argparser.add_argument('-d', '--delay', type=int, default=1, help='delay in seconds between each retry') +argparser.add_argument('-s', '--status-code', type=int, default=200, help='expected HTTP status code') args = argparser.parse_args() @retry(stop_max_delay = args.timeout * 1000, wait_fixed = args.delay * 1000) def check(): - print('Checking', args.url) + print('Checking', args.url, 'for HTTP code', args.status_code) sys.stdout.flush() response = requests.get(args.url, timeout = 1) - response.raise_for_status() - return response.status_code + if response.status_code != args.status_code: + raise Exception('Unexpected HTTP status code {} (Wanted: {})'.format(response.status_code , args.status_code)) -if check() == 200: + +try: + check() sys.exit(0) -else: +except Exception as e: + print(str(e)) sys.exit(1)
12edf5a5d77f96986a12105f922fabea83032bad
tests/scratchtest2.py
tests/scratchtest2.py
#!/usr/bin/env python import sys sys.path.append("../zvm") from zmemory import ZMemory from zlexer import ZLexer story = file("../stories/zork.z1").read() mem = ZMemory(story) lexer = ZLexer(mem) print "This story is z version", mem.version print "Standard dictionary:" print " word separators are", lexer._separators print " each dict value is", lexer.get_dictionary_entry_length(lexer._dict_addr), "bytes long" print " there are", lexer.get_dictionary_num_entries(lexer._dict_addr), "entries in the dictionary" dict = lexer.get_dictionary(lexer._dict_addr) print dict print print "dictionary has", len(dict.keys()), "items" print lexer._dict def lex_split(str, separators): split_str = [] prev_i = 0 i = 0 while i < len(str): if str[i] in separators: split_str.append(str[prev_i:i]) split_str.append(str[i]) prev_i = i+1 i = i+1
#!/usr/bin/env python import sys sys.path.append("../zvm") from zmemory import ZMemory from zlexer import ZLexer story = file("../stories/zork.z1").read() mem = ZMemory(story) lexer = ZLexer(mem) print "This story is z version", mem.version print "Standard dictionary:" print " word separators are", lexer._separators print " each dict value is", lexer.get_dictionary_entry_length(lexer._dict_addr), "bytes long" print " there are", lexer.get_dictionary_num_entries(lexer._dict_addr), "entries in the dictionary" print lexer._dict
Revert r67, which was not the changeset intended for commit.
Revert r67, which was not the changeset intended for commit.
Python
bsd-3-clause
BGCX262/zvm-hg-to-git,BGCX262/zvm-hg-to-git
--- +++ @@ -18,22 +18,4 @@ print " each dict value is", lexer.get_dictionary_entry_length(lexer._dict_addr), "bytes long" print " there are", lexer.get_dictionary_num_entries(lexer._dict_addr), "entries in the dictionary" -dict = lexer.get_dictionary(lexer._dict_addr) -print dict - -print - -print "dictionary has", len(dict.keys()), "items" - print lexer._dict - -def lex_split(str, separators): - split_str = [] - prev_i = 0 - i = 0 - while i < len(str): - if str[i] in separators: - split_str.append(str[prev_i:i]) - split_str.append(str[i]) - prev_i = i+1 - i = i+1
316d3b783d4ca9e1551add910440f20de27d0dff
redgreen.py
redgreen.py
#!/usr/bin/env python import pygame import random screen_width = 640 screen_height = 480 screen = None ready_text = None def start(): global screen, ready_text pygame.init() screen = pygame.display.set_mode( ( screen_width, screen_height ) ) font = pygame.font.Font( None, screen_height / 5 ) ready_text = font.render( "Ready?", 1, pygame.Color( "white" ) ) def ready_screen(): textpos = ready_text.get_rect( centerx = screen.get_width() / 2, centery = screen.get_height() / 2 ) screen.blit( ready_text, textpos ) pygame.display.flip() def wait(): time_to_wait = random.randint( 2000, 5000 ) # Between 2 and 5 seconds pygame.time.wait( time_to_wait ) # Note bug: can't quit during this time def shape(): screen.fill( pygame.Color( "black" ) ) pygame.display.flip() def end(): while True: evt = pygame.event.wait() if evt.type == pygame.QUIT: break start() ready_screen() wait() shape() end()
#!/usr/bin/env python import pygame import random screen_width = 640 screen_height = 480 screen = None ready_text = None def start(): global screen, ready_text, ready_text_pos pygame.init() screen = pygame.display.set_mode( ( screen_width, screen_height ) ) font = pygame.font.Font( None, screen_height / 5 ) ready_text = font.render( "Ready?", 1, pygame.Color( "white" ) ) ready_text_pos = ready_text.get_rect( centerx = screen.get_width() / 2, centery = screen.get_height() / 2 ) def ready_screen(): screen.fill( pygame.Color( "black" ) ) screen.blit( ready_text, ready_text_pos ) pygame.display.flip() def wait(): time_to_wait = random.randint( 1500, 3000 ) # Between 1.5 and 3 seconds pygame.time.wait( time_to_wait ) # Note bug: can't quit during this time def shape(): screen.fill( pygame.Color( "white" ) ) pygame.display.flip() def end(): while True: evt = pygame.event.wait() if evt.type == pygame.QUIT: break start() ready_screen() wait() shape() end()
Make ready screen explicitly black, and shape screen white
Make ready screen explicitly black, and shape screen white
Python
mit
andybalaam/redgreen
--- +++ @@ -10,27 +10,27 @@ ready_text = None def start(): - global screen, ready_text + global screen, ready_text, ready_text_pos pygame.init() screen = pygame.display.set_mode( ( screen_width, screen_height ) ) font = pygame.font.Font( None, screen_height / 5 ) ready_text = font.render( "Ready?", 1, pygame.Color( "white" ) ) - -def ready_screen(): - textpos = ready_text.get_rect( + ready_text_pos = ready_text.get_rect( centerx = screen.get_width() / 2, centery = screen.get_height() / 2 ) - screen.blit( ready_text, textpos ) +def ready_screen(): + screen.fill( pygame.Color( "black" ) ) + screen.blit( ready_text, ready_text_pos ) pygame.display.flip() def wait(): - time_to_wait = random.randint( 2000, 5000 ) # Between 2 and 5 seconds + time_to_wait = random.randint( 1500, 3000 ) # Between 1.5 and 3 seconds pygame.time.wait( time_to_wait ) # Note bug: can't quit during this time def shape(): - screen.fill( pygame.Color( "black" ) ) + screen.fill( pygame.Color( "white" ) ) pygame.display.flip() def end():
44426207ba65ba6c56c1092b0313f508c59d6b1f
core/exceptions.py
core/exceptions.py
import sublime from ..common import util MYPY = False if MYPY: from typing import Sequence class GitSavvyError(Exception): def __init__(self, msg, *args, cmd=None, stdout="", stderr="", **kwargs): # type: (str, object, Sequence[str], str, str, object) -> None super(GitSavvyError, self).__init__(msg, *args) self.message = msg self.cmd = cmd self.stdout = stdout self.stderr = stderr if msg: if kwargs.get('show_panel', True): util.log.display_panel(sublime.active_window(), msg) if kwargs.get('show_status', False): sublime.active_window().status_message(msg) util.debug.log_error(msg) class FailedGithubRequest(GitSavvyError): pass class FailedGitLabRequest(GitSavvyError): pass
import sublime from ..common import util MYPY = False if MYPY: from typing import Sequence class GitSavvyError(Exception): def __init__(self, msg, *args, cmd=None, stdout="", stderr="", **kwargs): # type: (str, object, Sequence[str], str, str, object) -> None super(GitSavvyError, self).__init__(msg, *args) self.message = msg self.cmd = cmd self.stdout = stdout self.stderr = stderr if msg: if kwargs.get('show_panel', True): util.log.display_panel(sublime.active_window(), msg) util.debug.log_error(msg) class FailedGithubRequest(GitSavvyError): pass class FailedGitLabRequest(GitSavvyError): pass
Remove unused `show_status` feature of `GitSavvyError`
Remove unused `show_status` feature of `GitSavvyError`
Python
mit
divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy
--- +++ @@ -18,8 +18,6 @@ if msg: if kwargs.get('show_panel', True): util.log.display_panel(sublime.active_window(), msg) - if kwargs.get('show_status', False): - sublime.active_window().status_message(msg) util.debug.log_error(msg)
7c518085d0e1901f12f251069c6b4b90595664b4
flocker/node/agents/functional/test_cinder.py
flocker/node/agents/functional/test_cinder.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for ``flocker.node.agents.cinder`` using a real OpenStack cluster. """ # A helper to check the environment for username and API key # Create an authenticated cinder API instance # Supply that to make_iblockdeviceapi_tests from uuid import uuid4 from ..cinder import cinder_api from ..testtools import ( make_iblockdeviceapi_tests, todo_except, cinder_client_for_test ) def cinderblockdeviceapi_for_test(test_case): """ """ return cinder_api( cinder_client=cinder_client_for_test(test_case), cluster_id=unicode(uuid4()), ) @todo_except( supported_tests=[ 'test_interface', 'test_created_is_listed', 'test_created_volume_attributes', 'test_list_volume_empty', 'test_listed_volume_attributes', ] ) class CinderBlockDeviceAPITests( make_iblockdeviceapi_tests( blockdevice_api_factory=cinderblockdeviceapi_for_test ) ): """ Interface adherence Tests for ``CinderBlockDeviceAPI``. """
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for ``flocker.node.agents.cinder`` using a real OpenStack cluster. """ # A helper to check the environment for username and API key # Create an authenticated cinder API instance # Supply that to make_iblockdeviceapi_tests from uuid import uuid4 from ..cinder import cinder_api from ..testtools import ( make_iblockdeviceapi_tests, todo_except, tidy_cinder_client_for_test ) def cinderblockdeviceapi_for_test(test_case): """ """ return cinder_api( cinder_client=tidy_cinder_client_for_test(test_case), cluster_id=unicode(uuid4()), ) @todo_except( supported_tests=[ 'test_interface', 'test_created_is_listed', 'test_created_volume_attributes', 'test_list_volume_empty', 'test_listed_volume_attributes', ] ) class CinderBlockDeviceAPITests( make_iblockdeviceapi_tests( blockdevice_api_factory=cinderblockdeviceapi_for_test ) ): """ Interface adherence Tests for ``CinderBlockDeviceAPI``. """
Use tidy client for cinderblockapi tests too.
Use tidy client for cinderblockapi tests too.
Python
apache-2.0
jml/flocker,lukemarsden/flocker,agonzalezro/flocker,runcom/flocker,runcom/flocker,w4ngyi/flocker,runcom/flocker,Azulinho/flocker,w4ngyi/flocker,lukemarsden/flocker,AndyHuu/flocker,LaynePeng/flocker,jml/flocker,1d4Nf6/flocker,adamtheturtle/flocker,moypray/flocker,mbrukman/flocker,jml/flocker,Azulinho/flocker,Azulinho/flocker,hackday-profilers/flocker,1d4Nf6/flocker,achanda/flocker,adamtheturtle/flocker,hackday-profilers/flocker,LaynePeng/flocker,hackday-profilers/flocker,moypray/flocker,achanda/flocker,wallnerryan/flocker-profiles,AndyHuu/flocker,wallnerryan/flocker-profiles,agonzalezro/flocker,w4ngyi/flocker,moypray/flocker,1d4Nf6/flocker,mbrukman/flocker,LaynePeng/flocker,achanda/flocker,agonzalezro/flocker,adamtheturtle/flocker,wallnerryan/flocker-profiles,lukemarsden/flocker,AndyHuu/flocker,mbrukman/flocker
--- +++ @@ -13,7 +13,7 @@ from ..cinder import cinder_api from ..testtools import ( - make_iblockdeviceapi_tests, todo_except, cinder_client_for_test + make_iblockdeviceapi_tests, todo_except, tidy_cinder_client_for_test ) @@ -21,7 +21,7 @@ """ """ return cinder_api( - cinder_client=cinder_client_for_test(test_case), + cinder_client=tidy_cinder_client_for_test(test_case), cluster_id=unicode(uuid4()), )
8e2cfa2845b6fadba1914246ed2169741164aa32
mastertickets/db_default.py
mastertickets/db_default.py
# Created by Noah Kantrowitz on 2007-07-04. # Copyright (c) 2007 Noah Kantrowitz. All rights reserved. from trac.db import Table, Column name = 'mastertickets' version = 2 tables = [ Table('mastertickets', key=('source','dest'))[ Column('source', type='integer'), Column('dest', type='integer'), ], ] def convert_to_int(data): """Convert both source and dest in the mastertickets table to ints.""" for row in data['mastertickets'][1]: for i, (n1, n2) in enumerate(row): row[i] = [int(n1), int(n2)] migrations = [ (xrange(1,2), convert_to_int), ]
# Created by Noah Kantrowitz on 2007-07-04. # Copyright (c) 2007 Noah Kantrowitz. All rights reserved. from trac.db import Table, Column name = 'mastertickets' version = 2 tables = [ Table('mastertickets', key=('source','dest'))[ Column('source', type='integer'), Column('dest', type='integer'), ], ] def convert_to_int(data): """Convert both source and dest in the mastertickets table to ints.""" rows = data['mastertickets'][1] for i, (n1, n2) in enumerate(rows): rows[i] = [int(n1), int(n2)] migrations = [ (xrange(1,2), convert_to_int), ]
Fix the migration to actual work.
Fix the migration to actual work.
Python
bsd-3-clause
thmo/trac-mastertickets,pombredanne/trac-mastertickets,pombredanne/trac-mastertickets,thmo/trac-mastertickets
--- +++ @@ -14,9 +14,9 @@ def convert_to_int(data): """Convert both source and dest in the mastertickets table to ints.""" - for row in data['mastertickets'][1]: - for i, (n1, n2) in enumerate(row): - row[i] = [int(n1), int(n2)] + rows = data['mastertickets'][1] + for i, (n1, n2) in enumerate(rows): + rows[i] = [int(n1), int(n2)] migrations = [ (xrange(1,2), convert_to_int),
369efdb0074ec29259e519b5d3974d55a17af56d
test_groupelo.py
test_groupelo.py
import groupelo def test_win_expectancy(): assert groupelo.win_expectancy(1500, 1500) == 0.5 assert groupelo.win_expectancy(1501, 1499) > 0.5 assert groupelo.win_expectancy(1550, 1450) > 0.6 assert groupelo.win_expectancy(1600, 1400) > 0.7 assert groupelo.win_expectancy(1700, 1300) > 0.9 assert groupelo.win_expectancy(2000, 1000) > 0.99 assert groupelo.win_expectancy(1499, 1501) < 0.5 assert groupelo.win_expectancy(1450, 1550) < 0.4 assert groupelo.win_expectancy(1400, 1600) < 0.3 assert groupelo.win_expectancy(1300, 1700) < 0.1 assert groupelo.win_expectancy(1000, 2000) < 0.01
# Run this with py.test or nose import groupelo def test_win_expectancy(): assert groupelo.win_expectancy(1500, 1500) == 0.5 assert groupelo.win_expectancy(1501, 1499) > 0.5 assert groupelo.win_expectancy(1550, 1450) > 0.6 assert groupelo.win_expectancy(1600, 1400) > 0.7 assert groupelo.win_expectancy(1700, 1300) > 0.9 assert groupelo.win_expectancy(2000, 1000) > 0.99 assert groupelo.win_expectancy(1499, 1501) < 0.5 assert groupelo.win_expectancy(1450, 1550) < 0.4 assert groupelo.win_expectancy(1400, 1600) < 0.3 assert groupelo.win_expectancy(1300, 1700) < 0.1 assert groupelo.win_expectancy(1000, 2000) < 0.01
Add a comment explaining how to run this unit test.
Add a comment explaining how to run this unit test.
Python
mit
dripton/groupelo
--- +++ @@ -1,3 +1,5 @@ +# Run this with py.test or nose + import groupelo def test_win_expectancy():
dca0598633350dfda2450552760ffbc774e63cb8
myfedora/lib/app_globals.py
myfedora/lib/app_globals.py
"""The application's Globals object""" from tg import config from shove import Shove from feedcache.cache import Cache from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} self.feed_storage = Shove('file://' + config['feed_cache']) self.feed_cache = Cache(self.feed_storage)
"""The application's Globals object""" from tg import config from app_factory import AppFactoryDict class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance}
Remove the feed cache and storage from the globals. This lives in moksha.
Remove the feed cache and storage from the globals. This lives in moksha.
Python
agpl-3.0
fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages
--- +++ @@ -1,8 +1,6 @@ """The application's Globals object""" from tg import config -from shove import Shove -from feedcache.cache import Cache from app_factory import AppFactoryDict class Globals(object): @@ -18,6 +16,3 @@ self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}} self.resourceviews = AppFactoryDict() # {name: ResourceView instance} self.apps = AppFactoryDict() # {name: App instance} - - self.feed_storage = Shove('file://' + config['feed_cache']) - self.feed_cache = Cache(self.feed_storage)
a52345306a1561496e2630fa12d938af84ff3f7d
management/commands/import_unit_data.py
management/commands/import_unit_data.py
# -*- encoding: UTF-8 -*- # # Copyright 2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of CVN. # # CVN is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # CVN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with CVN. If not, see # <http://www.gnu.org/licenses/>. # from django.core.management.base import BaseCommand from core.ws_utils import CachedWS as ws from cvn.models import ReportArea, ReportDept from django.utils.translation import ugettext as _ class Command(BaseCommand): help = _(u'Import department and area info from WebServices') def handle(self, *args, **options): ReportArea.reload() ReportDept.reload()
# -*- encoding: UTF-8 -*- # # Copyright 2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of CVN. # # CVN is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # CVN is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with CVN. If not, see # <http://www.gnu.org/licenses/>. # from django.core.management.base import BaseCommand from core.ws_utils import CachedWS as ws from cvn.models import ReportArea, ReportDept from django.utils.translation import ugettext as _ class Command(BaseCommand): help = _(u'Import department and area info from WebServices') def handle(self, *args, **options): ReportArea.objects.all().delete() ReportDept.objects.all().delete() ReportArea.reload() ReportDept.reload()
Delete Report models before reloading them
Delete Report models before reloading them
Python
agpl-3.0
tic-ull/portal-del-investigador-cvn,tic-ull/portal-del-investigador-cvn
--- +++ @@ -32,5 +32,7 @@ help = _(u'Import department and area info from WebServices') def handle(self, *args, **options): + ReportArea.objects.all().delete() + ReportDept.objects.all().delete() ReportArea.reload() ReportDept.reload()
3ab27c7ff2161d0ce4ccc7f2ffef8e4b5b745911
feder/cases/autocomplete_light_registry.py
feder/cases/autocomplete_light_registry.py
import autocomplete_light from models import Case class CaseAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name'] def choices_for_request(self, *args, **kwargs): qs = super(CaseAutocomplete, self).choices_for_request(*args, **kwargs) return qs.only('id', 'name') autocomplete_light.register(Case, CaseAutocomplete)
import autocomplete_light from .models import Case class CaseAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name'] def choices_for_request(self, *args, **kwargs): qs = super(CaseAutocomplete, self).choices_for_request(*args, **kwargs) return qs.only('id', 'name') autocomplete_light.register(Case, CaseAutocomplete)
Fix typo in cases autocomplete
Fix typo in cases autocomplete
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -1,5 +1,5 @@ import autocomplete_light -from models import Case +from .models import Case class CaseAutocomplete(autocomplete_light.AutocompleteModelBase):
a5d1879ce858618179258cca6eaed3ff087a8f42
vulndb/tests/test_proper_data_installation.py
vulndb/tests/test_proper_data_installation.py
import subprocess import unittest class TestDataIsInstalled(unittest.TestCase): TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(123)'" def test_data_is_installed_in_virtualenv(self): # When we run this in the current CMD it will load the python class # and db files from this directory (because of python's PATH) subprocess.check_output(self.TEST_CMD, shell=True) subprocess.check_output('python setup.py install', shell=True) # Now we run it in /tmp , where there is no vulndb in current PATH # so it will try to find it inside the site-packages subprocess.check_output(self.TEST_CMD, shell=True, cwd='/tmp/')
import subprocess import unittest class TestDataIsInstalled(unittest.TestCase): TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(1)'" def test_data_is_installed_in_virtualenv(self): # When we run this in the current CMD it will load the python class # and db files from this directory (because of python's PATH) subprocess.check_output(self.TEST_CMD, shell=True) subprocess.check_output('python setup.py install', shell=True) # Now we run it in /tmp , where there is no vulndb in current PATH # so it will try to find it inside the site-packages subprocess.check_output(self.TEST_CMD, shell=True, cwd='/tmp/')
Test with an existing id
Test with an existing id
Python
bsd-3-clause
vulndb/python-sdk,vulndb/python-sdk,LocutusOfBorg/python-sdk
--- +++ @@ -3,7 +3,7 @@ class TestDataIsInstalled(unittest.TestCase): - TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(123)'" + TEST_CMD = "python -c 'from vulndb import DBVuln; DBVuln.from_id(1)'" def test_data_is_installed_in_virtualenv(self): # When we run this in the current CMD it will load the python class
54054b4e007acbb5f1389a5e2091824a4c083e91
examples/plotting/LineAnimator_examples.py
examples/plotting/LineAnimator_examples.py
""" ============= LineAnimator ============= This example shows off some ways in which you can use the LineAnimator object to animate line plots. """ import numpy as np import matplotlib.pyplot as plt from sunpy.visualization.animator import LineAnimator ############################################################################### # Animate a 2D cube of random data as a line plot along an # axis where the x-axis drifts with time. # Define some random data data_shape0 = (10, 20) data0 = np.random.rand(*data_shape0) ############################################################################### # Define the axis that will make up the line plot plot_axis0 = 1 slider_axis0 = 0 ############################################################################### # Define value along x axis which drift with time. To do this, define # xdata to be the same shape as the data where each row/column # (depending on axis to be animated) represents the x-axis values for # a single frame of the animations. xdata = np.tile(np.linspace(0, 100, data_shape0[plot_axis0]), (data_shape0[slider_axis0], 1)) ############################################################################### # Generate animation object with variable x-axis data. ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata]) ############################################################################### # Show plot plt.show()
""" ============= LineAnimator ============= This example shows off some ways in which you can use the LineAnimator object to animate line plots. """ import numpy as np import matplotlib.pyplot as plt from sunpy.visualization.animator import LineAnimator ############################################################################### # Animate a 2D cube of random data as a line plot along an # axis where the x-axis drifts with time. # Define some random data data_shape0 = (10, 20) data0 = np.random.rand(*data_shape0) ############################################################################### # Define the axis that will make up the line plot plot_axis0 = 1 slider_axis0 = 0 ############################################################################### # Define value along x axis which drift with time. To do this, define # xdata to be the same shape as the data where each row/column # (depending on axis to be animated) represents the x-axis values for # a single frame of the animations. xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1)) ############################################################################### # Generate animation object with variable x-axis data. ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata]) ############################################################################### # Show plot plt.show()
Fix LineAnimator example to adhere to new pixel edges axis_ranges API.
Fix LineAnimator example to adhere to new pixel edges axis_ranges API.
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
--- +++ @@ -29,7 +29,7 @@ # xdata to be the same shape as the data where each row/column # (depending on axis to be animated) represents the x-axis values for # a single frame of the animations. -xdata = np.tile(np.linspace(0, 100, data_shape0[plot_axis0]), (data_shape0[slider_axis0], 1)) +xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1)) ############################################################################### # Generate animation object with variable x-axis data.
3ed6c303e935a78781d096ab90e77a6c1360322d
wutu/tests/modules/test_module/test_module.py
wutu/tests/modules/test_module/test_module.py
from wutu.module import Module class TestModule(Module): def __init__(self): super(TestModule, self).__init__() def ping(self): return "pong" def get(self): return {"result": "Hello"}
from wutu.module import Module class TestModule(Module): def __init__(self): super(TestModule, self).__init__() def ping(self): return "pong" def get(self, id): return {"result": id}
Make test module return dynamic value
Make test module return dynamic value
Python
mit
zaibacu/wutu,zaibacu/wutu,zaibacu/wutu
--- +++ @@ -8,5 +8,5 @@ def ping(self): return "pong" - def get(self): - return {"result": "Hello"} + def get(self, id): + return {"result": id}
f8a592301aa44e79e504f15e8c0b37a566c3e4cb
daybed/__init__.py
daybed/__init__.py
"""Main entry point """ import couchdb from pyramid.config import Configurator from pyramid.events import NewRequest from daybed.db import DatabaseConnection, sync_couchdb_views def add_db_to_request(event): request = event.request settings = request.registry.settings con_info = settings['db_server'][settings['db_name']] event.request.db = DatabaseConnection(con_info) def main(global_config, **settings): config = Configurator(settings=settings) config.include("cornice") config.scan("daybed.views") # CouchDB initialization db_server = couchdb.client.Server(settings['couchdb_uri']) config.registry.settings['db_server'] = db_server sync_couchdb_views(db_server[settings['db_name']]) config.add_subscriber(add_db_to_request, NewRequest) return config.make_wsgi_app()
"""Main entry point """ import couchdb from pyramid.config import Configurator from pyramid.events import NewRequest from daybed.db import DatabaseConnection, sync_couchdb_views def add_db_to_request(event): request = event.request settings = request.registry.settings con_info = settings['db_server'][settings['db_name']] event.request.db = DatabaseConnection(con_info) def create_db_if_not_exist(server, db_name, exist = False): try: if not exist: sync_couchdb_views(server[db_name]) except Exception, e: db = server.create(db_name) create_db_if_not_exist(server, db_name, True) def main(global_config, **settings): config = Configurator(settings=settings) config.include("cornice") config.scan("daybed.views") # CouchDB initialization db_server = couchdb.client.Server(settings['couchdb_uri']) config.registry.settings['db_server'] = db_server create_db_if_not_exist(db_server, settings['db_name'], False) config.add_subscriber(add_db_to_request, NewRequest) return config.make_wsgi_app()
Add test at init to create couchdb database if not already exists
Add test at init to create couchdb database if not already exists
Python
bsd-3-clause
spiral-project/daybed,spiral-project/daybed
--- +++ @@ -13,6 +13,14 @@ con_info = settings['db_server'][settings['db_name']] event.request.db = DatabaseConnection(con_info) +def create_db_if_not_exist(server, db_name, exist = False): + try: + if not exist: + sync_couchdb_views(server[db_name]) + except Exception, e: + db = server.create(db_name) + create_db_if_not_exist(server, db_name, True) + def main(global_config, **settings): config = Configurator(settings=settings) @@ -22,7 +30,6 @@ # CouchDB initialization db_server = couchdb.client.Server(settings['couchdb_uri']) config.registry.settings['db_server'] = db_server - sync_couchdb_views(db_server[settings['db_name']]) - + create_db_if_not_exist(db_server, settings['db_name'], False) config.add_subscriber(add_db_to_request, NewRequest) return config.make_wsgi_app()
dfc1851f27fa3de8de11d1facccfe28ae8e90dc6
subprocrunner/_which.py
subprocrunner/_which.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import shutil import warnings import six import typepy from ._error import CommandNotFoundError from ._error import InvalidCommandError class Which(object): @property def command(self): return self.__command def __init__(self, command): if not typepy.is_not_null_string(command): raise InvalidCommandError("invalid str {}: ".format(command)) self.__command = command def is_exist(self): return self.which() is not None def verify(self): if not self.is_exist(): raise CommandNotFoundError( "command not found: '{}'".format(self.command)) def abspath(self): if six.PY2: from distutils.spawn import find_executable return find_executable(self.command) return shutil.which(self.command) def full_path(self): warnings.warn( "full_path() deleted in the future, use abspath() instead.", DeprecationWarning) return self.abspath() def which(self): warnings.warn( "which() deleted in the future, use abspath() instead.", DeprecationWarning) return self.abspath()
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import shutil import warnings import six import typepy from ._error import CommandNotFoundError from ._error import InvalidCommandError class Which(object): @property def command(self): return self.__command def __init__(self, command): if not typepy.is_not_null_string(command): raise InvalidCommandError("invalid str {}: ".format(command)) self.__command = command def is_exist(self): return self.abspath() is not None def verify(self): if not self.is_exist(): raise CommandNotFoundError( "command not found: '{}'".format(self.command)) def abspath(self): if six.PY2: from distutils.spawn import find_executable return find_executable(self.command) return shutil.which(self.command) def full_path(self): warnings.warn( "full_path() deleted in the future, use abspath() instead.", DeprecationWarning) return self.abspath() def which(self): warnings.warn( "which() deleted in the future, use abspath() instead.", DeprecationWarning) return self.abspath()
Replace a method call to use the latest version method
Replace a method call to use the latest version method
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
--- +++ @@ -30,7 +30,7 @@ self.__command = command def is_exist(self): - return self.which() is not None + return self.abspath() is not None def verify(self): if not self.is_exist():
c613b59861d24a7627844114933c318423d18866
alpha_helix_generator/geometry.py
alpha_helix_generator/geometry.py
import numpy as np
import numpy as np def normalize(v): '''Normalize a vector based on its 2 norm.''' if 0 == np.linalg.norm(v): return v return v / np.linalg.norm(v) def create_frame_from_three_points(p1, p2, p3): '''Create a left-handed coordinate frame from 3 points. The p2 is the origin; the y-axis is the vector from p2 to p3; the z-axis is the cross product of the vector from p2 to p1 and the y-axis. Return a matrix where the axis vectors are the rows. ''' y = normalize(p3 - p2) z = normalize(np.cross(p1 - p2, y)) x = np.cross(y, z) return np.array([x, y, z]) def rotation_matrix_to_axis_and_angle(M): '''Calculate the axis and angle of a rotation matrix.''' u = np.array([M[2][1] - M[1][2], M[0][2] - M[2][0], M[1][0] - M[0][1]]) sin_theta = np.linalg.norm(u) / 2 cos_theta = (np.trace(M) - 1) / 2 return normalize(u), np.arctan2(sin_theta, cos_theta) def rotation_matrix_from_axis_and_angle(u, theta): '''Calculate a rotation matrix from an axis and an angle.''' u = normalize(u) x = u[0] y = u[1] z = u[2] s = np.sin(theta) c = np.cos(theta) return np.array([[c + x**2 * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s], [y * x * (1 - c) + z * s, c + y**2 * (1 - c), y * z * (1 - c) - x * s ], [z * x * (1 - c) + y * s, z * y * (1 - c) + x * s, c + z**2 * (1 - c) ]])
Add some basic geometric functions.
Add some basic geometric functions.
Python
bsd-3-clause
xingjiepan/ss_generator
--- +++ @@ -1 +1,47 @@ import numpy as np + + +def normalize(v): + '''Normalize a vector based on its 2 norm.''' + if 0 == np.linalg.norm(v): + return v + return v / np.linalg.norm(v) + +def create_frame_from_three_points(p1, p2, p3): + '''Create a left-handed coordinate frame from 3 points. + The p2 is the origin; the y-axis is the vector from p2 to p3; + the z-axis is the cross product of the vector from p2 to p1 + and the y-axis. + + Return a matrix where the axis vectors are the rows. + ''' + + y = normalize(p3 - p2) + z = normalize(np.cross(p1 - p2, y)) + x = np.cross(y, z) + return np.array([x, y, z]) + +def rotation_matrix_to_axis_and_angle(M): + '''Calculate the axis and angle of a rotation matrix.''' + u = np.array([M[2][1] - M[1][2], + M[0][2] - M[2][0], + M[1][0] - M[0][1]]) + + sin_theta = np.linalg.norm(u) / 2 + cos_theta = (np.trace(M) - 1) / 2 + + return normalize(u), np.arctan2(sin_theta, cos_theta) + +def rotation_matrix_from_axis_and_angle(u, theta): + '''Calculate a rotation matrix from an axis and an angle.''' + + u = normalize(u) + x = u[0] + y = u[1] + z = u[2] + s = np.sin(theta) + c = np.cos(theta) + + return np.array([[c + x**2 * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s], + [y * x * (1 - c) + z * s, c + y**2 * (1 - c), y * z * (1 - c) - x * s ], + [z * x * (1 - c) + y * s, z * y * (1 - c) + x * s, c + z**2 * (1 - c) ]])
e3828ae72ae778461eee9b93ccc87167505f91f8
validate.py
validate.py
"""Check for inconsistancies in the database.""" from server.db import BuildingBuilder, BuildingType, load, UnitType def main(): load() for name in UnitType.resource_names(): if UnitType.count(getattr(UnitType, name) == 1): continue else: print(f'There is no unit that can gather {name}.') for bt in BuildingType.all(): if not BuildingBuilder.count(building_type_id=bt.id): print(f'There is no way to build {bt.name}.') if __name__ == '__main__': try: main() except FileNotFoundError: print('No database file exists.')
"""Check for inconsistancies in the database.""" from server.db import ( BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType ) def main(): load() for name in UnitType.resource_names(): if UnitType.count(getattr(UnitType, name) >= 1): continue else: print(f'There is no unit that can gather {name}.') for bt in BuildingType.all(): if not BuildingBuilder.count(building_type_id=bt.id): print(f'There is no way to build {bt.name}.') for ut in UnitType.all(): if not BuildingRecruit.count(unit_type_id=ut.id): print(f'There is no way to recruit {ut.get_name()}.') if __name__ == '__main__': try: main() except FileNotFoundError: print('No database file exists.')
Make sure all unit types can be recruited.
Make sure all unit types can be recruited.
Python
mpl-2.0
chrisnorman7/pyrts,chrisnorman7/pyrts,chrisnorman7/pyrts
--- +++ @@ -1,18 +1,23 @@ """Check for inconsistancies in the database.""" -from server.db import BuildingBuilder, BuildingType, load, UnitType +from server.db import ( + BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType +) def main(): load() for name in UnitType.resource_names(): - if UnitType.count(getattr(UnitType, name) == 1): + if UnitType.count(getattr(UnitType, name) >= 1): continue else: print(f'There is no unit that can gather {name}.') for bt in BuildingType.all(): if not BuildingBuilder.count(building_type_id=bt.id): print(f'There is no way to build {bt.name}.') + for ut in UnitType.all(): + if not BuildingRecruit.count(unit_type_id=ut.id): + print(f'There is no way to recruit {ut.get_name()}.') if __name__ == '__main__':
99412f8b3394abdab900755095c788604669853d
ankieta/ankieta/petition/views.py
ankieta/ankieta/petition/views.py
# from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import SetHeadlineMixin from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(SetHeadlineMixin, CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html'
# from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm class SignatureList(OrderableListMixin, ListView): model = Signature orderable_columns = ("pk", "name", "city") orderable_columns_default = "created_on" ordering = 'desc' paginate_by = 10 def get_context_data(self, **kwargs): context = super(SignatureList, self).get_context_data(**kwargs) context['count'] = Signature.objects.visible().count() context['form'] = SignatureForm() return context def get_queryset(self, *args, **kwargs): qs = super(SignatureList, self).get_queryset(*args, **kwargs) return qs.visible() class SignatureCreate(CreateView): model = Signature form_class = SignatureForm def get_success_url(self): return reverse('petition:thank-you') class SignatureDetail(DetailView): model = Signature class SignatureCreateDone(TemplateView): template_name = 'petition/signature_thank_you.html'
Remove headline from create view
Remove headline from create view
Python
bsd-3-clause
watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl
--- +++ @@ -1,7 +1,6 @@ # from django.shortcuts import render from django.views.generic import ListView, CreateView, DetailView, TemplateView from django.core.urlresolvers import reverse -from braces.views import SetHeadlineMixin from braces.views import OrderableListMixin from .models import Signature from .forms import SignatureForm @@ -25,7 +24,7 @@ return qs.visible() -class SignatureCreate(SetHeadlineMixin, CreateView): +class SignatureCreate(CreateView): model = Signature form_class = SignatureForm
72216757991a2120bb81e0003496eee908373b0c
keystone/common/policies/ec2_credential.py
keystone/common/policies/ec2_credential.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base ec2_credential_policies = [ policy.RuleDefault( name=base.IDENTITY % 'ec2_get_credential', check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_list_credentials', check_str=base.RULE_ADMIN_REQUIRED), policy.RuleDefault( name=base.IDENTITY % 'ec2_create_credential', check_str=base.RULE_ADMIN_REQUIRED), policy.RuleDefault( name=base.IDENTITY % 'ec2_delete_credential', check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER), ] def list_rules(): return ec2_credential_policies
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from keystone.common.policies import base ec2_credential_policies = [ policy.RuleDefault( name=base.IDENTITY % 'ec2_get_credential', check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_list_credentials', check_str=base.RULE_ADMIN_OR_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_create_credential', check_str=base.RULE_ADMIN_OR_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_delete_credential', check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER), ] def list_rules(): return ec2_credential_policies
Set the correct in-code policy for ec2 operations
Set the correct in-code policy for ec2 operations In I8bd0fa342cdfee00acd3c7a33f7232fe0a87e23f we moved some of the policy defaults into code. Some of the policy were accidentally changed. Change-Id: Ib744317025d928c7397ab00dc706172592a9abaf Closes-Bug: #1675377
Python
apache-2.0
ilay09/keystone,rajalokan/keystone,openstack/keystone,ilay09/keystone,mahak/keystone,ilay09/keystone,mahak/keystone,openstack/keystone,rajalokan/keystone,rajalokan/keystone,mahak/keystone,openstack/keystone
--- +++ @@ -20,10 +20,10 @@ check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_list_credentials', - check_str=base.RULE_ADMIN_REQUIRED), + check_str=base.RULE_ADMIN_OR_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_create_credential', - check_str=base.RULE_ADMIN_REQUIRED), + check_str=base.RULE_ADMIN_OR_OWNER), policy.RuleDefault( name=base.IDENTITY % 'ec2_delete_credential', check_str=base.RULE_ADMIN_OR_CREDENTIAL_OWNER),
1090b8b4e17b29b69eb205ac0c7fea65f597807f
ffdnispdb/__init__.py
ffdnispdb/__init__.py
# -*- coding: utf-8 -*- from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
# -*- coding: utf-8 -*- from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface app = Flask(__name__) app.config.from_object('config') babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec): sqlite.enable_load_extension(True) sqlite.execute('select load_extension("libspatialite.so")') sqlite.enable_load_extension(False) from . import views from . import models
Enable NullCache so we can start implementing cache
Enable NullCache so we can start implementing cache
Python
bsd-3-clause
Psycojoker/ffdn-db,Psycojoker/ffdn-db
--- +++ @@ -3,6 +3,7 @@ from flask import Flask, g from flask.ext.babel import Babel from flask.ext.sqlalchemy import SQLAlchemy, event +from werkzeug.contrib.cache import NullCache from .sessions import MySessionInterface @@ -11,6 +12,7 @@ babel = Babel(app) db = SQLAlchemy(app) app.session_interface = MySessionInterface(db.engine, db.metadata) +cache = NullCache() @event.listens_for(db.engine, "connect") def connect(sqlite, connection_rec):
b16d634ee9390864da8de6f8d4e7f9e546c8f772
ifs/source/jenkins.py
ifs/source/jenkins.py
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update apt-get install -y jenkins """
version_cmd = 'java -jar /usr/share/jenkins/jenkins.war --version' version_re = '(\d\.\d{3})' depends = ['wget'] install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins """
Update Jenkins source to only update the Jenkins repository
Update Jenkins source to only update the Jenkins repository
Python
isc
cbednarski/ifs-python,cbednarski/ifs-python
--- +++ @@ -4,6 +4,6 @@ install_script = """ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add - echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list -apt-get update +apt-get update -o Dir::Etc::sourcelist="sources.list.d/jenkins.list" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" apt-get install -y jenkins """
77fac3732f1baae9f3c3be7b38f8837459fee163
src/markdown/makrdown.py
src/markdown/makrdown.py
from markdown import markdown from markdown.extensions.tables import TableExtension from .my_codehilite import CodeHiliteExtension from .my_fenced_code import FencedCodeExtension from .my_headerid import HeaderIdExtension def customized_markdown(text): return markdown(text, extensions=[FencedCodeExtension(), CodeHiliteExtension(css_class="code", guess_lang=False), HeaderIdExtension(), TableExtension()]) def jinja_aware_markdown(text, flatPages): app = flatPages.app template_context = {} app.update_template_context(template_context) env = app.jinja_env template = env.from_string(text) return customized_markdown(template.render(template_context))
import subprocess from xml.etree import ElementTree import pygments from bs4 import BeautifulSoup from pygments.formatters import get_formatter_by_name from pygments.lexers import get_lexer_by_name def customized_markdown(text): kramdown = subprocess.Popen( ["kramdown", "--input", "GFM", "--no-hard-wrap", "--smart-quotes", "apos,apos,quot,quot", "--no-enable-coderay" ], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8")) return stdout_data.decode("utf8") def highlight_code(text): tree = BeautifulSoup(text, 'html.parser') code_elements = tree.select('pre > code') for element in code_elements: class_names = element.get("class") lang = None if class_names is not None: for class_name in class_names: if class_name.startswith("language-"): lang = class_name[len("language-"):] if lang is not None: lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name('html', # linenos=self.linenums, cssclass="code _highlighted", # style=self.style, # noclasses=self.noclasses, # hl_lines=self.hl_lines ) highlighted = pygments.highlight(element.text, lexer, formatter) element.parent.replaceWith(BeautifulSoup(highlighted)) return unicode(str(tree.prettify(encoding="utf8")), "utf8") def jinja_aware_markdown(text, flatPages): app = flatPages.app template_context = {} app.update_template_context(template_context) env = app.jinja_env template = env.from_string(text) page_html = customized_markdown(template.render(template_context)) return highlight_code(page_html)
Use kramdown for markdown convertion.
Use kramdown for markdown convertion.
Python
apache-2.0
belovrv/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,madvirus/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,meilalina/kotlin-web-site,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,madvirus/kotlin-web-site,belovrv/kotlin-web-site,TeamKotl/kotlin-web-site,meilalina/kotlin-web-site,voddan/kotlin-web-site,hltj/kotlin-web-site-cn,voddan/kotlin-web-site,JetBrains/kotlin-web-site,belovrv/kotlin-web-site,madvirus/kotlin-web-site,TeamKotl/kotlin-web-site,JetBrains/kotlin-web-site,voddan/kotlin-web-site,TeamKotl/kotlin-web-site,meilalina/kotlin-web-site
--- +++ @@ -1,16 +1,46 @@ -from markdown import markdown -from markdown.extensions.tables import TableExtension +import subprocess +from xml.etree import ElementTree -from .my_codehilite import CodeHiliteExtension -from .my_fenced_code import FencedCodeExtension -from .my_headerid import HeaderIdExtension +import pygments +from bs4 import BeautifulSoup +from pygments.formatters import get_formatter_by_name +from pygments.lexers import get_lexer_by_name def customized_markdown(text): - return markdown(text, extensions=[FencedCodeExtension(), - CodeHiliteExtension(css_class="code", guess_lang=False), - HeaderIdExtension(), - TableExtension()]) + kramdown = subprocess.Popen( + ["kramdown", + "--input", "GFM", + "--no-hard-wrap", + "--smart-quotes", "apos,apos,quot,quot", + "--no-enable-coderay" + ], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + stdout_data, stderr_data = kramdown.communicate(input=text.encode("utf8")) + return stdout_data.decode("utf8") + + +def highlight_code(text): + tree = BeautifulSoup(text, 'html.parser') + code_elements = tree.select('pre > code') + for element in code_elements: + class_names = element.get("class") + lang = None + if class_names is not None: + for class_name in class_names: + if class_name.startswith("language-"): + lang = class_name[len("language-"):] + if lang is not None: + lexer = get_lexer_by_name(lang) + formatter = get_formatter_by_name('html', + # linenos=self.linenums, + cssclass="code _highlighted", + # style=self.style, + # noclasses=self.noclasses, + # hl_lines=self.hl_lines + ) + highlighted = pygments.highlight(element.text, lexer, formatter) + element.parent.replaceWith(BeautifulSoup(highlighted)) + return unicode(str(tree.prettify(encoding="utf8")), "utf8") def jinja_aware_markdown(text, flatPages): @@ -20,4 +50,5 @@ env = app.jinja_env template = env.from_string(text) - return customized_markdown(template.render(template_context)) + page_html = customized_markdown(template.render(template_context)) + return highlight_code(page_html)
ed9b7b6295f311dbbd7f66f0cbcb393ab122afec
django/__init__.py
django/__init__.py
VERSION = (1, 6, 0, 'beta', 2) def get_version(*args, **kwargs): # Don't litter django/__init__.py with all the get_version stuff. # Only import if it's actually called. from django.utils.version import get_version return get_version(*args, **kwargs)
VERSION = (1, 6, 0, 'beta', 3) def get_version(*args, **kwargs): # Don't litter django/__init__.py with all the get_version stuff. # Only import if it's actually called. from django.utils.version import get_version return get_version(*args, **kwargs)
Bump version number for 1.6 beta 3 security release.
[1.6.x] Bump version number for 1.6 beta 3 security release.
Python
bsd-3-clause
dex4er/django,django-nonrel/django,redhat-openstack/django,felixjimenez/django,redhat-openstack/django,dex4er/django,django-nonrel/django,dex4er/django,django-nonrel/django,redhat-openstack/django,redhat-openstack/django,django-nonrel/django,felixjimenez/django,felixjimenez/django,felixjimenez/django
--- +++ @@ -1,4 +1,4 @@ -VERSION = (1, 6, 0, 'beta', 2) +VERSION = (1, 6, 0, 'beta', 3) def get_version(*args, **kwargs): # Don't litter django/__init__.py with all the get_version stuff.
58ce11d293d19247e2765176983edc5e552bdfd5
celery/loaders/__init__.py
celery/loaders/__init__.py
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Python
bsd-3-clause
frac/celery,cbrepo/celery,cbrepo/celery,mitsuhiko/celery,ask/celery,frac/celery,ask/celery,WoLpH/celery,mitsuhiko/celery,WoLpH/celery
--- +++ @@ -14,24 +14,32 @@ if settings.configured: Loader = DjangoLoader else: - if not callable(getattr(os, "fork", None)): - # Platform doesn't support fork() - # XXX On systems without fork, multiprocessing seems to be launching - # the processes in some other way which does not copy the memory - # of the parent process. This means that any configured env might - # be lost. This is a hack to make it work on Windows. - # A better way might be to use os.environ to set the currently - # used configuration method so to propogate it to the "child" - # processes. But this has to be experimented with. - # [asksol/heyman] - try: - settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", - "settings") - project_settings = __import__(settings_mod, {}, {}, ['']) - setup_environ(project_settings) - Loader = DjangoLoader - except ImportError: - pass + try: + # A settings module may be defined, but Django didn't attempt to + # load it yet. As an alternative to calling the private _setup(), + # we could also check whether DJANGO_SETTINGS_MODULE is set. + settings._setup() + except ImportError: + if not callable(getattr(os, "fork", None)): + # Platform doesn't support fork() + # XXX On systems without fork, multiprocessing seems to be launching + # the processes in some other way which does not copy the memory + # of the parent process. This means that any configured env might + # be lost. This is a hack to make it work on Windows. + # A better way might be to use os.environ to set the currently + # used configuration method so to propogate it to the "child" + # processes. But this has to be experimented with. + # [asksol/heyman] + try: + settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", + "settings") + project_settings = __import__(settings_mod, {}, {}, ['']) + setup_environ(project_settings) + Loader = DjangoLoader + except ImportError: + pass + else: + Loader = DjangoLoader """ .. data:: current_loader
786e98f3c37e1c3bdedc424ed6eaec86e900ec83
test/test_testplugin.py
test/test_testplugin.py
"""Tests of the test-runner plugins.""" import py import unittest from nose.plugins import PluginTester from coverage.runners.noseplugin import Coverage class TestCoverage(PluginTester, unittest.TestCase): """Test the nose plugin.""" activate = '--with-coverage' # enables the plugin plugins = [Coverage()] args = ['--cover-report=report'] @py.test.mark.skipif(True) # "requires nose test runner" def test_output(self): assert "Processing Coverage..." in self.output, ( "got: %s" % self.output) def makeSuite(self): class TC(unittest.TestCase): def runTest(self): raise ValueError("Coverage down") return unittest.TestSuite([TC()]) pytest_plugins = ['pytester'] def test_functional(testdir): """Test the py.test plugin.""" testdir.makepyfile(""" def f(): x = 42 def test_whatever(): pass """) result = testdir.runpytest("--cover-report=annotate") assert result.ret == 0 assert result.stdout.fnmatch_lines([ '*Processing Coverage*' ]) coveragefile = testdir.tmpdir.join(".coverage") assert coveragefile.check() # XXX try loading it?
"""Tests of the test-runner plugins.""" import py import unittest from nose.plugins import PluginTester from coverage.runners.noseplugin import Coverage class TestCoverage(PluginTester, unittest.TestCase): """Test the nose plugin.""" activate = '--with-coverage' # enables the plugin plugins = [Coverage()] args = ['--cover-report=report'] @py.test.mark.skipif(True) # "requires nose test runner" def test_output(self): assert "Processing Coverage..." in self.output, ( "got: %s" % self.output) def makeSuite(self): class TC(unittest.TestCase): def runTest(self): raise ValueError("Coverage down") return unittest.TestSuite([TC()]) pytest_plugins = ['pytester'] def test_functional(testdir): """Test the py.test plugin.""" testdir.makepyfile(""" def f(): x = 42 def test_whatever(): pass """) result = testdir.runpytest("--cover-report=annotate") assert result.ret == 0 assert result.stdout.fnmatch_lines([ '*Processing Coverage*' ]) coveragefile = testdir.tmpdir.join(".coverage") assert coveragefile.check() # XXX try loading it? # Keep test_functional from running in nose: test_functional.__test__ = False
Mark the py.test test as not to be run in nose.
Mark the py.test test as not to be run in nose.
Python
apache-2.0
jayhetee/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,blueyed/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,hugovk/coveragepy,hugovk/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,nedbat/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,blueyed/coveragepy,hugovk/coveragepy,blueyed/coveragepy
--- +++ @@ -41,3 +41,6 @@ coveragefile = testdir.tmpdir.join(".coverage") assert coveragefile.check() # XXX try loading it? + +# Keep test_functional from running in nose: +test_functional.__test__ = False
8ce509a2a3df1fcc38442e35e8733bf00bd788ad
harvest/decorators.py
harvest/decorators.py
import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value is not None: setattr(self, cach_attr, value) return getattr(self, cach_attr, None) return wrap def cli(*args, **kwargs): def decorator(func): class Parser(ArgumentParser): def handle(self, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.error(e.message) # No catching of exceptions def handle_raw(self, *args, **kwargs): func(*args, **kwargs) return Parser(*args, **kwargs) return decorator def virtualenv(path): "Wraps a function and prefixes the call with the virtualenv active." if path is None: activate = None else: activate = os.path.join(path, 'bin/activate') def decorator(func): @wraps(func) def inner(*args, **kwargs): if path is not None: with prefix('source {0}'.format(activate)): func(*args, **kwargs) else: func(*args, **kwargs) return inner return decorator
import os from functools import wraps from argparse import ArgumentParser from fabric.context_managers import prefix def cached_property(func): cach_attr = '_{0}'.format(func.__name__) @property def wrap(self): if not hasattr(self, cach_attr): value = func(self) if value is not None: setattr(self, cach_attr, value) return getattr(self, cach_attr, None) return wrap def cli(*args, **kwargs): def decorator(func): class Parser(ArgumentParser): def handle(self, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.error(e.message) # No catching of exceptions def handle_raw(self, *args, **kwargs): func(*args, **kwargs) return Parser(*args, **kwargs) return decorator def virtualenv(path): "Wraps a function and prefixes the call with the virtualenv active." if path is None: activate = None else: activate = os.path.join(path, 'bin/activate') def decorator(func): @wraps(func) def inner(*args, **kwargs): if path is not None: with prefix('source {0}'.format(activate)): return func(*args, **kwargs) else: return func(*args, **kwargs) return inner return decorator
Return resulting object from decorated function if any
Return resulting object from decorated function if any
Python
bsd-2-clause
chop-dbhi/harvest,tjrivera/harvest
--- +++ @@ -46,8 +46,8 @@ def inner(*args, **kwargs): if path is not None: with prefix('source {0}'.format(activate)): - func(*args, **kwargs) + return func(*args, **kwargs) else: - func(*args, **kwargs) + return func(*args, **kwargs) return inner return decorator
28514ecf13ee124af6fee43e032cbbfe6a2a50e0
Lib/compiler/__init__.py
Lib/compiler/__init__.py
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from transformer import parse, parseFile from visitor import walk from pycodegen import compile, compileFile
"""Package for parsing and compiling Python source code There are several functions defined at the top level that are imported from modules contained in the package. parse(buf, mode="exec") -> AST Converts a string containing Python source code to an abstract syntax tree (AST). The AST is defined in compiler.ast. parseFile(path) -> AST The same as parse(open(path)) walk(ast, visitor, verbose=None) Does a pre-order walk over the ast using the visitor instance. See compiler.visitor for details. compile(source, filename, mode, flags=None, dont_inherit=None) Returns a code object. A replacement for the builtin compile() function. compileFile(filename) Generates a .pyc file by compiling filename. """ from .transformer import parse, parseFile from .visitor import walk from .pycodegen import compile, compileFile
Use relative imports in compiler package now that it is required. (Should this go into 2.5 or should we do compiler.XXX?)
Use relative imports in compiler package now that it is required. (Should this go into 2.5 or should we do compiler.XXX?)
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -21,6 +21,6 @@ Generates a .pyc file by compiling filename. """ -from transformer import parse, parseFile -from visitor import walk -from pycodegen import compile, compileFile +from .transformer import parse, parseFile +from .visitor import walk +from .pycodegen import compile, compileFile
5c3c0c60dc7047be8ad9f93d7e0b140ba243099e
iatidq/test_result.py
iatidq/test_result.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 FAIL = 0 PASS = 1 ERROR = 2
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3.0 FAIL = 0 PASS = 1 ERROR = 2 SKIP = 3
Add skipped result status; future compatibilty for non-run tests
Add skipped result status; future compatibilty for non-run tests
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
--- +++ @@ -10,3 +10,4 @@ FAIL = 0 PASS = 1 ERROR = 2 +SKIP = 3
27aad0e3ed95cb43b28eb3c02fa96b3a9b74de5b
tests/test_container.py
tests/test_container.py
# coding: utf8 from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
# coding: utf8 import os import sys import unittest from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.version_info >= (3, 0) and sys.version_info < (3, 6)) class TestContainers(TestCase): @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
Disable unicode filename test on Windows with Python 3.0 - 3.5
Disable unicode filename test on Windows with Python 3.0 - 3.5 Before PEP 529 landed in Python 3.6, unicode filename handling on Windows is hit-and-miss, so don't break CI.
Python
bsd-3-clause
PyAV-Org/PyAV,mikeboers/PyAV,PyAV-Org/PyAV,mikeboers/PyAV
--- +++ @@ -1,10 +1,25 @@ # coding: utf8 +import os +import sys +import unittest + from .common import * + +# On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. +# Starting with Python 3.6 the situation is saner thanks to PEP 529: +# +# https://www.python.org/dev/peps/pep-0529/ + +broken_unicode = ( + os.name == 'nt' and + sys.version_info >= (3, 0) and + sys.version_info < (3, 6)) class TestContainers(TestCase): + @unittest.skipIf(broken_unicode, 'Unicode filename handling is broken') def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
6b83217f422b46ef9cc4ef5aa124350eee825fe1
satchless/contrib/tax/flatgroups/models.py
satchless/contrib/tax/flatgroups/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the tax.")) rate_name = models.CharField(_("name of the rate"), max_length=30, help_text=_("Name of the rate which will be" " displayed to the user.")) def __unicode__(self): return self.name class TaxedProductMixin(models.Model): tax_group = models.ForeignKey(TaxGroup, related_name='products', null=True)
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the tax.")) rate_name = models.CharField(_("name of the rate"), max_length=30, help_text=_("Name of the rate which will be" " displayed to the user.")) def __unicode__(self): return self.name class TaxedProductMixin(models.Model): tax_group = models.ForeignKey(TaxGroup, related_name='products', null=True) class Meta: abstract = True
Fix - TaxedProductMixin is abstract model
Fix - TaxedProductMixin is abstract model
Python
bsd-3-clause
taedori81/satchless
--- +++ @@ -17,3 +17,5 @@ tax_group = models.ForeignKey(TaxGroup, related_name='products', null=True) + class Meta: + abstract = True
c7a002c3c0f86db931fdc0a3240ff38ffab03ff8
glanerbeard/web.py
glanerbeard/web.py
import logging from flask import ( Flask, render_template, abort ) from glanerbeard.server import Server app = Flask(__name__) app.config.from_pyfile('../settings.py') servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS']) @app.route('/') def index(): shows = [server.getShows() for server in servers] return str(shows) if __name__ == '__main__': app.debug = True app.run()
import logging from flask import ( Flask, render_template, abort ) from glanerbeard.server import Server app = Flask(__name__) app.config.from_object('glanerbeard.default_settings') app.config.from_envvar('GLANERBEARD_SETTINGS') servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS']) @app.route('/') def index(): shows = [server.getShows() for server in servers] return str(shows) if __name__ == '__main__': app.debug = True app.run()
Use the new settings loading method.
Use the new settings loading method.
Python
apache-2.0
daenney/glanerbeard
--- +++ @@ -9,7 +9,9 @@ from glanerbeard.server import Server app = Flask(__name__) -app.config.from_pyfile('../settings.py') +app.config.from_object('glanerbeard.default_settings') +app.config.from_envvar('GLANERBEARD_SETTINGS') + servers = Server.createFromConfig(app.config['SERVERS'], app.config['API_KEYS'])
0bc7ad27ec36832f7309af476efdabd25a677328
grako/rendering.py
grako/rendering.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): if template is None: template = self.template fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) if template is None: template = self.template fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Allow render_fields to override the default template.
Allow render_fields to override the default template.
Python
bsd-2-clause
vmuriart/grako,frnknglrt/grako
--- +++ @@ -31,10 +31,10 @@ pass def render(self, template=None, **fields): + fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) + self.render_fields(fields) if template is None: template = self.template - fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) - self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields)
08b998d63808b99cf96635bd50b7d33238cda633
Recorders.py
Recorders.py
from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) file_path = self.container + measure.device_id.split('/')[-1] + self.extension f = open(file_path, 'w+') f.writelines([log_entry])
import os from Measurement import Measurement class Recorder(object): def __init__(self, recorderType): self.recorderType = recorderType def record(self, measure: Measurement): None class PrintRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] def record(self, measure: Measurement): line = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) print(line, end='\n') class FileRecorder(Recorder): def __init__(self, config): Recorder.__init__(self, 'file') self.format = config['format'] self.container = config['container'] self.extension = config['extension'] def record(self, measure: Measurement): log_entry = self.format.format( device_id=measure.device_id, celsius=measure.get_celsius(), fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) directory = self.container + measure.device_id.split('/')[-1] file_path = directory + self.extension if not os.path.exists(directory): os.makedirs(directory) f = open(file_path, 'w+') f.writelines([log_entry])
Create folder if not exist
Create folder if not exist
Python
mit
hectortosa/py-temperature-recorder
--- +++ @@ -1,3 +1,4 @@ +import os from Measurement import Measurement class Recorder(object): @@ -37,7 +38,11 @@ fahrenheit=measure.get_fahrenheit(), timestamp=measure.timestamp) - file_path = self.container + measure.device_id.split('/')[-1] + self.extension + directory = self.container + measure.device_id.split('/')[-1] + file_path = directory + self.extension + + if not os.path.exists(directory): + os.makedirs(directory) f = open(file_path, 'w+') f.writelines([log_entry])
156093f3b4872d68663897b8525f4706ec5a555c
pyfr/template.py
pyfr/template.py
# -*- coding: utf-8 -*- import os import pkgutil from mako.lookup import TemplateLookup from mako.template import Template class DottedTemplateLookup(TemplateLookup): def __init__(self, pkg): self.dfltpkg = pkg def adjust_uri(self, uri, relto): return uri def get_template(self, name): div = name.rfind('.') # Break apart name into a package and base file name if div >= 0: pkg = name[:div] basename = name[div + 1:] else: pkg = self.dfltpkg basename = name # Attempt to load the template try: tpl = pkgutil.get_data(pkg, basename + '.mako') return Template(tpl, lookup=self) except IOError: raise RuntimeError('Template "{}" not found'.format(name))
# -*- coding: utf-8 -*- import os import pkgutil from mako.lookup import TemplateLookup from mako.template import Template class DottedTemplateLookup(TemplateLookup): def __init__(self, pkg): self.dfltpkg = pkg def adjust_uri(self, uri, relto): return uri def get_template(self, name): div = name.rfind('.') # Break apart name into a package and base file name if div >= 0: pkg = name[:div] basename = name[div + 1:] else: pkg = self.dfltpkg basename = name # Attempt to load the template src = pkgutil.get_data(pkg, basename + '.mako') if not src: raise RuntimeError('Template "{}" not found'.format(name)) return Template(src, lookup=self)
Enhance the dotted name lookup functionality.
Enhance the dotted name lookup functionality.
Python
bsd-3-clause
tjcorona/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,iyer-arvind/PyFR,Aerojspark/PyFR
--- +++ @@ -26,8 +26,8 @@ basename = name # Attempt to load the template - try: - tpl = pkgutil.get_data(pkg, basename + '.mako') - return Template(tpl, lookup=self) - except IOError: + src = pkgutil.get_data(pkg, basename + '.mako') + if not src: raise RuntimeError('Template "{}" not found'.format(name)) + + return Template(src, lookup=self)
1a74d34d358940175c9e5ac50a11ac3f0f40729b
app/sense.py
app/sense.py
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() direction = self.robot.direction() self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color
import threading import time class SensorThread(object): def __init__(self, notify, delay=0): self.notify = notify self.delay = delay self.interval = 0.2 self.color = -1 def start(self, control, robot): self.control = control self.robot = robot thread = threading.Thread(target=self.run, args=()) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self): while True: color = int(self.robot.color()) touch = self.robot.touch() try: direction = self.robot.direction() except: direction = 0 self.control.readings(color, touch, direction) time.sleep(self.interval) def sensors(self, color, touch, direction): #print "sense: %s %s" % (touch, direction) if not self.color == color: self.notify.emit('sense', color) self.color = color print "color %s%%" % color
Work without the Gyro sensor for retail set compatibility.
Work without the Gyro sensor for retail set compatibility.
Python
bsd-2-clause
legorovers/legoflask,legorovers/legoflask,legorovers/legoflask
--- +++ @@ -20,7 +20,10 @@ while True: color = int(self.robot.color()) touch = self.robot.touch() - direction = self.robot.direction() + try: + direction = self.robot.direction() + except: + direction = 0 self.control.readings(color, touch, direction) time.sleep(self.interval)
b3cbd97738c03975f89cc0264cfd47ea44b9728e
annoycode.py
annoycode.py
# == Requires python 3.4! == # Changes Unicode symbols with other symbols that looks the same. from data import Data if __name__ == "__main__": data = Data() if not data.load() or not data.hasMatches(): print("Use trainer.py to generate data for use.") exit(-1) string = "A B C ! -" (newString, subs) = data.subMatches(string) print("Input: ", string) print(" ", string.encode("utf-8")) print("Output: ", newString) print(" ", newString.encode("utf-8")) print("{} substitutions".format(subs))
# == Requires python 3.4! == # Changes Unicode symbols with other symbols that looks the same. from data import Data if __name__ == "__main__": data = Data() if not data.load() or not data.hasMatches(): print("Use trainer.py to generate data for use.") exit(-1) string = "ABC!-" stringEnc = string.encode("utf-8") (newString, subs) = data.subMatches(string) newStringEnc = newString.encode("utf-8") inCnt = len(stringEnc) outCnt = len(newStringEnc) incPerc = float(outCnt) / float(inCnt) * 100 print("Input: ", string) print(" ", stringEnc) print("Output: ", newString) print(" ", newStringEnc) print("{} substitutions".format(subs)) print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
Print stats on in/out byte count and increase in percent.
ac: Print stats on in/out byte count and increase in percent.
Python
mit
netromdk/annoycode
--- +++ @@ -8,11 +8,18 @@ print("Use trainer.py to generate data for use.") exit(-1) - string = "A B C ! -" + string = "ABC!-" + stringEnc = string.encode("utf-8") (newString, subs) = data.subMatches(string) + newStringEnc = newString.encode("utf-8") + + inCnt = len(stringEnc) + outCnt = len(newStringEnc) + incPerc = float(outCnt) / float(inCnt) * 100 print("Input: ", string) - print(" ", string.encode("utf-8")) + print(" ", stringEnc) print("Output: ", newString) - print(" ", newString.encode("utf-8")) + print(" ", newStringEnc) print("{} substitutions".format(subs)) + print("{} -> {} bytes, +{}%".format(inCnt, outCnt, incPerc))
b529bc715ff133147576aa9026fd281226b7f3b7
app/views.py
app/views.py
from app import app from app.models import Post from flask import render_template @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by_latest() if posts: pagination = posts.paginate(page=page, per_page=Post.PER_PAGE) return render_template('frontend/blog.html', pagination=pagination) @app.route('/archive') def archive(): """View an overview of all visible posts.""" posts = Post.query.filter_by_latest() return render_template('frontend/archive.html', posts=posts) @app.route('/<path:slug>', methods=['GET', 'POST']) def detail(slug): """View details of post with specified slug.""" post = Post.query.slug_or_404(slug) return render_template('frontend/detail.html', post=post)
from app import app from app.models import Post from flask import render_template @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by(visible=True) \ .order_by(Post.published.desc()) if posts: pagination = posts.paginate(page=page, per_page=Post.PER_PAGE) return render_template('blog.html', pagination=pagination) @app.route('/archive') def archive(): """View an overview of all visible posts.""" posts = Post.query.filter_by(visible=True) \ .order_by(Post.published.desc()) return render_template('archive.html', posts=posts) @app.route('/<path:slug>', methods=['GET', 'POST']) def detail(slug): """View details of post with specified slug.""" post = Post.query.filter_by(visible=True, slug=slug) \ .first_or_404() return render_template('detail.html', post=post)
Fix queries and path to templates
Fix queries and path to templates
Python
mit
thebitstick/Flask-Blog,thebitstick/Flask-Blog
--- +++ @@ -7,21 +7,24 @@ @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" - posts = Post.query.filter_by_latest() + posts = Post.query.filter_by(visible=True) \ + .order_by(Post.published.desc()) if posts: pagination = posts.paginate(page=page, per_page=Post.PER_PAGE) - return render_template('frontend/blog.html', pagination=pagination) + return render_template('blog.html', pagination=pagination) @app.route('/archive') def archive(): """View an overview of all visible posts.""" - posts = Post.query.filter_by_latest() - return render_template('frontend/archive.html', posts=posts) + posts = Post.query.filter_by(visible=True) \ + .order_by(Post.published.desc()) + return render_template('archive.html', posts=posts) @app.route('/<path:slug>', methods=['GET', 'POST']) def detail(slug): """View details of post with specified slug.""" - post = Post.query.slug_or_404(slug) - return render_template('frontend/detail.html', post=post) + post = Post.query.filter_by(visible=True, slug=slug) \ + .first_or_404() + return render_template('detail.html', post=post)
009a9f401fd0c1dba6702c1114a73b77f38b9ce3
bin/parse.py
bin/parse.py
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {} area = line[INDEX["CITY"]: INDEX["AREA"]] if not area in result[city]: result[city][area] = {} line = line[line.find(" "):].strip() road = line[:line.find(" ")] condition = line[line.find(" "):].replace(" ", "").strip() json.dump(result, open("zipcode.json", "w"), ensure_ascii=False, indent=4 ) sys.exit(0)
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {} area_index = INDEX["AREA"] if line[INDEX["AREA"]] != " ": area_index += 3 area = line[INDEX["CITY"]: area_index].strip() if not area in result[city]: result[city][area] = {} line = line[area_index:].strip() road = line.split(" ")[0] if len(line.split(" ")) == 1: road = line[:-3] if not road in result[city][area]: result[city][area][road] = {} condition = line[line.find(" "):].replace(" ", "").strip() json.dump(result, open("zipcode.json", "w"), ensure_ascii=False, indent=4 ) sys.exit(0)
Fix name parsing for roads
Fix name parsing for roads
Python
mit
lihengl/dizu-api,lihengl/dizu-api
--- +++ @@ -18,12 +18,17 @@ city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {} - area = line[INDEX["CITY"]: INDEX["AREA"]] + area_index = INDEX["AREA"] + if line[INDEX["AREA"]] != " ": area_index += 3 + area = line[INDEX["CITY"]: area_index].strip() if not area in result[city]: result[city][area] = {} - line = line[line.find(" "):].strip() + line = line[area_index:].strip() - road = line[:line.find(" ")] + road = line.split(" ")[0] + if len(line.split(" ")) == 1: road = line[:-3] + if not road in result[city][area]: result[city][area][road] = {} + condition = line[line.find(" "):].replace(" ", "").strip()
dfa3a3c120b2555706c37da19496557a55f743db
reports/views.py
reports/views.py
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import render from django.core.paginator import Paginator from .forms import ReportForm from .models import Report def can_add_reports(user): return user.is_authenticated() and user.has_perm('reports.add_report') @user_passes_test(can_add_reports) def add_report(request): data = request.POST if request else None form = ReportForm(data) if form.is_valid(): form.save() return render(request, 'reports/report.html', locals()) def listing(request, page): reports_list = Report.objects.all() paginator = Paginator(reports_list, 30) reports = paginator.page(page) return render(request, 'reports/listing.html', {"reports": reports})
from django.contrib.auth.decorators import permission_required from django.core.paginator import Paginator from django.shortcuts import render from .forms import ReportForm, CopyFormSet from .models import Report @permission_required('reports.add_report', login_url='members:login') def add_report(request): data = request.POST if request else None report_form = ReportForm(data) formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report())) if report_form.is_valid(): report = report_form.save() request.session['report_in_creation'] = formset.instance = report if formset.is_valid(): formset.save() del request.session['report_in_creation'] return render(request, 'reports/add.html', locals()) def listing(request, page): reports_list = Report.objects.all() paginator = Paginator(reports_list, 30) reports = paginator.page(page) return render(request, 'reports/listing.html', {"reports": reports})
Add add report with copies functionality and permission
Add add report with copies functionality and permission
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -1,23 +1,25 @@ -from django.contrib.auth.decorators import user_passes_test +from django.contrib.auth.decorators import permission_required +from django.core.paginator import Paginator from django.shortcuts import render -from django.core.paginator import Paginator -from .forms import ReportForm +from .forms import ReportForm, CopyFormSet from .models import Report -def can_add_reports(user): - return user.is_authenticated() and user.has_perm('reports.add_report') - - -@user_passes_test(can_add_reports) +@permission_required('reports.add_report', login_url='members:login') def add_report(request): data = request.POST if request else None - form = ReportForm(data) + report_form = ReportForm(data) + formset = CopyFormSet(data, instance=request.session.get('report_in_creation', Report())) - if form.is_valid(): - form.save() - return render(request, 'reports/report.html', locals()) + if report_form.is_valid(): + report = report_form.save() + request.session['report_in_creation'] = formset.instance = report + if formset.is_valid(): + formset.save() + del request.session['report_in_creation'] + + return render(request, 'reports/add.html', locals()) def listing(request, page):
2e5bcbea0b6adbc947e62c31726734c081500d14
scripts/generate_dump_for_offline_apps_off.py
scripts/generate_dump_for_offline_apps_off.py
#!/usr/bin/python from __future__ import absolute_import, division, print_function import csv from itertools import imap from operator import itemgetter def main(): import pandas df = pandas.read_csv('/srv/off/html/data/en.openfoodfacts.org.products.csv', sep='\t', low_memory=False) colnames = ['code','product_name','quantity','brands','nutrition_grade_fr','nova_group'] df.to_csv('/srv/off/html/data/offline/en.openfoodfacts.org.products.small.csv', columns = colnames,sep='\t',index=False) if __name__ == '__main__': main()
#!/usr/bin/python from __future__ import absolute_import, division, print_function import csv from itertools import imap from operator import itemgetter def main(): import pandas df = pandas.read_csv('/srv/off/html/data/en.openfoodfacts.org.products.csv', sep='\t', low_memory=False) colnames = ['code','product_name','quantity','brands','nutrition_grade_fr','nova_group','ecoscore_grade'] df.to_csv('/srv/off/html/data/offline/en.openfoodfacts.org.products.small.csv', columns = colnames,sep='\t',index=False) if __name__ == '__main__': main()
Add support for the Eco-Score for Offline-Scan
Add support for the Eco-Score for Offline-Scan Add support for the Eco-Score for Offline-Scan
Python
agpl-3.0
openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server,openfoodfacts/openfoodfacts-server
--- +++ @@ -8,7 +8,7 @@ def main(): import pandas df = pandas.read_csv('/srv/off/html/data/en.openfoodfacts.org.products.csv', sep='\t', low_memory=False) - colnames = ['code','product_name','quantity','brands','nutrition_grade_fr','nova_group'] + colnames = ['code','product_name','quantity','brands','nutrition_grade_fr','nova_group','ecoscore_grade'] df.to_csv('/srv/off/html/data/offline/en.openfoodfacts.org.products.small.csv', columns = colnames,sep='\t',index=False) if __name__ == '__main__':
9530f7a65b5381fbb178dab120454dfc40a8d604
djangopypi2/apps/pypi_users/views.py
djangopypi2/apps/pypi_users/views.py
from django.contrib.auth import logout as auth_logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.generic.detail import SingleObjectMixin from django.views.generic.list import MultipleObjectMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect class SingleUserMixin(SingleObjectMixin): model = User slug_field = 'username' slug_url_kwarg = 'username' context_object_name = 'user' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) class MultipleUsersMixin(MultipleObjectMixin): model = User slug_field = 'username' slug_url_kwarg = 'username' context_object_name = 'users' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(Index, self).dispatch(*args, **kwargs) class Index(MultipleUsersMixin, ListView): template_name = 'pypi_users/index.html' class UserDetails(SingleUserMixin, DetailView): template_name = 'pypi_users/user_profile.html' @login_required def logout(request): auth_logout(request) return HttpResponseRedirect('/')
from django.contrib.auth import logout as auth_logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.generic.detail import SingleObjectMixin from django.views.generic.list import MultipleObjectMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect class SingleUserMixin(SingleObjectMixin): model = User slug_field = 'username' slug_url_kwarg = 'username' context_object_name = 'user' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(SingleUserMixin, self).dispatch(*args, **kwargs) class MultipleUsersMixin(MultipleObjectMixin): model = User slug_field = 'username' slug_url_kwarg = 'username' context_object_name = 'users' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(MultipleUsersMixin, self).dispatch(*args, **kwargs) class Index(MultipleUsersMixin, ListView): template_name = 'pypi_users/index.html' class UserDetails(SingleUserMixin, DetailView): template_name = 'pypi_users/user_profile.html' @login_required def logout(request): auth_logout(request) return HttpResponseRedirect('/')
Fix bad super calls causing infinite recursion
Fix bad super calls causing infinite recursion
Python
bsd-3-clause
popen2/djangopypi2,popen2/djangopypi2,pitrho/djangopypi2,hsmade/djangopypi2,pitrho/djangopypi2,hsmade/djangopypi2
--- +++ @@ -17,7 +17,7 @@ @method_decorator(login_required) def dispatch(self, *args, **kwargs): - return super(Index, self).dispatch(*args, **kwargs) + return super(SingleUserMixin, self).dispatch(*args, **kwargs) class MultipleUsersMixin(MultipleObjectMixin): model = User @@ -27,7 +27,7 @@ @method_decorator(login_required) def dispatch(self, *args, **kwargs): - return super(Index, self).dispatch(*args, **kwargs) + return super(MultipleUsersMixin, self).dispatch(*args, **kwargs) class Index(MultipleUsersMixin, ListView): template_name = 'pypi_users/index.html'
dca70886d2535dd843ea995b8d193958997de41b
slack_sdk/oauth/state_store/state_store.py
slack_sdk/oauth/state_store/state_store.py
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
from logging import Logger class OAuthStateStore: @property def logger(self) -> Logger: raise NotImplementedError() def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool: raise NotImplementedError()
Enable additional data on state creation
Enable additional data on state creation This should allow for the creation of custom states where the additional data can be used to associate external accounts.
Python
mit
slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
--- +++ @@ -6,7 +6,7 @@ def logger(self) -> Logger: raise NotImplementedError() - def issue(self) -> str: + def issue(self, *args, **kwargs) -> str: raise NotImplementedError() def consume(self, state: str) -> bool:
f0017fc656bc3ee0cfbe1bafe73efe9abc27bc32
mqueue/apps.py
mqueue/apps.py
import importlib from typing import List, Tuple, Union from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" verbose_name = _(u"Events queue") def ready(self): # models registration from settings from django.conf import settings from .tracking import mqueue_tracker registered_models: Union[ Tuple[str, List[str]], List[Union[str, List[str]]] ] = getattr(settings, "MQUEUE_AUTOREGISTER", []) for modtup in registered_models: modpath = modtup[0] level = modtup[1] modsplit = modpath.split(".") path = ".".join(modsplit[:-1]) modname = ".".join(modsplit[-1:]) try: module = importlib.import_module(path) model = getattr(module, modname) mqueue_tracker.register(model, level) # type: ignore except ImportError as e: msg = "ERROR from Django Mqueue : can not import model " msg += modpath print(msg) raise (e) # watchers from .watchers import init_watchers from .conf import WATCH init_watchers(WATCH)
import importlib from typing import List, Tuple, Union from django.utils.translation import gettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" default_auto_field = "django.db.models.BigAutoField" verbose_name = _("Events queue") def ready(self): # models registration from settings from django.conf import settings from .tracking import mqueue_tracker registered_models: Union[ Tuple[str, List[str]], List[Union[str, List[str]]] ] = getattr(settings, "MQUEUE_AUTOREGISTER", []) for modtup in registered_models: modpath = modtup[0] level = modtup[1] modsplit = modpath.split(".") path = ".".join(modsplit[:-1]) modname = ".".join(modsplit[-1:]) try: module = importlib.import_module(path) model = getattr(module, modname) mqueue_tracker.register(model, level) # type: ignore except ImportError as e: msg = "ERROR from Django Mqueue : can not import model " msg += modpath print(msg) raise (e) # watchers from .watchers import init_watchers from .conf import WATCH init_watchers(WATCH)
Add bigautofield default in app conf
Add bigautofield default in app conf
Python
mit
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
--- +++ @@ -1,12 +1,13 @@ import importlib from typing import List, Tuple, Union -from django.utils.translation import ugettext_lazy as _ +from django.utils.translation import gettext_lazy as _ from django.apps import AppConfig class MqueueConfig(AppConfig): name = "mqueue" - verbose_name = _(u"Events queue") + default_auto_field = "django.db.models.BigAutoField" + verbose_name = _("Events queue") def ready(self): # models registration from settings
0d7a92f3f1bd405a33d4124bc6a3fb8fbfbba06c
telepathy/templatetags/custommardown.py
telepathy/templatetags/custommardown.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import markdown from django import template from django.template.defaultfilters import stringfilter from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True, name='markdown') @stringfilter def my_markdown(value): extensions = ["nl2br", "extra", "codehilite", "headerid(level=2)", "sane_lists"] return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=True, enable_attributes=False))
# -*- coding: utf-8 -*- from __future__ import unicode_literals import markdown from django import template from django.template.defaultfilters import stringfilter from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=False, name='markdown') @stringfilter def my_markdown(value): extensions = ["nl2br", "extra", "codehilite", "headerid(level=2)", "sane_lists"] return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=False, enable_attributes=False))
Make markdown unsafe and let django make it safe after
Make markdown unsafe and let django make it safe after
Python
agpl-3.0
UrLab/DocHub,UrLab/DocHub,UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub,UrLab/beta402
--- +++ @@ -12,12 +12,12 @@ register = template.Library() -@register.filter(is_safe=True, name='markdown') +@register.filter(is_safe=False, name='markdown') @stringfilter def my_markdown(value): extensions = ["nl2br", "extra", "codehilite", "headerid(level=2)", "sane_lists"] return mark_safe(markdown.markdown(force_unicode(value), extensions, - safe_mode=True, + safe_mode=False, enable_attributes=False))
1813413b33170f87cc9fb721c7b5a8cdecfab722
ckanext/googleanalytics/tests/conftest.py
ckanext/googleanalytics/tests/conftest.py
import pytest import factory from factory.alchemy import SQLAlchemyModelFactory from pytest_factoryboy import register import ckan.model as model from ckanext.googleanalytics.model import PackageStats, ResourceStats @pytest.fixture() def clean_db(reset_db, migrate_db_for): reset_db() migrate_db_for("googleanalytics") @register class PackageStatsFactory(SQLAlchemyModelFactory): class Meta: sqlalchemy_session = model.Session model = PackageStats package_id = factory.Faker("uuid4") visits_recently = factory.Faker("pyint") visits_ever = factory.Faker("pyint") @register class ResourceStatsFactory(SQLAlchemyModelFactory): class Meta: sqlalchemy_session = model.Session model = ResourceStats resource_id = factory.Faker("uuid4") visits_recently = factory.Faker("pyint") visits_ever = factory.Faker("pyint")
import pytest import factory from factory.alchemy import SQLAlchemyModelFactory from pytest_factoryboy import register from ckan.plugins import toolkit import ckan.model as model from ckanext.googleanalytics.model import PackageStats, ResourceStats if toolkit.requires_ckan_version("2.9"): @pytest.fixture() def clean_db(reset_db, migrate_db_for): reset_db() migrate_db_for("googleanalytics") else: from dbutil import init_tables @pytest.fixture() def clean_db(reset_db): reset_db() init_tables() @register class PackageStatsFactory(SQLAlchemyModelFactory): class Meta: sqlalchemy_session = model.Session model = PackageStats package_id = factory.Faker("uuid4") visits_recently = factory.Faker("pyint") visits_ever = factory.Faker("pyint") @register class ResourceStatsFactory(SQLAlchemyModelFactory): class Meta: sqlalchemy_session = model.Session model = ResourceStats resource_id = factory.Faker("uuid4") visits_recently = factory.Faker("pyint") visits_ever = factory.Faker("pyint")
Fix fixture for older versions
Fix fixture for older versions
Python
agpl-3.0
ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics,ckan/ckanext-googleanalytics
--- +++ @@ -3,16 +3,25 @@ from factory.alchemy import SQLAlchemyModelFactory from pytest_factoryboy import register +from ckan.plugins import toolkit import ckan.model as model from ckanext.googleanalytics.model import PackageStats, ResourceStats -@pytest.fixture() -def clean_db(reset_db, migrate_db_for): - reset_db() - migrate_db_for("googleanalytics") +if toolkit.requires_ckan_version("2.9"): + @pytest.fixture() + def clean_db(reset_db, migrate_db_for): + reset_db() + migrate_db_for("googleanalytics") +else: + from dbutil import init_tables + @pytest.fixture() + def clean_db(reset_db): + reset_db() + init_tables() + @register
cca432708ec6220c8d3b7f23ff8c7c5f29d6737a
app/tools/application.py
app/tools/application.py
# -*- coding:utf-8 -*- import os,time,asyncio,json import logging logging.basicConfig(level=logging.ERROR) try: from aiohttp import web except ImportError: logging.error("Can't import module aiohttp") from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from tools.config import Config from tools.database import create_pool logging.basicConfig(level=logging.INFO) class Application(web.Application): def __init__(self): self._loop=asyncio.get_event_loop() super(Application,self).__init__(loop=self._loop,middlewares=Middleware.allmiddlewares()) def run(self,addr='127.0.0.1',port='8000'): self._loop.run_until_complete(self.get_server(addr,port)) self._loop.run_forever() @asyncio.coroutine def get_server(self,addr,port): Template.init(self) Route.register_route(self) pool=yield from create_pool(self._loop) srv=yield from self._loop.create_server(self.make_handler(),addr,port) logging.info("server start at http://%s:%s"%(addr,port)) Log.info("server start at http://%s:%s"%(addr,port)) print("server start at http://%s:%s"%(addr,port)) return srv
# -*- coding:utf-8 -*- import os,time,asyncio,json import logging logging.basicConfig(level=logging.ERROR) try: from aiohttp import web except ImportError: logging.error("Can't import module aiohttp") from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from tools.config import Config from tools.database import create_pool,DB logging.basicConfig(level=logging.INFO) class Application(web.Application): def __init__(self): self._loop=asyncio.get_event_loop() super(Application,self).__init__(loop=self._loop,middlewares=Middleware.allmiddlewares()) def run(self,addr='127.0.0.1',port='8000'): self._loop.run_until_complete(self.get_server(addr,port)) self._loop.run_forever() @asyncio.coroutine def get_server(self,addr,port): Template.init(self) Route.register_route(self) yield from DB.createpool(self._loop) #pool=yield from create_pool(self._loop) srv=yield from self._loop.create_server(self.make_handler(),addr,port) logging.info("server start at http://%s:%s"%(addr,port)) Log.info("server start at http://%s:%s"%(addr,port)) print("server start at http://%s:%s"%(addr,port)) return srv
Change the way of creating database's connection pool
Change the way of creating database's connection pool
Python
mit
free-free/pyblog,free-free/pyblog,free-free/pyblog,free-free/pyblog
--- +++ @@ -10,7 +10,7 @@ from tools.httptools import Middleware,Route from tools.template import Template from tools.config import Config -from tools.database import create_pool +from tools.database import create_pool,DB logging.basicConfig(level=logging.INFO) class Application(web.Application): def __init__(self): @@ -23,7 +23,8 @@ def get_server(self,addr,port): Template.init(self) Route.register_route(self) - pool=yield from create_pool(self._loop) + yield from DB.createpool(self._loop) + #pool=yield from create_pool(self._loop) srv=yield from self._loop.create_server(self.make_handler(),addr,port) logging.info("server start at http://%s:%s"%(addr,port)) Log.info("server start at http://%s:%s"%(addr,port))
23bf1380d20e0782025ba997f3d33be6d873ae04
piwik/indico_piwik/views.py
piwik/indico_piwik/views.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from indico.core.plugins import WPJinjaMixinPlugin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPStatistics(WPJinjaMixinPlugin, WPConferenceModifBase): active_menu_item = 'statistics'
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from indico.core.plugins import WPJinjaMixinPlugin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPStatistics(WPJinjaMixinPlugin, WPConferenceModifBase): sidemenu_option = 'statistics'
Mark sidemenu entry as active
Piwik: Mark sidemenu entry as active
Python
mit
ThiefMaster/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins
--- +++ @@ -19,4 +19,4 @@ class WPStatistics(WPJinjaMixinPlugin, WPConferenceModifBase): - active_menu_item = 'statistics' + sidemenu_option = 'statistics'
c3ee23290183f240f52942a121ae048108e7853e
demo/urls.py
demo/urls.py
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailsearch.urls import frontend as wagtailsearch_frontend_urls from wagtail.wagtailsearch.signal_handlers import register_signal_handlers as wagtailsearch_register_signal_handlers import os wagtailsearch_register_signal_handlers() urlpatterns = patterns('', # url(r'^blog/', include('blog.urls', namespace="blog")), url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), # url(r'^comments/', include('django_comments_xtd.urls')), url(r'', include(wagtail_urls)), url(r'^docs/', include(wagtaildocs_urls)), ) if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) urlpatterns += patterns('', (r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) )
from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailsearch.urls import frontend as wagtailsearch_frontend_urls from wagtail.wagtailsearch.signal_handlers import register_signal_handlers as wagtailsearch_register_signal_handlers import os wagtailsearch_register_signal_handlers() urlpatterns = [ # url(r'^blog/', include('blog.urls', namespace="blog")), url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), # url(r'^comments/', include('django_comments_xtd.urls')), url(r'', include(wagtail_urls)), url(r'^docs/', include(wagtaildocs_urls)), ] if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) urlpatterns += [ url(r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) ]
Fix demo URLs for Dajngo 1.10
Fix demo URLs for Dajngo 1.10
Python
mit
apihackers/wapps,apihackers/wapps,apihackers/wapps,apihackers/wapps
--- +++ @@ -1,4 +1,4 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin @@ -13,19 +13,19 @@ wagtailsearch_register_signal_handlers() -urlpatterns = patterns('', +urlpatterns = [ # url(r'^blog/', include('blog.urls', namespace="blog")), url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), # url(r'^comments/', include('django_comments_xtd.urls')), url(r'', include(wagtail_urls)), url(r'^docs/', include(wagtaildocs_urls)), -) +] if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) - urlpatterns += patterns('', - (r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) - ) + urlpatterns += [ + url(r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) + ]
f8746cc68deb32d2c01201d8014c7e423e891c30
django_mysqlpool/__init__.py
django_mysqlpool/__init__.py
# -*- coding: utf-8 -*- """The top-level package for ``django-mysqlpool``.""" # These imports make 2 act like 3, making it easier on us to switch to PyPy or # some other VM if we need to for performance reasons. from __future__ import (absolute_import, print_function, unicode_literals, division) # Make ``Foo()`` work the same in Python 2 as it does in Python 3. __metaclass__ = type from functools import wraps __version__ = "0.2.0" def auto_close_db(f): """Ensure the database connection is closed when the function returns.""" from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
# -*- coding: utf-8 -*- """The top-level package for ``django-mysqlpool``.""" # These imports make 2 act like 3, making it easier on us to switch to PyPy or # some other VM if we need to for performance reasons. from __future__ import (absolute_import, print_function, unicode_literals, division) # Make ``Foo()`` work the same in Python 2 as it does in Python 3. __metaclass__ = type from functools import wraps __version__ = "0.2.1" def auto_close_db(f): """Ensure the database connection is closed when the function returns.""" from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
Cut a new release to incorporate the HashableDict fix.
Cut a new release to incorporate the HashableDict fix.
Python
mit
smartfile/django-mysqlpool
--- +++ @@ -12,7 +12,7 @@ from functools import wraps -__version__ = "0.2.0" +__version__ = "0.2.1" def auto_close_db(f):
bc9012c887065e503a5ac231df8ed4e47a2175ad
apps/challenges/forms.py
apps/challenges/forms.py
from django import forms from tower import ugettext_lazy as _ from challenges.models import Submission class EntryForm(forms.ModelForm): class Meta: model = Submission fields = ( 'title', 'brief_description', 'description', 'created_by' )
from django import forms from challenges.models import Submission class EntryForm(forms.ModelForm): class Meta: model = Submission fields = ( 'title', 'brief_description', 'description', 'created_by' )
Clear up an unused import.
Clear up an unused import.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
--- +++ @@ -1,6 +1,4 @@ from django import forms - -from tower import ugettext_lazy as _ from challenges.models import Submission
e228042b7b59ab1b2be6e772dabbf595befc2cf6
kombulogger/server.py
kombulogger/server.py
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = '{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default_broker_url queue = queue or default_queue_name self.connection = kombu.Connection(url) self.queue = self.connection.SimpleQueue(queue, no_ack=True) path = os.path.join(os.getcwd(), queue) if not path.endswith('.log'): path += '.log' self.output_file = codecs.open(path, mode='ab', encoding='UTF-8') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.queue.close() self.connection.close() self.output_file.close() return False def _format_dict(self, log_dict): return self.log_format.format(**log_dict) def run(self): while True: try: message = self.queue.get(block=True, timeout=1) payload = message.payload print(self._format_dict(payload), file=self.output_file) message.ack() except self.queue.Empty: pass
# -*- coding: utf-8 -*- from __future__ import print_function import os import codecs import kombu from kombulogger import default_broker_url, default_queue_name class KombuLogServer(object): log_format = u'{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default_broker_url queue = queue or default_queue_name self.connection = kombu.Connection(url) self.queue = self.connection.SimpleQueue(queue, no_ack=True) path = os.path.join(os.getcwd(), queue) if not path.endswith('.log'): path += '.log' self.output_file = codecs.open(path, mode='ab', encoding='UTF-8') def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.queue.close() self.connection.close() self.output_file.close() return False def _format_dict(self, log_dict): return self.log_format.format(**log_dict) def run(self): while True: try: message = self.queue.get(block=True, timeout=1) payload = message.payload print(self._format_dict(payload), file=self.output_file) message.ack() except self.queue.Empty: pass
Fix unicode error on py2
Fix unicode error on py2
Python
mit
tuomur/kombulogger
--- +++ @@ -12,7 +12,7 @@ class KombuLogServer(object): - log_format = '{host}\t{level}\t{message}' + log_format = u'{host}\t{level}\t{message}' def __init__(self, url=None, queue=None): url = url or default_broker_url
a8e87b389c8b61e986ffb3c9c25af71c09796b52
collector.py
collector.py
import yaml import newspaper from newspaper import news_pool def get_config(): with open('/options/config.yml') as file: config = yaml.safe_load(file) keys = config.keys() if not 'threads' in keys: config['threads'] = 2 if not 'source' in keys: raise Exception('"source" not defined in config.yml') if not 'words' in keys: raise Exception('"words" not defined in config.yml') return config def main(): config = get_config() target_words_set = set([i.lower() for i in config['words']]) paper = newspaper.build(config['source']) news_pool.set([paper], threads_per_source=config['threads']) news_pool.join() for a in paper.articles: a.parse() a.nlp() if target_words_set < set(a.keywords): print(a.title) print(a.keywords) # TODO: hand article to queue for processing if __name__ == '__main__': main()
import yaml import newspaper from rabbit.publisher import Publisher def main(): with open('/options/config.yml') as file: config = yaml.safe_load(file) paper = newspaper.build(config['source']) publisher = Publisher( rabbit_url=config['rabbit_url'], publish_interval=1, article_urls=paper.articles) publisher.run() if __name__ == '__main__': main()
Build paper and hand articles to queue
Build paper and hand articles to queue
Python
mit
projectweekend/Article-Collector
--- +++ @@ -1,35 +1,17 @@ import yaml import newspaper -from newspaper import news_pool - - -def get_config(): - with open('/options/config.yml') as file: - config = yaml.safe_load(file) - keys = config.keys() - if not 'threads' in keys: - config['threads'] = 2 - if not 'source' in keys: - raise Exception('"source" not defined in config.yml') - if not 'words' in keys: - raise Exception('"words" not defined in config.yml') - return config +from rabbit.publisher import Publisher def main(): - config = get_config() - target_words_set = set([i.lower() for i in config['words']]) + with open('/options/config.yml') as file: + config = yaml.safe_load(file) paper = newspaper.build(config['source']) - news_pool.set([paper], threads_per_source=config['threads']) - news_pool.join() - - for a in paper.articles: - a.parse() - a.nlp() - if target_words_set < set(a.keywords): - print(a.title) - print(a.keywords) - # TODO: hand article to queue for processing + publisher = Publisher( + rabbit_url=config['rabbit_url'], + publish_interval=1, + article_urls=paper.articles) + publisher.run() if __name__ == '__main__':
75433ba1f8a0c057eacc49c77caf17fe19ffcda1
snapp/models.py
snapp/models.py
from django.db import models class Snap(models.Model): filename = models.CharField() downloaded = models.DateTimeField('date downloaded')
from django.db import models class Snap(models.Model): filename = models.CharField('124') downloaded = models.DateTimeField('date downloaded')
Add length to filename field
Add length to filename field
Python
mit
burk/helgapp,burk/helgapp
--- +++ @@ -1,6 +1,6 @@ from django.db import models class Snap(models.Model): - filename = models.CharField() + filename = models.CharField('124') downloaded = models.DateTimeField('date downloaded')
c104c70ad79edfa23d1a2ed76d37a25f77cd6586
PRESUBMIT.py
PRESUBMIT.py
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. """Top-level presubmit script for Dart. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ def CheckChangeOnCommit(input_api, output_api): results = [] status_check = input_api.canned_checks.CheckTreeIsOpen( input_api, output_api, json_url='http://dart-status.appspot.com/current?format=json') results.extend(status_check) return results
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. """Top-level presubmit script for Dart. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ def CheckChangeOnCommit(input_api, output_api): results = [] status_check = input_api.canned_checks.CheckTreeIsOpen( input_api, output_api, json_url='http://dart-status.appspot.com/current?format=json') # TODO(ricow): reenable when status page is back in shape # results.extend(status_check) return results
Disable status tree check until we figure out what is wrong with dart-status.appspot.com
Disable status tree check until we figure out what is wrong with dart-status.appspot.com R=kustermann@google.com, ngeoffray@google.com Review URL: https://codereview.chromium.org//23270003 git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@26257 260f80e4-7a28-3924-810f-c04153c831b5
Python
bsd-3-clause
dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk
--- +++ @@ -14,5 +14,6 @@ input_api, output_api, json_url='http://dart-status.appspot.com/current?format=json') - results.extend(status_check) + # TODO(ricow): reenable when status page is back in shape + # results.extend(status_check) return results
26e43b23a72a85c23184c2f5551885d65cc17831
conda_verify/errors.py
conda_verify/errors.py
from collections import namedtuple class PackageError(Exception): """Exception to be raised when user wants to exit on error.""" class RecipeError(Exception): """Exception to be raised when user wants to exit on error.""" class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])): """Error class creates error codes to be shown to the user.""" def __repr__(self): """Override namedtuple's __repr__ so that error codes are readable.""" return '{}:{}: {} {}' .format(self.file, self.line_number, self.code, self.message)
from collections import namedtuple class PackageError(Exception): """Exception to be raised when user wants to exit on error.""" class RecipeError(Exception): """Exception to be raised when user wants to exit on error.""" class Error(namedtuple('Error', ['code', 'message'])): """Error class creates error codes to be shown to the user.""" def __repr__(self): """Override namedtuple's __repr__ so that error codes are readable.""" return '{} {}' .format(self.code, self.message)
Remove file and line_number from Error class (may add at a later date)
Remove file and line_number from Error class (may add at a later date)
Python
bsd-3-clause
mandeep/conda-verify
--- +++ @@ -9,9 +9,9 @@ """Exception to be raised when user wants to exit on error.""" -class Error(namedtuple('Error', ['file', 'line_number', 'code', 'message'])): +class Error(namedtuple('Error', ['code', 'message'])): """Error class creates error codes to be shown to the user.""" def __repr__(self): """Override namedtuple's __repr__ so that error codes are readable.""" - return '{}:{}: {} {}' .format(self.file, self.line_number, self.code, self.message) + return '{} {}' .format(self.code, self.message)
6ae9da5ddf987873abb6f54992907542eaf80237
movieman2/tests.py
movieman2/tests.py
import datetime from django.contrib.auth.models import User from django.test import TestCase import tmdbsimple as tmdb from .models import Movie class MovieTestCase(TestCase): def setUp(self): User.objects.create(username="test_user", password="pass", email="test@user.tld", first_name="Test", last_name="User") def test_can_create_movie(self): """Can movies be created in the database?""" movie_data = tmdb.Movies(550).info() m = Movie.objects.create(tmdb_id=movie_data["id"], score=10, submitter=User.objects.first(), title=movie_data["title"], tagline=movie_data["tagline"], overview=movie_data["overview"], release_date=datetime.datetime.strptime(movie_data["release_date"], "%Y-%m-%d"), budget=movie_data["budget"], vote_average=movie_data["vote_average"], vote_count=movie_data["vote_count"], original_language=movie_data["original_language"]) m.save() def test_can_create_movie_from_id(self): """Does Movie.add_from_id work?""" Movie.add_from_id(550, User.objects.first())
import datetime import tmdbsimple as tmdb from django.contrib.auth.models import User from django.test import TestCase from .models import Movie class MovieTestCase(TestCase): def setUp(self): User.objects.create(username="movie_test_case", password="pass", email="movie@test_case.tld", first_name="Movie", last_name="TestCase") def test_can_create_movie(self): """Can movies be created in the database?""" movie_data = tmdb.Movies(550).info() m = Movie.objects.create(tmdb_id=movie_data["id"], score=10, submitter=User.objects.first(), title=movie_data["title"], tagline=movie_data["tagline"], overview=movie_data["overview"], release_date=datetime.datetime.strptime(movie_data["release_date"], "%Y-%m-%d"), budget=movie_data["budget"], vote_average=movie_data["vote_average"], vote_count=movie_data["vote_count"], original_language=movie_data["original_language"]) m.save() def test_can_create_movie_from_id(self): """Does Movie.add_from_id work?""" Movie.add_from_id(550, User.objects.first())
Change test case user info
Change test case user info
Python
mit
simon-andrews/movieman2,simon-andrews/movieman2
--- +++ @@ -1,16 +1,16 @@ import datetime +import tmdbsimple as tmdb from django.contrib.auth.models import User from django.test import TestCase -import tmdbsimple as tmdb from .models import Movie class MovieTestCase(TestCase): def setUp(self): - User.objects.create(username="test_user", password="pass", email="test@user.tld", first_name="Test", - last_name="User") + User.objects.create(username="movie_test_case", password="pass", email="movie@test_case.tld", + first_name="Movie", last_name="TestCase") def test_can_create_movie(self): """Can movies be created in the database?"""
732a49045d0e5f2dabc6c3d4b89e9be41633b1d8
contacts/views/__init__.py
contacts/views/__init__.py
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.get('book'): try: bookowner = BookOwner.objects.get( user=self.request.user, book_id=self.kwargs.get('book'), ) return self.model.objects.for_user( self.request.user, book=bookowner.book, ) except BookOwner.DoesNotExist: pass return self.model.objects.for_user(self.request.user) def get_object(self, queryset=None): instance = super(BookOwnerMixin, self).get_object(queryset) if not instance.can_be_viewed_by(self.request.user): raise PermissionDenied return instance def form_valid(self, form): form.instance.book = BookOwner.objects.get( user=self.request.user ).book response = super(BookOwnerMixin, self).form_valid(form) return response
from braces.views import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.shortcuts import ( get_object_or_404, redirect ) from contacts.models import ( Book, BookOwner, ) class BookOwnerMixin(LoginRequiredMixin): def get_queryset(self): if self.kwargs.get('book'): try: bookowner = BookOwner.objects.get( user=self.request.user, book_id=self.kwargs.get('book'), ) return self.model.objects.for_user( self.request.user, book=bookowner.book, ) except BookOwner.DoesNotExist: pass return self.model.objects.for_user(self.request.user) def get_object(self, queryset=None): instance = super(BookOwnerMixin, self).get_object(queryset) if not instance.can_be_viewed_by(self.request.user): raise PermissionDenied return instance def form_valid(self, form): try: form.instance.book = BookOwner.objects.get( user=self.request.user ).book except BookOwner.DoesNotExist: form.instance.book = Book.objects.create( name="{}'s Contacts".format(self.request.user), ) BookOwner.objects.create(book=form.instance.book, user=self.request.user) return super(BookOwnerMixin, self).form_valid(form)
Create book if one doesn't exist during tag creation
Create book if one doesn't exist during tag creation
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
--- +++ @@ -36,9 +36,13 @@ return instance def form_valid(self, form): - form.instance.book = BookOwner.objects.get( - user=self.request.user - ).book - response = super(BookOwnerMixin, self).form_valid(form) - - return response + try: + form.instance.book = BookOwner.objects.get( + user=self.request.user + ).book + except BookOwner.DoesNotExist: + form.instance.book = Book.objects.create( + name="{}'s Contacts".format(self.request.user), + ) + BookOwner.objects.create(book=form.instance.book, user=self.request.user) + return super(BookOwnerMixin, self).form_valid(form)
fbb8408c0f31079d79e08cd77fe54d27d6eb5f45
byceps/services/party/models/setting.py
byceps/services/party/models/setting.py
""" byceps.services.party.models.setting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import PartyID from ....util.instances import ReprBuilder class Setting(db.Model): """A party-specific setting.""" __tablename__ = 'party_settings' party_id = db.Column(db.Unicode(20), db.ForeignKey('parties.id'), primary_key=True) name = db.Column(db.Unicode(40), primary_key=True) value = db.Column(db.Unicode(200)) def __init__(self, party_id: PartyID, name: str, value: str) -> None: self.party_id = party_id self.name = name self.value = value def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('party_id') \ .add_with_lookup('name') \ .add_with_lookup('value') \ .build()
""" byceps.services.party.models.setting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ....database import db from ....typing import PartyID from ....util.instances import ReprBuilder class Setting(db.Model): """A party-specific setting.""" __tablename__ = 'party_settings' party_id = db.Column(db.Unicode(40), db.ForeignKey('parties.id'), primary_key=True) name = db.Column(db.Unicode(40), primary_key=True) value = db.Column(db.Unicode(200)) def __init__(self, party_id: PartyID, name: str, value: str) -> None: self.party_id = party_id self.name = name self.value = value def __repr__(self) -> str: return ReprBuilder(self) \ .add_with_lookup('party_id') \ .add_with_lookup('name') \ .add_with_lookup('value') \ .build()
Align foreign key field length with maximum party ID length
Align foreign key field length with maximum party ID length
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
--- +++ @@ -15,7 +15,7 @@ """A party-specific setting.""" __tablename__ = 'party_settings' - party_id = db.Column(db.Unicode(20), db.ForeignKey('parties.id'), primary_key=True) + party_id = db.Column(db.Unicode(40), db.ForeignKey('parties.id'), primary_key=True) name = db.Column(db.Unicode(40), primary_key=True) value = db.Column(db.Unicode(200))
ea0d732972d4b86cffdc63d73ff04b3da06b6860
osmwriter/_version.py
osmwriter/_version.py
"""Store the version info so that setup.py and __init__ can access it. """ __version__ = "0.2.0"
"""Store the version info so that setup.py and __init__ can access it. """ __version__ = "0.2.0.dev"
Prepare version 0.2.0.dev for next development cycle
Prepare version 0.2.0.dev for next development cycle
Python
agpl-3.0
rory/openstreetmap-writer
--- +++ @@ -1,2 +1,2 @@ """Store the version info so that setup.py and __init__ can access it. """ -__version__ = "0.2.0" +__version__ = "0.2.0.dev"
5b151720d3a2e5409e28d7f4a9c989fc8176cb32
main.py
main.py
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config/config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('b>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>')) extensions = ('cat', 'default', 'eddb', 'osu', 'nsfw', 'repl', 'rpg', 'stats', 'wolfram', 'xkcd') for extension in extensions: try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
#!/usr/bin/env python import asyncio import logging import sys import discord from discord.ext.commands import when_mentioned_or import yaml from bot import BeattieBot try: import uvloop except ImportError: pass else: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with open('config/config.yaml') as file: config = yaml.load(file) self_bot = 'self' in sys.argv if self_bot: token = config['self'] bot = BeattieBot('self>', self_bot=True) else: token = config['token'] bot = BeattieBot(when_mentioned_or('>', 'b>')) extensions = ('cat', 'default', 'eddb', 'osu', 'nsfw', 'repl', 'rpg', 'stats', 'wolfram', 'xkcd') for extension in extensions: try: bot.load_extension(extension) except Exception as e: print(f'Failed to load extension {extension}\n{type(e).__name__}: {e}') if not self_bot: logger = logging.getLogger('discord') logger.setLevel(logging.DEBUG) handler = logging.FileHandler( filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) bot.logger = logger bot.run(token, bot=not self_bot)
Use self> for selfbot prefix, and >/b> for normal bot prefix
Use self> for selfbot prefix, and >/b> for normal bot prefix
Python
mit
BeatButton/beattie,BeatButton/beattie-bot
--- +++ @@ -23,10 +23,10 @@ if self_bot: token = config['self'] - bot = BeattieBot('b>', self_bot=True) + bot = BeattieBot('self>', self_bot=True) else: token = config['token'] - bot = BeattieBot(when_mentioned_or('>')) + bot = BeattieBot(when_mentioned_or('>', 'b>')) extensions = ('cat', 'default', 'eddb', 'osu', 'nsfw', 'repl', 'rpg', 'stats', 'wolfram', 'xkcd')
643d7c2515c663777a058c9fce02beedeb34b77a
plotly/graph_objs/graph_objs_tools.py
plotly/graph_objs/graph_objs_tools.py
def update_keys(keys): """Change keys we used to support to their new equivalent.""" updated_keys = list() for key in keys: if key in translations: updated_keys += [translations[key]] else: updated_keys += [key] return updated_keys translations = dict( scl="colorscale", reversescale="reversescale" )
def update_keys(keys): """Change keys we used to support to their new equivalent.""" updated_keys = list() for key in keys: if key in translations: updated_keys += [translations[key]] else: updated_keys += [key] return updated_keys translations = dict( scl="colorscale", reversescl="reversescale" )
Fix typo in reversescale translation
Fix typo in reversescale translation - allows 'reversescl' (old key) to get map to 'reversescale' (new key)
Python
mit
plotly/python-api,plotly/plotly.py,plotly/python-api,ee-in/python-api,ee-in/python-api,plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/plotly.py
--- +++ @@ -10,5 +10,5 @@ translations = dict( scl="colorscale", - reversescale="reversescale" + reversescl="reversescale" )
ff66e137532593bfa3ce16b993be636236f549a2
polyaxon/scheduler/spawners/templates/init_containers.py
polyaxon/scheduler/spawners/templates/init_containers.py
class InitCommands(object): COPY = 'copy' CREATE = 'create' DELETE = 'delete' @classmethod def is_copy(cls, command): return command == cls.COPY @classmethod def is_create(cls, command): return command == cls.CREATE @classmethod def is_delete(cls, command): return command == cls.DELETE def get_output_args(command, outputs_path, original_outputs_path=None): get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -p {dir}; fi;'.format(dir=outputs_path) delete_dir = 'if [ -d {path} ]; then rm -r {path}; fi;'.format(path=outputs_path) copy_file_if_exist = 'if [ -f {original_path} ]; then cp {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) copy_dir_if_exist = 'if [ -d {original_path} ]; then cp -r {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) if InitCommands.is_create(command=command): return '{} {}'.format(get_or_create, delete_dir) if InitCommands.is_copy(command=command): return '{} {} {} {}'.format( get_or_create, delete_dir, copy_dir_if_exist, copy_file_if_exist) if InitCommands.is_delete(command=command): return '{}'.format(delete_dir)
class InitCommands(object): COPY = 'copy' CREATE = 'create' DELETE = 'delete' @classmethod def is_copy(cls, command): return command == cls.COPY @classmethod def is_create(cls, command): return command == cls.CREATE @classmethod def is_delete(cls, command): return command == cls.DELETE def get_output_args(command, outputs_path, original_outputs_path=None): get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -p {dir}; fi;'.format(dir=outputs_path) delete_dir = 'if [ -d {path} ]; then rm -r {path}/*; fi;'.format(path=outputs_path) copy_file_if_exist = 'if [ -f {original_path} ]; then cp {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) copy_dir_if_exist = 'if [ -d {original_path} ]; then cp -r {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) if InitCommands.is_create(command=command): return '{} {}'.format(get_or_create, delete_dir) if InitCommands.is_copy(command=command): return '{} {} {} {}'.format( get_or_create, delete_dir, copy_dir_if_exist, copy_file_if_exist) if InitCommands.is_delete(command=command): return '{}'.format(delete_dir)
Fix delete command in pod initializer
Fix delete command in pod initializer
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
--- +++ @@ -18,7 +18,7 @@ def get_output_args(command, outputs_path, original_outputs_path=None): get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -p {dir}; fi;'.format(dir=outputs_path) - delete_dir = 'if [ -d {path} ]; then rm -r {path}; fi;'.format(path=outputs_path) + delete_dir = 'if [ -d {path} ]; then rm -r {path}/*; fi;'.format(path=outputs_path) copy_file_if_exist = 'if [ -f {original_path} ]; then cp {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) copy_dir_if_exist = 'if [ -d {original_path} ]; then cp -r {original_path} {path}; fi;'.format(
cfac1504b590d329ffb56d1a46cad7cc1b4b22ff
corehq/apps/couch_sql_migration/util.py
corehq/apps/couch_sql_migration/util.py
from functools import wraps import gevent from greenlet import GreenletExit def exit_on_error(func): @wraps(func) def wrapper(*args, **kw): try: func(*args, **kw) except gevent.get_hub().SYSTEM_ERROR: raise except GreenletExit: raise except BaseException as err: raise UnhandledError(err) from err return wrapper def wait_for_one_task_to_complete(pool): if not pool: raise ValueError("pool is empty") with gevent.iwait(pool) as completed: next(completed) class UnhandledError(SystemExit): pass
from functools import wraps import gevent from greenlet import GreenletExit def exit_on_error(func): @wraps(func) def wrapper(*args, **kw): try: return func(*args, **kw) except gevent.get_hub().SYSTEM_ERROR: raise except GreenletExit: raise except BaseException as err: raise UnhandledError(err) from err return wrapper def wait_for_one_task_to_complete(pool): if not pool: raise ValueError("pool is empty") with gevent.iwait(pool) as completed: next(completed) class UnhandledError(SystemExit): pass
Fix exit_on_error in case of return value
Fix exit_on_error in case of return value
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -8,7 +8,7 @@ @wraps(func) def wrapper(*args, **kw): try: - func(*args, **kw) + return func(*args, **kw) except gevent.get_hub().SYSTEM_ERROR: raise except GreenletExit:
3484610b0c711b000da8dc37ab76649aa4abfc58
ptt_preproc_filter.py
ptt_preproc_filter.py
#!/usr/bin/env python import json import sys from os import scandir, remove from datetime import datetime START_DT = datetime(2016, 7, 1, 0, 0, 0) END_DT = datetime(2016, 12, 1, 0, 0, 0) DRY_RUN = True for dir_entry in scandir('preprocessed'): path = dir_entry.path with open(path) as f: # read the json into d try: d = json.load(f) except: print('[Error]', path, sep='\t', file=sys.stderr) continue # decide keep or remove authores_dt = datetime.fromtimestamp(d['authored_ts']) # print [DATETIME] path KEEP|REMOVE DRY_RUN? print(authores_dt, path, sep='\t', end='\t') if START_DT <= authores_dt < END_DT: print('KEEP') else: if DRY_RUN: print('REMOVE', 'DRY_RUN', sep='\t') else: print('REMOVE', sep='\t') remove(path)
#!/usr/bin/env python import json import sys from pathlib import Path from os import remove from datetime import datetime START_DT = datetime(2016, 7, 1, 0, 0, 0) END_DT = datetime(2016, 12, 1, 0, 0, 0) DRY_RUN = True for path in Path('preprocessed/').iterdir(): with path.open() as f: # read the json into d try: d = json.load(f) except: print('[Error]', path, sep='\t', file=sys.stderr) continue # decide keep or remove authores_dt = datetime.fromtimestamp(d['authored_ts']) # print [DATETIME] path KEEP|REMOVE DRY_RUN? print(authores_dt, path, sep='\t', end='\t') if START_DT <= authores_dt < END_DT: print('KEEP') else: if DRY_RUN: print('REMOVE', 'DRY_RUN', sep='\t') else: print('REMOVE', sep='\t') remove(str(path))
Use pathlib in the filter
Use pathlib in the filter
Python
mit
moskytw/mining-news
--- +++ @@ -3,7 +3,8 @@ import json import sys -from os import scandir, remove +from pathlib import Path +from os import remove from datetime import datetime @@ -12,10 +13,9 @@ DRY_RUN = True -for dir_entry in scandir('preprocessed'): +for path in Path('preprocessed/').iterdir(): - path = dir_entry.path - with open(path) as f: + with path.open() as f: # read the json into d @@ -37,4 +37,4 @@ print('REMOVE', 'DRY_RUN', sep='\t') else: print('REMOVE', sep='\t') - remove(path) + remove(str(path))
71cf0ce2348b46841f2f37c2c8934726832e5094
takeyourmeds/groups/groups_admin/tests.py
takeyourmeds/groups/groups_admin/tests.py
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, login=True, ) def test_create_access_tokens(self): group = self.user.profile.group self.assertEqual(group.access_tokens.count(), 0) self.assertPOST( 302, {'num_tokens': 10}, 'groups:admin:create-access-tokens', group.pk, login=True, ) self.assertEqual(group.access_tokens.count(), 10)
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, login=True, ) def test_access_tokens_csv(self): self.assertGET( 200, 'groups:admin:access-tokens-csv', self.user.profile.group_id, login=True, ) def test_create_access_tokens(self): group = self.user.profile.group self.assertEqual(group.access_tokens.count(), 0) self.assertPOST( 302, {'num_tokens': 10}, 'groups:admin:create-access-tokens', group.pk, login=True, ) self.assertEqual(group.access_tokens.count(), 10)
Test access token csv download
Test access token csv download Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
--- +++ @@ -8,6 +8,14 @@ self.assertGET( 200, 'groups:admin:view', + self.user.profile.group_id, + login=True, + ) + + def test_access_tokens_csv(self): + self.assertGET( + 200, + 'groups:admin:access-tokens-csv', self.user.profile.group_id, login=True, )
808b248d71785e44f764b7724e0d2812a750c9b4
Memoir/urls.py
Memoir/urls.py
"""Memoir URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
"""Memoir URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda request: HttpResponse('<h1>Memoir</h1>'), name = 'index'), url(r'^admin/', admin.site.urls), ]
Configure a simple index page
Configure a simple index page For now, this is a place-holder.
Python
mit
nivbend/memoir,nivbend/memoir,nivbend/memoir
--- +++ @@ -15,7 +15,9 @@ """ from django.conf.urls import url from django.contrib import admin +from django.http import HttpResponse urlpatterns = [ + url(r'^$', lambda request: HttpResponse('<h1>Memoir</h1>'), name = 'index'), url(r'^admin/', admin.site.urls), ]
bd4b4af4596120d1deee6db4e420829c0d40e377
boris/settings/config.py
boris/settings/config.py
import os import boris from .base import STATIC_URL # helper for building absolute paths PROJECT_ROOT = os.path.abspath(os.path.dirname(boris.__file__)) p = lambda x: os.path.join(PROJECT_ROOT, x) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'boris.db', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'charset': 'utf8', 'init_command': 'SET ' 'storage_engine=MyISAM,' 'character_set_connection=utf8,' 'collation_connection=utf8_general_ci' }, }, } STATIC_ROOT = p('static') ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # List of callables that know how to import templates from various sources. SECRET_KEY = 'od94mflb73jdjhw63hr7v9jfu7f6fhdujckwlqld87ff'
import os import boris from .base import STATIC_URL # helper for building absolute paths PROJECT_ROOT = os.path.abspath(os.path.dirname(boris.__file__)) p = lambda x: os.path.join(PROJECT_ROOT, x) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'boris', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'charset': 'utf8', 'init_command': 'SET ' 'storage_engine=MyISAM,' 'character_set_connection=utf8,' 'collation_connection=utf8_general_ci' }, }, } STATIC_ROOT = p('static') ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # List of callables that know how to import templates from various sources. SECRET_KEY = 'od94mflb73jdjhw63hr7v9jfu7f6fhdujckwlqld87ff'
Change default database from sqlite to mysql.
Change default database from sqlite to mysql.
Python
mit
fragaria/BorIS,fragaria/BorIS,fragaria/BorIS
--- +++ @@ -9,8 +9,8 @@ DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'boris.db', + 'ENGINE': 'django.db.backends.mysql', + 'NAME': 'boris', 'USER': '', 'PASSWORD': '', 'OPTIONS': {
a2d4381de5dc50110a0e57d7e56a668edbee2ccf
bot/utils.py
bot/utils.py
from discord import Embed def build_embed(ctx, desc: str, title: str = ''): name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, description=desc, color=status.value if status is not None else OpStatus.WARNING ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
Add support for colored output in embeds
Add support for colored output in embeds
Python
apache-2.0
HellPie/discord-reply-bot
--- +++ @@ -1,11 +1,19 @@ +from enum import IntEnum from discord import Embed -def build_embed(ctx, desc: str, title: str = ''): +class OpStatus(IntEnum): + SUCCESS = 0x2ECC71, + FAILURE = 0xc0392B, + WARNING = 0xf39C12 + + +def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name embed = Embed( title=title, - description=desc + description=desc, + color=status.value if status is not None else OpStatus.WARNING ) embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url) return embed
e44d32f18b438dc56bf483aecd3b9f3db03e6fae
gpn/graph.py
gpn/graph.py
# -*- coding: utf-8 -*- import os import pprint import warnings from gpn.node import Node suffix = '.node' suffix_default = '.node-default' class Graph(object): def __init__(self, path=None, nodes=None): global suffix global suffix_default assert not path or not nodes, ('Cannot specify both path ' 'and nodes.') # Get nodes. if not nodes: if not path: path = os.getcwd() # Defaule to cwd. def is_node(x): return x.endswith(suffix) or x.endswith(suffix_default) nodes = [Node(x) for x in os.listdir(path) if is_node(x)] self.path = path else: self.path = '<from collection>' # Set nodes. def node_item(p): assert isinstance(p, Node), '%r is not a Node.' % p if p.name: key = p.name else: key = p.get_hash()[:12] # <- TODO!!!: Implement get_hash(). warnings.warn("Node is unnamed--using " "short hash '%s'." % key) return (key, p) self.nodes = dict(node_item(p) for p in nodes) # Set edges. self.edges = [None]
# -*- coding: utf-8 -*- import os import pprint import warnings from gpn.node import Node suffix = '.node' suffix_default = '.node-default' class Graph(object): def __init__(self, path=None, nodes=None): global suffix global suffix_default assert not path or not nodes, ('Cannot specify both path and nodes.') # Get nodes. if not nodes: if not path: path = os.getcwd() # Default to cwd. def is_node(x): return x.endswith(suffix) or x.endswith(suffix_default) nodes = [Node(x) for x in os.listdir(path) if is_node(x)] self.path = path else: self.path = '<from collection>' # Set nodes. def node_item(p): assert isinstance(p, Node), '%r is not a Node.' % p if p.name: key = p.name else: key = p.get_hash()[:12] # <- TODO!!!: Implement get_hash(). warnings.warn("Node is unnamed--using " "short hash '%s'." % key) return (key, p) self.nodes = dict(node_item(p) for p in nodes) # Set edges. self.edges = [None]
Fix typo and minor formatting.
Fix typo and minor formatting.
Python
mit
shawnbrown/gpn,shawnbrown/gpn
--- +++ @@ -13,12 +13,12 @@ def __init__(self, path=None, nodes=None): global suffix global suffix_default - assert not path or not nodes, ('Cannot specify both path ' - 'and nodes.') + assert not path or not nodes, ('Cannot specify both path and nodes.') + # Get nodes. if not nodes: if not path: - path = os.getcwd() # Defaule to cwd. + path = os.getcwd() # Default to cwd. def is_node(x): return x.endswith(suffix) or x.endswith(suffix_default)
81189460862be9d03c951c318df6ada2ffefb02f
functest/tests/unit/utils/test_utils.py
functest/tests/unit/utils/test_utils.py
#!/usr/bin/env python # Copyright (c) 2016 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 import logging import unittest from functest.utils import functest_utils class FunctestUtilsTesting(unittest.TestCase): logging.disable(logging.CRITICAL) def setUp(self): self.test = functest_utils def test_check_internet_connectivity(self): self.assertTrue(self.test.check_internet_connectivity()) # TODO # ... if __name__ == "__main__": unittest.main(verbosity=2)
#!/usr/bin/env python # Copyright (c) 2016 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 import logging import mock import unittest import urllib2 from functest.utils import functest_utils class FunctestUtilsTesting(unittest.TestCase): logging.disable(logging.CRITICAL) def setUp(self): self.url = 'http://www.opnfv.org/' self.timeout = 5 @mock.patch('urllib2.urlopen', side_effect=urllib2.URLError('no host given')) def test_check_internet_connectivity_failed(self, mock_method): self.assertFalse(functest_utils.check_internet_connectivity()) mock_method.assert_called_once_with(self.url, timeout=self.timeout) @mock.patch('urllib2.urlopen') def test_check_internet_connectivity_default(self, mock_method): self.assertTrue(functest_utils.check_internet_connectivity()) mock_method.assert_called_once_with(self.url, timeout=self.timeout) @mock.patch('urllib2.urlopen') def test_check_internet_connectivity_debian(self, mock_method): self.url = "https://www.debian.org/" self.assertTrue(functest_utils.check_internet_connectivity(self.url)) mock_method.assert_called_once_with(self.url, timeout=self.timeout) if __name__ == "__main__": unittest.main(verbosity=2)
Allow unit testing w/o internet connectivity
Allow unit testing w/o internet connectivity urllib2.urlopen() is now patched when testing the internet connectivity helper. Change-Id: I4ddf1dd8f494fe282735e1051986a0b5dd1a040f Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
Python
apache-2.0
mywulin/functest,opnfv/functest,mywulin/functest,opnfv/functest
--- +++ @@ -8,7 +8,9 @@ # http://www.apache.org/licenses/LICENSE-2.0 import logging +import mock import unittest +import urllib2 from functest.utils import functest_utils @@ -18,12 +20,25 @@ logging.disable(logging.CRITICAL) def setUp(self): - self.test = functest_utils + self.url = 'http://www.opnfv.org/' + self.timeout = 5 - def test_check_internet_connectivity(self): - self.assertTrue(self.test.check_internet_connectivity()) -# TODO -# ... + @mock.patch('urllib2.urlopen', + side_effect=urllib2.URLError('no host given')) + def test_check_internet_connectivity_failed(self, mock_method): + self.assertFalse(functest_utils.check_internet_connectivity()) + mock_method.assert_called_once_with(self.url, timeout=self.timeout) + + @mock.patch('urllib2.urlopen') + def test_check_internet_connectivity_default(self, mock_method): + self.assertTrue(functest_utils.check_internet_connectivity()) + mock_method.assert_called_once_with(self.url, timeout=self.timeout) + + @mock.patch('urllib2.urlopen') + def test_check_internet_connectivity_debian(self, mock_method): + self.url = "https://www.debian.org/" + self.assertTrue(functest_utils.check_internet_connectivity(self.url)) + mock_method.assert_called_once_with(self.url, timeout=self.timeout) if __name__ == "__main__":
23d5d0e0e77dc0b0816df51a8a1e42bc4069112b
rst2pdf/style2yaml.py
rst2pdf/style2yaml.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Convert older RSON stylesheets to YAML format Run the script with the filename to convert, it outputs to stdout """ import argparse import json import yaml from rst2pdf.dumpstyle import fixstyle from rst2pdf.rson import loads as rloads def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( 'paths', metavar='PATH', nargs='+', help='An RSON-formatted file to convert.', ) args = parser.parse_args() for path in args.paths: # read rson from a file with open(path, 'rb') as fh: style_data = fixstyle(rloads(fh.read())) # output the style as json, then parse that json_style = json.dumps(style_data) reparsed_style = json.loads(json_style) yaml_style = yaml.dump(reparsed_style, default_flow_style=None) print(yaml_style) if __name__ == '__main__': main()
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Convert older RSON stylesheets to YAML format Run the script with this list of filenames to convert. It outputs to stdout, or use the --save3 flag to have it create .yaml files """ import argparse import json import os import yaml from rst2pdf.dumpstyle import fixstyle from rst2pdf.rson import loads as rloads def main(): # set up the command, optional --save parameter, and a list of paths parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( '--save', action='store_true', help='Save .yaml version of the file (rather than output to stdout)', ) parser.add_argument( 'paths', metavar='PATH', nargs='+', help='An RSON-formatted file to convert.', ) args = parser.parse_args() # loop over the files for path in args.paths: # read rson from a file with open(path, 'rb') as fh: style_data = fixstyle(rloads(fh.read())) # output the style as json (already supported), then parse that json_style = json.dumps(style_data) reparsed_style = json.loads(json_style) yaml_style = yaml.dump(reparsed_style, default_flow_style=None) # output the yaml or save to a file if args.save: new_path = '.'.join((os.path.splitext(path)[0], 'yaml')) if os.path.exists(new_path): print("File " + new_path + " exists, cannot overwrite") else: print("Creating file " + new_path) with open(new_path, 'w') as file: file.write(yaml_style) else: print(yaml_style) if __name__ == '__main__': main()
Add save functionality to the conversion script
Add save functionality to the conversion script
Python
mit
rst2pdf/rst2pdf,rst2pdf/rst2pdf
--- +++ @@ -3,11 +3,13 @@ """Convert older RSON stylesheets to YAML format -Run the script with the filename to convert, it outputs to stdout +Run the script with this list of filenames to convert. It outputs to stdout, or +use the --save3 flag to have it create .yaml files """ import argparse import json +import os import yaml @@ -16,9 +18,15 @@ def main(): + # set up the command, optional --save parameter, and a list of paths parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + '--save', + action='store_true', + help='Save .yaml version of the file (rather than output to stdout)', ) parser.add_argument( 'paths', @@ -27,17 +35,31 @@ help='An RSON-formatted file to convert.', ) args = parser.parse_args() + + # loop over the files for path in args.paths: # read rson from a file with open(path, 'rb') as fh: style_data = fixstyle(rloads(fh.read())) - # output the style as json, then parse that + # output the style as json (already supported), then parse that json_style = json.dumps(style_data) reparsed_style = json.loads(json_style) yaml_style = yaml.dump(reparsed_style, default_flow_style=None) - print(yaml_style) + + # output the yaml or save to a file + if args.save: + new_path = '.'.join((os.path.splitext(path)[0], 'yaml')) + + if os.path.exists(new_path): + print("File " + new_path + " exists, cannot overwrite") + else: + print("Creating file " + new_path) + with open(new_path, 'w') as file: + file.write(yaml_style) + else: + print(yaml_style) if __name__ == '__main__':
e380ef8d890db4cd21ab9ceb943a38758526976f
numba/tests/issues/test_issue_184.py
numba/tests/issues/test_issue_184.py
import sys from numba import * import numpy as np @jit(object_(double[:, :])) def func2(A): L = [] n = A.shape[0] for i in range(10): for j in range(10): temp = A[i-n : i+n+1, j-2 : j+n+1] L.append(temp) return L A = np.empty(1000000, dtype=np.double).reshape(1000, 1000) refcnt = sys.getrefcount(A) func2(A) new_refcnt = sys.getrefcount(A) assert refcnt == new_refcnt normal_result = map(sys.getrefcount, func2.py_func(A)) numba_result = map(sys.getrefcount, func2(A)) assert normal_result == numba_result
import sys from numba import * import numpy as np @jit(object_(double[:, :])) def func2(A): L = [] n = A.shape[0] for i in range(10): for j in range(10): temp = A[i-n : i+n+1, j-2 : j+n+1] L.append(temp) return L A = np.empty(1000000, dtype=np.double).reshape(1000, 1000) refcnt = sys.getrefcount(A) func2(A) new_refcnt = sys.getrefcount(A) assert refcnt == new_refcnt normal_result = list(map(sys.getrefcount, func2.py_func(A))) numba_result = list(map(sys.getrefcount, func2(A))) assert normal_result == numba_result
Fix test 184 for python 3
Fix test 184 for python 3
Python
bsd-2-clause
gdementen/numba,seibert/numba,numba/numba,ssarangi/numba,pombredanne/numba,pitrou/numba,cpcloud/numba,gmarkall/numba,ssarangi/numba,stefanseefeld/numba,gmarkall/numba,seibert/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3/numba,stefanseefeld/numba,gdementen/numba,stefanseefeld/numba,gmarkall/numba,pombredanne/numba,pitrou/numba,pitrou/numba,seibert/numba,shiquanwang/numba,IntelLabs/numba,ssarangi/numba,stuartarchibald/numba,seibert/numba,GaZ3ll3/numba,pombredanne/numba,stefanseefeld/numba,stonebig/numba,IntelLabs/numba,jriehl/numba,cpcloud/numba,stuartarchibald/numba,pombredanne/numba,IntelLabs/numba,stefanseefeld/numba,GaZ3ll3/numba,GaZ3ll3/numba,jriehl/numba,gdementen/numba,cpcloud/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,gdementen/numba,ssarangi/numba,GaZ3ll3/numba,sklam/numba,sklam/numba,numba/numba,cpcloud/numba,stonebig/numba,sklam/numba,jriehl/numba,jriehl/numba,IntelLabs/numba,gmarkall/numba,shiquanwang/numba,cpcloud/numba,numba/numba,pombredanne/numba,stonebig/numba,stonebig/numba,numba/numba,jriehl/numba,stuartarchibald/numba,shiquanwang/numba,gmarkall/numba,pitrou/numba,gdementen/numba,ssarangi/numba,sklam/numba,pitrou/numba,numba/numba,sklam/numba
--- +++ @@ -20,6 +20,6 @@ new_refcnt = sys.getrefcount(A) assert refcnt == new_refcnt -normal_result = map(sys.getrefcount, func2.py_func(A)) -numba_result = map(sys.getrefcount, func2(A)) +normal_result = list(map(sys.getrefcount, func2.py_func(A))) +numba_result = list(map(sys.getrefcount, func2(A))) assert normal_result == numba_result
5439f17fb2ebea7f8c5695c79324c29c483bfb78
wger/nutrition/migrations/0004_auto_20200819_2310.py
wger/nutrition/migrations/0004_auto_20200819_2310.py
# Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0003_auto_20170118_2308'), ] operations = [ migrations.AlterField( model_name='nutritionplan', name='description', field=models.CharField(blank=True, help_text='A description of the goal of the plan, e.g. "Gain mass" or "Prepare for summer"', max_length=80, verbose_name='Description'), ), ]
# flake8: noqa # Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0003_auto_20170118_2308'), ] operations = [ migrations.AlterField( model_name='nutritionplan', name='description', field=models.CharField(blank=True, help_text='A description of the goal of the plan, e.g. "Gain mass" or "Prepare for summer"', max_length=80, verbose_name='Description'), ), ]
Add noqa flag to migration file
Add noqa flag to migration file
Python
agpl-3.0
rolandgeider/wger,petervanderdoes/wger,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,wger-project/wger,petervanderdoes/wger,petervanderdoes/wger,rolandgeider/wger,rolandgeider/wger,wger-project/wger,wger-project/wger
--- +++ @@ -1,3 +1,4 @@ +# flake8: noqa # Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models
2dfe6e78088f974310c1e7fc309f008310be0080
dask_ndmeasure/_utils.py
dask_ndmeasure/_utils.py
# -*- coding: utf-8 -*- import operator import numpy import dask.array from . import _compat def _norm_input_labels_index(input, labels=None, index=None): """ Normalize arguments to a standard form. """ input = _compat._asarray(input) if labels is None: labels = (input != 0).astype(numpy.int64) index = None if index is None: labels = (labels > 0).astype(numpy.int64) index = dask.array.ones(tuple(), dtype=numpy.int64, chunks=tuple()) labels = _compat._asarray(labels) index = _compat._asarray(index) # SciPy transposes these for some reason. # So we do the same thing here. # This only matters if index is some array. index = index.T if input.shape != labels.shape: raise ValueError("The input and labels arrays must be the same shape.") return (input, labels, index) def _get_label_matches(input, labels, index): input_i = _compat._indices( input.shape, dtype=numpy.int64, chunks=input.chunks ) lbl_mtch = operator.eq( index[(Ellipsis,) + labels.ndim * (None,)], labels[index.ndim * (None,)] ) input_i_mtch = dask.array.where( lbl_mtch[index.ndim * (slice(None),) + (None,)], input_i[index.ndim * (None,)], input_i.dtype.type(0) ) input_mtch = dask.array.where( lbl_mtch, input[index.ndim * (None,)], input.dtype.type(0) ) return (lbl_mtch, input_i_mtch, input_mtch)
# -*- coding: utf-8 -*- import operator import numpy import dask.array from . import _compat def _norm_input_labels_index(input, labels=None, index=None): """ Normalize arguments to a standard form. """ input = _compat._asarray(input) if labels is None: labels = (input != 0).astype(numpy.int64) index = None if index is None: labels = (labels > 0).astype(numpy.int64) index = dask.array.ones(tuple(), dtype=numpy.int64, chunks=tuple()) labels = _compat._asarray(labels) index = _compat._asarray(index) # SciPy transposes these for some reason. # So we do the same thing here. # This only matters if index is some array. index = index.T if input.shape != labels.shape: raise ValueError("The input and labels arrays must be the same shape.") return (input, labels, index) def _get_label_matches(labels, index): lbl_mtch = operator.eq( index[(Ellipsis,) + labels.ndim * (None,)], labels[index.ndim * (None,)] ) return lbl_mtch
Simplify the label matches function
Simplify the label matches function Focus only creating a mask of selected labels and none of the other products that this function was creating before.
Python
bsd-3-clause
dask-image/dask-ndmeasure
--- +++ @@ -39,24 +39,10 @@ return (input, labels, index) -def _get_label_matches(input, labels, index): - input_i = _compat._indices( - input.shape, dtype=numpy.int64, chunks=input.chunks - ) - +def _get_label_matches(labels, index): lbl_mtch = operator.eq( index[(Ellipsis,) + labels.ndim * (None,)], labels[index.ndim * (None,)] ) - input_i_mtch = dask.array.where( - lbl_mtch[index.ndim * (slice(None),) + (None,)], - input_i[index.ndim * (None,)], - input_i.dtype.type(0) - ) - - input_mtch = dask.array.where( - lbl_mtch, input[index.ndim * (None,)], input.dtype.type(0) - ) - - return (lbl_mtch, input_i_mtch, input_mtch) + return lbl_mtch
c790e1dd756495f0e34ff3c2cdadb02b4d6ee320
protocols/admin.py
protocols/admin.py
from django.contrib import admin from .models import Protocol, Topic, Institution class ProtocolAdmin(admin.ModelAdmin): list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'get_absent'] list_display_links = ['number'] list_filter = ['topics'] search_fields =['number', 'information', 'topics__name', 'topics__description'] admin.site.register(Institution) admin.site.register(Topic) admin.site.register(Protocol, ProtocolAdmin)
from django.contrib import admin from .models import Protocol, Topic, Institution class ProtocolAdmin(admin.ModelAdmin): list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution'] list_display_links = ['number'] list_filter = ['institution__name', 'topics'] search_fields =['number', 'institution__name', 'topics__name', 'information'] admin.site.register(Institution) admin.site.register(Topic) admin.site.register(Protocol, ProtocolAdmin)
Change search and list fields
Change search and list fields
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -3,13 +3,13 @@ class ProtocolAdmin(admin.ModelAdmin): - list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'get_absent'] + list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution'] list_display_links = ['number'] - list_filter = ['topics'] + list_filter = ['institution__name', 'topics'] - search_fields =['number', 'information', 'topics__name', 'topics__description'] + search_fields =['number', 'institution__name', 'topics__name', 'information'] admin.site.register(Institution) admin.site.register(Topic)
299fed5e4531b9cf3bc6043f69b4c7c4db62b6dc
proxy/data/clients.py
proxy/data/clients.py
import blocks connectedClients = {} class ClientData(object): """docstring for ClientData""" def __init__(self, ipAddress, segaId, handle): self.ipAddress = ipAddress self.segaId = segaId self.handle = handle def getHandle(self): return self.handle def setHandle(self, handle): self.handle = handle def addClient(handle): connectedClients[handle.playerId] = ClientData(handle.transport.getPeer().host, handle.myUsername, handle) print('[Clients] Registered client %s (ID:%i) in online clients' % (handle.myUsername, handle.playerId)) def removeClient(handle): print("[Clients] Removing client %s (ID:%i) from online clients" % (handle.myUsername, handle.playerId)) del connectedClients[handle.playerId] def populateData(handle): cData = connectedClients[handle.playerId] cData.handle = handle handle.myUsername = cData.segaId if handle.transport.getHost().port in blocks.blockList: bName = blocks.blockList[handle.transport.getHost().port][1] else: bName = None print("[ShipProxy] %s has successfully changed blocks to %s!" % (handle.myUsername, bName)) handle.loaded = True
import blocks connectedClients = {} class ClientData(object): """docstring for ClientData""" def __init__(self, ipAddress, segaId, handle): self.ipAddress = ipAddress self.segaId = segaId self.handle = handle def getHandle(self): return self.handle def setHandle(self, handle): self.handle = handle def addClient(handle): connectedClients[handle.playerId] = ClientData(handle.transport.getPeer().host, handle.myUsername, handle) print('[Clients] Registered client %s (ID:%i) in online clients' % (handle.myUsername, handle.playerId)) def removeClient(handle): print("[Clients] Removing client %s (ID:%i) from online clients" % (handle.myUsername, handle.playerId)) del connectedClients[handle.playerId] def populateData(handle): cData = connectedClients[handle.playerId] cData.handle = handle handle.myUsername = cData.segaId handle.peer.myUsername = cData.segaId if handle.transport.getHost().port in blocks.blockList: bName = blocks.blockList[handle.transport.getHost().port][1] else: bName = None print("[ShipProxy] %s has successfully changed blocks to %s!" % (handle.myUsername, bName)) handle.loaded = True
Update SEGA Id in server side too
Update SEGA Id in server side too
Python
agpl-3.0
alama/PSO2Proxy,cyberkitsune/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy
--- +++ @@ -25,6 +25,7 @@ cData = connectedClients[handle.playerId] cData.handle = handle handle.myUsername = cData.segaId + handle.peer.myUsername = cData.segaId if handle.transport.getHost().port in blocks.blockList: bName = blocks.blockList[handle.transport.getHost().port][1] else:
c74cb57a8c0186b4186319018a1ed6d7f3687882
celery/tests/test_serialization.py
celery/tests/test_serialization.py
import sys import unittest class TestAAPickle(unittest.TestCase): def test_no_cpickle(self): from celery.tests.utils import mask_modules del(sys.modules["celery.serialization"]) with mask_modules("cPickle"): from celery.serialization import pickle import pickle as orig_pickle self.assertTrue(pickle.dumps is orig_pickle.dumps)
from __future__ import with_statement import sys import unittest class TestAAPickle(unittest.TestCase): def test_no_cpickle(self): from celery.tests.utils import mask_modules del(sys.modules["celery.serialization"]) with mask_modules("cPickle"): from celery.serialization import pickle import pickle as orig_pickle self.assertTrue(pickle.dumps is orig_pickle.dumps)
Make tests pass in Python 2.5 by importing with_statement from __future__
Make tests pass in Python 2.5 by importing with_statement from __future__
Python
bsd-3-clause
frac/celery,WoLpH/celery,mitsuhiko/celery,frac/celery,ask/celery,cbrepo/celery,WoLpH/celery,cbrepo/celery,ask/celery,mitsuhiko/celery
--- +++ @@ -1,3 +1,4 @@ +from __future__ import with_statement import sys import unittest
adb658a874a7d0437607bf828e99adf2dee74438
openassessment/fileupload/backends/__init__.py
openassessment/fileupload/backends/__init__.py
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # Use S3 backend by default (current behaviour) backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
""" File Upload backends. """ from django.conf import settings from . import django_storage, filesystem, s3, swift def get_backend(): # .. setting_name: ORA2_FILEUPLOAD_BACKEND # .. setting_default: s3 # .. setting_description: The backend used to upload the ora2 submissions attachments # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend() elif backend_setting == "filesystem": return filesystem.Backend() elif backend_setting == "swift": return swift.Backend() elif backend_setting == "django": return django_storage.Backend() else: raise ValueError("Invalid ORA2_FILEUPLOAD_BACKEND setting value: %s" % backend_setting)
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Add annotation for ORA2_FILEUPLOAD_BACKEND setting
Python
agpl-3.0
edx/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,EDUlib/edx-ora2,edx/edx-ora2
--- +++ @@ -7,7 +7,10 @@ def get_backend(): - # Use S3 backend by default (current behaviour) + # .. setting_name: ORA2_FILEUPLOAD_BACKEND + # .. setting_default: s3 + # .. setting_description: The backend used to upload the ora2 submissions attachments + # the supported values are: s3, filesystem, swift and django. backend_setting = getattr(settings, "ORA2_FILEUPLOAD_BACKEND", "s3") if backend_setting == "s3": return s3.Backend()
b84dff394f4c9b0b5aeaeb6bdc1d67ef4a9f02e0
neuroimaging/setup.py
neuroimaging/setup.py
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('data_io') config.add_subpackage('externals') config.add_subpackage('fixes') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils') config.add_subpackage('testing') config.add_data_dir('testing') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('neuroimaging', parent_package, top_path) config.add_subpackage('algorithms') config.add_subpackage('core') config.add_subpackage('externals') config.add_subpackage('fixes') config.add_subpackage('io') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils') config.add_subpackage('testing') config.add_data_dir('testing') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Change neuroimaging package list data_io to io.
Change neuroimaging package list data_io to io.
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
--- +++ @@ -6,9 +6,9 @@ config.add_subpackage('algorithms') config.add_subpackage('core') - config.add_subpackage('data_io') config.add_subpackage('externals') config.add_subpackage('fixes') + config.add_subpackage('io') config.add_subpackage('modalities') config.add_subpackage('ui') config.add_subpackage('utils')
b7f2efe79e5a91ab78850842eafc73d1ee0a52cc
shortuuid/__init__.py
shortuuid/__init__.py
from shortuuid.main import ( encode, decode, uuid, get_alphabet, set_alphabet, ShortUUID, )
from shortuuid.main import ( encode, decode, uuid, random, get_alphabet, set_alphabet, ShortUUID, )
Include `random` in imports from shortuuid.main
Include `random` in imports from shortuuid.main When `random` was added to `main.py` the `__init__.py` file wasn't updated to expose it. Currently, to use, you have to do: `import shortuuid; shortuuid.main.random(24)`. With these changes you can do `import shortuuid; shortuuid.random()`. This better mirrors the behavior of `uuid`, etc.
Python
bsd-3-clause
skorokithakis/shortuuid,stochastic-technologies/shortuuid
--- +++ @@ -2,6 +2,7 @@ encode, decode, uuid, + random, get_alphabet, set_alphabet, ShortUUID,
4d8c7aea5e808075a68d810fb7c966808ad28bca
scripts/upload_2_crowdai.py
scripts/upload_2_crowdai.py
#!/usr/bin/env python try: import crowdai except: raise Exception("Please install the `crowdai` python client by : pip install crowdai") import argparse parser = argparse.ArgumentParser(description='Upload saved docker environments to crowdai for grading') parser.add_argument('--api_key', dest='api_key', action='store', required=True) parser.add_argument('--docker_container', dest='docker_container', action='store', required=True) args = parser.parse_args() challenge = crowdai.Challenge("Learning2RunChallengeNIPS2017", args.api_key) result = challenge.submit(docker_container) print(result)
#!/usr/bin/env python try: import crowdai except: raise Exception("Please install the `crowdai` python client by : pip install crowdai") import argparse parser = argparse.ArgumentParser(description='Upload saved docker environments to crowdai for grading') parser.add_argument('--api_key', dest='api_key', action='store', required=True) parser.add_argument('--docker_container', dest='docker_container', action='store', required=True) args = parser.parse_args() challenge = crowdai.Challenge("Learning2RunChallengeNIPS2017", args.api_key) result = challenge.submit(args.docker_container) print(result)
Use parseargs reference for docker_container
Use parseargs reference for docker_container
Python
mit
stanfordnmbl/osim-rl,vzhuang/osim-rl
--- +++ @@ -10,6 +10,6 @@ args = parser.parse_args() challenge = crowdai.Challenge("Learning2RunChallengeNIPS2017", args.api_key) -result = challenge.submit(docker_container) +result = challenge.submit(args.docker_container) print(result)
2db6e8e294059847251feb9610c42180ae44e05b
fbone/appointment/views.py
fbone/appointment/views.py
# -*- coding: utf-8 -*- from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form fields. for key in form.data.keys(): setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) return render_template('appointment/create.html', form=form)
# -*- coding: utf-8 -*- from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405)
Fix some error about session.
Fix some error about session.
Python
bsd-3-clause
wpic/flask-appointment-calendar,wpic/flask-appointment-calendar
--- +++ @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- -from flask import (Blueprint, render_template, request, +from datetime import datetime + +from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message @@ -14,27 +16,41 @@ @appointment.route('/create', methods=['GET', 'POST']) def create(): - form = MakeAppointmentForm(formdata=request.args, - next=request.args.get('next')) + if request.method == 'POST': + form = MakeAppointmentForm(next=request.args.get('next')) - # Dump all available data from request or session object to form fields. - for key in form.data.keys(): - setattr(getattr(form, key), 'data', - request.args.get(key) or session.get(key)) + if form.validate_on_submit(): + appointment = Appointment() + form.populate_obj(appointment) - if form.validate_on_submit(): - appointment = Appointment() - form.populate_obj(appointment) + db.session.add(appointment) + db.session.commit() - db.session.add(appointment) - db.session.commit() + flash_message = """ + Congratulations! You've just made an appointment + on WPIC Web Calendar system, please check your email for details. + """ + flash(flash_message) - flash_message = """ - Congratulations! You've just made an appointment - on WPIC Web Calendar system, please check your email for details. - """ - flash(flash_message) + return redirect(url_for('appointment.create')) - return redirect(url_for('appointment.create')) + elif request.method == 'GET': + form = MakeAppointmentForm(formdata=request.args, + next=request.args.get('next')) + # Dump all available data from request or session object to form + # fields. + for key in form.data.keys(): + if key == "date": + setattr(getattr(form, key), 'data', + datetime.strptime(request.args.get(key) or + session.get(key) or + datetime.today().strftime('%Y-%m-%d'), + "%Y-%m-%d")) + else: + setattr(getattr(form, key), 'data', + request.args.get(key) or session.get(key)) - return render_template('appointment/create.html', form=form) + return render_template('appointment/create.html', form=form) + + else: + abort(405)
f694b582e72412d4022d6ff21a97d32f77484b9b
heap/heap.py
heap/heap.py
# -*- coding:utf-8 -*- import numpy as np class ArrayHeap(object): def __init__(self, sz, data = None): self.sz = sz self.cnt = 0 self.heap = [0 for i in range(sz + 1)] if data is not None: for i, val in enumerate(data): self.heap[i + 1] = val self.cnt = len(data) self._build_heap() def _build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = ArrayHeap(100, data) print(heap.heap)
# -*- coding:utf-8 -*- import numpy as np class MaxHeap(object): def __init__(self, sz, data): self.sz = sz self.heap = [0] * (sz + 1) self.cnt = len(data) self.heap[1: self.cnt + 1] = data self.build_heap() def build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = MaxHeap(100, data) print(heap.heap)
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Python
apache-2.0
free-free/algorithm,free-free/algorithm
--- +++ @@ -4,20 +4,17 @@ import numpy as np -class ArrayHeap(object): +class MaxHeap(object): - def __init__(self, sz, data = None): + def __init__(self, sz, data): self.sz = sz - self.cnt = 0 - self.heap = [0 for i in range(sz + 1)] - if data is not None: - for i, val in enumerate(data): - self.heap[i + 1] = val - self.cnt = len(data) - self._build_heap() + self.heap = [0] * (sz + 1) + self.cnt = len(data) + self.heap[1: self.cnt + 1] = data + self.build_heap() - def _build_heap(self): + def build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x @@ -38,5 +35,5 @@ if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) - heap = ArrayHeap(100, data) + heap = MaxHeap(100, data) print(heap.heap)
5d6b729232e086212ea46590d80b02366ae5a236
bin/start.py
bin/start.py
#!/usr/bin/python import sys, os from paste.deploy import loadapp, loadserver import logging if __name__ == '__main__': logging.basicConfig(filename = '/var/log/reporting-api.log', level = logging.INFO) realfile = os.path.realpath(__file__) realdir = os.path.dirname(realfile) pardir = os.path.realpath(os.path.join(realdir, os.pardir)) confdir = os.path.join(pardir, 'conf') paste_config = os.path.join(confdir, 'paste.config') sys.path.append(pardir) reporting_app = loadapp('config:' + paste_config) server = loadserver('config:' + paste_config) server(reporting_app)
#!/usr/bin/python import sys, os from paste.deploy import loadapp, loadserver import logging if __name__ == '__main__': logging.basicConfig(filename = '/var/log/reporting-api.log', level = logging.INFO) realfile = os.path.realpath(__file__) realdir = os.path.dirname(realfile) pardir = os.path.realpath(os.path.join(realdir, os.pardir)) confdir = os.path.join(pardir, 'conf') paste_config = os.path.join(confdir, 'paste.config') sys.path.insert(0, pardir) reporting_app = loadapp('config:' + paste_config) server = loadserver('config:' + paste_config) server(reporting_app)
Insert the path to the source tree at the front of the python path rather than at the end. Something broken got put into some one of the python include directories somehow.
Insert the path to the source tree at the front of the python path rather than at the end. Something broken got put into some one of the python include directories somehow.
Python
apache-2.0
NCI-Cloud/reporting-api,NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api,NeCTAR-RC/reporting-api
--- +++ @@ -11,7 +11,7 @@ pardir = os.path.realpath(os.path.join(realdir, os.pardir)) confdir = os.path.join(pardir, 'conf') paste_config = os.path.join(confdir, 'paste.config') - sys.path.append(pardir) + sys.path.insert(0, pardir) reporting_app = loadapp('config:' + paste_config) server = loadserver('config:' + paste_config) server(reporting_app)
f075f083d002cb7ca3819ec1115eb82681b1e9b1
test.py
test.py
#!/usr/bin/python import unittest import subprocess class TestWilkins(unittest.TestCase): def test_cliusage(self): output = subprocess.check_output(['./wilkins.py', '--word', 'remain', '--output', 'json']) self.assertEqual(output.strip(), '{"synonyms": ["stay", "rest"], "type": "Verb", "residual": ["1 (stay%2:30:00::)", "6 (rest%2:30:00::)"]}') if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestWilkins) unittest.TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/python import unittest import subprocess class TestWilkins(unittest.TestCase): def test_cliusage(self): output = subprocess.check_output(['./wilkins.py', '--word', 'remain', '--output', 'json']) self.assertEqual(output.strip(), '{"synonyms": ["bla", "rest"], "type": "Verb", "residual": ["1 (stay%2:30:00::)", "6 (rest%2:30:00::)"]}') if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestWilkins) unittest.TextTestRunner(verbosity=2).run(suite)
Test broken - just demo
Test broken - just demo
Python
mit
az-labs/wilkins-python
--- +++ @@ -7,7 +7,7 @@ def test_cliusage(self): output = subprocess.check_output(['./wilkins.py', '--word', 'remain', '--output', 'json']) - self.assertEqual(output.strip(), '{"synonyms": ["stay", "rest"], "type": "Verb", "residual": ["1 (stay%2:30:00::)", "6 (rest%2:30:00::)"]}') + self.assertEqual(output.strip(), '{"synonyms": ["bla", "rest"], "type": "Verb", "residual": ["1 (stay%2:30:00::)", "6 (rest%2:30:00::)"]}') if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestWilkins)
1ade5cef22e162ce07edb6d94859268727da4949
agile.py
agile.py
import requests import xml.etree.ElementTree as ET from credentials import app_key, user_key, corp_id, report_id base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render' date = '&DatePicker=thisweek' report = '&MembershipMultiPicker=130&filename=memberactivity.xml' url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id, date, report) # r = requests.get(url) # text = r.text # xml = text[3:] # root = ET.fromstring(xml) tree = ET.parse('data.xml') root = tree.getroot() members = root[1] collections = members[3] details = collections[0] first_name = details[2].text # print(first_name) for name in root.iter('{Membership_MemberList_Extract}FirstName'): print(name.text) for name in root.iter(): print(name.tag)
import requests import xml.etree.ElementTree as ET from credentials import app_key, user_key, corp_id, report_id base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render' date = '&DatePicker=thisweek' report = '&MembershipMultiPicker=130&filename=memberactivity.xml' url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id, date, report) # r = requests.get(url) # text = r.text # xml = text[3:] # root = ET.fromstring(xml) tree = ET.parse('data.xml') root = tree.getroot() members = root[1] collection = members[3] summary = root[0].attrib record_count = int(summary['Record_Count']) members = [] def append_contacts(collection): '''Populates the contact and address dictionaries and then appends them to a contacts list. Arguments: contacts = The list the dictionary will be appended to. ''' contact = {} address = {} contact['email_addresses'] = [collection[7].text] contact['first_name'] = collection[2].text.title() contact['last_name'] = collection[4].text.title() contact['home_phone'] = collection[19][0].attrib contact['custom_field 1'] = collection[26].text contact['addresses'] = [address] address['line1'] = collection[9].text address['line2'] = collection[10].text address['city'] = collection[11].text.title() address['state_code'] = collection[12].text address['postal_code'] = collection[13].text members.append(contact) for count in range(record_count): append_contacts(collection[count]) print(members)
Create dict out of member info and append to list
Create dict out of member info and append to list append_members() work identically to append_contacts(). A for loop is also needed to loop over every member entry in the XML file.
Python
mit
deadlyraptor/reels
--- +++ @@ -17,14 +17,40 @@ root = tree.getroot() members = root[1] -collections = members[3] -details = collections[0] +collection = members[3] +summary = root[0].attrib +record_count = int(summary['Record_Count']) -first_name = details[2].text -# print(first_name) +members = [] -for name in root.iter('{Membership_MemberList_Extract}FirstName'): - print(name.text) -for name in root.iter(): - print(name.tag) +def append_contacts(collection): + '''Populates the contact and address dictionaries and then appends them to + a contacts list. + + Arguments: + contacts = The list the dictionary will be appended to. + ''' + contact = {} + address = {} + + contact['email_addresses'] = [collection[7].text] + contact['first_name'] = collection[2].text.title() + contact['last_name'] = collection[4].text.title() + contact['home_phone'] = collection[19][0].attrib + contact['custom_field 1'] = collection[26].text + + contact['addresses'] = [address] + + address['line1'] = collection[9].text + address['line2'] = collection[10].text + address['city'] = collection[11].text.title() + address['state_code'] = collection[12].text + address['postal_code'] = collection[13].text + + members.append(contact) + +for count in range(record_count): + append_contacts(collection[count]) + +print(members)
e598426d190fbe9ccd6a2f11e4fd75de6e749071
test_settings.py
test_settings.py
from gem.settings import * # noqa: F401, F403 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'gem_test.db', } } DEBUG = True CELERY_ALWAYS_EAGER = True STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
from gem.settings import * # noqa: F401, F403 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'gem_test.db', } } LOGGING = { 'version': 1, 'handlers': { 'console': { 'level': 'WARNING', 'class': 'logging.StreamHandler', }, }, } DEBUG = True CELERY_ALWAYS_EAGER = True STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
Set log level for test
Set log level for test When moving to Python 3 the logger starts putting out loads of DEBUG and INFO lines, but we only really care about WARNING.
Python
bsd-2-clause
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
--- +++ @@ -7,6 +7,16 @@ } } +LOGGING = { + 'version': 1, + 'handlers': { + 'console': { + 'level': 'WARNING', + 'class': 'logging.StreamHandler', + }, + }, +} + DEBUG = True CELERY_ALWAYS_EAGER = True
f6b40cbe9da0552b27b7c4c5d1a2d9bb0a75dafd
custom/icds_reports/permissions.py
custom/icds_reports/permissions.py
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) if icds_pre_release_features(request.couch_user): loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
from functools import wraps from django.http import HttpResponse from corehq.apps.locations.permissions import user_can_access_location_id from custom.icds_core.view_utils import icds_pre_release_features def can_access_location_data(view_fn): """ Decorator controlling a user's access to VIEW data for a specific location. """ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) loc_id = request.GET.get('location_id') def return_no_location_access_response(): return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), status=403) if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): return return_no_location_access_response() if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
Remove Feature flag from the location security check for dashboard
Remove Feature flag from the location security check for dashboard
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -13,14 +13,14 @@ @wraps(view_fn) def _inner(request, domain, *args, **kwargs): def call_view(): return view_fn(request, domain, *args, **kwargs) - if icds_pre_release_features(request.couch_user): - loc_id = request.GET.get('location_id') - def return_no_location_access_response(): - return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), - status=403) - if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): - return return_no_location_access_response() - if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): + loc_id = request.GET.get('location_id') + + def return_no_location_access_response(): + return HttpResponse('No access to the location {} for the logged in user'.format(loc_id), + status=403) + if not loc_id and not request.couch_user.has_permission(domain, 'access_all_locations'): + return return_no_location_access_response() + if loc_id and not user_can_access_location_id(domain, request.couch_user, loc_id): return return_no_location_access_response() return call_view() return _inner
62eea0104615b5d75183d5392fe250fa07d2a988
src/bulksms/config.py
src/bulksms/config.py
# BULKSMS Config. CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CLEAN_MOBILE_NUMBERS': False }
# BULKSMS Config. CONFIG = { 'BULK_SMS': { 'AUTH': { 'USERNAME': '', 'PASSWORD': '' }, 'URL': { 'SENDING': { { 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' } }, 'CREDITS': { 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' } } }, 'CLEAN_MOBILE_NUMBERS': False }
Add url for getting credits.
Add url for getting credits.
Python
mit
tsotetsi/django-bulksms
--- +++ @@ -6,8 +6,15 @@ 'PASSWORD': '' }, 'URL': { - 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', - 'BATCH': 'http://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' + 'SENDING': { + { + 'SINGLE': 'https://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0', + 'BATCH': 'https://bulksms.2way.co.za/eapi/submission/send_batch/1/1.0' + } + }, + 'CREDITS': { + 'CREDITS': 'https://bulksms.2way.co.za/user/get_credits/1/1.1' + } } }, 'CLEAN_MOBILE_NUMBERS': False