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... | # 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... | 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/cryptograp... |
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 quot... | # 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 qu... | 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... | 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 cat... | 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()
d... | 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 = ObjectIdF... | 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_arg... | 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_arg... | 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 fo... | 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/ci... |
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 dispat... | # -*- 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 dispat... | 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'
# Impo... | 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... | 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... | 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
"""
... | #--
# 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
"""
... | 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 cal... | 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 cal... | 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"... | 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).... | 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_... | # -*- 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")
... | 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
... | """
: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
... | 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
####################... | ## 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
####################... | 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... | #--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... | 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<... | 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`.
... | 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... | 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.uui... | 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.SkipTes... | 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.SkipTes... | 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... |
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_confi... | 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... | 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
clas... | 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
clas... | 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/fi... |
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... | 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).hexdiges... | 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 TestHerokuCloc... | #!/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 no... | 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()[ re... | 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(... | 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',
... | #!/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',
... | 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_c... | 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',... | 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',... | 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
de... | 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
de... | 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"... | 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:
rev... | 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,T... |
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(... | 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... | 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/... |
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)
n... | #%%
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 ... | 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:
... | 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:
... | 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",
V... | #!/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",
V... | 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':
paylo... | 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, ... | 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._n... | 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 = ... | 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.... |
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_... | 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 agree... | # 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 agree... | 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 __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
... | 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,... |
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, ... | 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)._... | 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_... | """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_... | 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, ... | 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, ... | 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 =... | 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... | 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["... | 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.envir... | 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... | 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 mat... | 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_module... | 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:... | 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... | # -*- 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=No... | 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)
... | 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... | 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 endors... | """
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 endors... | 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['... | #!/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['... | 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 t... | # -*- 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 t... | 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,beetbo... |
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... | """
"""
__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 i... | 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_r... | 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_r... | 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... | # 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 confi... | 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.setMagnetometerUpdateInte... | '''
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)... | 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... | 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)
... | 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(
"confer... | 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(
"confer... | 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 A... | 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 * FRO... | 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 appli... | # 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 appli... | 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"),
... | # 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"),
... | 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')
... | 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'... | 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,... | #!/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,... | 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://... | # 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
#
# Unles... | 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 ... | 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):
"""
... | 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. Thi... | 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)
... |
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 = fin... | 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/... |
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(br... | """
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(br... | 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)... | 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 th... | 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/... |
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... | 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... | 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 =... | 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... | 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 ... | # 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_addres... | 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 = g... | 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=Qu... | 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... | 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... | 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.u... | 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.u... | 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 ma... | """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 mac... | 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.urlresolve... | 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.ME... | 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 __in... | # 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 __in... | 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 ... | 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:
resp... | 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)
i... | 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... | 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.sta... | #!/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.st... | 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(s... | """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(s... | 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, *... | 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):
... | 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):
... | 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 agr... | # 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 agr... | 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: #157885... | 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 multi... | 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... | 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 lena... | 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")
... | 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... |
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... | 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['mome... | # -*- 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['mome... | 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()... | 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()... | 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... | # 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)
## Djan... | 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-... |
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": {
... | # 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": {
... | 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__ = (... | # -*- 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
_... | 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:]:
... | #!/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 += '_'
... | 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):
... | 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):
... | Add a test for _get_table_from_database | Add a test for _get_table_from_database
| Python | mit | numberly/mongo-thingy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.