commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
5a09c6e9545373cece95f87ed28579f05959fced
tests/skip_check.py
tests/skip_check.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 __future__ import absolute_import, division, print_function import pytest def skip_check(name, iface, item): if name in item.keywords and item.funcargs.get('backend') is not None: if not isinstance(item.funcargs['backend'], iface): pytest.skip("Backend does not support {0}".format(name))
# 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 __future__ import absolute_import, division, print_function import pytest def skip_check(name, iface, item): if name in item.keywords and "backend" in item.funcargs: if not isinstance(item.funcargs["backend"], iface): pytest.skip("{0} backend does not support {1}".format( item.funcargs["backend"], name ))
Include teh name of the backend in the error message
Include teh name of the backend in the error message
Python
bsd-3-clause
Hasimir/cryptography,skeuomorf/cryptography,skeuomorf/cryptography,dstufft/cryptography,bwhmather/cryptography,skeuomorf/cryptography,Lukasa/cryptography,bwhmather/cryptography,Hasimir/cryptography,kimvais/cryptography,sholsapp/cryptography,Ayrx/cryptography,Hasimir/cryptography,sholsapp/cryptography,dstufft/cryptography,Lukasa/cryptography,sholsapp/cryptography,Ayrx/cryptography,dstufft/cryptography,dstufft/cryptography,bwhmather/cryptography,glyph/cryptography,bwhmather/cryptography,kimvais/cryptography,kimvais/cryptography,Ayrx/cryptography,dstufft/cryptography,glyph/cryptography,skeuomorf/cryptography,Lukasa/cryptography,kimvais/cryptography,sholsapp/cryptography,Ayrx/cryptography,Hasimir/cryptography
8e6aebf8cb96f5ccf4a119ab213c888a4c33a0d8
tests/testQuotas.py
tests/testQuotas.py
import json import os import sys sys.path.append('..') from skytap.Quotas import Quotas # noqa quotas = Quotas() def test_quota_count(): assert len(quotas) > 0 def test_quota_id(): for quota in quotas: assert len(quota.id) > 0 def test_quota_usage(): for quota in quotas: assert quota.usage > 0 def test_quota_units(): for quota in quotas: assert len(quota.units) > 0 def test_quota_limit(): for quota in quotas: if quota.limit is not None: assert quota.usage <= quota.limit assert quota.pct == quota.usage / quota.limit def test_quota_time(): for quota in quotas: if quota.units == 'hours': assert quota.time.seconds > 0 def test_quota_str_conversion(): for quota in quotas: assert len(str(quota)) > 0
# import json # import os # import sys # # sys.path.append('..') # from skytap.Quotas import Quotas # noqa # # quotas = Quotas() # # # def test_quota_count(): # assert len(quotas) > 0 # # # def test_quota_id(): # for quota in quotas: # assert len(quota.id) > 0 # # # def test_quota_usage(): # for quota in quotas: # assert quota.usage > 0 # # # def test_quota_units(): # for quota in quotas: # assert len(quota.units) > 0 # # # def test_quota_limit(): # for quota in quotas: # if quota.limit is not None: # assert quota.usage <= quota.limit # assert quota.pct == quota.usage / quota.limit # # # def test_quota_time(): # for quota in quotas: # if quota.units == 'hours': # assert quota.time.seconds > 0 # # # def test_quota_str_conversion(): # for quota in quotas: # assert len(str(quota)) > 0
Remove quota testing from notestest since API change == quotas broken
Remove quota testing from notestest since API change == quotas broken
Python
mit
FulcrumIT/skytap,mapledyne/skytap
737fa51dc31b315e554553fc5e3b971de663d0e5
blog/models.py
blog/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Post(models.Model): title = models.CharField(max_length=63) slug = models.SlugField() text = models.TextField() pub_date = models.DateField()
from django.db import models from organizer.models import Startup, Tag # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Post(models.Model): title = models.CharField(max_length=63) slug = models.SlugField() text = models.TextField() pub_date = models.DateField() tags = models.ManyToManyField(Tag) startups = models.ManyToManyField(Startup)
Define Post model related fields.
Ch03: Define Post model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#manytomanyfield Blog Posts may be about multiple Startups, just as Startups may be written about multiple times. Posts may also be categorized by multiple Tags, just as Tags may be used multiple times to categorize different Posts.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
64fb250967775c690e1ae6a7c43c562f4c94438b
tests/test_utils.py
tests/test_utils.py
from springfield_mongo.entities import Entity as MongoEntity from springfield_mongo import utils from springfield import fields from bson.objectid import ObjectId # This dummy class just used to have an extra attribute to verify during # using the utils class FooEntity(MongoEntity): foo = fields.StringField() def test_entity_to_mongo(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'monkey' mongo_document = utils.entity_to_mongo(m) assert '_id' in mongo_document assert mongo_document['_id'] == i assert 'foo' in mongo_document assert mongo_document['foo'] == 'monkey' def test_entity_from_mongo(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'gorilla' mongo_document = utils.entity_to_mongo(m) entity = utils.entity_from_mongo(FooEntity, mongo_document) assert '_id' not in entity assert 'id' in entity assert entity['id'] == i assert 'foo' in entity assert entity['foo'] == 'gorilla' def test_to_and_from_equality(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'giraffe' mongo_document = utils.entity_to_mongo(m) entity = utils.entity_from_mongo(FooEntity, mongo_document) assert m == entity mongo_document2 = utils.entity_to_mongo(entity) assert mongo_document2 == mongo_document
from springfield_mongo import utils from springfield_mongo.fields import ObjectIdField from springfield import fields from springfield import Entity from bson.objectid import ObjectId # This dummy class just used to have an extra attribute to verify during # using the utils class FooEntity(Entity): id = ObjectIdField() foo = fields.StringField() def test_entity_to_mongo(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'monkey' mongo_document = utils.entity_to_mongo(m) assert '_id' in mongo_document assert mongo_document['_id'] == i assert 'foo' in mongo_document assert mongo_document['foo'] == 'monkey' def test_entity_from_mongo(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'gorilla' mongo_document = utils.entity_to_mongo(m) entity = utils.entity_from_mongo(FooEntity, mongo_document) assert '_id' not in entity assert 'id' in entity assert entity['id'] == i assert 'foo' in entity assert entity['foo'] == 'gorilla' def test_to_and_from_equality(): i = ObjectId() m = FooEntity() m.id = i m.foo = 'giraffe' mongo_document = utils.entity_to_mongo(m) entity = utils.entity_from_mongo(FooEntity, mongo_document) assert m == entity mongo_document2 = utils.entity_to_mongo(entity) assert mongo_document2 == mongo_document
Update tests to reflect removal of springfield_mongo Entity.
Update tests to reflect removal of springfield_mongo Entity.
Python
mit
six8/springfield-mongo
fb08c6cfe6b6295a9aca9e579a067f34ee1c69c2
test/get-gh-comment-info.py
test/get-gh-comment-info.py
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() print(args.__dict__[args.retrieve])
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() # Update kernel_version to expected format args.kernel_version = args.kernel_version.replace('.', '') if args.kernel_version == "netnext": args.kernel_version = "net-next" print(args.__dict__[args.retrieve])
Format test-only's kernel_version to avoid mistakes
test: Format test-only's kernel_version to avoid mistakes I often try to start test-only builds with e.g.: test-only --kernel_version=4.19 --focus="..." That fails because our tests expect "419". We can extend the Python script used to parse argument to recognize that and update kernel_version to the expected format. Signed-off-by: Paul Chaignon <a027184a55211cd23e3f3094f1fdc728df5e0500@cilium.io>
Python
apache-2.0
cilium/cilium,tklauser/cilium,tgraf/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/cilium,tgraf/cilium,cilium/cilium,michi-covalent/cilium,tgraf/cilium,tgraf/cilium,michi-covalent/cilium,michi-covalent/cilium,tgraf/cilium,cilium/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/cilium,tgraf/cilium
4fc109c93daa3a5d39a184cd692ac7c6b19b9fab
simpleflow/swf/process/worker/dispatch/dynamic_dispatcher.py
simpleflow/swf/process/worker/dispatch/dynamic_dispatcher.py
# -*- coding: utf-8 -*- import importlib from simpleflow.activity import Activity from .exceptions import DispatchError class Dispatcher(object): """ Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher but without a hierarchy. """ @staticmethod def dispatch_activity(name): """ :param name: :type name: str :return: :rtype: Activity :raise DispatchError: if doesn't exist or not an activity """ module_name, activity_name = name.rsplit('.', 1) module = importlib.import_module(module_name) activity = getattr(module, activity_name, None) if not activity: raise DispatchError("unable to import '{}'".format(name)) if not isinstance(activity, Activity): activity = Activity(activity, activity_name) return activity
# -*- coding: utf-8 -*- import importlib from simpleflow.activity import Activity from .exceptions import DispatchError class Dispatcher(object): """ Dispatch by name, like simpleflow.swf.process.worker.dispatch.by_module.ModuleDispatcher but without a hierarchy. """ @staticmethod def dispatch_activity(name): """ :param name: :type name: str :return: :rtype: Activity :raise DispatchError: if doesn't exist or not an activity """ module_name, activity_name = name.rsplit('.', 1) module = importlib.import_module(module_name) activity = getattr(module, activity_name, None) if not activity: # We were not able to import a function at all. raise DispatchError("unable to import '{}'".format(name)) if not isinstance(activity, Activity): # We managed to import a function (or callable) but it's not an # "Activity". We will transform it into an Activity now. That way # we can accept functions that are *not* decorated with # "@activity.with_attributes()" or equivalent. This dispatcher is # used in the context of an activity worker, so we don't actually # care if the task is decorated or not. We only need the decorated # function for the decider (options to schedule, retry, fail, etc.). activity = Activity(activity, activity_name) return activity
Add comment to explain the choice in dynamic dispatcher
Add comment to explain the choice in dynamic dispatcher
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
85897c2bf4e4e9c89db6111894879d18fef577dd
app.tmpl/__init__.py
app.tmpl/__init__.py
# Main application file # # Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com> from flask import Flask app = Flask(__name__) # Import anything that depended on `app` from {{PROJECTNAME}}.views import * from {{PROJECTNAME}}.models import *
# Main application file # # Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com> from flask import Flask from flask_login import LoginManager app = Flask(__name__) app.secret_key = 'default-secret-key' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' # Import anything that depended on `app` from {{PROJECTNAME}}.views import * from {{PROJECTNAME}}.models import *
Use the login manager and set a default app secret key
Use the login manager and set a default app secret key
Python
mit
0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template
4f45e55e5b0e14cf6bf32b42a14cbdf9b3c08258
dbus_notify.py
dbus_notify.py
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 if is_string(icon): # File path icon_file = icon else: icon_file = "" # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
from cgi import escape import dbus from utils import is_string ITEM = "org.freedesktop.Notifications" PATH = "/org/freedesktop/Notifications" INTERFACE = "org.freedesktop.Notifications" APP_NAME = "mpd-hiss" def dbus_raw_image(im): """Convert image for DBUS""" raw = im.tobytes("raw", "RGBA") alpha, bps, channels = 0, 8, 4 stride = channels * im.size[0] return (im.size[0], im.size[1], stride, alpha, bps, channels, dbus.ByteArray(raw)) def native_load_image(image): return image def notify(title, description, icon): actions = "" hint = {"suppress-sound": True, "urgency": 0} time = 5000 icon_file = "" if is_string(icon): # File path icon_file = icon elif icon: # Not all notifiers support this # Some require "icon" and an image on disk hint["icon_data"] = dbus_raw_image(icon) bus = dbus.SessionBus() notif = bus.get_object(ITEM, PATH) notify = dbus.Interface(notif, INTERFACE) notify.Notify(APP_NAME, 1, icon_file, title, escape(description), actions, hint, time)
Make sure we do not try to convert None
Make sure we do not try to convert None
Python
cc0-1.0
hellhovnd/mpd-hiss,ahihi/mpd-hiss
6b4ec52a3fa6fdbb4f70f9d24904bc978341150c
nagare/admin/info.py
nagare/admin/info.py
#-- # Copyright (c) 2008, 2009 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- """The ``info`` administrative command Display informations about the framework environment """ import sys from nagare.admin import util class Info(util.Command): """Display informations about the framework environment""" desc = 'Display various informations' @staticmethod def run(parser, options, args): """Display the informations In: - ``parser`` -- the optparse.OptParser object used to parse the configuration file - ``options`` -- options in the command lines - ``args`` -- arguments in the command lines """ # For the moment, just diplay the Python version print sys.version
#-- # Copyright (c) 2008, 2009 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- """The ``info`` administrative command Display informations about the framework environment """ import sys, pkg_resources from nagare.admin import util class Info(util.Command): """Display informations about the framework environment""" desc = 'Display various informations' @staticmethod def run(parser, options, args): """Display the informations In: - ``parser`` -- the optparse.OptParser object used to parse the configuration file - ``options`` -- options in the command lines - ``args`` -- arguments in the command lines """ # For the moment, just diplay the Python version print sys.version print print 'Nagare version', pkg_resources.get_distribution('nagare').version
Print the Nagare version number
Print the Nagare version number --HG-- extra : convert_revision : svn%3Afc25bd86-f976-46a1-be41-59ef0291ea8c/trunk%4076
Python
bsd-3-clause
nagareproject/core,nagareproject/core
9fffcafca0f611cfcbbf3e80435c250f43a0c68b
tests/dataretrival_tests.py
tests/dataretrival_tests.py
import unittest from bluefin.dataretrieval.clients import V1Client from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException from tests.api_details import API_DETAILS, TEST_CARD class TransactionReportingTest(unittest.TestCase): """ Tests for transaction reporting API calls. """ def test_basic(self): """ Test a basic successful API call. """ api = V1Client() api.send_request({ 'transactions_after': '2006-12-30', 'account_id': API_DETAILS['account_id'], 'authorization': 'qRdNQK0lkc7vwHP2h6mm', }) def test_no_input(self): api = V1Client() self.assertRaises(V1ClientInputException, api.send_request, {})
import unittest from bluefin.dataretrieval.clients import V1Client from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException from tests.api_details import API_DETAILS, TEST_CARD class TransactionReportingTest(unittest.TestCase): """ Tests for transaction reporting API calls. """ def test_basic(self): """ Test a basic successful API call. """ api = V1Client() result = api.send_request({ 'transactions_after': '2006-12-30', 'account_id': API_DETAILS['account_id'], 'authorization': 'LIGONIER_DOT_ORG', }) print result def test_no_input(self): api = V1Client() self.assertRaises(V1ClientInputException, api.send_request, {})
Use the new auth keyword set by Ligonier. We're working now.
Use the new auth keyword set by Ligonier. We're working now.
Python
bsd-3-clause
duointeractive/python-bluefin
60a10e8fbfd40197db8226f0791c7064c80fe370
run.py
run.py
import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--run', action="store_true") parser.add_argument('--deploy', action="store_true") args = parser.parse_args() if not any(vars(args).values()): parser.print_help() elif args.run: os.system("ENVIRONMENT=development python server.py") elif args.deploy: os.system("git push heroku master")
import sys import os import argparse import shutil from efselab import build parser = argparse.ArgumentParser() parser.add_argument('--run', action="store_true") parser.add_argument('--deploy', action="store_true") parser.add_argument('--update', action="store_true") args = parser.parse_args() if not any(vars(args).values()): parser.print_help() elif args.run: os.system("ENVIRONMENT=development python server.py") elif args.deploy: os.system("git push heroku master") elif args.update: if not os.path.exists("../efselab/"): sys.exit("Couldn't find a local efselab checkout...") shutil.copy("../efselab/fasthash.c", "./efselab") shutil.copy("../efselab/lemmatize.c", "./efselab") shutil.copy("../efselab/pysuc.c", "./efselab/suc.c") if not os.path.exists("../efselab/swe-pipeline"): sys.exit("Couldn't find a local swe-pipeline directory for models...") shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab") shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab") print("Building new files...") os.chdir("efselab") build.main()
Add new update command that updates efselab dependencies.
Add new update command that updates efselab dependencies. Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7
Python
mit
EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger
073dd8529c95f44d7d250508dd10b8ffc8208926
two_factor/migrations/0003_auto_20150817_1733.py
two_factor/migrations/0003_auto_20150817_1733.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import two_factor.models class Migration(migrations.Migration): dependencies = [ ('two_factor', '0002_auto_20150110_0810'), ] operations = [ migrations.AlterField( model_name='phonedevice', name='number', field=two_factor.models.PhoneNumberField(max_length=16, verbose_name='number'), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.db import models, migrations import phonenumbers import two_factor.models logger = logging.getLogger(__name__) def migrate_phone_numbers(apps, schema_editor): PhoneDevice = apps.get_model("two_factor", "PhoneDevice") for device in PhoneDevice.objects.all(): try: number = phonenumbers.parse(device.number) if not phonenumbers.is_valid_number(number): logger.info("User '%s' has an invalid phone number '%s'." % (device.user.username, device.number)) device.number = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) device.save() except phonenumbers.NumberParseException as e: # Do not modify/delete the device, as it worked before. However this might result in issues elsewhere, # so do log a warning. logger.warning("User '%s' has an invalid phone number '%s': %s. Please resolve this issue, " "as it might result in errors." % (device.user.username, device.number, e)) class Migration(migrations.Migration): dependencies = [ ('two_factor', '0002_auto_20150110_0810'), ] operations = [ migrations.RunPython(migrate_phone_numbers, reverse_code=lambda apps, schema_editor: None), migrations.AlterField( model_name='phonedevice', name='number', field=two_factor.models.PhoneNumberField(max_length=16, verbose_name='number'), ), ]
Migrate phone numbers to E.164 format
Migrate phone numbers to E.164 format
Python
mit
koleror/django-two-factor-auth,Bouke/django-two-factor-auth,koleror/django-two-factor-auth,Bouke/django-two-factor-auth
ac664513eb1e99bc7aad9dda70a155e25fcff084
tests/services/shop/order/test_models_order_payment_state.py
tests/services/shop/order/test_models_order_payment_state.py
""" :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import PaymentState from testfixtures.shop_order import create_order from testfixtures.user import create_user def test_is_open(): payment_state = PaymentState.open order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == True assert order.is_canceled == False assert order.is_paid == False def test_is_open(): payment_state = PaymentState.canceled order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == True assert order.is_paid == False def test_is_open(): payment_state = PaymentState.paid order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == False assert order.is_paid == True # helpers def create_order_with_payment_state(payment_state): user = create_user(42) party_id = 'acme-party-2016' placed_by = user order = create_order(party_id, placed_by) order.payment_state = payment_state return order
""" :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import PaymentState from testfixtures.shop_order import create_order from testfixtures.user import create_user def test_is_open(): payment_state = PaymentState.open order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == True assert order.is_canceled == False assert order.is_paid == False def test_is_canceled(): payment_state = PaymentState.canceled order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == True assert order.is_paid == False def test_is_paid(): payment_state = PaymentState.paid order = create_order_with_payment_state(payment_state) assert order.payment_state == payment_state assert order.is_open == False assert order.is_canceled == False assert order.is_paid == True # helpers def create_order_with_payment_state(payment_state): user = create_user(42) party_id = 'acme-party-2016' placed_by = user order = create_order(party_id, placed_by) order.payment_state = payment_state return order
Fix overshadowed tests by giving test functions unique names
Fix overshadowed tests by giving test functions unique names
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
9545c2d78696d7f75299d958cf44f8cf695581ac
DGEclust/readCountData.py
DGEclust/readCountData.py
## Copyright (C) 2012-2013 Dimitrios V. Vavoulis ## Computational Genomics Group (http://bioinformatics.bris.ac.uk/) ## Department of Computer Science ## University of Bristol ################################################################################ import numpy as np import pandas as pd ################################################################################ def readCountData(fname, classes = None, *args, **kargs): df = pd.read_table(fname, *args, **kargs) ## add attributes df.counts = df.values df.exposures = df.sum() / df.sum().astype('double') #df.sum() / df.sum().max().astype('double') df.samples = df.columns df.genes = df.index ## classes if classes is None: df.classes = np.arange(df.samples.size).astype('str') else: df.classes = classes return df ################################################################################
## Copyright (C) 2012-2013 Dimitrios V. Vavoulis ## Computational Genomics Group (http://bioinformatics.bris.ac.uk/) ## Department of Computer Science ## University of Bristol ################################################################################ import numpy as np import pandas as pd ################################################################################ def readCountData(fname, classes = None, *args, **kargs): df = pd.read_table(fname, *args, **kargs) ## add attributes df.counts = df.values df.exposures = df.sum() / df.sum().max().astype('double') df.samples = df.columns df.genes = df.index ## classes if classes is None: df.classes = np.arange(df.samples.size).astype('str') else: df.classes = classes return df ################################################################################
Normalize by the size of the library
Normalize by the size of the library
Python
mit
dvav/dgeclust
6c31af53cdc16d9f9cb3b643e9d7f0fee14cbc85
__main__.py
__main__.py
#--coding:utf-8-- from __init__ import * import json import Queue open('Chinese.bak.json', 'ab').write('[') open('Foreigner.bak.json', 'ab').write('[') open('Student.bak.json', 'ab').write('[') Output = open('result.json', 'wb') TaskQueue = Queue.Queue(maxsize = 0) downloader = Downloader(TaskQueue) downloader.start() colony = Colony(Spider, InfoExtracter, Output, TaskQueue, json.load(open('RegularExpression.json')), './Icon') colony.Push(('thelyad', 'username', )) colony.Push(('100000965387047', 'uid', )) colony.SpiderInit() try: print "Info: Start Colony.Manage()" colony.Manage() finally: colony.End() downloader.stop()
#--coding:utf-8-- from __init__ import * import json import Queue open('Chinese.bak.json', 'ab').write('[') open('Foreigner.bak.json', 'ab').write('[') open('Student.bak.json', 'ab').write('[') Output = open('result.json', 'wb') TaskQueue = Queue.Queue(maxsize = 0) downloader = Downloader(TaskQueue) downloader.start() colony = Colony(Spider, InfoExtracter, Output, TaskQueue, json.load(open('RegularExpression.json')), './Icon') colony.Push(('thelyad', 'username', )) colony.Push(('100000965387047', 'uid', )) colony.SpiderInit() try: print "Info: Start Colony.Manage()" colony.Manage() except KeyboardInterrupt: pass
Fix Bugs: Cannot Backup Scan Task Queue
Fix Bugs: Cannot Backup Scan Task Queue
Python
mit
nday-dev/FbSpider
e19cee4b47d296967286a7f065f363f1e64e58f6
linter.py
linter.py
from SublimeLinter.lint import PythonLinter class Pyflakes(PythonLinter): cmd = 'pyflakes' regex = r'''(?x) ^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s # The rest of the line is the error message. # Within that, capture anything within single quotes as `near`. (?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*) ''' multiline = True # stderr has all syntax errors, parse it via our regex on_stderr = None defaults = { 'selector': 'source.python' }
from SublimeLinter.lint import PythonLinter import re class Pyflakes(PythonLinter): cmd = 'pyflakes' regex = r'''(?x) ^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s # The rest of the line is the error message. # Within that, capture anything within single quotes as `near`. (?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*) ''' multiline = True # stderr has all syntax errors, parse it via our regex on_stderr = None defaults = { 'selector': 'source.python' } def reposition_match(self, line, col, match, vv): if 'imported but unused' in match.message: # Consider: # from foo import bar # import foo.bar # In both cases `pyflakes` reports `'foo.bar' ... unused`. import_id = re.escape(match.near[1:-1]) # unquote last_part = import_id.split('.')[-1] # So we match either `bar` or `foo.bar` against the line content text = vv.select_line(line) pattern = r"\s({}|{})".format(last_part, import_id) match = re.search(pattern, text) if match: return line, match.start(1), match.end(1) return super().reposition_match(line, col, match, vv)
Improve col reporting for unused imports
Improve col reporting for unused imports
Python
mit
SublimeLinter/SublimeLinter-pyflakes
aac08ae7dbfa8542210664922b8857de0b185b6f
apps/bluebottle_utils/tests.py
apps/bluebottle_utils/tests.py
import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ # If no username is set, create a random unique username while not username or User.objects.filter(username=username).exists(): # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user
import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ def generate_username(): return str(uuid.uuid4())[:30] # If username is set and not unique, it will raise a clearly # interpretable IntegrityError. # If auto-generated, make sure it's unique. if not username: username = generate_username() while User.objects.filter(username=username).exists(): username = generate_username() user = User.objects.create_user(username=username) return user
Fix bug in username uniqueness.
Fix bug in username uniqueness.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
d49d383c62233036d4195d71ba4fda78ff2278de
distarray/core/tests/test_distributed_array_protocol.py
distarray/core/tests/test_distributed_array_protocol.py
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTest('Must run with comm size > 4.') else: self.arr = da.LocalArray((16,16), grid_shape=(4,), comm=comm, buf=None, offset=0) def test_export(self): self.assertIsInstance(self.arr, da.LocalArray) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTest('Must run with comm size > 4.') else: self.arr = da.LocalArray((16,16), grid_shape=(4,), comm=comm, buf=None, offset=0) def test_has_export(self): self.assertTrue(hasattr(self.arr, '__distarray__')) def test_well_formedness(self): required_keys = set(("buffer", "dimdata")) export = self.arr.__distarray__() exported_keys = set(export.keys()) self.assertEqual(required_keys, exported_keys) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
Improve basic checks of distarray export.
Improve basic checks of distarray export.
Python
bsd-3-clause
enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray
bc78bf85442b0ffb7962a1c9c4a3560a0fd1960d
skimage/io/_plugins/matplotlib_plugin.py
skimage/io/_plugins/matplotlib_plugin.py
import matplotlib.pyplot as plt def imshow(*args, **kwargs): kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') plt.imshow(*args, **kwargs) imread = plt.imread show = plt.show def _app_show(): show()
import matplotlib.pyplot as plt def imshow(*args, **kwargs): if plt.gca().has_data(): plt.figure() kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') plt.imshow(*args, **kwargs) imread = plt.imread show = plt.show def _app_show(): show()
Create a new figure for imshow if there is already data
Create a new figure for imshow if there is already data
Python
bsd-3-clause
keflavich/scikit-image,GaZ3ll3/scikit-image,pratapvardhan/scikit-image,jwiggins/scikit-image,oew1v07/scikit-image,robintw/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,paalge/scikit-image,paalge/scikit-image,michaelaye/scikit-image,warmspringwinds/scikit-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,dpshelio/scikit-image,blink1073/scikit-image,Britefury/scikit-image,bsipocz/scikit-image,youprofit/scikit-image,ofgulban/scikit-image,warmspringwinds/scikit-image,robintw/scikit-image,paalge/scikit-image,keflavich/scikit-image,ofgulban/scikit-image,bennlich/scikit-image,ClinicalGraphics/scikit-image,newville/scikit-image,ClinicalGraphics/scikit-image,Midafi/scikit-image,ajaybhat/scikit-image,juliusbierk/scikit-image,juliusbierk/scikit-image,bsipocz/scikit-image,Britefury/scikit-image,oew1v07/scikit-image,Midafi/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,rjeli/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,michaelpacer/scikit-image,ajaybhat/scikit-image,dpshelio/scikit-image,newville/scikit-image,vighneshbirodkar/scikit-image,pratapvardhan/scikit-image,chriscrosscutler/scikit-image,youprofit/scikit-image,emon10005/scikit-image,blink1073/scikit-image,rjeli/scikit-image,Hiyorimi/scikit-image,bennlich/scikit-image,michaelpacer/scikit-image,jwiggins/scikit-image
7b9b1a7bb7f9e48e466bd00b3edffc67be841b4e
pavement.py
pavement.py
import os.path from paver.easy import sh, task config = """# replace pass with values you would like to overwrite from DefaultConfig in # default_config.py. Values you do not explicitly overwrite will be inherited # from DefaultConfig. At the very least, you must set secret_key and # tmdb_api_key. from default_config import DefaultConfig class Config(DefaultConfig): pass """ @task def setup(): """Writes a default config to config.py""" if not os.path.isfile('config.py'): print('Writing default config.') f = open('config.py', 'w') f.write(config) f.close() else: print('Config file already exists, will not overwrite.') @task def lint(): """Checks code quality using flake8""" sh("flake8 --max-line-length=120 --max-complexity=10 .") @task def run_tests(): """Run unit tests""" sh("./manage.py test") @task def check_source(): """Identify any potential problems with code""" sh("./manage.py check") @task def inspect(): """Inspects project source for a variety of problems""" lint() check_source() run_tests()
import os.path import shutil from paver.easy import sh, task config = """# replace pass with values you would like to overwrite from DefaultConfig in # default_config.py. Values you do not explicitly overwrite will be inherited # from DefaultConfig. At the very least, you must set secret_key and # tmdb_api_key. from default_config import DefaultConfig class Config(DefaultConfig): pass """ @task def apply_hooks(): """Copies hooks from git_hooks folder into .git/hooks""" os.chdir('git_hooks') for item in os.listdir('.'): if os.path.isfile(item): print('Applying hook: ' + item) shutil.copyfile(item, '../.git/hooks/' + item) @task def make_hooks_executable(): os.chdir('.git/hooks') for item in os.listdir('.'): if os.path.isfile(item): sh("chmod +x " + item) @task def setup(): """Writes a default config to config.py""" if not os.path.isfile('config.py'): print('Writing default config.') f = open('config.py', 'w') f.write(config) f.close() else: print('Config file already exists, will not overwrite.') @task def lint(): """Checks code quality using flake8""" sh("flake8 --max-line-length=120 --max-complexity=10 .") @task def run_tests(): """Run unit tests""" sh("./manage.py test") @task def check_source(): """Identify any potential problems with code""" sh("./manage.py check") @task def inspect(): """Inspects project source for a variety of problems""" lint() check_source() run_tests()
Add some git hook related tasks to paver file
Add some git hook related tasks to paver file
Python
mit
simon-andrews/movieman2,simon-andrews/movieman2
1c3bffed864fab3163244486441f08fba00b1a65
fireplace/cards/gvg/warlock.py
fireplace/cards/gvg/warlock.py
from ..utils import * ## # Minions # Mistress of Pain class GVG_018: events = [ Damage().on( lambda self, source, target, amount: source is self and [Heal(FRIENDLY_HERO, amount)] or [] ) ] # Fel Cannon class GVG_020: events = [ OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2)) ] # Anima Golem class GVG_077: events = [ TURN_END.on( lambda self, player: self.controller.field != [self] and [Destroy(SELF)] or [] ) ] # Floating Watcher class GVG_100: events = [ Damage(FRIENDLY_HERO).on( lambda self, target, amount, source: self.controller.current_player and [Buff(SELF, "GVG_100e")] or [] ) ] ## # Spells # Darkbomb class GVG_015: action = [Hit(TARGET, 3)] # Demonheart class GVG_019: def action(self, target): if target.controller == self.controller and target.race == Race.DEMON: return [Buff(TARGET, "GVG_019e")] else: return [Hit(TARGET, 5)]
from ..utils import * ## # Minions # Mistress of Pain class GVG_018: events = [ Damage().on( lambda self, target, amount, source: source is self and [Heal(FRIENDLY_HERO, amount)] or [] ) ] # Fel Cannon class GVG_020: events = [ OWN_TURN_END.on(Hit(RANDOM(ALL_MINIONS - MECH), 2)) ] # Anima Golem class GVG_077: events = [ TURN_END.on( lambda self, player: self.controller.field != [self] and [Destroy(SELF)] or [] ) ] # Floating Watcher class GVG_100: events = [ Damage(FRIENDLY_HERO).on( lambda self, target, amount, source: self.controller.current_player and [Buff(SELF, "GVG_100e")] or [] ) ] ## # Spells # Darkbomb class GVG_015: action = [Hit(TARGET, 3)] # Demonheart class GVG_019: def action(self, target): if target.controller == self.controller and target.race == Race.DEMON: return [Buff(TARGET, "GVG_019e")] else: return [Hit(TARGET, 5)]
Fix argument ordering in Mistress of Pain
Fix argument ordering in Mistress of Pain Fixes #71
Python
agpl-3.0
amw2104/fireplace,smallnamespace/fireplace,liujimj/fireplace,Meerkov/fireplace,NightKev/fireplace,oftc-ftw/fireplace,butozerca/fireplace,jleclanche/fireplace,Ragowit/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,butozerca/fireplace,Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,smallnamespace/fireplace
843b4c4c0ec7176f4b60fc9d39e7a033c2d4ef7d
utils/crypto.py
utils/crypto.py
import hashlib import os import string import random from django.conf import settings def hasher(string): '''Helper method to hash a string to SHA512''' h = hashlib.sha512(settings.SECRET_KEY + string).hexdigest() for _ in range(settings.HASH_PASSES): h = hashlib.sha512(h).hexdigest() return h def get_random_string(length, set=string.ascii_letters+string.digits): '''Gets a random string''' return ''.join(random.choice(set) for _ in range(length))
import hashlib import os import string import random from django.conf import settings def hasher(string): '''Helper method to hash a string to SHA512''' h = hashlib.sha512(settings.SECRET_KEY + string.encode("utf-8")).hexdigest() for _ in range(settings.HASH_PASSES): h = hashlib.sha512(h).hexdigest() return h def get_random_string(length, set=string.ascii_letters+string.digits): '''Gets a random string''' return ''.join(random.choice(set) for _ in range(length))
Make the password hashing unicode safe.
Make the password hashing unicode safe.
Python
bsd-3-clause
AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker
7403e79c9e3cccc7ea97e61915ec01c2176c0f57
tests/test_heroku.py
tests/test_heroku.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import mock from dallinger.config import get_config from dallinger.heroku import app_name class TestHeroku(object): def test_heroku_app_name(self): id = "8fbe62f5-2e33-4274-8aeb-40fc3dd621a0" assert(len(app_name(id)) < 30) class TestHerokuClock(object): def test_check_db_for_missing_notifications_assembles_resources(self): os.chdir('tests/experiment') config = get_config() if not config.ready: config.load_config() # Can't import until after config is loaded: from dallinger.heroku.clock import check_db_for_missing_notifications runner = 'dallinger.heroku.clock._run_notifications_check' with mock.patch(runner) as mock_runner: check_db_for_missing_notifications() mock_runner.assert_called()
#!/usr/bin/python # -*- coding: utf-8 -*- import os import mock import pytest import dallinger.db from dallinger.config import get_config from dallinger.heroku import app_name @pytest.fixture def setup(): db = dallinger.db.init_db(drop_all=True) os.chdir('tests/experiment') config = get_config() if not config.ready: config.load_config() yield config db.rollback() db.close() os.chdir('../..') class TestHeroku(object): def test_heroku_app_name(self): id = "8fbe62f5-2e33-4274-8aeb-40fc3dd621a0" assert(len(app_name(id)) < 30) class TestHerokuClock(object): def test_check_db_for_missing_notifications_assembles_resources(self, setup): # Can't import until after config is loaded: from dallinger.heroku.clock import check_db_for_missing_notifications with mock.patch.multiple('dallinger.heroku.clock', _run_notifications_check=mock.DEFAULT, MTurkConnection=mock.DEFAULT) as mocks: mocks['MTurkConnection'].return_value = 'fake connection' check_db_for_missing_notifications() mocks['_run_notifications_check'].assert_called()
Allow test to run without MTurk/AWS credentials configured, and defend against other tests which don’t clean up database
Allow test to run without MTurk/AWS credentials configured, and defend against other tests which don’t clean up database
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger
c1a38cb5fd2f6dd0f81515bece18a47f2b20234b
data_record.py
data_record.py
class DataRecord: @classmethod def get_store( cls ): if hasattr( cls, 'store' ): return cls.store cls.store = {} return cls.store @classmethod def find( cls, record_id ): return cls.get_store().get( record_id, None ) @classmethod def save( cls, record_id, record ): cls.get_store()[ record_id ] = record @classmethod def create_or_update( cls, record_id, **kwargs ): found_record = cls.find( record_id ) if found_record is not None: for name, value in kwargs.items(): setattr( found_record, name, value ) return found_record return cls( record_id, **kwargs ) def __init__( self, record_id ): self.record_id = record_id self.__class__.save( record_id, self )
class DataRecord: @classmethod def get_store( cls ): if hasattr( cls, 'store' ): return cls.store cls.store = {} return cls.store @classmethod def find( cls, record_id ): return cls.get_store().get( str(record_id), None ) @classmethod def save( cls, record_id, record ): cls.get_store()[ str(record_id) ] = record @classmethod def create_or_update( cls, record_id, **kwargs ): found_record = cls.find( str(record_id) ) if found_record is not None: for name, value in kwargs.items(): setattr( found_record, name, value ) return found_record return cls( str(record_id), **kwargs ) def __init__( self, record_id ): self.record_id = str(record_id) self.__class__.save( str(record_id), self )
Make all data records store record id keys as strings
Make all data records store record id keys as strings
Python
mit
fire-uta/iiix-data-parser
5780f72ff95329295c735fff61463315ec3856d7
manage.py
manage.py
#!/usr/bin/env python # This manage.py exists for the purpose of creating migrations import sys import django from django.conf import settings settings.configure( ROOT_URLCONF='', DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', }}, PAYPAL_RECEIVER_EMAIL='', PAYPAL_IDENTITY_TOKEN='', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'paypal.pro', 'paypal.standard', 'paypal.standard.ipn', 'paypal.standard.pdt', ] + (['south'] if django.VERSION < (1,7) else []), CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'TIMEOUT': 0, 'KEY_PREFIX': 'paypal_tests_', } }, MIDDLEWARE_CLASSES=[], ) from django.core.management import execute_from_command_line if __name__ == '__main__': execute_from_command_line(sys.argv)
#!/usr/bin/env python # This manage.py exists for the purpose of creating migrations import sys import django from django.conf import settings settings.configure( ROOT_URLCONF='', DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', }}, PAYPAL_RECEIVER_EMAIL='', PAYPAL_IDENTITY_TOKEN='', INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'paypal.pro', 'paypal.standard', 'paypal.standard.ipn', 'paypal.standard.pdt', ], CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'TIMEOUT': 0, 'KEY_PREFIX': 'paypal_tests_', } }, MIDDLEWARE_CLASSES=[], ) from django.core.management import execute_from_command_line if __name__ == '__main__': execute_from_command_line(sys.argv)
Remove stupid South thing that is messing up Heroku
Remove stupid South thing that is messing up Heroku remove, I say!!
Python
mit
millanp/django-paypal,millanp/django-paypal
b363b0ffc9e4fd7790f418f84107c3b7233642f1
zou/app/utils/chats.py
zou/app/utils/chats.py
from slackclient import SlackClient def send_to_slack(app_token, userid, message): client = SlackClient(token=app_token) client.api_call( "chat.postMessage", channel="@%s" % userid, text=message, as_user=True ) return True
from slackclient import SlackClient def send_to_slack(app_token, userid, message): client = SlackClient(token=app_token) blocks = [ { "type": "section", "text": { "type": "mrkdwn", "text": message, } }, ] client.api_call( "chat.postMessage", channel="@%s" % userid, blocks=blocks, as_user=True ) return True
Allow to format messages sent to Slack
Allow to format messages sent to Slack
Python
agpl-3.0
cgwire/zou
cd2b628ca118ffae8090004e845e399110aada21
disk/datadog_checks/disk/__init__.py
disk/datadog_checks/disk/__init__.py
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from .disk import Disk __all__ = ['Disk']
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from .__about__ import __version__ from .disk import Disk all = [ '__version__', 'Disk' ]
Allow Agent to properly pull version info
[Disk] Allow Agent to properly pull version info
Python
bsd-3-clause
DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core
06c3e03db75617b824eae088053a9fc563b936a7
virtool/user_permissions.py
virtool/user_permissions.py
#: A list of the permission strings used by Virtool. PERMISSIONS = [ "cancel_job", "create_sample", "create_subtraction", "manage_users", "modify_hmm", "modify_options", "modify_virus", "rebuild_index", "remove_job", "remove_virus" ]
#: A list of the permission strings used by Virtool. PERMISSIONS = [ "cancel_job", "create_sample", "manage_users", "modify_hmm", "modify_options", "modify_subtraction", "modify_virus", "rebuild_index", "remove_job", "remove_virus" ]
Change create_subtraction permission to modify_subtraction
Change create_subtraction permission to modify_subtraction
Python
mit
virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool
1424ce565ee8b47e6a9a3bc143589c7e7e0c3e53
cloudenvy/commands/envy_scp.py
cloudenvy/commands/envy_scp.py
import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source') subparser.add_argument('target') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.')
import logging import fabric.api import fabric.operations from cloudenvy.envy import Envy class EnvySCP(object): """SCP Files to your ENVy""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('scp', help='scp help') subparser.set_defaults(func=self.run) subparser.add_argument('source', help='Local path to copy into your ENVy.') subparser.add_argument('target', help='Location in your ENVy to place file(s). Non-absolute ' 'paths are interpreted relative to remote_user homedir.') subparser.add_argument('-n', '--name', action='store', default='', help='specify custom name for an ENVy') return subparser def run(self, config, args): envy = Envy(config) if envy.ip(): host_string = '%s@%s' % (envy.remote_user, envy.ip()) with fabric.api.settings(host_string=host_string): fabric.operations.put(args.source, args.target) else: logging.error('Could not find IP to upload file to.')
Document source and target arguments of envy scp
Document source and target arguments of envy scp Fix issue #67
Python
apache-2.0
cloudenvy/cloudenvy
901e6cc8bdafcd6e6d419ffd5eee4e58d266d40a
extensions.py
extensions.py
import subprocess from functools import wraps import os extensions = {} def extension(f): # keep unwrapped function unwrapped = f @wraps(f) def wrapper(**kwargs): wrapper.settings = dict(kwargs) return unwrapped extensions[f.__name__] = wrapper return wrapper @extension def coffee(filename, data): command = ['coffee', '-c', '-s'] bare = coffee.settings.get('bare') if bare: command.append('-b') process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate(data) if process.returncode: return None, err else: _, ext = os.path.splitext(filename) dest = filename.replace(ext, '.js') return dest, out @extension def dest(filename, data): destination = dest.settings.get('destination') if destination: filename = os.path.join(destination, tail) fo = open(filename, 'w') fo.write(data) fo.close()
import subprocess from functools import wraps import os extensions = {} def extension(f): # keep unwrapped function unwrapped = f @wraps(f) def wrapper(**kwargs): wrapper.settings = dict(kwargs) return unwrapped extensions[f.__name__] = wrapper return wrapper @extension def coffee(filename, data): command = ['coffee', '-c', '-s'] bare = coffee.settings.get('bare') if bare: command.append('-b') process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate(data) if process.returncode: return None, err else: _, ext = os.path.splitext(filename) dest = filename.replace(ext, '.js') return dest, out @extension def dest(filename, data): destination = dest.settings.get('destination') if destination: if not os.path.exists(destination): os.mkdir(destination) _, tail = os.path.split(filename) filename = os.path.join(destination, tail) fo = open(filename, 'w') fo.write(data) fo.close()
Fix file not found error on directory
Fix file not found error on directory
Python
mit
rolurq/flask-gulp
aca3cf45ba32cdad69c232794497fc8033b63cc6
utils/builder.py
utils/builder.py
import sys import os output = '../build/Tween.js'; # os.system("java -jar yuicompressor-2.4.2.jar ../src/Tween.js -o ../build/Tween.js --charset utf-8 -v"); os.system("java -jar compiler.jar --js ../src/Tween.js --js_output_file ../build/Tween.js") # HEADER string = "// Tween.js - http://github.com/sole/tween.js\n" src_file = open(output,'r') string += src_file.read() dep_file = open(output,'w') dep_file.write(string) dep_file.close()
import sys import os output = '../build/tween.js'; # os.system("java -jar yuicompressor-2.4.2.jar ../src/Tween.js -o ../build/Tween.js --charset utf-8 -v"); os.system("java -jar compiler.jar --js ../src/Tween.js --js_output_file %s" % (output)) # HEADER with open(os.path.join('..', 'REVISION'), 'r') as handle: revision = handle.read().rstrip() string = "// tween.js r%s - http://github.com/sole/tween.js\n" % (revision) src_file = open(output,'r') string += src_file.read() dep_file = open(output,'w') dep_file.write(string) dep_file.close()
Update packer system to include REVISION number too
Update packer system to include REVISION number too
Python
mit
CasualBot/tween.js,JITBALJINDER/tween.js,altereagle/tween.js,gopalindians/tween.js,rocbear/tween.js,Twelve-60/tween.js,wangzuo/cxx-tween,Twelve-60/tween.js,olizilla/tween.js,gopalindians/tween.js,camellhf/tween.js,camellhf/tween.js,olizilla/tween.js,rocbear/tween.js,npmcomponent/bestander-tween.js,altereagle/tween.js,Twelve-60/tween.js,olizilla/tween.js,yyx990803/tween.js,mcanthony/tween.js,yyx990803/tween.js,EskenderDev/tween.js,npmcomponent/bestander-tween.js,gopalindians/tween.js,rocbear/tween.js,camellhf/tween.js,EskenderDev/tween.js,JITBALJINDER/tween.js,mcanthony/tween.js,EskenderDev/tween.js,JITBALJINDER/tween.js,altereagle/tween.js,CasualBot/tween.js,mcanthony/tween.js,CasualBot/tween.js
ef67ce4372128d8f7e9689e1090ee44674c8f391
scripts/analytics/run_keen_events.py
scripts/analytics/run_keen_events.py
from framework.celery_tasks import app as celery_app from scripts.analytics.base import DateAnalyticsHarness from scripts.analytics.node_log_events import NodeLogEvents class EventAnalyticsHarness(DateAnalyticsHarness): @property def analytics_classes(self): return [NodeLogEvents] @celery_app.task(name='scripts.run_keen_events') def run_main(date): EventAnalyticsHarness().main(date) if __name__ == '__main__': EventAnalyticsHarness().main()
from framework.celery_tasks import app as celery_app from scripts.analytics.base import DateAnalyticsHarness from scripts.analytics.node_log_events import NodeLogEvents from scripts.analytics.user_domain_events import UserDomainEvents class EventAnalyticsHarness(DateAnalyticsHarness): @property def analytics_classes(self): return [NodeLogEvents, UserDomainEvents] @celery_app.task(name='scripts.run_keen_events') def run_main(date): EventAnalyticsHarness().main(date) if __name__ == '__main__': EventAnalyticsHarness().main()
Add new user domain event collector to main keen events script
Add new user domain event collector to main keen events script
Python
apache-2.0
chrisseto/osf.io,caneruguz/osf.io,felliott/osf.io,alexschiller/osf.io,leb2dg/osf.io,chrisseto/osf.io,caseyrollins/osf.io,baylee-d/osf.io,icereval/osf.io,hmoco/osf.io,leb2dg/osf.io,chrisseto/osf.io,mluo613/osf.io,rdhyee/osf.io,acshi/osf.io,mluo613/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,felliott/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,binoculars/osf.io,leb2dg/osf.io,aaxelb/osf.io,laurenrevere/osf.io,cslzchen/osf.io,saradbowman/osf.io,chennan47/osf.io,mluo613/osf.io,brianjgeiger/osf.io,mluo613/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,adlius/osf.io,baylee-d/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,chennan47/osf.io,caneruguz/osf.io,hmoco/osf.io,laurenrevere/osf.io,felliott/osf.io,icereval/osf.io,aaxelb/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,crcresearch/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,Nesiehr/osf.io,binoculars/osf.io,hmoco/osf.io,cwisecarver/osf.io,rdhyee/osf.io,mluo613/osf.io,crcresearch/osf.io,adlius/osf.io,alexschiller/osf.io,binoculars/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,adlius/osf.io,icereval/osf.io,erinspace/osf.io,sloria/osf.io,crcresearch/osf.io,felliott/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,TomBaxter/osf.io,aaxelb/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,sloria/osf.io,acshi/osf.io,alexschiller/osf.io,chrisseto/osf.io,hmoco/osf.io,monikagrabowska/osf.io,erinspace/osf.io,cslzchen/osf.io,erinspace/osf.io,acshi/osf.io,Nesiehr/osf.io,alexschiller/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,cslzchen/osf.io,mattclark/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,acshi/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,baylee-d/osf.io,pattisdr/osf.io,acshi/osf.io,cslzchen/osf.io,alexschiller/osf.io,mattclark/osf.io,cwisecarver/osf.io,sloria/osf.io,leb2dg/osf.io,adlius/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,monikagrabowska/osf.io
2b64dc699e222a011d5946fd53a2bda4df77d0fe
scripts/rename_tutorial_src_files.py
scripts/rename_tutorial_src_files.py
#%% from pathlib import Path from string import digits #%% directory = Path("./docs/tutorial/src") output_directory = Path("./docs/tutorial/out") output_directory.mkdir(exist_ok=True) files = sorted([Path(f) for f in directory.iterdir()]) for i, f in enumerate(files): f: Path index = str(i + 1).zfill(2) new_name = output_directory / f"tutorial{index}.py" print(new_name) f.rename(new_name)
#%% from pathlib import Path, PurePath from string import digits #%% directory = Path("./docs/tutorial/src") dirs = sorted([Path(f) for f in directory.iterdir()]) d: PurePath sufix = "__out__" for d in dirs: if d.name.endswith(sufix): continue output_dir_name = d.name + "__out__" output_directory = directory / output_dir_name output_directory.mkdir(exist_ok=True) files = sorted([Path(f) for f in d.iterdir()]) for i, f in enumerate(files): index = str(i + 1).zfill(3) new_name = output_directory / f"tutorial{index}.py" print(new_name) f.rename(new_name) for d in dirs: current_dir = Path(str(d) + sufix) print(current_dir) current_dir.rename(d) #%%
Update tutorial src renamer to use sub-directories
:sparkles: Update tutorial src renamer to use sub-directories
Python
mit
tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi
1fce6a621ad4fe149988147478e15c7415295a7b
changes/api/serializer/models/source.py
changes/api/serializer/models/source.py
from changes.api.serializer import Serializer, register from changes.models import Source @register(Source) class SourceSerializer(Serializer): def serialize(self, instance, attrs): if instance.patch_id: patch = { 'id': instance.patch_id.hex, } else: patch = None return { 'id': instance.id.hex, 'patch': patch, 'revision': instance.revision, 'dateCreated': instance.date_created, }
from changes.api.serializer import Serializer, register from changes.models import Source @register(Source) class SourceSerializer(Serializer): def serialize(self, instance, attrs): if instance.patch_id: patch = { 'id': instance.patch_id.hex, } else: patch = None return { 'id': instance.id.hex, 'patch': patch, 'revision': instance.revision, 'dateCreated': instance.date_created, 'tails_data': dict(instance.data), }
Add data to Source serialization
Add data to Source serialization
Python
apache-2.0
dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes
50367a2d73c395a85bb7dae058f9435be6ad7c36
vtimshow/__init__.py
vtimshow/__init__.py
#!/usr/bin/env python3 # Module imports import logging import os import vitables _defaults = dict( AUTHOR = "Keith F Prussing", AUTHOR_EMAIL = "kprussing74@gmail.com", LICENSE = "MIT", PLUGIN_CLASS = "VtImageViewer", PLUGIN_NAME = "Image Viewer", COMMENT = "Display data sets as images", VERSION = "{VERSION!s}", UID = "image_viewer" ) _defaults["FOLDER"], _defaults["MODULE_NAME"] = os.path.split( os.path.dirname(__file__) ) _defaults["LOGGER"] = logging.getLogger(_defaults["MODULE_NAME"]) _defaults["LOGGER"].addHandler(logging.NullHandler()) __docformat__ = "restructuredtext" __version__ = _defaults["VERSION"] plugin_class = _defaults["PLUGIN_CLASS"] plugin_name = _defaults["PLUGIN_NAME"] comment = _defaults["COMMENT"] from vtimshow.vtimageviewer import VtImageViewer
#!/usr/bin/env python3 # Module imports import logging import os import vitables _defaults = dict( AUTHOR = "Keith F Prussing", AUTHOR_EMAIL = "kprussing74@gmail.com", LICENSE = "MIT", PLUGIN_CLASS = "VtImageViewer", PLUGIN_NAME = "Image Viewer", COMMENT = "Display data sets as images", VERSION = "{VERSION!s}", UID = "image_viewer" ) _defaults["FOLDER"], _defaults["MODULE_NAME"] = os.path.split( os.path.dirname(__file__) ) _defaults["LOGGER"] = logging.getLogger(_defaults["MODULE_NAME"]) _defaults["LOGGER"].addHandler(logging.NullHandler()) __docformat__ = "restructuredtext" __version__ = _defaults["VERSION"] plugin_class = _defaults["PLUGIN_CLASS"] plugin_name = _defaults["PLUGIN_NAME"] comment = _defaults["COMMENT"] from vtimshow.vtimageviewer import VtImageViewer def _setup_logger(name): """ Add the GUI's logging window as a stream handler. By default, the stream logger is removed during the invocation of ``vitables``. The logging window in the GUI is a stream handler for the ``vitables`` logger _only_. This method will add the logging window in the GUI as a stream handler for the named logger. The method checks to see if ``vitables`` is an active application. If it is not, nothing is done. """ logger = logging.getLogger(name) app = vitables.utils.getApp() if app is not None: stream = logging.StreamHandler(app.gui.logger) stream.setFormatter( logging.Formatter(vitables.vtgui._GUI_LOG_FORMAT) ) logger.addHandler(stream) return _setup_logger(_defaults["MODULE_NAME"])
Add method to log to console
Add method to log to console Add a method to set the GUI logging window to be the stream handler for my plug in.
Python
mit
kprussing/vtimshow
67b86cb3ddfb7c9e95ebed071ba167472276cc29
utils/decorators/require.py
utils/decorators/require.py
import requests from functools import wraps from flask import request, current_app from utils.decorators.signature import sign def require(resource_namespace, permissions, resource_id=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if request.method == 'GET': payload = request.args client_key = current_app.config['CLIENTS']['plutonium']['client_key'] client_id = current_app.config['CLIENTS']['plutonium']['client_id'] data = [] for permission in permissions: data.append({ 'client_namespace' : 'app', 'client_id' : payload['client_id'], 'resource_namespace' : resource_namespace, 'permission' : permission, 'resource_id' : resource_id or '*' }) result = f(*args, **kwargs) return result return decorated_function return decorator
import json import requests from functools import wraps from flask import request, current_app from utils.decorators.signature import sign from utils.exceptions import HttpUnauthorized def require(resource_namespace, permissions, resource_id=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if request.method == 'GET': payload = request.args client_key = current_app.config['CLIENTS']['plutonium']['client_key'] client_id = current_app.config['CLIENTS']['plutonium']['client_id'] apq = current_app.config['CLIENTS']['apq'] data = [] for permission in permissions: data.append({ 'client_namespace' : 'app', 'client_id' : payload['client_id'], 'resource_namespace' : resource_namespace, 'permission' : permission, 'resource_id' : resource_id or '*' }) signature = sign(client_key, json.dumps(data)) payload = { 'data' : json.dumps(data), 'client_id': client_id, 'signature': signature } apq = requests.get("http://%s/has_perm" % apq['host'], params=payload) permission = json.loads(apq.content) granted = [granted for granted in permission if granted == 'True'] if len(permission) != len(granted): raise HttpUnauthorized("You don't have enough permission to access this resource") result = f(*args, **kwargs) return result return decorated_function return decorator
Check for permission in apq
Check for permission in apq
Python
apache-2.0
PressLabs/lithium
e2be9eb27d6fc7cfa424cbf908347796ab595526
groundstation/broadcast_announcer.py
groundstation/broadcast_announcer.py
import socket import logger from groundstation.broadcast_socket import BroadcastSocket import logger log = logger.getLogger(__name__) class BroadcastAnnouncer(BroadcastSocket): def __init__(self, port): super(BroadcastAnnouncer, self).__init__() self._addr = '255.255.255.255', port self._name = None self.broadcast_payload = "PING None" @property def name(self): return self._name @name.setter def name(self, value): self._name = value self.broadcast_payload = "PING %s" % (self._name) def ping(self): log.info("ping payload: %s" % (self.broadcast_payload)) transmitted = self.socket.sendto(self.broadcast_payload, self._addr) if transmitted != len(self.broadcast_payload): log.warning("ping wasn't successfully broadcast")
import socket import logger from sockets.broadcast_socket import BroadcastSocket import logger log = logger.getLogger(__name__) class BroadcastAnnouncer(BroadcastSocket): def __init__(self, port): super(BroadcastAnnouncer, self).__init__() self._addr = '255.255.255.255', port self._name = None self.broadcast_payload = "PING None" @property def name(self): return self._name @name.setter def name(self, value): self._name = value self.broadcast_payload = "PING %s" % (self._name) def ping(self): log.info("ping payload: %s" % (self.broadcast_payload)) transmitted = self.socket.sendto(self.broadcast_payload, self._addr) if transmitted != len(self.broadcast_payload): log.warning("ping wasn't successfully broadcast")
Fix an import path bug masked by remaining .pyc files
Fix an import path bug masked by remaining .pyc files
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
f859964c3d8d193da92fb521f4a696a28ef9452a
cisco_olt_http/tests/test_operations.py
cisco_olt_http/tests/test_operations.py
import os import pytest from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir): class Response: pass response = Response() with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
Use mock instead of own class
Use mock instead of own class
Python
mit
beezz/cisco-olt-http-client,Vnet-as/cisco-olt-http-client
37da0285ac6b08994700952e04278e1049577745
yanico/config.py
yanico/config.py
# Copyright 2015-2016 Masayuki Yamamoto # # 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. """Handle yanico configuration.""" import os.path CONFIG_FILENAME = '.yanico.conf' def user_path(): return os.path.join(os.path.expanduser('~'), CONFIG_FILENAME)
# Copyright 2015-2016 Masayuki Yamamoto # # 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. """Handle yanico configuration.""" import os.path CONFIG_FILENAME = '.yanico.conf' def user_path(): """Return user configuration filepath. The filepath depends home directory and CONFIG_FILENAME constants. """ return os.path.join(os.path.expanduser('~'), CONFIG_FILENAME)
Add docstring into user_path function
Add docstring into user_path function Describe dependnce for constants and environments.
Python
apache-2.0
ma8ma/yanico
956d68b6e29b1e319d043945393db3825b5167d1
dask/compatibility.py
dask/compatibility.py
from __future__ import absolute_import, division, print_function import sys PY3 = sys.version_info[0] == 3 PY2 = sys.version_info[0] == 2 if PY3: import builtins from queue import Queue, Empty from itertools import zip_longest from io import StringIO, BytesIO from urllib.request import urlopen from urllib.parse import urlparse from urllib.parse import quote, unquote unicode = str long = int def apply(func, args, kwargs=None): if not isinstance(args, list) and kwargs is None: return func(args) elif not isinstance(args, list): return func(args, **kwargs) elif kwargs: return func(*args, **kwargs) else: return func(*args) range = range else: import __builtin__ as builtins from Queue import Queue, Empty import operator from itertools import izip_longest as zip_longest from StringIO import StringIO from io import BytesIO from urllib2 import urlopen from urlparse import urlparse from urllib import quote, unquote unicode = unicode long = long apply = apply range = xrange def skip(func): return
from __future__ import absolute_import, division, print_function import sys PY3 = sys.version_info[0] == 3 PY2 = sys.version_info[0] == 2 if PY3: import builtins from queue import Queue, Empty from itertools import zip_longest from io import StringIO, BytesIO from urllib.request import urlopen from urllib.parse import urlparse from urllib.parse import quote, unquote unicode = str long = int def apply(func, args, kwargs=None): if not isinstance(args, list) and not isinstance(args, tuple) and kwargs is None: return func(args) elif not isinstance(args, list) and not isinstance(args, tuple): return func(args, **kwargs) elif kwargs: return func(*args, **kwargs) else: return func(*args) range = range else: import __builtin__ as builtins from Queue import Queue, Empty import operator from itertools import izip_longest as zip_longest from StringIO import StringIO from io import BytesIO from urllib2 import urlopen from urlparse import urlparse from urllib import quote, unquote unicode = unicode long = long apply = apply range = xrange def skip(func): return
Allow for tuple-based args in map also
Allow for tuple-based args in map also
Python
bsd-3-clause
blaze/dask,blaze/dask,mrocklin/dask,gameduell/dask,wiso/dask,mraspaud/dask,PhE/dask,cowlicks/dask,wiso/dask,dask/dask,PhE/dask,ContinuumIO/dask,jakirkham/dask,mraspaud/dask,jakirkham/dask,pombredanne/dask,jayhetee/dask,jayhetee/dask,ssanderson/dask,dask/dask,mikegraham/dask,clarkfitzg/dask,jcrist/dask,pombredanne/dask,vikhyat/dask,ssanderson/dask,mrocklin/dask,clarkfitzg/dask,chrisbarber/dask,jcrist/dask,ContinuumIO/dask,vikhyat/dask,cpcloud/dask
39e038373b0691f14605a5aec3f917b5cee40091
django_google_charts/charts.py
django_google_charts/charts.py
import six import json from django.utils.html import format_html, mark_safe from django.core.urlresolvers import reverse from django.utils.encoding import python_2_unicode_compatible CHARTS = {} class ChartMeta(type): def __new__(cls, name, bases, attrs): klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs) if klass.chart_slug: CHARTS[klass.chart_slug] = klass return klass @six.add_metaclass(ChartMeta) @python_2_unicode_compatible class Chart(object): options = {} chart_slug = None columns = None def get_data(self): raise NotImplementedError def __str__(self): return format_html( "<div " "data-chart-options='{0}'" "data-chart-url='{1}'" "></div>", json.dumps(self.options), reverse( 'djgc-chart-data', args=(self.chart_slug,), ), )
import json from django.utils import six from django.utils.html import format_html, mark_safe from django.core.urlresolvers import reverse from django.utils.encoding import python_2_unicode_compatible CHARTS = {} class ChartMeta(type): def __new__(cls, name, bases, attrs): klass = super(ChartMeta, cls).__new__(cls, name, bases, attrs) if klass.chart_slug: CHARTS[klass.chart_slug] = klass return klass @six.add_metaclass(ChartMeta) @python_2_unicode_compatible class Chart(object): options = {} chart_slug = None columns = None def get_data(self): raise NotImplementedError def __str__(self): return format_html( "<div " "data-chart-options='{0}'" "data-chart-url='{1}'" "></div>", json.dumps(self.options), reverse( 'djgc-chart-data', args=(self.chart_slug,), ), )
Use django's bundled and customised version of six
Use django's bundled and customised version of six
Python
mit
danpalmer/django-google-charts,danpalmer/django-google-charts
92ca956dc8f4229a1c427cb24843c7fe3baef405
tests/integration/test_parked.py
tests/integration/test_parked.py
"""Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' }
"""Parked check integration test.""" def test_parked_query(webapp): """Test the parked API against our own domain.""" request = webapp.get('/api/parked/dnstwister.report') assert request.status_code == 200 assert request.json == { u'domain': u'dnstwister.report', u'domain_as_hexadecimal': u'646e73747769737465722e7265706f7274', u'fuzz_url': u'http://localhost:80/api/fuzz/646e73747769737465722e7265706f7274', u'redirects': False, u'redirects_to': None, u'resolve_ip_url': u'http://localhost:80/api/ip/646e73747769737465722e7265706f7274', u'score': 0.07, u'score_text': u'Possibly', u'url': u'http://localhost:80/api/parked/dnstwister.report' } def test_parked_query_on_broken_domain(webapp): """Test the parked API against a domain that doesn't exist.""" request = webapp.get('/api/parked/there-is-little-chance-this-domain-exists-i-hope.com') assert request.status_code == 200 assert request.json['score'] == 0 assert request.json['redirects'] is False assert request.json['redirects_to'] is None assert request.json['score_text'] == 'Unlikely'
Test for parked check against unresolvable domain
Test for parked check against unresolvable domain
Python
unlicense
thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister
8005d43146669e98d921bb36c4afd5dffb08e2e3
Tests/varLib/featureVars_test.py
Tests/varLib/featureVars_test.py
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, end)}] subst = {'g%.2g'%start: 'g%.2g'%end} conds.append((region, subst)) overlaps = overlayFeatureVariations(conds) # XXX Currently fails for n > 2! #assert len(overlaps) == 2 * n - 1, overlaps return conds, overlaps if __name__ == "__main__": import sys from pprint import pprint quiet = False args = {} if len(sys.argv) > 1: if sys.argv[1] == '-q': quiet = True del sys.argv[1] args['n'] = int(sys.argv[1]) input, output = test_explosion(**args) if quiet: print(len(output)) else: print("Input:") pprint(input) print() print("Output:") pprint(output)
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, end)}] subst = {'g%.2g'%start: 'g%.2g'%end} conds.append((region, subst)) overlaps = overlayFeatureVariations(conds) assert len(overlaps) == 2 * n - 1, overlaps return conds, overlaps if __name__ == "__main__": import sys from pprint import pprint quiet = False args = {} if len(sys.argv) > 1: if sys.argv[1] == '-q': quiet = True del sys.argv[1] args['n'] = int(sys.argv[1]) input, output = test_explosion(**args) if quiet: print(len(output)) else: print("Input:") pprint(input) print() print("Output:") pprint(output)
Enable test now that it passes
[varLib.featureVars] Enable test now that it passes
Python
mit
googlefonts/fonttools,fonttools/fonttools
cf13e81d2e41608bfc8e22d9e1f669382a5bdfc6
indra/preassembler/make_wm_ontmap.py
indra/preassembler/make_wm_ontmap.py
import sys from indra.sources import eidos from indra.sources.hume.make_hume_tsv import make_file as mht from indra.sources.sofia.make_sofia_tsv import make_file as mst from indra.java_vm import autoclass eidos_package = 'org.clulab.wm.eidos' if __name__ == '__main__': sofia_ont_path = sys.argv[1] hume_path = 'hume_ontology_examaples.tsv' mht(hume_path) sofia_path = 'sofia_ontology_examples.tsv' mst(sofia_ont_path, sofia_path) om = autoclass(eidos_package + '.apps.OntologyMapper') eidos = autoclass(eidos_package + '.EidosSystem') es = eidos(autoclass('java.lang.Object')()) example_weight = 0.8 parent_weight = 0.1 topn = 10 table_str = om.mapOntologies(es, hume_path, sofia_path, example_weight, parent_weight, topn)
import sys import os from os.path import join, dirname, abspath from indra import preassembler from indra.sources import eidos from indra.sources.hume.make_hume_tsv import make_file as mht from indra.sources.sofia.make_sofia_tsv import make_file as mst from indra.java_vm import autoclass eidos_package = 'org.clulab.wm.eidos' if __name__ == '__main__': sofia_ont_path = sys.argv[1] hume_path = 'hume_ontology_examples.tsv' mht(hume_path) sofia_path = 'sofia_ontology_examples.tsv' mst(sofia_ont_path, sofia_path) om = autoclass(eidos_package + '.apps.OntologyMapper') eidos = autoclass(eidos_package + '.EidosSystem') es = eidos(autoclass('java.lang.Object')()) example_weight = 0.8 parent_weight = 0.1 topn = 10 table_str = om.mapOntologies(es, hume_path, sofia_path, example_weight, parent_weight, topn) with open(join(dirname(abspath(__file__)), os.pardir, 'resources', 'wm_ontomap.tsv'), 'w') as fh: fh.write(table_str)
Save ontology map in script
Save ontology map in script
Python
bsd-2-clause
sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/indra
7c38eae5a07e07789713baf5ab3aaea772e76422
routes.py
routes.py
from flask import Flask, render_template, redirect import psycopg2 import os import urlparse app = Flask(__name__) # def connectDB(wrapped): # def inner(*args, **kwargs): # api_token = os.environ["API_TOKEN"] # urlparse.uses_netloc.append("postgres") # url = urlparse.urlparse(os.environ["DATABASE_URL"]) # conn = psycopg2.connect( # database=url.path[1:], # user=url.username, # password=url.password, # host=url.hostname, # port=url.port # ) # cur = conn.cursor() # ret = wrapped(*args, **kwargs) # return ret # return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') # @connectDB def participants(): return render_template('participants.html') @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) # @connectDB def complete(): return redirect('/')
from flask import Flask, render_template, redirect, request import psycopg2 from functools import wraps import os import urlparse app = Flask(__name__) def connectDB(wrapped): @wraps(wrapped) def inner(*args, **kwargs): urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) cur = conn.cursor() return wrapped(cur, *args, **kwargs) return inner @app.route('/') def home(): return render_template('home.html') @app.route('/participants') @connectDB def participants(*args): return args[0] @app.route('/setup') def setup(): return render_template('setup.html') @app.route('/register') def register(): return render_template('register.html') @app.route('/complete', methods=['POST']) @connectDB def complete(*args): return render_template('/success.html')
Add decorator to connect to database
Add decorator to connect to database
Python
mit
AlexMathew/csipy-home
79978bd00fc4834b01f7473cc5b7b8407abec51c
Lib/test/test_nis.py
Lib/test/test_nis.py
import nis verbose = 0 if __name__ == '__main__': verbose = 1 maps = nis.maps() try: for nismap in maps: if verbose: print nismap mapping = nis.cat(nismap) for k, v in mapping.items(): if verbose: print ' ', k, v if not k: continue if nis.match(k, nismap) <> v: print "NIS match failed for key `%s' in map `%s'" % (k, nismap) else: # just test the one key, otherwise this test could take a # very long time raise 'done' except 'done': pass
import nis verbose = 0 if __name__ == '__main__': verbose = 1 maps = nis.maps() done = 0 for nismap in maps: if verbose: print nismap mapping = nis.cat(nismap) for k, v in mapping.items(): if verbose: print ' ', k, v if not k: continue if nis.match(k, nismap) <> v: print "NIS match failed for key `%s' in map `%s'" % (k, nismap) else: # just test the one key, otherwise this test could take a # very long time done = 1 break if done: break
Rewrite without using try-except to break out of two loops.
Rewrite without using try-except to break out of two loops.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
b624552af638652147ca8b5e49ca109a4723dca1
MoMMI/Modules/development.py
MoMMI/Modules/development.py
from discord import Message from typing import re as typing_re from MoMMI.commands import command from MoMMI.master import master from MoMMI.server import MChannel @command("reload", "reload", roles=["owner"]) async def reload(channel: MChannel, match: typing_re.Match, message: Message): await master.reload_modules() @command("modules", "modules", roles=["owner"]) async def modules(channel: MChannel, match: typing_re.Match, message: Message): msg = "```" for module in channel.server.master.modules.values(): msg += f"{module.name}:\n" for handler in module.handlers.values(): msg += f"* {handler.name} ({type(handler)})\n" msg += "```" await channel.send(msg)
from discord import Message from typing import re as typing_re from MoMMI.commands import command from MoMMI.master import master from MoMMI.server import MChannel from MoMMI.role import MRoleType @command("reload", "reload", roles=[MRoleType.OWNER]) async def reload(channel: MChannel, match: typing_re.Match, message: Message): await master.reload_modules() @command("modules", "modules", roles=[MRoleType.OWNER]) async def modules(channel: MChannel, match: typing_re.Match, message: Message): msg = "```" for module in channel.server.master.modules.values(): msg += f"{module.name}:\n" for handler in module.handlers.values(): msg += f"* {handler.name} ({type(handler)})\n" msg += "```" await channel.send(msg)
Fix dev commands using string roles.
Fix dev commands using string roles.
Python
mit
PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI
a003a7b0d52365c5f5976c7382bc1daf2f5960ac
glitter_news/search_indexes.py
glitter_news/search_indexes.py
# -*- coding: utf-8 -*- from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.select_related().filter( published=True ).exclude( current_version=None )
# -*- coding: utf-8 -*- from django.utils import timezone from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().objects.published().select_related().filter( date__lte=timezone.now())
Fix the queryset for news indexing
Fix the queryset for news indexing
Python
bsd-2-clause
blancltd/glitter-news
bd6b969b85a1c8df7cf8d6da7b93f5c94cf8a180
sum-of-multiples/sum_of_multiples.py
sum-of-multiples/sum_of_multiples.py
def sum_of_multiples(limit, factors): return sum(filter(lambda n: n < limit, {f*i for i in range(1, limit) for f in factors}))
def sum_of_multiples(limit, factors): return sum({n for f in factors for n in range(f, limit, f)})
Use more optimal method of getting multiples
Use more optimal method of getting multiples
Python
agpl-3.0
CubicComet/exercism-python-solutions
cfa0b71f056c88f14f79f4f47a169ade9ce08096
serrano/resources/base.py
serrano/resources/base.py
from restlib2.resources import Resource from avocado.models import DataContext class BaseResource(Resource): param_defaults = {} def get_params(self, request): params = request.GET.copy() for param, default in self.param_defaults.items(): params.setdefault(param, default) return params def get_context(self, request): params = self.get_params(request) context = params.get('context') # Explicit request to not use a context if context != 'null': kwargs = { 'archived': False, } if hasattr(request, 'user') and request.user.is_authenticated(): kwargs['user'] = request.user else: kwargs['session_key'] = request.session.session_key # Assume it is a primary key and fallback to the sesssion try: kwargs['pk'] = int(context) except (ValueError, TypeError): kwargs['session'] = True try: return DataContext.objects.get(**kwargs) except DataContext.DoesNotExist: pass return DataContext()
from restlib2.resources import Resource from avocado.models import DataContext, DataView class BaseResource(Resource): param_defaults = {} def get_params(self, request): params = request.GET.copy() for param, default in self.param_defaults.items(): params.setdefault(param, default) return params def get_context(self, request): params = self.get_params(request) context = params.get('context') # Explicit request to not use a context if context != 'null': kwargs = { 'archived': False, } if hasattr(request, 'user') and request.user.is_authenticated(): kwargs['user'] = request.user else: kwargs['session_key'] = request.session.session_key # Assume it is a primary key and fallback to the sesssion try: kwargs['pk'] = int(context) except (ValueError, TypeError): kwargs['session'] = True try: return DataContext.objects.get(**kwargs) except DataContext.DoesNotExist: pass return DataContext() def get_view(self, request): params = self.get_params(request) view = params.get('view') # Explicit request to not use a view if view != 'null': kwargs = { 'archived': False, } if hasattr(request, 'user') and request.user.is_authenticated(): kwargs['user'] = request.user else: kwargs['session_key'] = request.session.session_key # Assume it is a primary key and fallback to the sesssion try: kwargs['pk'] = int(view) except (ValueError, TypeError): kwargs['session'] = True try: return DataView.objects.get(**kwargs) except DataView.DoesNotExist: pass return DataView()
Add method to get the most appropriate DataView
Add method to get the most appropriate DataView
Python
bsd-2-clause
rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano
c5aa1c7ee17313e3abe156c2bfa429f124a451d5
bc125csv/__init__.py
bc125csv/__init__.py
""" bc125csv - Channel import and export tool for the Uniden BC125AT, UBC125XLT and UBC126AT. Copyright (c) 2015, fdev.nl. All rights reserved. Released under the MIT license. Uniden and Bearcat are registered trademarks of Uniden America Corporation. This application and its author are not affiliated with or endorsed by Uniden in any way. """ __author__ = "Folkert de Vries" __email__ = "bc125csv@fdev.nl" __version__ = "1.0.0" __date__ = "Aug 02, 2015" # Expose main function for setup.py console_scripts from bc125csv.handler import main
""" bc125csv - Channel import and export tool for the Uniden BC125AT, UBC125XLT and UBC126AT. Copyright (c) 2015, fdev.nl. All rights reserved. Released under the MIT license. Uniden and Bearcat are registered trademarks of Uniden America Corporation. This application and its author are not affiliated with or endorsed by Uniden in any way. """ __author__ = "Folkert de Vries" __email__ = "bc125csv@fdev.nl" __version__ = "1.0.0" __date__ = "Aug 02, 2015" # Expose main function for setup.py console_scripts from bc125csv.handler import main if __name__ == "__main__": main()
Call main when run directly
Call main when run directly
Python
mit
fdev/bc125csv
d6b9be8145316f6f90e47bb3a55c861f993a375a
tweetyr.py
tweetyr.py
#!/usr/bin/env python # -*- coding: UTF-8 ''' A simple twitter client that posts current weather to twitter ''' import tweepy import json from urllib2 import urlopen import os root =os.path.dirname(os.path.abspath(__file__)) conf = json.loads(file(root+'/twitterconfig.json').read()) auth = tweepy.OAuthHandler(conf['consumerkey'], conf['consumersecret']) auth.set_access_token(conf['accesstoken'], conf['accesssecret']) api = tweepy.API(auth) w = json.loads(urlopen(conf['apiurl']).read())[0] api.update_status('%(outtemp).1f °C, %(windspeed).1f m/s vind, %(rain).1f mm nedbør' %w);
#!/usr/bin/env python # -*- coding: UTF-8 ''' A simple twitter client that posts current weather to twitter ''' import tweepy import json from urllib2 import urlopen import os root = os.path.dirname(os.path.abspath(__file__)) conf = json.loads(file(root+'/twitterconfig.json').read()) auth = tweepy.OAuthHandler(conf['consumerkey'], conf['consumersecret']) auth.set_access_token(conf['accesstoken'], conf['accesssecret']) api = tweepy.API(auth) w = json.loads(urlopen(conf['apiurl']).read())[0] api.update_status('%(outtemp).1f °C, %(windspeed).1f m/s vind, %(rain).1f mm nedbør' %w,lat=conf['lat'],long=conf['long'])
Add geo info to status update
Add geo info to status update
Python
bsd-3-clause
torhve/Amatyr,torhve/Amatyr,torhve/Amatyr
00ddeefdcdacb811f5e665a91139e165d7217f84
week1/poc_2048_merge_template.py
week1/poc_2048_merge_template.py
""" Merge function for 2048 game. """ def merge(line): """ Function that merges a single row or column in 2048. """ l = len(line) s1 = [0]*l j = 0 for i in range(l): if l[i] != 0: s1[j] = l[i] return [] a = [2,0,2,4] print merge(a)
""" Merge function for 2048 game. """ def merge(line): """ Function that merges a single row or column in 2048. """ l = len(line) s1 = [0]*l j = 0 for i in range(l): if line[i] != 0: s1[j] = line[i] j += 1 return s1 a = [2,0,2,4] print (merge(a))
Modify the correct merge 1 fct
Modify the correct merge 1 fct
Python
mit
Crescent-Saturn/Principles-of-Computing
dafde564f3ea18655b1e15f410df70d05b3eb8f5
beets/util/collections.py
beets/util/collections.py
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Custom collections classes """ class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all keys not in it. """ def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return key
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Custom collections classes. """ from __future__ import division, absolute_import, print_function class IdentityFallbackDict(dict): """A dictionary which is "transparent" (maps keys to themselves) for all keys not in it. """ def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return key
Add __future__ imports to a new module
Add __future__ imports to a new module
Python
mit
mosesfistos1/beetbox,ibmibmibm/beets,mosesfistos1/beetbox,MyTunesFreeMusic/privacy-policy,artemutin/beets,jackwilsdon/beets,sampsyo/beets,pkess/beets,xsteadfastx/beets,shamangeorge/beets,diego-plan9/beets,MyTunesFreeMusic/privacy-policy,jackwilsdon/beets,beetbox/beets,sampsyo/beets,beetbox/beets,madmouser1/beets,beetbox/beets,madmouser1/beets,pkess/beets,shamangeorge/beets,diego-plan9/beets,MyTunesFreeMusic/privacy-policy,xsteadfastx/beets,Kraymer/beets,MyTunesFreeMusic/privacy-policy,SusannaMaria/beets,jackwilsdon/beets,lengtche/beets,Kraymer/beets,lengtche/beets,jackwilsdon/beets,artemutin/beets,madmouser1/beets,sampsyo/beets,ibmibmibm/beets,pkess/beets,Kraymer/beets,mosesfistos1/beetbox,shamangeorge/beets,Kraymer/beets,lengtche/beets,diego-plan9/beets,ibmibmibm/beets,SusannaMaria/beets,beetbox/beets,xsteadfastx/beets,madmouser1/beets,ibmibmibm/beets,artemutin/beets,pkess/beets,xsteadfastx/beets,artemutin/beets,SusannaMaria/beets,SusannaMaria/beets,lengtche/beets,shamangeorge/beets,mosesfistos1/beetbox,sampsyo/beets,diego-plan9/beets
c178e9aba40f6cf775dce5badf60cff9acd9e908
boardinghouse/__init__.py
boardinghouse/__init__.py
""" """ __version__ = '0.1' __release__ = '0.1a2' def inject_app_defaults(): try: import settings as app_settings from django.conf import settings, global_settings from django.core.exceptions import ImproperlyConfigured except ImportError: return for key in dir(app_settings): if key.isupper(): value = getattr(app_settings, key) setattr(global_settings, key, value) if not hasattr(settings, key): # We can just ignore failures, as this means we are # not set up, so global_settings will suffice. try: setattr(settings, key, value) except (ImproperlyConfigured, ImportError): pass inject_app_defaults()
""" """ __version__ = '0.1' __release__ = '0.1a2' def inject_app_defaults(): """ Automatically inject the default settings for this app. If settings has already been configured, then we need to add our defaults to that (if not overridden), and in all cases we also want to inject our settings into the global_settings object, so we can use diffsettings. Based on: http://passingcuriosity.com/2010/default-settings-for-django-applications/ but with improvements for importing/assignation failures. """ try: import settings as app_settings from django.conf import settings, global_settings from django.core.exceptions import ImproperlyConfigured except ImportError: return for key in dir(app_settings): if key.isupper(): value = getattr(app_settings, key) setattr(global_settings, key, value) if not hasattr(settings, key): # We can just ignore failures, as this means we are # not set up, so global_settings will suffice. try: setattr(settings, key, value) except (ImproperlyConfigured, ImportError): pass inject_app_defaults()
Document where we got settings injection from.
Document where we got settings injection from.
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
f8ae44cb19584a2b7d08b08dc4f32651acfe90f9
core/templatetags/tags.py
core/templatetags/tags.py
from core.models import Comment, Tag from django import template register = template.Library() #May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template @register.simple_tag def recent_comments(): comments = Comment.objects.select_related('entry').filter(deleted=False, spam=False).order_by('-id')[:3] output = '<ul id="recent">' for comment in comments: if not comment.name: comment.name = "Anonymous" if comment.website: output += '<li><a href="' + comment.website + '">' + comment.name + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>' elif comment.user: output += '<li><a href="http://www.github.com/mburst">' + comment.user.get_full_name() + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>' else: output += '<li>' + comment.name + ' - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>' output += '</ul>' return output @register.simple_tag def tags(): tags = Tag.objects.order_by('?')[:10] return tags
from core.models import Comment, Tag from django import template register = template.Library() #May want to ditch this for a middleware that passes in the comments object so that I can do the manipulations in the actual template @register.simple_tag def recent_comments(): comments = Comment.objects.select_related('entry').filter(deleted=False, spam=False).order_by('-id')[:3] output = '<ul id="recent">' for comment in comments: if not comment.name: comment.name = "Anonymous" elif comment.user: output += '<li><a href="http://www.github.com/mburst">' + comment.user.get_full_name() + '</a> - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>' else: output += '<li>' + comment.name + ' - <a href="' + comment.entry.get_absolute_url() + '">' + comment.entry.title + '</a></li>' output += '</ul>' return output @register.simple_tag def tags(): tags = Tag.objects.order_by('?')[:10] return tags
Remove website from recent comments
Remove website from recent comments
Python
bsd-2-clause
mburst/burstolio,mburst/burstolio,mburst/burstolio
d7ed79ec53279f0fea0881703079a1c5b82bf938
_settings.py
_settings.py
# Configuration settings # ID of HPO to validate (see resources/hpo.csv) hpo_id = 'hpo_id' # location of files to validate, evaluate csv_dir = 'path/to/csv_files' # sprint number being validated against sprint_num = 0 # Submissions and logs stored here # For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
# Configuration settings # ID of HPO to validate (see resources/hpo.csv) hpo_id = 'hpo_id' # location of files to validate, evaluate csv_dir = 'path/to/csv_files' # sprint number being validated against sprint_num = 0 # Submissions and logs stored here # Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY) # For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'
Add comment regarding freetds config
Add comment regarding freetds config
Python
mit
cumc-dbmi/pmi_sprint_reporter
703ff26008525bce769b137fafe51ac080a6af81
plyer/platforms/ios/compass.py
plyer/platforms/ios/compass.py
''' iOS Compass --------------------- ''' from plyer.facades import Compass from pyobjus import autoclass class IosCompass(Compass): def __init__(self): super(IosCompass, self).__init__() self.bridge = autoclass('bridge').alloc().init() self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1) def _enable(self): self.bridge.startMagnetometer() def _disable(self): self.bridge.stopMagnetometer() def _get_orientation(self): return ( self.bridge.mg_x, self.bridge.mg_y, self.bridge.mg_z) def instance(): return IosCompass()
''' iOS Compass ----------- ''' from plyer.facades import Compass from pyobjus import autoclass class IosCompass(Compass): def __init__(self): super(IosCompass, self).__init__() self.bridge = autoclass('bridge').alloc().init() self.bridge.motionManager.setMagnetometerUpdateInterval_(0.1) self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) def _enable(self): self.bridge.startMagnetometer() self.bridge.startDeviceMotionWithReferenceFrame() def _disable(self): self.bridge.stopMagnetometer() self.bridge.stopDeviceMotion() def _get_orientation(self): return ( self.bridge.mf_x, self.bridge.mf_y, self.bridge.mf_z) def _get_field_uncalib(self): return ( self.bridge.mg_x, self.bridge.mg_y, self.bridge.mg_z, self.bridge.mg_x - self.bridge.mf_x, self.bridge.mg_y - self.bridge.mf_y, self.bridge.mg_z - self.bridge.mf_z) def instance(): return IosCompass()
Add iOS implementation to get uncalibrated values
Add iOS implementation to get uncalibrated values
Python
mit
kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer
52a07b32eb499d74b1770a42ac0851be71da8288
polygraph/types/object_type.py
polygraph/types/object_type.py
from collections import OrderedDict from graphql.type.definition import GraphQLObjectType from marshmallow import Schema, SchemaOpts class ObjectTypeOpts(SchemaOpts): def __init__(self, meta, **kwargs): SchemaOpts.__init__(self, meta, **kwargs) self.name = getattr(meta, 'name', None) self.description = getattr(meta, 'name', None) class ObjectType(Schema): OPTIONS_CLASS = ObjectTypeOpts def __init__(self, only=(), exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False): super().__init__(only, exclude, prefix, strict, many, context, load_only, dump_only, partial) self._name = self.opts.name or self.__class__.__name__ self._description = self.opts.description or self.__doc__ def build_definition(self): field_map = OrderedDict() for fieldname, field in self.fields.items(): field_map[fieldname] = field.build_definition() return GraphQLObjectType(name=self._name, fields=field_map)
from collections import OrderedDict from graphql.type.definition import GraphQLObjectType from marshmallow import Schema, SchemaOpts from polygraph.utils.trim_docstring import trim_docstring class ObjectTypeOpts(SchemaOpts): def __init__(self, meta, **kwargs): SchemaOpts.__init__(self, meta, **kwargs) self.name = getattr(meta, 'name', None) self.description = getattr(meta, 'name', None) class ObjectType(Schema): OPTIONS_CLASS = ObjectTypeOpts def __init__(self, only=(), exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False): super().__init__(only, exclude, prefix, strict, many, context, load_only, dump_only, partial) self._name = self.opts.name or self.__class__.__name__ self._description = self.opts.description or trim_docstring(self.__doc__) def build_definition(self): field_map = OrderedDict() for fieldname, field in self.fields.items(): field_map[fieldname] = field.build_definition() return GraphQLObjectType(name=self._name, fields=field_map, description=self._description)
Modify ObjectType to derive description from docstring
Modify ObjectType to derive description from docstring
Python
mit
polygraph-python/polygraph
3cccb20cb9de803867084cab47f43401bf044e63
backend/sponsors/models.py
backend/sponsors/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel from ordered_model.models import OrderedModel class SponsorLevel(OrderedModel): name = models.CharField(_("name"), max_length=20) conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), related_name="sponsor_levels", ) class Meta(OrderedModel.Meta): unique_together = ["name", "conference"] class Sponsor(TimeStampedModel): name = models.CharField(_("name"), max_length=200) link = models.URLField(_("link"), blank=True) image = models.ImageField(_("image"), null=True, blank=True, upload_to="sponsors") level = models.ForeignKey( SponsorLevel, on_delete=models.CASCADE, verbose_name=_("level"), related_name="sponsors", ) def __str__(self): return self.name
from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel from ordered_model.models import OrderedModel class SponsorLevel(OrderedModel): name = models.CharField(_("name"), max_length=20) conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), related_name="sponsor_levels", ) def __str__(self): return self.name class Meta(OrderedModel.Meta): unique_together = ["name", "conference"] class Sponsor(TimeStampedModel): name = models.CharField(_("name"), max_length=200) link = models.URLField(_("link"), blank=True) image = models.ImageField(_("image"), null=True, blank=True, upload_to="sponsors") level = models.ForeignKey( SponsorLevel, on_delete=models.CASCADE, verbose_name=_("level"), related_name="sponsors", ) def __str__(self): return self.name
Fix sponsor level name in the django admin
Fix sponsor level name in the django admin
Python
mit
patrick91/pycon,patrick91/pycon
9db490d5d175f108231cc87afd87a593359837e8
app/views.py
app/views.py
import os from flask import render_template, jsonify, request from app import app import pymysql as mdb con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1') @app.route('/') @app.route('/index') def index(): with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Auctions LIMIT 12") rows = cur.fetchall() for key in rows: key['thumb'] = key['image'].split(".")[2] + "-thumb.jpg" return render_template('destination2.html', auctions=rows) @app.route('/slides') def cities_page(): return render_template('slides_wide.html') @app.route("/slides_wide", methods=["GET"]) def slides_wide(): title="HammerPricer Slides" return render_template("slides_wide.html", title=title)
import os from flask import render_template, jsonify, request from app import app import pymysql as mdb @app.route('/') @app.route('/index') def index(): con = mdb.connect('localhost', "root", "ozfgefgvrwix", 'test1') with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Auctions LIMIT 12") rows = cur.fetchall() for key in rows: key['thumb'] = key['image'].split(".")[2] + "-thumb.jpg" return render_template('destination2.html', auctions=rows) @app.route('/slides') def cities_page(): return render_template('slides_wide.html') @app.route("/slides_wide", methods=["GET"]) def slides_wide(): title="HammerPricer Slides" return render_template("slides_wide.html", title=title)
Fix the disconnect after 8 hours bug.
Fix the disconnect after 8 hours bug.
Python
mit
jbwhit/hammer-pricer,jbwhit/hammer-pricer
b16c49cfd6a0ee659e4493ef959e0483e93d350a
os_client_config/defaults.py
os_client_config/defaults.py
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. _defaults = dict( auth_type='password', compute_api_version='2', floating_ip_source='neutron', identity_api_version='2', image_api_use_tasks=False, image_api_version='1', network_api_version='2', object_api_version='1', volume_api_version='1', )
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by 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. _defaults = dict( auth_type='password', baremetal_api_version='1', compute_api_version='2', database_api_version='1.0', floating_ip_source='neutron', identity_api_version='2', image_api_use_tasks=False, image_api_version='1', network_api_version='2', object_api_version='1', volume_api_version='1', )
Add default versions for trove and ironic
Add default versions for trove and ironic Change-Id: Ib7af38664cfbe75c78c70693117f1193c4beb7e6
Python
apache-2.0
openstack/python-openstacksdk,stackforge/python-openstacksdk,redhat-openstack/os-client-config,dtroyer/python-openstacksdk,openstack/os-client-config,dtroyer/python-openstacksdk,switch-ch/os-client-config,stackforge/python-openstacksdk,dtroyer/os-client-config,openstack/python-openstacksdk
c5bfe6f408163267a16b8137e5871943657fb211
conftest.py
conftest.py
from __future__ import absolute_import pytest_plugins = [ 'sentry.utils.pytest' ] def pytest_configure(config): from django.conf import settings settings.INSTALLED_APPS += ('sentry_jira',)
from __future__ import absolute_import import os os.environ.setdefault('DB', 'sqlite') pytest_plugins = [ 'sentry.utils.pytest' ] def pytest_configure(config): from django.conf import settings settings.INSTALLED_APPS += ('sentry_jira',)
Fix tests to run against sqlite
Fix tests to run against sqlite
Python
bsd-3-clause
getsentry/sentry-jira,thurloat/sentry-jira,thurloat/sentry-jira,getsentry/sentry-jira
389330f4cd1d49ab8fdcfa9554046dedbc5dcffc
plugins/Views/SimpleView/__init__.py
plugins/Views/SimpleView/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple") } } def register(app): return { "view": SimpleView.SimpleView() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import SimpleView from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Simple View"), "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."), "api": 2 }, "view": { "name": i18n_catalog.i18nc("@item:inmenu", "Simple"), "visible": False } } def register(app): return { "view": SimpleView.SimpleView() }
Hide simple view by default
Hide simple view by default It is an example implementation, most actual applications would probably use something with more features.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
d9b804f72e54ffc9cb0f1cef8ce74aef1079ef76
tosec/management/commands/tosecscan.py
tosec/management/commands/tosecscan.py
import os import hashlib from tosec.models import Rom from django.core.management.base import BaseCommand class Command(BaseCommand): args = '<folder>' help = 'Scan a folder for TOSEC roms' def handle(self, *args, **kwargs): directory = args[0] dest = os.path.join(directory, 'TOSEC') if not os.path.exists(dest): os.makedirs(dest) self.stdout.write("Scanning %s" % directory) for filename in os.listdir(directory): abspath = os.path.join(directory, filename) if not os.path.isfile(abspath): continue md5sum = hashlib.md5(open(abspath).read()).hexdigest() rom = Rom.objects.filter(md5=md5sum) if not rom: continue else: rom = rom[0] self.stdout.write("Found %s" % rom.name) new_path = os.path.join(dest, rom.name) os.rename(abspath, new_path)
import os import hashlib from tosec.models import Rom, Game from django.core.management.base import BaseCommand class Command(BaseCommand): args = '<folder>' help = 'Scan a folder for TOSEC roms' def handle(self, *args, **kwargs): directory = args[0] dest = os.path.join(directory, 'TOSEC') if not os.path.exists(dest): os.makedirs(dest) self.stdout.write("Scanning %s" % directory) filenames = os.listdir(directory) total_files = len(filenames) tosec_sets = {} # Store TOSEC sets with number of found roms for index, filename in enumerate(filenames, start=1): abspath = os.path.join(directory, filename) if not os.path.isfile(abspath): continue md5sum = hashlib.md5(open(abspath).read()).hexdigest() try: rom = Rom.objects.get(md5=md5sum) except Rom.DoesNotExist: continue set_name = rom.game.category.name if set_name in tosec_sets: tosec_sets[set_name] += 1 else: tosec_sets[set_name] = 1 self.stdout.write("[{} of {}] Found {}".format(index, total_files, rom.name)) new_path = os.path.join(dest, rom.name) os.rename(abspath, new_path) for set_name in tosec_sets: set_size = Game.objects.filter(category__name=set_name).count() self.stdout.write("{}: imported {} of {} games".format( set_name, tosec_sets[set_name], set_size ))
Print report on imported TOSEC sets
Print report on imported TOSEC sets
Python
agpl-3.0
Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website
05db0c3dc6affdc3938d45195fb807be78ae5ff1
dit/math/__init__.py
dit/math/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mathematical tools for dit. """ from __future__ import absolute_import # Global random number generator import numpy as np prng = np.random.RandomState() # Set the error level to ignore...for example: log2(0). np.seterr(all='ignore') del np from .equal import close, allclose from .sampling import sample, _sample, _samples from .ops import get_ops, LinearOperations, LogOperations from .fraction import approximate_fraction from .sigmaalgebra import sigma_algebra, is_sigma_algebra, atom_set from . import aitchison from . import combinatorics
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mathematical tools for dit. """ from __future__ import absolute_import # Global random number generator import numpy as np prng = np.random.RandomState() # Set the error level to ignore...for example: log2(0). np.seterr(all='ignore') del np from .equal import close, allclose from .sampling import sample, _sample, _samples from .ops import get_ops, LinearOperations, LogOperations from .fraction import approximate_fraction from .sigmaalgebra import sigma_algebra, is_sigma_algebra, atom_set from .perturb import perturb_pmf from . import aitchison from . import combinatorics
Make perturb_pmf available in dit.math.
Make perturb_pmf available in dit.math.
Python
bsd-3-clause
Autoplectic/dit,chebee7i/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,Autoplectic/dit,Autoplectic/dit,dit/dit,dit/dit,chebee7i/dit,dit/dit,dit/dit,chebee7i/dit,dit/dit
5a7f88a7d033a8005d09792d62827689d6d5230d
mox3/fixture.py
mox3/fixture.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
# Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
Remove vim header from source files
Remove vim header from source files trivialfix Change-Id: I6ccd551bc5cec8f5a682502b0a6e99a6d02cad3b
Python
apache-2.0
openstack/mox3
6692476cc7523516275f4512c32b0378574210bf
django_tenants/routers.py
django_tenants/routers.py
from django.conf import settings class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def allow_migrate(self, db, app_label, model_name=None, **hints): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from django_tenants.utils import get_public_schema_name # for INSTALLED_APPS we need a name from django.apps import apps app_name = apps.get_app_config(app_label).name if connection.schema_name == get_public_schema_name(): if app_name not in settings.SHARED_APPS: return False else: if app_name not in settings.TENANT_APPS: return False return None
from django.conf import settings from django.apps import apps as django_apps class TenantSyncRouter(object): """ A router to control which applications will be synced, depending if we are syncing the shared apps or the tenant apps. """ def app_in_list(self, app_label, apps_list): """ Is 'app_label' present in 'apps_list'? apps_list is either settings.SHARED_APPS or settings.TENANT_APPS, a list of app names. We check the presense of the app's name or the full path to the apps's AppConfig class. https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications """ appconfig = django_apps.get_app_config(app_label) appconfig_full_name = '{}.{}'.format( appconfig.__module__, appconfig.__class__.__name__) return (appconfig.name in apps_list) or (appconfig_full_name in apps_list) def allow_migrate(self, db, app_label, model_name=None, **hints): # the imports below need to be done here else django <1.5 goes crazy # https://code.djangoproject.com/ticket/20704 from django.db import connection from django_tenants.utils import get_public_schema_name if connection.schema_name == get_public_schema_name(): if not self.app_in_list(app_label, settings.SHARED_APPS): return False else: if not self.app_in_list(app_label, settings.TENANT_APPS): return False return None
Fix check of an app's presence in INSTALLED_APPS
Fix check of an app's presence in INSTALLED_APPS In TenantSyncRouter, the logic to check whether an app is a tenant app or shared app was too simplistic. Django 1.7 allows two ways to add an app to INSTALLED_APPS. 1) By specifying the app's name, and 2) By specifying the dotted path to the app's AppConfig's class. This commit ensures that we check for the latter case as well. https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications
Python
mit
sigma-geosistemas/django-tenants,tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants,sigma-geosistemas/django-tenants
b7971d68256b23646de1ef648181da5ceacd67f8
scipy/constants/tests/test_codata.py
scipy/constants/tests/test_codata.py
import warnings from scipy.constants import find from numpy.testing import assert_equal, run_module_suite def test_find(): warnings.simplefilter('ignore', DeprecationWarning) keys = find('weak mixing', disp=False) assert_equal(keys, ['weak mixing angle']) keys = find('qwertyuiop', disp=False) assert_equal(keys, []) keys = find('natural unit', disp=False) assert_equal(keys, sorted(['natural unit of velocity', 'natural unit of action', 'natural unit of action in eV s', 'natural unit of mass', 'natural unit of energy', 'natural unit of energy in MeV', 'natural unit of momentum', 'natural unit of momentum in MeV/c', 'natural unit of length', 'natural unit of time'])) if __name__ == "__main__": run_module_suite()
import warnings import codata import constants from scipy.constants import find from numpy.testing import assert_equal, run_module_suite def test_find(): warnings.simplefilter('ignore', DeprecationWarning) keys = find('weak mixing', disp=False) assert_equal(keys, ['weak mixing angle']) keys = find('qwertyuiop', disp=False) assert_equal(keys, []) keys = find('natural unit', disp=False) assert_equal(keys, sorted(['natural unit of velocity', 'natural unit of action', 'natural unit of action in eV s', 'natural unit of mass', 'natural unit of energy', 'natural unit of energy in MeV', 'natural unit of momentum', 'natural unit of momentum in MeV/c', 'natural unit of length', 'natural unit of time'])) def test_basic_table_parse(): c = 'speed of light in vacuum' assert_equal(codata.value(c), constants.c) assert_equal(codata.value(c), constants.speed_of_light) def test_basic_lookup(): assert_equal('%d %s' % (codata.c, codata.unit('speed of light in vacuum')), '299792458 m s^-1') if __name__ == "__main__": run_module_suite()
Add very basic tests for codata and constants.
ENH: Add very basic tests for codata and constants.
Python
bsd-3-clause
WarrenWeckesser/scipy,arokem/scipy,aeklant/scipy,vhaasteren/scipy,lhilt/scipy,jseabold/scipy,fernand/scipy,e-q/scipy,nonhermitian/scipy,ndchorley/scipy,newemailjdm/scipy,scipy/scipy,grlee77/scipy,zerothi/scipy,FRidh/scipy,Shaswat27/scipy,trankmichael/scipy,mgaitan/scipy,vigna/scipy,woodscn/scipy,andyfaff/scipy,jonycgn/scipy,arokem/scipy,mtrbean/scipy,minhlongdo/scipy,jor-/scipy,pbrod/scipy,nvoron23/scipy,efiring/scipy,scipy/scipy,zaxliu/scipy,jseabold/scipy,andim/scipy,giorgiop/scipy,sonnyhu/scipy,zaxliu/scipy,zerothi/scipy,sauliusl/scipy,chatcannon/scipy,larsmans/scipy,mingwpy/scipy,larsmans/scipy,lukauskas/scipy,njwilson23/scipy,surhudm/scipy,Shaswat27/scipy,jamestwebber/scipy,Eric89GXL/scipy,ales-erjavec/scipy,WarrenWeckesser/scipy,WillieMaddox/scipy,perimosocordiae/scipy,vanpact/scipy,gfyoung/scipy,zxsted/scipy,haudren/scipy,fredrikw/scipy,dominicelse/scipy,ogrisel/scipy,petebachant/scipy,anielsen001/scipy,raoulbq/scipy,ogrisel/scipy,pnedunuri/scipy,zerothi/scipy,dch312/scipy,rgommers/scipy,maniteja123/scipy,juliantaylor/scipy,piyush0609/scipy,mortonjt/scipy,Eric89GXL/scipy,njwilson23/scipy,sonnyhu/scipy,grlee77/scipy,Shaswat27/scipy,WarrenWeckesser/scipy,piyush0609/scipy,dch312/scipy,trankmichael/scipy,endolith/scipy,fernand/scipy,grlee77/scipy,surhudm/scipy,pyramania/scipy,e-q/scipy,WarrenWeckesser/scipy,nmayorov/scipy,befelix/scipy,chatcannon/scipy,giorgiop/scipy,vanpact/scipy,argriffing/scipy,Gillu13/scipy,kalvdans/scipy,Dapid/scipy,rmcgibbo/scipy,jakevdp/scipy,vhaasteren/scipy,josephcslater/scipy,mhogg/scipy,FRidh/scipy,Kamp9/scipy,njwilson23/scipy,mgaitan/scipy,richardotis/scipy,jakevdp/scipy,perimosocordiae/scipy,njwilson23/scipy,mdhaber/scipy,nvoron23/scipy,Gillu13/scipy,FRidh/scipy,zxsted/scipy,ales-erjavec/scipy,mikebenfield/scipy,befelix/scipy,jamestwebber/scipy,befelix/scipy,jseabold/scipy,mgaitan/scipy,gdooper/scipy,richardotis/scipy,sriki18/scipy,jseabold/scipy,zxsted/scipy,pyramania/scipy,zaxliu/scipy,mhogg/scipy,mtrbean/scipy,jjhelmus/scipy,mgaitan/scipy,aman-iitj/scipy,person142/scipy,mhogg/scipy,mortada/scipy,matthewalbani/scipy,richardotis/scipy,piyush0609/scipy,fernand/scipy,teoliphant/scipy,andim/scipy,aarchiba/scipy,nonhermitian/scipy,mingwpy/scipy,giorgiop/scipy,Stefan-Endres/scipy,vanpact/scipy,jor-/scipy,ortylp/scipy,gertingold/scipy,aeklant/scipy,aeklant/scipy,mhogg/scipy,ogrisel/scipy,juliantaylor/scipy,maniteja123/scipy,pnedunuri/scipy,efiring/scipy,lukauskas/scipy,sauliusl/scipy,vanpact/scipy,tylerjereddy/scipy,pyramania/scipy,aman-iitj/scipy,niknow/scipy,tylerjereddy/scipy,zaxliu/scipy,gef756/scipy,cpaulik/scipy,ilayn/scipy,pnedunuri/scipy,teoliphant/scipy,lukauskas/scipy,lukauskas/scipy,ortylp/scipy,pnedunuri/scipy,futurulus/scipy,larsmans/scipy,hainm/scipy,vigna/scipy,bkendzior/scipy,mortonjt/scipy,argriffing/scipy,efiring/scipy,Stefan-Endres/scipy,lhilt/scipy,trankmichael/scipy,sonnyhu/scipy,zxsted/scipy,maciejkula/scipy,pnedunuri/scipy,mhogg/scipy,arokem/scipy,richardotis/scipy,matthewalbani/scipy,sargas/scipy,aarchiba/scipy,grlee77/scipy,pbrod/scipy,anielsen001/scipy,kalvdans/scipy,arokem/scipy,gef756/scipy,lhilt/scipy,gdooper/scipy,Kamp9/scipy,sargas/scipy,apbard/scipy,vanpact/scipy,giorgiop/scipy,WillieMaddox/scipy,zxsted/scipy,juliantaylor/scipy,sriki18/scipy,futurulus/scipy,mikebenfield/scipy,vhaasteren/scipy,anielsen001/scipy,haudren/scipy,futurulus/scipy,zxsted/scipy,mdhaber/scipy,teoliphant/scipy,bkendzior/scipy,ChanderG/scipy,rmcgibbo/scipy,WillieMaddox/scipy,ilayn/scipy,jsilter/scipy,Stefan-Endres/scipy,Gillu13/scipy,jjhelmus/scipy,larsmans/scipy,Dapid/scipy,witcxc/scipy,raoulbq/scipy,jakevdp/scipy,vhaasteren/scipy,andyfaff/scipy,gdooper/scipy,mtrbean/scipy,Newman101/scipy,endolith/scipy,pbrod/scipy,anielsen001/scipy,Dapid/scipy,anntzer/scipy,aeklant/scipy,mdhaber/scipy,apbard/scipy,felipebetancur/scipy,aeklant/scipy,felipebetancur/scipy,ChanderG/scipy,josephcslater/scipy,minhlongdo/scipy,ilayn/scipy,vberaudi/scipy,Newman101/scipy,kleskjr/scipy,pschella/scipy,kalvdans/scipy,woodscn/scipy,andyfaff/scipy,arokem/scipy,gfyoung/scipy,fernand/scipy,zaxliu/scipy,matthewalbani/scipy,matthewalbani/scipy,gef756/scipy,cpaulik/scipy,newemailjdm/scipy,rgommers/scipy,jonycgn/scipy,apbard/scipy,surhudm/scipy,matthew-brett/scipy,chatcannon/scipy,Dapid/scipy,jonycgn/scipy,Newman101/scipy,aman-iitj/scipy,jor-/scipy,FRidh/scipy,kalvdans/scipy,jakevdp/scipy,nvoron23/scipy,perimosocordiae/scipy,juliantaylor/scipy,Stefan-Endres/scipy,njwilson23/scipy,witcxc/scipy,fernand/scipy,rgommers/scipy,mortada/scipy,ogrisel/scipy,sargas/scipy,gertingold/scipy,scipy/scipy,maciejkula/scipy,person142/scipy,mingwpy/scipy,lukauskas/scipy,gdooper/scipy,tylerjereddy/scipy,WillieMaddox/scipy,matthewalbani/scipy,njwilson23/scipy,andim/scipy,jjhelmus/scipy,bkendzior/scipy,fredrikw/scipy,haudren/scipy,larsmans/scipy,apbard/scipy,vigna/scipy,mingwpy/scipy,newemailjdm/scipy,nvoron23/scipy,petebachant/scipy,sriki18/scipy,raoulbq/scipy,WarrenWeckesser/scipy,andim/scipy,jamestwebber/scipy,jamestwebber/scipy,ilayn/scipy,maniteja123/scipy,minhlongdo/scipy,sauliusl/scipy,rmcgibbo/scipy,nonhermitian/scipy,ndchorley/scipy,gfyoung/scipy,surhudm/scipy,hainm/scipy,efiring/scipy,gdooper/scipy,dominicelse/scipy,Newman101/scipy,giorgiop/scipy,pbrod/scipy,pizzathief/scipy,josephcslater/scipy,raoulbq/scipy,witcxc/scipy,anntzer/scipy,richardotis/scipy,mikebenfield/scipy,behzadnouri/scipy,mdhaber/scipy,rgommers/scipy,scipy/scipy,sonnyhu/scipy,mtrbean/scipy,jsilter/scipy,anntzer/scipy,lhilt/scipy,pnedunuri/scipy,petebachant/scipy,nvoron23/scipy,gertingold/scipy,ortylp/scipy,ndchorley/scipy,chatcannon/scipy,minhlongdo/scipy,fredrikw/scipy,futurulus/scipy,surhudm/scipy,cpaulik/scipy,endolith/scipy,pizzathief/scipy,hainm/scipy,Kamp9/scipy,vberaudi/scipy,efiring/scipy,vhaasteren/scipy,mortada/scipy,chatcannon/scipy,gertingold/scipy,jjhelmus/scipy,pschella/scipy,pschella/scipy,witcxc/scipy,WillieMaddox/scipy,jseabold/scipy,andyfaff/scipy,maciejkula/scipy,sriki18/scipy,pizzathief/scipy,apbard/scipy,josephcslater/scipy,ChanderG/scipy,zerothi/scipy,Srisai85/scipy,newemailjdm/scipy,aman-iitj/scipy,jakevdp/scipy,aarchiba/scipy,maniteja123/scipy,nonhermitian/scipy,chatcannon/scipy,endolith/scipy,hainm/scipy,person142/scipy,maniteja123/scipy,Kamp9/scipy,ilayn/scipy,jamestwebber/scipy,endolith/scipy,ogrisel/scipy,Stefan-Endres/scipy,Gillu13/scipy,futurulus/scipy,cpaulik/scipy,anntzer/scipy,dominicelse/scipy,vhaasteren/scipy,ChanderG/scipy,nonhermitian/scipy,bkendzior/scipy,matthew-brett/scipy,matthew-brett/scipy,grlee77/scipy,gfyoung/scipy,WarrenWeckesser/scipy,sargas/scipy,mgaitan/scipy,Srisai85/scipy,andyfaff/scipy,jonycgn/scipy,kleskjr/scipy,ales-erjavec/scipy,anielsen001/scipy,niknow/scipy,Gillu13/scipy,woodscn/scipy,woodscn/scipy,ndchorley/scipy,aarchiba/scipy,behzadnouri/scipy,gfyoung/scipy,behzadnouri/scipy,rmcgibbo/scipy,behzadnouri/scipy,Dapid/scipy,argriffing/scipy,tylerjereddy/scipy,vberaudi/scipy,gef756/scipy,haudren/scipy,maciejkula/scipy,andim/scipy,dch312/scipy,befelix/scipy,lhilt/scipy,mortada/scipy,sargas/scipy,befelix/scipy,Shaswat27/scipy,jonycgn/scipy,behzadnouri/scipy,argriffing/scipy,argriffing/scipy,Eric89GXL/scipy,hainm/scipy,anielsen001/scipy,minhlongdo/scipy,haudren/scipy,newemailjdm/scipy,niknow/scipy,fredrikw/scipy,pizzathief/scipy,rmcgibbo/scipy,e-q/scipy,ndchorley/scipy,teoliphant/scipy,Newman101/scipy,nmayorov/scipy,maniteja123/scipy,pschella/scipy,FRidh/scipy,e-q/scipy,Srisai85/scipy,endolith/scipy,piyush0609/scipy,andyfaff/scipy,maciejkula/scipy,rmcgibbo/scipy,sriki18/scipy,Srisai85/scipy,mingwpy/scipy,pizzathief/scipy,mortonjt/scipy,vanpact/scipy,vberaudi/scipy,aman-iitj/scipy,pyramania/scipy,scipy/scipy,vberaudi/scipy,dominicelse/scipy,nmayorov/scipy,petebachant/scipy,mdhaber/scipy,ales-erjavec/scipy,Srisai85/scipy,jsilter/scipy,haudren/scipy,vigna/scipy,ales-erjavec/scipy,nmayorov/scipy,kleskjr/scipy,mingwpy/scipy,Shaswat27/scipy,felipebetancur/scipy,niknow/scipy,lukauskas/scipy,gertingold/scipy,andim/scipy,ales-erjavec/scipy,niknow/scipy,perimosocordiae/scipy,gef756/scipy,sauliusl/scipy,jjhelmus/scipy,trankmichael/scipy,gef756/scipy,hainm/scipy,mortada/scipy,raoulbq/scipy,jonycgn/scipy,vberaudi/scipy,perimosocordiae/scipy,kleskjr/scipy,efiring/scipy,Newman101/scipy,tylerjereddy/scipy,Srisai85/scipy,woodscn/scipy,behzadnouri/scipy,kalvdans/scipy,giorgiop/scipy,ortylp/scipy,minhlongdo/scipy,zerothi/scipy,nmayorov/scipy,zerothi/scipy,nvoron23/scipy,cpaulik/scipy,jsilter/scipy,mhogg/scipy,mortonjt/scipy,anntzer/scipy,person142/scipy,mdhaber/scipy,piyush0609/scipy,person142/scipy,aman-iitj/scipy,niknow/scipy,Stefan-Endres/scipy,sriki18/scipy,mortada/scipy,Eric89GXL/scipy,witcxc/scipy,bkendzior/scipy,juliantaylor/scipy,aarchiba/scipy,ChanderG/scipy,mortonjt/scipy,fredrikw/scipy,trankmichael/scipy,Gillu13/scipy,mtrbean/scipy,Kamp9/scipy,pbrod/scipy,sauliusl/scipy,larsmans/scipy,jseabold/scipy,ilayn/scipy,Eric89GXL/scipy,sauliusl/scipy,petebachant/scipy,WillieMaddox/scipy,pschella/scipy,kleskjr/scipy,anntzer/scipy,matthew-brett/scipy,felipebetancur/scipy,fredrikw/scipy,surhudm/scipy,sonnyhu/scipy,argriffing/scipy,FRidh/scipy,mikebenfield/scipy,ndchorley/scipy,dch312/scipy,mikebenfield/scipy,mortonjt/scipy,kleskjr/scipy,zaxliu/scipy,trankmichael/scipy,ortylp/scipy,Eric89GXL/scipy,newemailjdm/scipy,raoulbq/scipy,vigna/scipy,mgaitan/scipy,scipy/scipy,dch312/scipy,pbrod/scipy,sonnyhu/scipy,ortylp/scipy,felipebetancur/scipy,josephcslater/scipy,ChanderG/scipy,matthew-brett/scipy,piyush0609/scipy,woodscn/scipy,jor-/scipy,petebachant/scipy,teoliphant/scipy,cpaulik/scipy,felipebetancur/scipy,rgommers/scipy,pyramania/scipy,Kamp9/scipy,dominicelse/scipy,fernand/scipy,jsilter/scipy,mtrbean/scipy,perimosocordiae/scipy,jor-/scipy,futurulus/scipy,richardotis/scipy,Dapid/scipy,e-q/scipy,Shaswat27/scipy
234e50c105b7d7d1e77e1c392200668891130840
formish/__init__.py
formish/__init__.py
""" Base package to import top level modules """ from formish.forms import Form from formish.validation import FieldError, FormError, FormishError from formish.widgets import * from formish.util import form_in_request
""" Base package to import top level modules """ from formish.forms import Form from formish.validation import FieldError, FormError, FormishError, NoActionError from formish.widgets import * from formish.util import form_in_request
Add missing exception to package-level exports.
Add missing exception to package-level exports.
Python
bsd-3-clause
ish/formish,ish/formish,ish/formish
813ebbce962e7d59602a1f1693359b9d61bbef07
byceps/services/email/service.py
byceps/services/email/service.py
""" byceps.services.email.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import List, Optional from ... import email from ...typing import BrandID from .models import EmailConfig def find_sender_address_for_brand(brand_id: BrandID) -> Optional[str]: """Return the configured sender e-mail address for the brand.""" config = EmailConfig.query.get(brand_id) return config.sender_address def send_email(recipients: List[str], subject: str, body: str, *, sender: Optional[str]=None) -> None: """Send an e-mail.""" email.send(recipients, subject, body, sender=sender)
""" byceps.services.email.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import List, Optional from ... import email from ...typing import BrandID from .models import EmailConfig def find_sender_address_for_brand(brand_id: BrandID) -> Optional[str]: """Return the configured sender e-mail address for the brand.""" config = EmailConfig.query.get(brand_id) if config is None: return None return config.sender_address def send_email(recipients: List[str], subject: str, body: str, *, sender: Optional[str]=None) -> None: """Send an e-mail.""" email.send(recipients, subject, body, sender=sender)
Return `None` if no email configuration exists for brand instead of raising an exception
Return `None` if no email configuration exists for brand instead of raising an exception
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps
7822598afa31f0f556766c53ecff27cb8aca76d6
chipy_org/apps/meetings/utils.py
chipy_org/apps/meetings/utils.py
from django.core.exceptions import ObjectDoesNotExist import requests from apps.meetings.models import Meeting, RSVP def meetup_meeting_sync(api_key, meetup_event_id): url = "http://api.meetup.com/2/rsvps" params = dict(key=api_key, event_id=meetup_event_id) api_response = requests.get(url, params=params) chipy_meeting_instance = Meeting.objects.get(meetup_id=meetup_event_id) response = api_response.json() results = response['results'] for result in results: meetup_user_id = result['member']['member_id'] try: rsvp = RSVP.objects.get(meetup_user_id=meetup_user_id, meeting=chipy_meeting_instance) except ObjectDoesNotExist: rsvp = RSVP(meetup_user_id=meetup_user_id, meeting=chipy_meeting_instance) rsvp.response = 'Y' if result['response'] == 'yes' else 'N' rsvp.name = result['member']['name'] rsvp.save()
from django.core.exceptions import ObjectDoesNotExist import requests from apps.meetings.models import Meeting, RSVP def get_rsvp(meeting, meetup_member): """ Handles getting the rsvp instance to update from Meetup. Will return a new instance if needed. If there is a name collision, it will update the current RSVP with the Meetup Info. This isn't perfect by any stretch, but for our uses it should be good enough. """ meetup_user_id = meetup_member['member_id'] name_collisions = RSVP.objects.filter(name=meetup_member['name']) if name_collisions: rsvp = name_collisions[0] rsvp.meetup_user_id=meetup_user_id else: try: rsvp = RSVP.objects.get(meetup_user_id=meetup_user_id, meeting=meeting) except ObjectDoesNotExist: rsvp = RSVP(meetup_user_id=meetup_user_id, meeting=meeting) return rsvp def meetup_meeting_sync(api_key, meetup_event_id): url = "http://api.meetup.com/2/rsvps" params = dict(key=api_key, event_id=meetup_event_id) api_response = requests.get(url, params=params) meeting = Meeting.objects.get(meetup_id=meetup_event_id) response = api_response.json() results = response['results'] for result in results: rsvp = get_rsvp(meeting, result['member']) rsvp.response = 'Y' if result['response'] == 'yes' else 'N' rsvp.name = result['member']['name'] rsvp.save()
Handle name collisions from meetup by attaching the meetup id to the user. While not perfect, should be good enough.
Handle name collisions from meetup by attaching the meetup id to the user. While not perfect, should be good enough.
Python
mit
brianray/chipy.org,brianray/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,agfor/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,agfor/chipy.org,chicagopython/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org
fb719c54a41d90e07b62c82d1995f9c3149b68ec
adhocracy4/projects/views.py
adhocracy4/projects/views.py
from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated() @property def project(self): """ Emulate ProjectMixin interface for template sharing. """ return self.get_object()
from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated()
Remove project property which is already set by the PhaseDispatchMixin
Remove project property which is already set by the PhaseDispatchMixin
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
a910295b2cbffdcb78c99218a48cb0120ecc3085
ynr/apps/ynr_refactoring/settings.py
ynr/apps/ynr_refactoring/settings.py
from .helpers.popolo_fields import simple_fields SIMPLE_POPOLO_FIELDS = simple_fields
from enum import Enum, unique from .helpers.popolo_fields import simple_fields SIMPLE_POPOLO_FIELDS = simple_fields @unique class PersonIdentifierFields(Enum): email = "Email" facebook_page_url = "Facebook Page" facebook_personal_url = "Facebook Personal" homepage_url = "Homepage" linkedin_url = "Linkedin" party_ppc_page_url = "Party PPC Page" twitter_username = "Twitter" wikipedia_url = "Wikipedia" # party_candidate_page = "Party Candidate Page" # other = "Other"
Add Enum for PersonIdentifier Fields
Add Enum for PersonIdentifier Fields This is similar to the work to remove SimplePopoloFields from the database layer. The values here are all the values we want in the initial version of the "n-links" on the person page model. One day we want to enable any type of link, specified by the user. That's too big a change to do all at once, so step one is to remove ComplexPopoloFields in the database but still use a fixed list of fields.
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
0b3499beebeb789323d293513fdfc98565f6e02a
examples/IPLoM_example.py
examples/IPLoM_example.py
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * RawLogPath = '/home/hudan/Git/labeled-authlog/dataset/161.166.232.17/' RawLogFile = 'auth.log.anon' OutputPath = './results' para = Para(path=RawLogPath, logname=RawLogFile, save_path=OutputPath) myparser = IPLoM(para) time = myparser.main_process() print ('The running time of IPLoM is', time)
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/clustering') from ClusterUtility import * from ClusterEvaluation import * ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address + '/' standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.get_logs() ClusterUtility.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ClusterEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
Add evaluation metrics to example
Add evaluation metrics to example
Python
mit
studiawan/pygraphc
f3f210b523f1733e48bb6316ecbb15e198dd503c
examples/field_example.py
examples/field_example.py
import graphene class Person(graphene.Interface): name = graphene.String() age = graphene.ID() class Patron(Person): id = graphene.ID() class Query(graphene.ObjectType): patron = graphene.Field(Patron) def resolve_patron(self, args, info): return Patron(id=1, name='Demo') schema = graphene.Schema(query=Query) query = ''' query something{ patron { id name } } ''' result = schema.execute(query) # Print the result print(result.data['patron'])
import graphene class Patron(graphene.ObjectType): id = graphene.ID() name = graphene.String() age = graphene.ID() class Query(graphene.ObjectType): patron = graphene.Field(Patron) def resolve_patron(self, args, info): return Patron(id=1, name='Demo') schema = graphene.Schema(query=Query) query = ''' query something{ patron { id name } } ''' result = schema.execute(query) print(result.data['patron'])
Modify the field example to remove the use of interface
Modify the field example to remove the use of interface
Python
mit
sjhewitt/graphene,Globegitter/graphene,Globegitter/graphene,graphql-python/graphene,graphql-python/graphene,sjhewitt/graphene
ed4666b0d1bf5b8f82e298dfb043cce158c4ba2f
morepath/tests/fixtures/template_unknown_extension_no_render.py
morepath/tests/fixtures/template_unknown_extension_no_render.py
import morepath import os from .template_engine import FormatLoader class App(morepath.App): pass @App.path(path='{name}') class Person(object): def __init__(self, name): self.name = name @App.template_loader(extension='.unknown') def get_template_loader(template_directories, settings): return FormatLoader(template_directories) @App.html(model=Person, template='person.unknown') def person_default(self, request): return { 'name': self.name }
import morepath import os from .template_engine import FormatLoader class App(morepath.App): pass @App.path(path='{name}') class Person(object): def __init__(self, name): self.name = name @App.template_loader(extension='.unknown') def get_template_loader(template_directories, settings): return FormatLoader(template_directories) @App.template_directory() def get_template_directory(): return 'templates' @App.html(model=Person, template='person.unknown') def person_default(self, request): return { 'name': self.name }
Fix so that error under test actually gets triggered.
Fix so that error under test actually gets triggered.
Python
bsd-3-clause
taschini/morepath,faassen/morepath,morepath/morepath
27fe9d6531a2e76affd9388db53c0433062a9cfa
photonix/photos/management/commands/create_library.py
photonix/photos/management/commands/create_library.py
import os from pathlib import Path from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from photonix.photos.models import Library, LibraryPath, LibraryUser from photonix.photos.utils.db import record_photo from photonix.photos.utils.fs import determine_destination, download_file User = get_user_model() class Command(BaseCommand): help = 'Create a library for a user' def create_library(self, username, library_name): # Get user user = User.objects.get(username=username) # Create Library library, _ = Library.objects.get_or_create( name=library_name, ) library_path, _ = LibraryPath.objects.get_or_create( library=library, type='St', backend_type='Lo', path='/data/photos/', url='/photos/', ) library_user, _ = LibraryUser.objects.get_or_create( library=library, user=user, owner=True, ) print(f'Library "{library_name}" created successfully for user "{username}"') def add_arguments(self, parser): # Positional arguments parser.add_argument('username', nargs='+', type=str) parser.add_argument('library_name', nargs='+', type=str) def handle(self, *args, **options): self.create_library(options['username'][0], options['library_name'][0])
import os from pathlib import Path from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from photonix.photos.models import Library, LibraryPath, LibraryUser from photonix.photos.utils.db import record_photo from photonix.photos.utils.fs import determine_destination, download_file User = get_user_model() class Command(BaseCommand): help = 'Create a library for a user' def create_library(self, username, library_name, path): # Get user user = User.objects.get(username=username) # Create Library library, _ = Library.objects.get_or_create( name=library_name, ) library_path, _ = LibraryPath.objects.get_or_create( library=library, type='St', backend_type='Lo', path=path, ) library_user, _ = LibraryUser.objects.get_or_create( library=library, user=user, owner=True, ) print(f'Library "{library_name}" with path "{path}" created successfully for user "{username}"') def add_arguments(self, parser): # Positional arguments parser.add_argument('username', type=str) parser.add_argument('library_name', type=str) parser.add_argument('--path', type=str, default='/data/photos') def handle(self, *args, **options): self.create_library(options['username'], options['library_name'], options['path'])
Fix path cannot be set when creating new library
Fix path cannot be set when creating new library
Python
agpl-3.0
damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager
93756f6f72d9f797c058bedcb3d6d7546a5a83f3
server/management/commands/friendly_model_name.py
server/management/commands/friendly_model_name.py
''' Retrieves the firendly model name for machines that don't have one yet. ''' from django.core.management.base import BaseCommand, CommandError from server.models import Machine from django.db.models import Q import server.utils as utils class Command(BaseCommand): help = 'Retrieves friendly model names for machines without one' def handle(self, *args, **options): # Get all the machines without a friendly model name and have a model no_friendly = Machine.objects.filter( Q(machine_model_friendly__isnull=True) | Q(machine_model_friendly='') ).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin') for machine in no_friendly[:100]: print(f'Processing {machine}' machine.machine_model_friendly = utils.friendly_machine_model(machine) machine.save()
"""Retrieves the friendly model name for machines that don't have one yet.""" from django.core.management.base import BaseCommand, CommandError from django.db.models import Q import server.utils as utils from server.models import Machine class Command(BaseCommand): help = 'Retrieves friendly model names for machines without one' def handle(self, *args, **options): # Get all the machines without a friendly model name and have a model no_friendly = Machine.objects.filter( Q(machine_model_friendly__isnull=True) | Q(machine_model_friendly='') ).exclude(machine_model__isnull=True).exclude(machine_model='').filter(os_family='Darwin') for machine in no_friendly[:100]: print(f'Processing {machine}') machine.machine_model_friendly = utils.friendly_machine_model(machine) machine.save()
Fix missing paren, imports, spelling.
Fix missing paren, imports, spelling.
Python
apache-2.0
sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal
ab41dfa53325ee90032c4ed1b2e6e3c90b808ecf
contact/views.py
contact/views.py
import binascii from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.db import IntegrityError, transaction from django.conf import settings from django.template.loader import render_to_string from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.http import Http404 from contact.forms import ContactForm # Create your views here. def contact(request): form_init = { 'username': request.user.username, 'ip_address': request.META.get('REMOTE_ADDR'), } if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): messages.success('Success!') else: messages.error('Boo! Hiss!') else: form = ContactForm(initial=form_init) return render(request, 'contact/contact.html', {'form': form})
import binascii from django.shortcuts import render from django.contrib import messages from django.core.mail import send_mail from contact.forms import ContactForm # Create your views here. def contact(request): form_init = { 'username': request.user.username, 'ip_address': request.META.get('REMOTE_ADDR'), 'email': request.user.email, } if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): messages.success(request, 'Success!') else: messages.error(request, 'Boo! Hiss!') else: form = ContactForm(initial=form_init) return render(request, 'contact/contact.html', {'form': form})
Clean up import, pre-fill email address
Clean up import, pre-fill email address If user is logged in, their email address is automatically filled in for them. Also fixed an error with the messages usage, namely I forgot to pass in the request object.
Python
mit
Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters
7641293947dba9f721cdd0364a638b9f7714033a
examples/pax_mininet_node.py
examples/pax_mininet_node.py
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __init__(self, name, **params): super(PaxNode, self).__init__(name, **params) def config(self, **params): super(PaxNode, self).config(**params) # Setup iptable rules to drop incoming packets on each interface: # Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets # to prevent the OS from handling them and responding. print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man" for intf in self.intfList(): self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name) def terminate( self ): # Remove iptables rules for intf in self.intfList(): runCmd(net, nat0, "iptables -D INPUT -p tcp -i %s -j DROP" % intf.name) super( NAT, self ).terminate()
# coding: latin-1 """ pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node. """ from mininet.node import Node from mininet.log import info, warn class PaxNode( Node ): "PaxNode: A node which allows Pax to behave as the sole packet hander on that node." def __init__(self, name, **params): super(PaxNode, self).__init__(name, **params) def config(self, **params): super(PaxNode, self).config(**params) # Setup iptable rules to drop incoming packets on each interface: # Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets # to prevent the OS from handling them and responding. print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man" for intf in self.intfList(): self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name) def terminate(self): # Remove iptables rules for intf in self.intfList(): self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name) super(PaxNode, self).terminate()
Fix bug in Pax Mininet node class
Fix bug in Pax Mininet node class
Python
apache-2.0
niksu/pax,TMVector/pax,niksu/pax,niksu/pax,TMVector/pax
09a78126595ff355f59f70e4f381c3e2c4bef045
apps/innovate/tests/test_views.py
apps/innovate/tests/test_views.py
from django.core.urlresolvers import reverse from django.test import Client from projects.models import Project from innovate import urls def test_routes(): c = Client() for pattern in urls.urlpatterns: response = c.get(reverse(pattern.name)) assert response.status_code == 301 assert response.has_header('location') location = response.get('location', None) assert location is not None response = c.get(location) assert response.status_code == 200 def test_featured(): project = Project.objects.create( name=u'Test Project', slug=u'test-project', description=u'Blah', featured=True ) c = Client() response = c.get('/en-US/') assert response.status_code == 200 assert project.name in response.content
from django.core.urlresolvers import reverse from django.test import Client from django.test.client import RequestFactory from projects.models import Project from innovate import urls from innovate.views import handle404, handle500 def test_routes(): c = Client() for pattern in urls.urlpatterns: response = c.get(reverse(pattern.name)) assert response.status_code == 301 assert response.has_header('location') location = response.get('location', None) assert location is not None response = c.get(location) assert response.status_code == 200 def test_featured(): project = Project.objects.create( name=u'Test Project', slug=u'test-project', description=u'Blah', featured=True ) c = Client() response = c.get('/en-US/') assert response.status_code == 200 assert project.name in response.content def test_404_handler(): """Test that the 404 error handler renders and gives the correct code.""" response = handle404(RequestFactory().get('/not/a/real/path/')) assert response.status_code == 404 def test_500_handler(): """Test that the 500 error handler renders and gives the correct code.""" response = handle500(RequestFactory().get('/not/a/real/path/')) assert response.status_code == 500
Add tests for the 404 and 500 error handlers.
Add tests for the 404 and 500 error handlers.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
fe451116ffcb12621600310b6d4ca9b6316494ff
scripts/zpe.py
scripts/zpe.py
import logging from vaspy.iter import OutCar _logger = logging.getLogger("vaspy.script") if "__main__" == __name__: outcar = OutCar() poscar = outcar.poscar freq_types = outcar.freq_types # Frequency info. _logger.info("{:<10s}{:<20s}".format("atom", "freq_type")) _logger.info("-"*25) idx = 0 tfs = poscar.tf.tolist() for atom_idx, tf in enumerate(tfs): if tf == ["T", "T", "T"]: _logger.info("{:<10d}{:<5s}{:<5s}{:<5s}".format(atom_idx+1, *freq_types[idx])) idx += 1 # Zero point energy. _logger.info("") _logger.info("ZPE = {}".format(outcar.zpe))
import logging from vaspy.iter import OutCar _logger = logging.getLogger("vaspy.script") if "__main__" == __name__: outcar = OutCar() poscar = outcar.poscar freq_types = outcar.freq_types # Frequency info. _logger.info("{:<10s}{:<10s}{:<20s}".format("atom", "type", "freq_type")) _logger.info("-"*35) # Get atom types. atom_types = [] for t, n in zip(poscar.atoms, poscar.atoms_num): atom_types += [t]*n idx = 0 tfs = poscar.tf.tolist() for atom_idx, tf in enumerate(tfs): if tf == ["T", "T", "T"]: msg = "{:<10d}{:<10s}{:<5s}{:<5s}{:<5s}" msg = msg.format(atom_idx+1, atom_types[atom_idx], *freq_types[idx]) _logger.info(msg) idx += 1 # Zero point energy. _logger.info("") _logger.info("ZPE = {}".format(outcar.zpe))
Add atom type info output.
Add atom type info output.
Python
mit
PytLab/VASPy,PytLab/VASPy
24fe59c0f5df9343337549eb4495d6ca0e1e58d1
iconizer/iconizer_main.py
iconizer/iconizer_main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from iconizer.console.launcher import CrossGuiLauncher from iconizer.qtconsole.PyQtGuiFactory import PyQtGuiFactory class Iconizer(object): def __init__(self): self.server = CrossGuiLauncher(PyQtGuiFactory()) self.server.start() self.server.start_cross_gui_launcher_no_return() def execute(self, app_descriptor_dict): #Send request to start a new app self.server.launch(app_descriptor_dict) def main(): Iconizer() if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from iconizer.console.launcher import CrossGuiLauncher from iconizer.qtconsole.PyQtGuiFactory import PyQtGuiFactory class Iconizer(object): def start_gui(self): self.server = CrossGuiLauncher(PyQtGuiFactory()) self.server.start() self.server.start_cross_gui_launcher_no_return() def execute(self, app_descriptor_dict): #Send request to start a new app self.server.launch(app_descriptor_dict) def main(): Iconizer().start_gui() if __name__ == '__main__': main()
Move GUI creation out of __init__ function.
Move GUI creation out of __init__ function.
Python
bsd-3-clause
weijia/iconizer
dad3eb5c1b0e188671884e97260422a90bdd5c21
gitcommitautosave.py
gitcommitautosave.py
"""Git Commit Auto Save. Sublime Text 3 package to auto save commit messages when the window is closed. This allows the user to close the window without having to save before, or having to deal with the "Save File" popup. """ import sublime_plugin class GitCommitAutoSave(sublime_plugin.EventListener): def on_load(self, view): if view.file_name().endswith('COMMIT_EDITMSG'): view.set_scratch(True) # disable save file dialog on exit def on_pre_close(self, view): if view.file_name().endswith('COMMIT_EDITMSG'): view.run_command("save")
"""Git Commit Auto Save. Sublime Text 3 package to auto save commit messages when the window is closed. This allows the user to close the window without having to save before, or having to deal with the "Save File" popup. """ import sublime_plugin class GitCommitAutoSave(sublime_plugin.EventListener): def on_load(self, view): if view.file_name() and view.file_name().endswith('COMMIT_EDITMSG'): view.set_scratch(True) # disable save file dialog on exit def on_pre_close(self, view): if view.file_name() and view.file_name().endswith('COMMIT_EDITMSG'): view.run_command("save")
Fix 'NoneType' object has no attribute 'endswith'
Fix 'NoneType' object has no attribute 'endswith'
Python
mit
aristidesfl/sublime-git-commit-message-auto-save
c300453131360ef9c48586f48287d6c24b3a94a2
jsonrpcclient/__init__.py
jsonrpcclient/__init__.py
"""__init__.py""" from .request import Request, Notification
"""__init__.py""" from .request import Request, Notification from .http_client import HTTPClient def request(endpoint, method, *args, **kwargs): """ A convenience function. Instantiates and executes a HTTPClient request, then throws it away. """ return HTTPClient(endpoint).request(method, *args, **kwargs) def notify(endpoint, method, *args, **kwargs): """ A convenience function. Instantiates and executes a HTTPClient request, then throws it away. """ return HTTPClient(endpoint).notify(method, *args, **kwargs)
Add convenience functions 'request' and 'notify'
Add convenience functions 'request' and 'notify' Closes #54
Python
mit
bcb/jsonrpcclient
91b9e5d71c323be2e5e0d1aa16e47cc49d45acc4
likes/middleware.py
likes/middleware.py
try: from hashlib import md5 except ImportError: from md5 import md5 from django.http import HttpResponseBadRequest from secretballot.middleware import SecretBallotIpUseragentMiddleware class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware): def generate_token(self, request): if request.user.is_authenticated(): return request.user.username else: try: s = u''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT'])) return md5(s).hexdigest() except KeyError: return None
try: from hashlib import md5 except ImportError: from md5 import md5 from django.http import HttpResponseBadRequest from secretballot.middleware import SecretBallotIpUseragentMiddleware class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware): def generate_token(self, request): if request.user.is_authenticated(): return request.user.username else: try: s = ''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT'])) return md5(s.encode('utf-8')).hexdigest() except KeyError: return None
Fix hashing for Python 3
Fix hashing for Python 3
Python
bsd-3-clause
Afnarel/django-likes,Afnarel/django-likes,Afnarel/django-likes
c62e1b325a536294b3285f8cbcad7d66a415ee23
heat/objects/base.py
heat/objects/base.py
# Copyright 2015 Intel Corp. # # 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. """Heat common internal object model""" from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0'
# Copyright 2015 Intel Corp. # # 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. """Heat common internal object model""" import weakref from oslo_versionedobjects import base as ovoo_base class HeatObject(ovoo_base.VersionedObject): OBJ_PROJECT_NAMESPACE = 'heat' VERSION = '1.0' @property def _context(self): if self._contextref is None: return ctxt = self._contextref() assert ctxt is not None, "Need a reference to the context" return ctxt @_context.setter def _context(self, context): if context: self._contextref = weakref.ref(context) else: self._contextref = None
Use a weakref for the data object context
Use a weakref for the data object context There are no known circular reference issues caused by storing the context in data objects, but the following changes will refer to data objects in the context, so this change prevents any later issues. Change-Id: I3680e5678003cf339a98fbb7a2b1b387fb2243c0 Related-Bug: #1578854
Python
apache-2.0
noironetworks/heat,openstack/heat,openstack/heat,cwolferh/heat-scratch,noironetworks/heat,cwolferh/heat-scratch
c6dae4cbd8d8dcbcd323526c2811fea9525bcb74
__init__.py
__init__.py
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
Add an event module import
Add an event module import
Python
lgpl-2.1
platipy/spyral
42701f0ba5147bbd1aeeb2871f1b9970bcb7e01e
pygraphc/clustering/ClusterUtility.py
pygraphc/clustering/ClusterUtility.py
from itertools import combinations class ClusterUtility(object): @staticmethod def get_geometric_mean(weights): multiplication = 1 for weight in weights: multiplication = multiplication * weight gmean = 0.0 multiplication = round(multiplication, 5) if multiplication > 0.0: k = float(len(weights)) gmean = multiplication ** (1 / k) return round(gmean, 5) @staticmethod def get_weighted_cliques(graph, cliques, threshold): weighted_kcliques = [] for clique in cliques: weights = [] for u, v in combinations(clique, 2): reduced_precision = round(graph[u][v]['weight'], 5) weights.append(reduced_precision) gmean = ClusterUtility.get_geometric_mean(weights) if gmean > threshold: weighted_kcliques.append(frozenset(clique)) return weighted_kcliques @staticmethod def set_cluster_id(graph, clusters): cluster_id = 0 for cluster in clusters: for node in cluster: graph.node[node]['cluster'] = cluster_id cluster_id += 1
from itertools import combinations class ClusterUtility(object): @staticmethod def get_geometric_mean(weights): multiplication = 1 for weight in weights: multiplication = multiplication * weight gmean = 0.0 if multiplication > 0.0: k = float(len(weights)) gmean = multiplication ** (1 / k) return round(gmean, 5) @staticmethod def get_weighted_cliques(graph, cliques, threshold): weighted_kcliques = [] for clique in cliques: weights = [] for u, v in combinations(clique, 2): reduced_precision = round(graph[u][v][0]['weight'], 5) weights.append(reduced_precision) gmean = ClusterUtility.get_geometric_mean(weights) if gmean > threshold: weighted_kcliques.append(frozenset(clique)) return weighted_kcliques @staticmethod def set_cluster_id(graph, clusters): cluster_id = 0 for cluster in clusters: for node in cluster: graph.node[node]['cluster'] = cluster_id cluster_id += 1
Remove round of multiplication result for get_geometric_mean and bug fix get edge weight
Remove round of multiplication result for get_geometric_mean and bug fix get edge weight
Python
mit
studiawan/pygraphc
039a19032bebd1e6852990f8aacf05042f000070
args.py
args.py
import inspect def argspec_set(func): if not hasattr(func, 'argspec'): func.argspec = inspect.getargspec(func) def argspec_iscompat(func, lenargs): spec = func.argspec minargs = len(spec.args) - len(spec.defaults or ()) maxargs = len(spec.args) if spec.varargs is None else None return lenargs >= minargs and (maxargs is None or lenargs <= maxargs) class ArgCountError(Exception): pass
import inspect def argspec_set(func): if not hasattr(func, 'argspec'): func.argspec = inspect.getargspec(func) def argspec_iscompat(func, lenargs): spec = func.argspec minargs = len(spec.args) - len(spec.defaults or ()) maxargs = len(spec.args) if spec.varargs is None else float("infinity") return minargs <= lenargs <= maxargs class ArgCountError(Exception): pass
Simplify funcion arg compatibility check
Simplify funcion arg compatibility check
Python
mit
infogulch/pyspades-events
bdfc87ff9f9b67f038248052805327278309e558
openacademy/model/openacademy_session.py
openacademy/model/openacademy_session.py
from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor", "=", True), ("category_id", "ilike", "Teacher"), ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
Add domain or and ilike
[REF] openacademy: Add domain or and ilike
Python
apache-2.0
mapuerta/openacademy-proyect
8d50750ae94e2c94059dcbf1009dd46441d44842
__init__.py
__init__.py
# -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser from .momentjs import momentjs app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' app.jinja_env.globals['momentjs'] = momentjs # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB'] = config['MongoDB']['db_name'] app.config['MONGODB_HOST'] = config['MongoDB']['host'] app.config['MONGODB_PORT'] = int(config['MongoDB']['port']) app.config['MONGODB_USERNAME'] = config['MongoDB']['username'] app.config['MONGODB_PASSWORD'] = config['MongoDB']['password'] db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) from weighttracker.views.foodjournal_views import foodjournals app.register_blueprint(foodjournals) register_blueprints(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': app.run()
# -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser from .momentjs import momentjs app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' app.jinja_env.globals['momentjs'] = momentjs # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB_SETTINGS'] = { 'name': config['MongoDB']['db_name'], 'host': config['MongoDB']['host'], 'port': int(config['MongoDB']['port']), 'username': config['MongoDB']['username'], 'password': config['MongoDB']['password']} db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) from weighttracker.views.foodjournal_views import foodjournals app.register_blueprint(foodjournals) register_blueprints(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': app.run()
Update how we set the connection information for MongoDB to support Mongo 3.0.5
Update how we set the connection information for MongoDB to support Mongo 3.0.5 Signed-off-by: Robert Dempsey <715b5a941e732be1613fdd9d94dfd8e50c02b187@gmail.com>
Python
mit
rdempsey/weight-tracker,rdempsey/weight-tracker,rdempsey/weight-tracker
5057b70a59c1a3c8301928c0297d4012bd96b21a
mapApp/views/index.py
mapApp/views/index.py
from django.shortcuts import render from mapApp.models import Incident, Theft, Hazard, Official, AlertArea from mapApp.forms import IncidentForm, HazardForm, TheftForm, GeofenceForm, EditForm import datetime def index(request, lat=None, lng=None, zoom=None): incidents = Incident.objects.select_related('point').all() now = datetime.datetime.now() context = { # Model data used by map 'collisions': incidents.filter(p_type__exact="collision"), 'nearmisses': incidents.filter(p_type__exact="nearmiss"), 'hazards': Hazard.objects.select_related('point').exclude(expires_date__lt=now), 'thefts': Theft.objects.select_related('point').all(), # 'officials': officialResult, "geofences": AlertArea.objects.filter(user=request.user.id), # Form data used by map "incidentForm": IncidentForm(), "hazardForm": HazardForm(), "theftForm": TheftForm(), "geofenceForm": GeofenceForm(), "editForm": EditForm() } # Add zoom and center data if present if not None in [lat, lng, zoom]: context['lat']= float(lat) context['lng']= float(lng) context['zoom']= int(zoom) return render(request, 'mapApp/index.html', context)
from django.shortcuts import render from mapApp.models import Incident, Theft, Hazard, Official, AlertArea from mapApp.forms import IncidentForm, HazardForm, TheftForm, GeofenceForm, EditForm import datetime def index(request, lat=None, lng=None, zoom=None): incidents = Incident.objects.select_related('point').all() now = datetime.datetime.now() context = { # Model data used by map 'collisions': incidents.filter(p_type__exact="collision"), 'nearmisses': incidents.filter(p_type__exact="nearmiss"), 'hazards': Hazard.objects.select_related('point').exclude(expires_date__lt=now).exclude(hazard_fixed=True), 'thefts': Theft.objects.select_related('point').all(), # 'officials': officialResult, "geofences": AlertArea.objects.filter(user=request.user.id), # Form data used by map "incidentForm": IncidentForm(), "hazardForm": HazardForm(), "theftForm": TheftForm(), "geofenceForm": GeofenceForm(), "editForm": EditForm() } # Add zoom and center data if present if not None in [lat, lng, zoom]: context['lat']= float(lat) context['lng']= float(lng) context['zoom']= int(zoom) return render(request, 'mapApp/index.html', context)
Remove expired hazards from main map
Remove expired hazards from main map
Python
mit
SPARLab/BikeMaps,SPARLab/BikeMaps,SPARLab/BikeMaps
19af4b621a50639a0c1156bab1c97c7b827b89a8
django_nose/tools.py
django_nose/tools.py
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8 """ Assertions that sort of follow Python unittest/Django test cases """ from django.test.testcases import TestCase import re ## Python from nose import tools for t in dir(tools): if t.startswith('assert_'): vars()[t] = getattr(tools, t) ## Django caps = re.compile('([A-Z])') def pep8(name): return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) class Dummy(TestCase): def nop(): pass _t = Dummy('nop') for at in [ at for at in dir(_t) if at.startswith('assert') and not '_' in at ]: pepd = pep8(at) vars()[pepd] = getattr(_t, at) del Dummy del _t del pep8 ## New def assert_code(response, status_code, msg_prefix=''): """Asserts the response was returned with the given status code """ if msg_prefix: msg_prefix = '%s: ' % msg_prefix assert response.status_code == status_code, \ 'Response code was %d (expected %d)' % \ (response.status_code, status_code) def assert_ok(response, msg_prefix=''): """Asserts the response was returned with status 200 (OK) """ return assert_code(response, 200, msg_prefix=msg_prefix) # EOF
# vim: tabstop=4 expandtab autoindent shiftwidth=4 fileencoding=utf-8 """ Provides Nose and Django test case assert functions """ from django.test.testcases import TestCase import re ## Python from nose import tools for t in dir(tools): if t.startswith('assert_'): vars()[t] = getattr(tools, t) ## Django caps = re.compile('([A-Z])') def pep8(name): return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) class Dummy(TestCase): def nop(): pass _t = Dummy('nop') for at in [ at for at in dir(_t) if at.startswith('assert') and not '_' in at ]: pepd = pep8(at) vars()[pepd] = getattr(_t, at) del Dummy del _t del pep8 ## New def assert_code(response, status_code, msg_prefix=''): """Asserts the response was returned with the given status code """ if msg_prefix: msg_prefix = '%s: ' % msg_prefix assert response.status_code == status_code, \ 'Response code was %d (expected %d)' % \ (response.status_code, status_code) def assert_ok(response, msg_prefix=''): """Asserts the response was returned with status 200 (OK) """ return assert_code(response, 200, msg_prefix=msg_prefix) # EOF
Make the heading doc string a bit more descriptive
Make the heading doc string a bit more descriptive
Python
bsd-3-clause
brilliant-org/django-nose,franciscoruiz/django-nose,sociateru/django-nose,millerdev/django-nose,fabiosantoscode/django-nose-123-fix,dgladkov/django-nose,aristiden7o/django-nose,krinart/django-nose,aristiden7o/django-nose,krinart/django-nose,fabiosantoscode/django-nose-123-fix,franciscoruiz/django-nose,millerdev/django-nose,harukaeru/django-nose,alexhayes/django-nose,Deepomatic/django-nose,harukaeru/django-nose,360youlun/django-nose,sociateru/django-nose,Deepomatic/django-nose,daineX/django-nose,brilliant-org/django-nose,360youlun/django-nose,daineX/django-nose,alexhayes/django-nose,dgladkov/django-nose
78ec1cffde6443016bae2c8aefdb67ab26bfab10
__init__.py
__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "Wifi connection", "author": "Ultimaker", "description": catalog.i18nc("Wifi connection", "Wifi connection"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import OctoPrintOutputDevicePlugin from . import DiscoverOctoPrintAction from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "type": "extension", "plugin": { "name": "OctoPrint connection", "author": "fieldOfView", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"), "api": 3 } } def register(app): return { "output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(), "machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction() }
Update plugin information (name, description, version, author)
Update plugin information (name, description, version, author)
Python
agpl-3.0
fieldOfView/OctoPrintPlugin
762ba71537cebac83970fbfb19725054b127191b
__init__.py
__init__.py
from .blendergltf import *
if 'loaded' in locals(): import imp imp.reload(blendergltf) from .blendergltf import * else: loaded = True from .blendergltf import *
Improve reloading of the module
Improve reloading of the module
Python
apache-2.0
Kupoman/blendergltf,lukesanantonio/blendergltf
37069b80e9ab17f7d3cdbe8baf7085ff67780914
minimongo/__init__.py
minimongo/__init__.py
# -*- coding: utf-8 -*- ''' minimongo ~~~~~~~~~ Minimongo is a lightweight, schemaless, Pythonic Object-Oriented interface to MongoDB. ''' from minimongo.index import Index from minimongo.collection import Collection from minimongo.model import Model from minimongo.options import configure __all__ = ('Collection', 'Index', 'Model', 'configure')
# -*- coding: utf-8 -*- ''' minimongo ~~~~~~~~~ Minimongo is a lightweight, schemaless, Pythonic Object-Oriented interface to MongoDB. ''' from minimongo.index import Index from minimongo.collection import Collection from minimongo.model import Model, AttrDict from minimongo.options import configure __all__ = ('Collection', 'Index', 'Model', 'configure', 'AttrDict')
Add AttrDict to the top level
Add AttrDict to the top level
Python
bsd-2-clause
terianil/minimongo,slacy/minimongo,terianil/minimongo
95e1f9517d79fb48bb9601e2d94419c6e2c984ca
tools/data2c.py
tools/data2c.py
#!/usr/bin/python import sys import os.path import string def path2varname(path): path = os.path.basename(path) s = '' for c in path: if c in string.ascii_letters or c in string.digits: s += c else: s += '_' return s def main(): for path in sys.argv[1:]: varname = path2varname(path) with open(path, 'rb') as f: sys.stdout.write('static const char %s[] = {' % varname) data = f.read() i = 0 for c in data: if i % 16 == 0: sys.stdout.write('\n\t') i += 1 sys.stdout.write('0x%02x, ' % ord(c)) sys.stdout.write('\n};\n\n') if __name__ == '__main__': main()
#!/usr/bin/python import sys import os.path import string import getopt cflag = 0 # clean output: just the hexdump def path2varname(path): path = os.path.basename(path) s = '' for c in path: if c in string.ascii_letters or c in string.digits: s += c else: s += '_' return s def main(): global cflag opts, args = getopt.getopt(sys.argv[1:], "c") for (x, y) in opts: if x == "-c": cflag += 1 for path in args: varname = path2varname(path) with open(path, 'rb') as f: if not cflag: sys.stdout.write('static const char %s[] = {' % varname) data = f.read() i = 0 for c in data: if i % 16 == 0: sys.stdout.write('\n') if not cflag: sys.stdout.write('\t') i += 1 sys.stdout.write('0x%02x, ' % ord(c)) if not cflag: sys.stdout.write('\n};') sys.stdout.write('\n') if __name__ == '__main__': main()
Add -c option: output only hexdump, without C variable wrapper.
Add -c option: output only hexdump, without C variable wrapper.
Python
isc
S010/misc,S010/misc,S010/misc,S010/misc,S010/misc,S010/misc,S010/misc,S010/misc,S010/misc
aedc449ec40a2c0407a38608e8e800b09c6c25b0
tests/model.py
tests/model.py
import mongomock from mongo_thingy import Model def test_collection_alias(): col = mongomock.MongoClient().db.collection class Foo(Model): _collection = col assert Foo.collection == col def test_get_database_from_table(): col = mongomock.MongoClient().db.collection class Foo(Model): _collection = col assert isinstance(Foo.database, mongomock.Database)
import mongomock from mongo_thingy import Model def test_collection_alias(): col = mongomock.MongoClient().db.collection class Foo(Model): _collection = col assert Foo.collection == col def test_get_database_from_table(): col = mongomock.MongoClient().db.collection class Foo(Model): _collection = col assert isinstance(Foo.database, mongomock.Database) def test_get_table_from_database(): db = mongomock.MongoClient().db class Foo(Model): _database = db assert Foo.collection_name == "foo"
Add a test for _get_table_from_database
Add a test for _get_table_from_database
Python
mit
numberly/mongo-thingy