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 |
|---|---|---|---|---|---|---|---|---|---|
06f0edb71086573a3d7f9efb01b97b073cf415a3 | tests/DdlTextWrterTest.py | tests/DdlTextWrterTest.py | import io
import os
import unittest
from pyddl import *
__author__ = "Jonathan Hale"
class DdlTextWriterTest(unittest.TestCase):
def tearDown(self):
try:
os.remove("test.oddl")
except FileNotFoundError:
pass # test_empty failed?
def test_empty(self):
# creat... | import os
import unittest
from pyddl import *
from pyddl.enum import *
__author__ = "Jonathan Hale"
class DdlTextWriterTest(unittest.TestCase):
def tearDown(self):
try:
os.remove("test.oddl")
except FileNotFoundError:
pass # test_empty failed?
def test_empty(self):
... | Create a document in DdlTextWriterTest.test_full() | Create a document in DdlTextWriterTest.test_full()
Signed-off-by: Squareys <0f6a03d4883e012ba4cb2c581a68f35544703cd6@googlemail.com>
| Python | mit | Squareys/PyDDL |
125dfa47e5656c3f9b1e8846be03010ed02c6f91 | tests/rules_tests/isValid_tests/InvalidSyntaxTest.py | tests/rules_tests/isValid_tests/InvalidSyntaxTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class InvalidSyntaxTest(TestCase):
pass
if __name__ == '__main__':
main() | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
from grammpy.exceptions import RuleSyntaxException
from .grammar import *
class InvalidSyntaxTest(TestCase):
def test_rulesMissingEncloseLis... | Add base set of rule's invalid syntax tests | Add base set of rule's invalid syntax tests
| Python | mit | PatrikValkovic/grammpy |
12cb8ca101faa09e4cc07f9e257b3d3130892297 | tests/sentry/web/frontend/tests.py | tests/sentry/web/frontend/tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
@pytest.mark.xfail
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': s... | Remove xfail from replay test | Remove xfail from replay test
| Python | bsd-3-clause | mitsuhiko/sentry,fotinakis/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,alexm92/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,nicholasserra/sentry,JackDanger/sentry,fotinakis/sentry,gencer/sentry,fotinakis/sentry,beeftornado/sentry,ifduyue/sentry,JamesMura/sentry,imankulov/sentry,l... |
f920f7e765dac7057e3c48ebe0aa9723c3d431f5 | src/cclib/progress/__init__.py | src/cclib/progress/__init__.py | __revision__ = "$Revision$"
from textprogress import TextProgress
try:
import qt
except ImportError:
pass # import QtProgress will cause an error
else:
from qtprogress import QtProgress
| __revision__ = "$Revision$"
from textprogress import TextProgress
import sys
if 'qt' in sys.modules.keys():
from qtprogress import QtProgress
| Check to see if qt is loaded; if so, export QtProgress class | Check to see if qt is loaded; if so, export QtProgress class
git-svn-id: d468cea6ffe92bc1eb1f3bde47ad7e70b065426a@224 5acbf244-8a03-4a8b-a19b-0d601add4d27
| Python | lgpl-2.1 | Clyde-fare/cclib_bak,Clyde-fare/cclib_bak |
23675e41656cac48f390d97f065b36de39e27d58 | duckbot.py | duckbot.py | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot... | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = di... | Add a real roll command | Add a real roll command
| Python | mit | andrewlin16/duckbot,andrewlin16/duckbot |
30ed3800fdeec4aec399e6e0ec0760e46eb891ec | djangoautoconf/model_utils/model_reversion.py | djangoautoconf/model_utils/model_reversion.py | from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(s... | from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager... | Fix broken initial version creation. | Fix broken initial version creation.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf |
5237cb7f1339eb13b4c01f1c3611448a8f865726 | terms/templatetags/terms.py | terms/templatetags/terms.py | # coding: utf-8
from django.template import Library
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
| # coding: utf-8
from django.template import Library
from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
@stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
| Make sure the filter arg is a string. | Make sure the filter arg is a string.
| Python | bsd-3-clause | BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms |
1b218de76e8b09c70abcd88a2c6dd2c043bfc7f0 | drcli/__main__.py | drcli/__main__.py | #!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=sys.argv[1:]):
lo... | #!/usr/bin/env python
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=None):
if args is... | Allow sub-commands to use same main function | Allow sub-commands to use same main function
| Python | mit | schwa-lab/dr-apps-python |
85d684369e72aa2968f9ffbd0632f84558e1b44e | tests/test_vector2_dot.py | tests/test_vector2_dot.py | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magn... | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x... | Test that x² == |x|² | tests/dot: Test that x² == |x|²
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
fd81c4cea0d28275123539c23c27dcfdd71e9aef | scipy/testing/nulltester.py | scipy/testing/nulltester.py | ''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, ... | ''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, ... | Fix bench error on scipy import when nose is not installed | Fix bench error on scipy import when nose is not installed
| Python | bsd-3-clause | aman-iitj/scipy,maciejkula/scipy,efiring/scipy,gfyoung/scipy,teoliphant/scipy,pizzathief/scipy,pbrod/scipy,Eric89GXL/scipy,jor-/scipy,larsmans/scipy,anntzer/scipy,behzadnouri/scipy,pschella/scipy,ogrisel/scipy,sriki18/scipy,aarchiba/scipy,WarrenWeckesser/scipy,newemailjdm/scipy,Srisai85/scipy,pbrod/scipy,surhudm/scipy,... |
6d08c13fbf42eb4251d3477a904ab6d8513620df | dataset.py | dataset.py | from scrapy.item import Item, Field
class DatasetItem(Item):
name = Field()
frequency = Field()
| from scrapy.item import Item, Field
class DatasetItem(Item):
url = Field()
name = Field()
frequency = Field()
| Add url field to Dataset web item | Add url field to Dataset web item
| Python | mit | MaxLikelihood/CODE |
b5006a2820051e00c9fe4f5efe43e90129c12b4d | troposphere/cloudtrail.py | troposphere/cloudtrail.py | from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"IncludeManagementE... | from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"ExcludeManagementE... | Update Cloudtrail per 2021-09-10 changes | Update Cloudtrail per 2021-09-10 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
fddd44624f1c8ff6f66a2f33cafe908a5853389d | glaciercmd/command_delete_archive_from_vault.py | glaciercmd/command_delete_archive_from_vault.py | import boto
from boto.glacier.exceptions import UnexpectedHTTPResponseError
class CommandDeleteArchiveFromVault(object):
def execute(self, args, config):
glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_sec... | import boto
from boto.glacier.exceptions import UnexpectedHTTPResponseError
from boto.dynamodb2.table import Table
from boto.dynamodb2.layer1 import DynamoDBConnection
class CommandDeleteArchiveFromVault(object):
def execute(self, args, config):
glacier_connection = boto.connect_glacier(aws_access_key_id=confi... | Clean up dynamodb table when deleting an archive | Clean up dynamodb table when deleting an archive
| Python | mit | carsonmcdonald/glacier-cmd |
053d6a2ca13b1f36a02fa3223092a10af35f6579 | erpnext/patches/v10_0/item_barcode_childtable_migrate.py | erpnext/patches/v10_0/item_barcode_childtable_migrate.py | # Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
frappe... | # Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_barcode")
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })... | Move reload doc before get query | Move reload doc before get query
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
a2efdbc7c790df31f511d9a347774a961132d565 | txircd/modules/cmode_l.py | txircd/modules/cmode_l.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
intParam = int(param)
if str(intParam) != param:
return [False, param]
return [(intParam >= 0), param]
def checkPermission(self, user,... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
try:
intParam = int(param)
except ValueError:
return [False, param]
if str(intParam) != param:
return [False, param]
... | Fix checking of limit parameter | Fix checking of limit parameter
| Python | bsd-3-clause | DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd |
4de5050deda6c73fd9812a5e53938fea11e0b2cc | tests/unit/minion_test.py | tests/unit/minion_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
from salt import minion
from salt.exceptions import ... | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import python libs
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
# Import salt libs
f... | Add test for sock path length | Add test for sock path length
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
27ab83010f7cc8308debfec16fab38544a9c7ce7 | running.py | running.py | import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky... | import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
import json
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')
tcx = tc... | Print all hourly temperatures from run date | Print all hourly temperatures from run date
| Python | mit | briansuhr/slowburn |
e379aa75690d5bacc1d0bdec325ed4c16cf1a183 | lims/permissions/views.py | lims/permissions/views.py | from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
| from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
search_fields = ('name',)
| Add search functionality to permissions endpoint | Add search functionality to permissions endpoint
| Python | mit | GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend |
00922099d6abb03a0dbcca19781eb586d367eab0 | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim
| from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim
| Remove double import of find contours. | BUG: Remove double import of find contours.
| Python | bsd-3-clause | robintw/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,SamHames/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,chintak/scikit-image,rjeli/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,pratapvardha... |
985cefd81472069240b074423a831fe6031d6887 | website_sale_available/controllers/website_sale_available.py | website_sale_available/controllers/website_sale_available.py | # -*- coding: utf-8 -*-
from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res ... | # -*- coding: utf-8 -*-
from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res ... | FIX sale_available integration with delivery | FIX sale_available integration with delivery
| Python | mit | it-projects-llc/website-addons,it-projects-llc/website-addons,it-projects-llc/website-addons |
3f26d3c53f4bff36ec05da7a51a026b7d3ba5517 | tests/modules/test_atbash.py | tests/modules/test_atbash.py | """Tests for the Caeser module"""
import pycipher
from lantern.modules import atbash
def _test_atbash(plaintext, *fitness_functions, top_n=1):
ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True)
decryption = atbash.decrypt(ciphertext)
assert decryption == plaintext.upper()
def test_de... | """Tests for the Caeser module"""
from lantern.modules import atbash
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encryption"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
| Remove unnecessary testing code from atbash | Remove unnecessary testing code from atbash
| Python | mit | CameronLonsdale/lantern |
2c7065f82a242e6f05eaefda4ec902ddf9d90037 | tests/test_stanc_warnings.py | tests/test_stanc_warnings.py | """Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=pr... | """Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=pr... | Update test for Stan 2.29 | test: Update test for Stan 2.29
| Python | isc | stan-dev/pystan,stan-dev/pystan |
03b685055037283279394d940602520c5ff7a817 | email_log/models.py | email_log/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = mod... | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = mod... | Fix indentation problem and line length (PEP8) | Fix indentation problem and line length (PEP8)
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log |
9cbb73371db450599b7a3a964ab43f2f717b8bb7 | connector/__manifest__.py | connector/__manifest__.py | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',... | Remove application flag, not an application | Remove application flag, not an application
| Python | agpl-3.0 | OCA/connector,OCA/connector |
efab6ea568c11411d901249d7660765cd987b532 | examples/completion.py | examples/completion.py | import gtk
from kiwi.ui.widgets.entry import Entry
entry = Entry()
entry.set_completion_strings(['apa', 'apapa', 'apbla',
'apppa', 'aaspa'])
win = gtk.Window()
win.connect('delete-event', gtk.main_quit)
win.add(entry)
win.show_all()
gtk.main()
| # encoding: iso-8859-1
import gtk
from kiwi.ui.widgets.entry import Entry
def on_entry_activate(entry):
print 'You selected:', entry.get_text().encode('latin1')
gtk.main_quit()
entry = Entry()
entry.connect('activate', on_entry_activate)
entry.set_completion_strings(['Belo Horizonte',
... | Extend example to include non-ASCII characters | Extend example to include non-ASCII characters
| Python | lgpl-2.1 | Schevo/kiwi,Schevo/kiwi,Schevo/kiwi |
b25164e69d255beae1a76a9e1f7168a436a81f38 | tests/test_utils.py | tests/test_utils.py | import helper
from rock import utils
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.a... | import helper
from rock import utils
from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s._... | Test isexecutable check in utils.Shell | Test isexecutable check in utils.Shell
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock |
fc14e41432fece7d724aef73dd8ad7fef5e85c9a | flow/__init__.py | flow/__init__.py | from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimite... | from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimite... | Add IdentityEncoder to top-level exports | Add IdentityEncoder to top-level exports
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow |
ff4477c870b9c618b7432047071792c3a8055eb7 | coffeeraspi/messages.py | coffeeraspi/messages.py | class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name... | class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name... | Add nicer drink order logging | Add nicer drink order logging
| Python | apache-2.0 | umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp |
056bb4adada68d96f127a7610289d874ebe0cf1b | cray_test.py | cray_test.py | # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())... | # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.ap... | Add test cases for module post_manager, refactor part of class PostManager and update TODO list. | Add test cases for module post_manager, refactor part of class PostManager and update TODO list.
| Python | mit | boluny/cray,boluny/cray |
58be36ca646c4bb7fd4263a592cf3a240fbca64f | post_tag.py | post_tag.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = ... | Fix tag creation with non-ascii chars. (Dammit bottle!) | Fix tag creation with non-ascii chars. (Dammit bottle!)
| Python | mit | drougge/wwwwellpapp,drougge/wwwwellpapp,drougge/wwwwellpapp |
bb32f2327d2e3aa386fffd2fd320a7af7b03ce95 | corehq/apps/domain/project_access/middleware.py | corehq/apps/domain/project_access/middleware.py | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickc... | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickc... | Include superusers in web user domaing access record | Include superusers in web user domaing access record
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
3d3809931b5683b69e57507320b6d78df102f8d1 | warehouse/database/mixins.py | warehouse/database/mixins.py | from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_defaul... | from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
... | Mark TimeStampedMixin.modified as an onupdate FetchedValue | Mark TimeStampedMixin.modified as an onupdate FetchedValue
| Python | bsd-2-clause | davidfischer/warehouse |
d9f20935f6a0d5bf4e2c1dd1a3c5b41167f8518b | email_log/migrations/0001_initial.py | email_log/migrations/0001_initial.py | # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=Tru... | # encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False,
... | Fix migration file for Python 3.2 (and PEP8) | Fix migration file for Python 3.2 (and PEP8)
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log |
733404ba2eb7218bb4d253cd74fe88107ff75afc | test/test_live_openid_login.py | test/test_live_openid_login.py | import time
import pytest
from chatexchange.browser import SEChatBrowser, LoginError
import live_testing
if live_testing.enabled:
def test_openid_login():
"""
Tests login to the Stack Exchange OpenID provider.
"""
browser = SEChatBrowser()
# avoid hitting the SE servers... | import time
import pytest
from chatexchange.browser import SEChatBrowser, LoginError
import live_testing
if live_testing.enabled:
def test_openid_login_recognizes_failure():
"""
Tests that failed SE OpenID logins raise errors.
"""
browser = SEChatBrowser()
# avoid hitti... | Remove successful OpenID login live test. It's redundant with our message-related live tests. | Remove successful OpenID login live test.
It's redundant with our message-related live tests.
| Python | apache-2.0 | ByteCommander/ChatExchange6,hichris1234/ChatExchange,Charcoal-SE/ChatExchange,hichris1234/ChatExchange,ByteCommander/ChatExchange6,Charcoal-SE/ChatExchange |
210e99b9b19484991f4d7d4106ed9c0ae802b2f7 | windmill/server/__init__.py | windmill/server/__init__.py | # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# 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
#
# ... | # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# 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
#
# ... | Stop forwarding flash by default, it breaks more than it doesn't. | Stop forwarding flash by default, it breaks more than it doesn't.
git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1279 78c7df6f-8922-0410-bcd3-9426b1ad491b
| Python | apache-2.0 | windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill |
9c428fbfb69c93ef3da935d0d2ab098fbeb1c317 | dsh.py | dsh.py | # ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from tinyAPI.base.data_store.provider import DataStoreProvider
import tinyAPI
__all__ = [
'dsh'
]
... | # ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from tinyAPI.base.data_store.provider import DataStoreProvider
import tinyAPI
__all__ = [
'dsh'
]
... | Revert "Testing NoOpDSH() when database commands are executed without a connection being opened." | Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."
This reverts commit 57dd36da6f558e9bd5c9b7c97e955600c2fa0b8e.
| Python | mit | mcmontero/tinyAPI,mcmontero/tinyAPI |
eced06f6f523fa6fd475987ae688b7ca2b6c3415 | checks/system/__init__.py | checks/system/__init__.py | """
Return information about the given platform.
"""
import sys
class Platform(object):
@staticmethod
def is_darwin(name=None):
name = name or sys.platform
return 'darwin' in name
@staticmethod
def is_freebsd(name=None):
name = name or sys.platform
return name.start... | """
Return information about the given platform.
"""
import sys
class Platform(object):
@staticmethod
def is_darwin(name=None):
name = name or sys.platform
return 'darwin' in name
@staticmethod
def is_freebsd(name=None):
name = name or sys.platform
return name.start... | Add win32 to platform information | Add win32 to platform information
| Python | bsd-3-clause | jraede/dd-agent,tebriel/dd-agent,JohnLZeller/dd-agent,a20012251/dd-agent,remh/dd-agent,tebriel/dd-agent,AntoCard/powerdns-recursor_check,tebriel/dd-agent,AniruddhaSAtre/dd-agent,urosgruber/dd-agent,polynomial/dd-agent,JohnLZeller/dd-agent,Mashape/dd-agent,JohnLZeller/dd-agent,eeroniemi/dd-agent,c960657/dd-agent,mderomp... |
b974bbcc7e243fca7c3dc63fbbaf530fe9b69e50 | runtests.py | runtests.py | import sys
try:
from django.conf import settings
from django.test.utils import get_runner
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
... | import os
import sys
try:
sys.path.append('demoproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings")
from django.conf import settings
from django.core.management import call_command
settings.DATABASES['default']['NAME'] = ':memory:'
settings.INSTALLED_APPS.append('... | Load DB migrations before testing and use verbose=2 and failfast | Load DB migrations before testing and use verbose=2 and failfast
Note that we use `manage.py test` instead of
`manage.py migrate` and manually running the tests. This
lets Django take care of applying migrations before running tests.
This works around https://code.djangoproject.com/ticket/22487
which causes a test fai... | Python | bsd-2-clause | pgollakota/django-chartit,pgollakota/django-chartit,pgollakota/django-chartit |
471bb3847b78f36f79af6cbae288a8876357cb3c | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | Add missing config that caused test to fail | Add missing config that caused test to fail
| Python | mit | Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget |
25224af8c002c05397e5c3163f0b77cb82ce325e | data_collection/management/commands/assignfirms.py | data_collection/management/commands/assignfirms.py | from django.core.management.base import BaseCommand, CommandError
from data_collection.models import User, Firm, Assignment
import itertools
class Command(BaseCommand):
help = "Assign firms to users"
def add_arguments(self, parser):
parser.add_argument('users', nargs='+', type=str)
def handle(sel... | from django.core.management.base import BaseCommand, CommandError
from data_collection.models import User, Firm, Assignment
import itertools, random
class Command(BaseCommand):
help = "Assign firms to users"
def add_arguments(self, parser):
parser.add_argument('users', nargs='+', type=str)
par... | Add ability to proportionally assign to different users | Add ability to proportionally assign to different users
| Python | bsd-3-clause | sunlightlabs/hanuman,sunlightlabs/hanuman,sunlightlabs/hanuman |
54b3b69d152611d55ce7db66c2c34dc2b1140cc7 | wellknown/models.py | wellknown/models.py | from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml')
#
# resource model
#
class Resource(mo... | from django.db import models
from django.db.models.signals import post_save
import mimetypes
import wellknown
#
# create default host-meta handler
#
from wellknown.resources import HostMeta
wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml')
#
# resource model
#
class Resource(mo... | Remove code that was causing a problem running syncdb. Code seems to be redundant anyway. | Remove code that was causing a problem running syncdb. Code seems to be redundant anyway.
| Python | bsd-3-clause | jcarbaugh/django-wellknown |
75289980c658e081fec2d7e34651837c4629d4b7 | settings.py | settings.py | # -*- coding: utf-8 -*-
"""
* Project: udacity-fsnd-p4-conference-app
* Author name: Iraquitan Cordeiro Filho
* Author login: iraquitan
* File: settings
* Date: 3/23/16
* Time: 12:16 AM
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = 'your-app-i... | # -*- coding: utf-8 -*-
"""
* Project: udacity-fsnd-p4-conference-app
* Author name: Iraquitan Cordeiro Filho
* Author login: iraquitan
* File: settings
* Date: 3/23/16
* Time: 12:16 AM
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = 'your-web-c... | Fix the placeholder for better understanding | fix: Fix the placeholder for better understanding
| Python | mit | iraquitan/udacity-fsnd-p4-conference-app,iraquitan/udacity-fsnd-p4-conference-app,iraquitan/udacity-fsnd-p4-conference-app |
68b52fedf5b22891a4fc9cf121417ced38d0ea00 | rolepermissions/utils.py | rolepermissions/utils.py | from __future__ import unicode_literals
import re
import collections
def user_is_authenticated(user):
if isinstance(user.is_authenticated, collections.Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s)... | from __future__ import unicode_literals
import re
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
def user_is_authenticated(user):
if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
authenticated... | Fix import of Callable for Python 3.9 | Fix import of Callable for Python 3.9
Python 3.3 moved Callable to collections.abc and Python 3.9 removes Callable from collections module | Python | mit | vintasoftware/django-role-permissions |
7f7fd4e7547af3a6d7e3cd4da025c2b0ab24508b | widgy/contrib/widgy_mezzanine/migrations/0001_initial.py | widgy/contrib/widgy_mezzanine/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import widgy.db.fields
import django.db.models.deletion
import widgy.contrib.widgy_mezzanine.models
class Migration(migrations.Migration):
dependencies = [
('pages', '__first__'),
('review_qu... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import widgy.db.fields
import django.db.models.deletion
import widgy.contrib.widgy_mezzanine.models
class Migration(migrations.Migration):
dependencies = [
('pages', '__first__'),
('widgy', '... | Remove dependency for ReviewedVersionTracker in migrations | Remove dependency for ReviewedVersionTracker in migrations
The base widgy migrations had references to ReviewedVersionTracker,
which is not part of the base widgy install. This commit changes the
dependency to VersionTracker instead, which is part of the base widgy
install.
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy |
16369ed6a11aaa39e94479b06ed78eb75f5b33e1 | src/args.py | src/args.py | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2014 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from argparse import ArgumentParser
from gl... | #!/usr/bin/env python3
# chameleon-crawler
#
# Copyright 2014 ghostwords.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from glob import glob
from os import path
... | Fix --crx arg error reporting. | Fix --crx arg error reporting.
| Python | mpl-2.0 | ghostwords/chameleon-crawler,ghostwords/chameleon-crawler,ghostwords/chameleon-crawler |
78675420e9d23d9978f68ed002de0fc1284d3d0c | node.py | node.py | class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
... | class Node(object):
def __init__(self):
# Node(s) from which this Node receives values
self.inbound_nodes = inbound_nodes
# Node(s) to which this Node passes values
self.outbound_nodes = []
# For each inbound Node here, add this Node as an outbound to that Node.
for n in self.inbound_nodes:
... | Add forward function declaration to Class Node | Add forward function declaration to Class Node
| Python | mit | YabinHu/miniflow |
238578d41beec33d7428cb53d79fc21c028cfc87 | tests/specifications/external_spec_test.py | tests/specifications/external_spec_test.py | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
... | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(item_type, item_id, item):
if item_type == "check" and item_id in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", ... | Use auto_register's filter_func to filter tests | Use auto_register's filter_func to filter tests
| Python | apache-2.0 | moyogo/fontbakery,moyogo/fontbakery,googlefonts/fontbakery,googlefonts/fontbakery,moyogo/fontbakery,graphicore/fontbakery,graphicore/fontbakery,graphicore/fontbakery,googlefonts/fontbakery |
a7be90536618ac52c91f599bb167e05f831cddfb | mangopaysdk/entities/transaction.py | mangopaysdk/entities/transaction.py | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
#... | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
#... | Add possibilty to get ResultMessage | Add possibilty to get ResultMessage | Python | mit | chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk |
3cacced39d9cb8bd5d6a2b3db8aa4b5aa1b37f58 | jaraco/util/meta.py | jaraco/util/meta.py | """
meta.py
Some useful metaclasses.
"""
from __future__ import unicode_literals
class LeafClassesMeta(type):
"""
A metaclass for classes that keeps track of all of them that
aren't base classes.
"""
_leaf_classes = set()
def __init__(cls, name, bases, attrs):
if not hasattr(cls, '_leaf_classes'):
cls._... | """
meta.py
Some useful metaclasses.
"""
from __future__ import unicode_literals
class LeafClassesMeta(type):
"""
A metaclass for classes that keeps track of all of them that
aren't base classes.
"""
_leaf_classes = set()
def __init__(cls, name, bases, attrs):
if not hasattr(cls, '_leaf_classes'):
cls._... | Allow attribute to be customized in TagRegistered | Allow attribute to be customized in TagRegistered
| Python | mit | jaraco/jaraco.classes |
7b6838ea292e011f96f5212992d00c1009e1f6b2 | examples/gitter_example.py | examples/gitter_example.py | # -*- coding: utf-8 -*-
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from settings import GITTER
# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)
chatbot = ChatBot(
'GitterBot',
gitter_room=GITTER['... | # -*- coding: utf-8 -*-
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from settings import GITTER
# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)
'''
To use this example, create a new file called settings.p... | Add better instructions to the Gitter example | Add better instructions to the Gitter example
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot |
260a5601a9b2990374d2f97d92898236e0b9342e | tests/profiling_test_script.py | tests/profiling_test_script.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
u"""
:author: Joseph Martinot-Lagarde
Created on Sat Jan 19 14:57:57 2013
"""
from __future__ import (
print_function, division, unicode_literals, absolute_import)
import subdir.profiling_test_script2 as script2
@profile
def fact(n):
result = 1
for i in xrange... | #!/usr/bin/python
# -*- coding: utf-8 -*-
u"""
:author: Joseph Martinot-Lagarde
Created on Sat Jan 19 14:57:57 2013
"""
from __future__ import (
print_function, division, unicode_literals, absolute_import)
import subdir.profiling_test_script2 as script2
@profile
def fact(n):
result = 1
for i in xrange... | Add diversity to test script | Add diversity to test script
| Python | mit | jitseniesen/spyder-memory-profiler,jitseniesen/spyder-memory-profiler,Nodd/spyder_line_profiler,spyder-ide/spyder.line_profiler,spyder-ide/spyder.memory_profiler,spyder-ide/spyder.line-profiler,Nodd/spyder.line_profiler |
97a67e022d094743e806896386bdbe317cb56fb6 | gitcloner.py | gitcloner.py | #! /usr/bin/env python3
import sys
from gitaccount import GitAccount
def main():
if len(sys.argv) < 2:
print("""Usage:
gitcloner.py [OPTION] [NAME]
OPTIONS:
-u - for user repositories
-o - for organization repositories
NAME:
Username or Organization Name
""")
... | #! /usr/bin/env python3
import sys
import argparse
from gitaccount import GitAccount
def main():
parser = argparse.ArgumentParser(
prog='gitcloner',
description='Clone all the repositories from a github user/org\naccount to the current directory')
group = parser.add_mutually_exclusiv... | Use argparse instead of sys.argv | Use argparse instead of sys.argv
| Python | mit | shakib609/gitcloner |
d42b9da06d5cde89a6116d711fc6ae216256cabc | shell/view/home/IconLayout.py | shell/view/home/IconLayout.py | import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
i... | import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
i... | Use get/set_property rather than direct accessors | Use get/set_property rather than direct accessors
| Python | lgpl-2.1 | Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,ceibal-tatu/suga... |
911094754fc908d99009c5cfec22ac9033ffd472 | my_account_helper/model/__init__.py | my_account_helper/model/__init__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.ch>
#
# The licence is in the f... | Fix comment header on init | Fix comment header on init
| Python | agpl-3.0 | Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,MickSandoz/compassion-switzerland,ecino/compassion-swit... |
5c61d7f125078cb6b3bd0c5700ae9219baab0078 | webapp/tests/test_dashboard.py | webapp/tests/test_dashboard.py | from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('graphite.dashboard.views.dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
| from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
| Update reverse call to use named URL | Update reverse call to use named URL
| Python | apache-2.0 | redice/graphite-web,dbn/graphite-web,Skyscanner/graphite-web,penpen/graphite-web,lyft/graphite-web,esnet/graphite-web,bpaquet/graphite-web,atnak/graphite-web,section-io/graphite-web,kkdk5535/graphite-web,cosm0s/graphite-web,cgvarela/graphite-web,gwaldo/graphite-web,redice/graphite-web,edwardmlyte/graphite-web,atnak/gra... |
4124297475fb7d77bf492e721a74fcfa02547a14 | benchmark/bench_logger_level_low.py | benchmark/bench_logger_level_low.py | """Benchmarks too low logger levels"""
from logbook import Logger, ERROR
log = Logger('Test logger')
log.level = ERROR
def run():
for x in xrange(500):
log.warning('this is not handled')
| """Benchmarks too low logger levels"""
from logbook import Logger, StreamHandler, ERROR
from cStringIO import StringIO
log = Logger('Test logger')
log.level = ERROR
def run():
out = StringIO()
with StreamHandler(out):
for x in xrange(500):
log.warning('this is not handled')
| Create a stream handler even though it's not used to have the same overhead on both logbook and logging | Create a stream handler even though it's not used to have the same overhead on both logbook and logging
| Python | bsd-3-clause | DasIch/logbook,maykinmedia/logbook,alonho/logbook,fayazkhan/logbook,maykinmedia/logbook,Rafiot/logbook,dvarrazzo/logbook,mbr/logbook,mitsuhiko/logbook,dvarrazzo/logbook,RazerM/logbook,FintanH/logbook,omergertel/logbook,dommert/logbook,DasIch/logbook,alex/logbook,alonho/logbook,pombredanne/logbook,alonho/logbook,alex/lo... |
b71db5eb72fd5529be060d5f90ad744f0ea0870e | library.py | library.py | class Library:
"""This class represents a simaris target and is initialized with
data in JSON format
"""
def __init__(self, data):
self.target = data['CurrentTarget']['EnemyType']
self.scans = data['CurrentTarget']['PersonalScansRequired']
self.progress ... | class Library:
"""This class represents a simaris target and is initialized with
data in JSON format
"""
def __init__(self, data):
if 'CurrentTarget' in data:
self.target = data['CurrentTarget']['EnemyType']
self.scans = data['CurrentTarget']['Persona... | Add is_active() method to the Library class | Add is_active() method to the Library class
| Python | mit | pabletos/Hubot-Warframe,pabletos/Hubot-Warframe |
5c6f277caf3496da5f10b0150abb2c3b856e6584 | nagare/services/prg.py | nagare/services/prg.py | # --
# Copyright (c) 2008-2020 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.
# --
"""If the ``activated`` parameter of the ``[redirect_after_post]``
section is `on`` (the default... | # --
# Copyright (c) 2008-2020 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.
# --
"""If the ``activated`` parameter of the ``[redirect_after_post]``
section is `on`` (the default... | Store in the current state, not the previous one | Store in the current state, not the previous one
| Python | bsd-3-clause | nagareproject/core,nagareproject/core |
c1d8bf0916e1f59610fc69f0b11909964755ee38 | pyaavso/formats/visual.py | pyaavso/formats/visual.py | from __future__ import unicode_literals
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-visual-file-forma... | from __future__ import unicode_literals
import pyaavso
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here mimics the ``csv`` module in Python standard library.
.. _`Visual File Format`: http://www.aavso.org/aavso-v... | Write name and version to output file. | Write name and version to output file.
| Python | mit | zsiciarz/pyaavso |
313aee17c8e2e1c86b96b40017ac4618c66df463 | __init__.py | __init__.py | # -*- coding: utf-8 -*-
# This file is part of OpenFisca
# Copyright © 2012 Mahdi Ben Jelloul, Clément Schaff
# Licensed under the terms of the GPL License v3 or later version
# (see src/__init__.py for details)
# Model parameters
ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CUR... | # -*- coding: utf-8 -*-
# This file is part of OpenFisca
# Copyright © 2012 Mahdi Ben Jelloul, Clément Schaff
# Licensed under the terms of the GPL License v3 or later version
# (see src/__init__.py for details)
# Model parameters
ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CUR... | Generalize graph and some new example scripts | Generalize graph and some new example scripts
| Python | agpl-3.0 | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia |
09fc3d53b2814f940bcaf7d6136ed2ce0595fb2f | hyperion/importers/tests/test_sph.py | hyperion/importers/tests/test_sph.py | import os
import h5py
import numpy as np
from ..sph import construct_octree
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_construct_octree():
np.random.seed(0)
N = 5000
px = np.random.uniform(-10., 10., N)
py = np.random.uniform(-10., 10., N)
pz = np.random.uniform(-10., 10.... | import os
import h5py
import numpy as np
from numpy.testing import assert_allclose
from ..sph import construct_octree
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_construct_octree():
np.random.seed(0)
N = 5000
px = np.random.uniform(-10., 10., N)
py = np.random.uniform(-10., 10... | Use assert_allclose for comparison of octree densities | Use assert_allclose for comparison of octree densities
| Python | bsd-2-clause | hyperion-rt/hyperion,bluescarni/hyperion,hyperion-rt/hyperion,hyperion-rt/hyperion,bluescarni/hyperion |
fd96170fd15ccbe0b42463fe8d4ac78f511d10c7 | example/testtags/admin.py | example/testtags/admin.py | from django.contrib import admin
from models import TestName
class TestNameAdmin(admin.ModelAdmin):
model = TestName
alphabet_filter = 'sorted_name'
admin.site.register(TestName, TestNameAdmin) | from django.contrib import admin
from models import TestName
class TestNameAdmin(admin.ModelAdmin):
model = TestName
alphabet_filter = 'sorted_name'
## Testing a custom Default Alphabet
#DEFAULT_ALPHABET = 'ABC'
## Testing a blank alphabet-- only shows the characters in the database
#... | Put in some testing code to test the new overrides | Put in some testing code to test the new overrides
| Python | apache-2.0 | bltravis/django-alphabetfilter,affan2/django-alphabetfilter,affan2/django-alphabetfilter,affan2/django-alphabetfilter,bltravis/django-alphabetfilter,bltravis/django-alphabetfilter |
8165aa65e96d32ed908cdf8e3c475c28181e0d93 | hierarchical_auth/admin.py | hierarchical_auth/admin.py | from django.contrib import admin
from django.conf import settings
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.forms import UserChangeForm
from mptt.forms import TreeNodeMultipleChoiceField
if getattr(settings, 'MPTT_USE_FEINC... | from django.contrib import admin
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
User = settings.AUTH_USER_MODEL
except:
from django.contrib.auth.models import User
try... | Work with custom user models in django >= 1.5 | Work with custom user models in django >= 1.5
Work with Custom User Models introduced in django >= 1.5
Also tries to get a AUTH_USER_ADMIN_MODEL, not only AUTH_USER_MODEL | Python | bsd-3-clause | zhangguiyu/django-hierarchical-auth,digitalemagine/django-hierarchical-auth |
731e48b1b81e9249fc8bdd0f826c6e009559fcc3 | mempoke.py | mempoke.py | import gdb
import struct
class DeviceMemory:
def __init__(self):
self.inferior = gdb.selected_inferior()
def __del__(self):
del self.inferior
def read(self, address):
return struct.unpack('I', self.inferior.read_memory(address, 4))[0]
def write(self, address, value):
... | import gdb
import struct
class DeviceMemory:
def __init__(self):
self.inferior = gdb.selected_inferior()
def __del__(self):
del self.inferior
def read(self, address):
return struct.unpack('I', self.inferior.read_memory(address, 4))[0]
def write(self, address, value):
... | Add mechanism for defining MCU control structures | Add mechanism for defining MCU control structures
| Python | mit | fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing |
65cd0c8865761af434756b313c7e29b1904e647c | h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py | h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py | import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
... | import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
... | Add usage of nbins_cats to RF pyunit. | Add usage of nbins_cats to RF pyunit.
| Python | apache-2.0 | spennihana/h2o-3,h2oai/h2o-3,PawarPawan/h2o-v3,mathemage/h2o-3,datachand/h2o-3,mrgloom/h2o-3,printedheart/h2o-3,weaver-viii/h2o-3,weaver-viii/h2o-3,bospetersen/h2o-3,mathemage/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,datachand/h2o-3,YzPaul3/h2o-3,ChristosChristofidis/h2o-3,mathemage/h2o-3,mrgloom/h2o-3,madmax98... |
973496ad5111e408ea4832962987098d8c9ca003 | example/example/urls.py | example/example/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'example.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'example.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Add an entry in you... | Add an entry in URLconf | Add an entry in URLconf
| Python | mit | dkdndes/django-flatpages-example |
afa3cd7c6e4c82f94eef7edd4bc8db609943226c | api/urls.py | api/urls.py | from django.conf.urls import url
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'),
]
| from django.conf.urls import url
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'),
url(r'^signup/$', views.SignupView.as_vie... | Add URL for signup api endpoint | Add URL for signup api endpoint
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles |
f59ac3cc752698ce1755d8953c8771dc978ae6b7 | opendebates/urls.py | opendebates/urls.py | from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^healthcheck.html$', 'opendebates.views.health_check', name='health_check'),
url(r'^(?P<prefix>[-\w]+)/', include('opendebates.prefixed_urls')),
]
| from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='https://opendebatecoalition.com', permanent=False)),
url(r'^admin/', include(admin.site.urls)),
url(r'^healthcheck.html$', 'ope... | Add a (temporary) redirect to opendebatecoalition.com from / | Add a (temporary) redirect to opendebatecoalition.com from /
Temporary because permanent is really hard to take back, if you decide
later that you wanted something else.
| Python | apache-2.0 | caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates |
c6c397dab0e5549ddce59c388dbf0235bc6b44c3 | app/groups/utils.py | app/groups/utils.py | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard ... | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from django.contrib.sites.models import Site
def send_group_email(request, to_email, subject, email_text_template, email_html_template):
"""Sends ... | Rename the function, and provide the "domain" context for url linking in the emails | Rename the function, and provide the "domain" context for url linking in the emails
| Python | bsd-3-clause | nikdoof/test-auth |
aa0b61b44e631c3a12a16025e93d7e962de23c2f | fabix/system/crontab.py | fabix/system/crontab.py | # coding: utf-8
import fabric.api as fab
import cuisine
def install(filename, user="root", append=False):
"""
Installs crontab from a given cronfile
"""
new_crontab = fab.run("mktemp fabixcron.XXXX")
cuisine.file_upload(new_crontab, filename)
if append is True:
sorted_crontab = fab.run... | # coding: utf-8
import fabric.api as fab
import cuisine
def install(filename, user="root", append=False):
"""
Installs crontab from a given cronfile
"""
new_crontab = fab.run("mktemp fabixcron.XXXX")
cuisine.file_upload(new_crontab, filename)
if append is True:
# When user have no cron... | Remove duplicate lines from cron file without sorting | Remove duplicate lines from cron file without sorting
| Python | mit | vmalavolta/fabix |
02da417b238256878cfab7c0adef8f86f5532b01 | tamper/randomcomments.py | tamper/randomcomments.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.common import randomRange
from lib.core.data import kb
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOW
def tamper(payload, **kwargs)... | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.common import randomRange
from lib.core.data import kb
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOW
def tamper(payload, **kwargs)... | Fix for a tamper script (in some cases comments were not inserted) | Fix for a tamper script (in some cases comments were not inserted)
| Python | mit | dtrip/.ubuntu,RexGene/monsu-server,RexGene/monsu-server,dtrip/.ubuntu |
2b758185e0de0d41c5ecc9a5511308ee36c60c91 | Python_Data/smpl4.py | Python_Data/smpl4.py | '''
2.1 - Numpy Array library
'''
#!/usr/bin/env
import numpy as np
def main():
''''
# 1) Create two vectors 'a' and 'b', and sum them.
# Standart
n = 3
a = [x**2 for x in range(1, n + 1)]
b = [x**3 for x in range(1, n + 1)]
v = plainVectorAddition(a, b)
# Numpy
n = 3
a = np.ara... | '''
2.1 - Numpy Array library
- Sum of two vectors -
Usage: python smpl4.py n
Where 'n' specifies the size of the vector.
The program make performance comparisons and print the results.
'''
#!/usr/bin/env
import numpy as np
import sys
from datetime import datetime
def main():
size = int(sys.argv[1])
s... | Add file with linear algebra numpy operations | Add file with linear algebra numpy operations
| Python | unlicense | robotenique/RandomAccessMemory,robotenique/RandomAccessMemory,robotenique/RandomAccessMemory |
b83acdc08ed0211c8b53d8f8a158c4ac43c8587c | test/test_issue655.py | test/test_issue655.py | from rdflib import Graph, Namespace, URIRef, Literal
from rdflib.compare import to_isomorphic
import unittest
class TestIssue655(unittest.TestCase):
def test_issue655(self):
PROV = Namespace('http://www.w3.org/ns/prov#')
bob = URIRef("http://example.org/object/Bob")
value = Literal(float... | from rdflib import Graph, Namespace, URIRef, Literal
from rdflib.compare import to_isomorphic
import unittest
class TestIssue655(unittest.TestCase):
def test_issue655(self):
PROV = Namespace('http://www.w3.org/ns/prov#')
bob = URIRef("http://example.org/object/Bob")
value = Literal(float... | Remove test on serialisation (order is not fixed) | Remove test on serialisation (order is not fixed)
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib |
8b7aef341aadefb859790684f41453f561813083 | tmi/views/__init__.py | tmi/views/__init__.py | from flask import g
from flask.ext.login import current_user
from tmi.core import app
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa
from tmi.views.admin import admin # noqa
from tmi.views.cards_api import blueprint as cards_api
@app.before_req... | from flask import g, request
from flask.ext.login import current_user
from werkzeug.exceptions import HTTPException
from tmi.core import app
from tmi.forms import Invalid
from tmi.util import jsonify
from tmi.assets import assets # noqa
from tmi.views.ui import ui # noqa
from tmi.views.auth import login, logout # noqa... | Handle errors with JSON messages. | Handle errors with JSON messages. | Python | mit | pudo/storyweb,pudo/storyweb |
f5f728074b257aac371fc59af8de02e440e57819 | furikura/desktop/unity.py | furikura/desktop/unity.py | import gi
gi.require_version('Unity', '7.0')
from gi.repository import Unity, Dbusmenu
launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop")
def update_counter(count):
launcher.set_property("count", count)
launcher.set_property("count_visible", True)
def add_quicklist_item(item):
quick_l... | import gi
from threading import Timer
gi.require_version('Unity', '7.0')
from gi.repository import Unity, Dbusmenu
launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop")
def update_counter(count):
launcher.set_property("count", count)
launcher.set_property("count_visible", True)
if count... | Apply "Urgent" icon animation on new message | Apply "Urgent" icon animation on new message
| Python | mit | benjamindean/furi-kura,benjamindean/furi-kura |
3b5ad132f3670d1c1210190ecd7b41a379fbd10e | trakt/core/helpers.py | trakt/core/helpers.py | import arrow
def to_datetime(value):
if value is None:
return None
# Parse ISO8601 datetime
dt = arrow.get(value)
# Return python datetime object
return dt.datetime
| import arrow
def to_datetime(value):
if value is None:
return None
# Parse ISO8601 datetime
dt = arrow.get(value)
# Convert to UTC
dt = dt.to('UTC')
# Return naive datetime object
return dt.naive
| Convert all datetime properties to UTC | Convert all datetime properties to UTC
| Python | mit | shad7/trakt.py,fuzeman/trakt.py |
5e3b712c4c2eac7227d6e894ce05db6f1ede074a | hgtools/tests/conftest.py | hgtools/tests/conftest.py | import os
import pytest
from hgtools import managers
def _ensure_present(mgr):
try:
mgr.version()
except Exception:
pytest.skip()
@pytest.fixture
def hg_repo(tmpdir):
tmpdir.chdir()
mgr = managers.MercurialManager()
_ensure_present(mgr)
mgr._invoke('init', '.')
os.makedirs('bar')
touch('bar/baz')
mgr... | import os
import pytest
from hgtools import managers
def _ensure_present(mgr):
try:
mgr.version()
except Exception:
pytest.skip()
@pytest.fixture
def tmpdir_as_cwd(tmpdir):
with tmpdir.as_cwd():
yield tmpdir
@pytest.fixture
def hg_repo(tmpdir_as_cwd):
mgr = managers.MercurialManager()
_ensure_present... | Fix test failures by restoring working directory in fixtures. | Fix test failures by restoring working directory in fixtures.
| Python | mit | jaraco/hgtools |
cf83c92ee2160a9d27d18347137b55b4a111228d | zvm/zcpu.py | zvm/zcpu.py | #
# A class which represents the CPU itself, the brain of the virtual
# machine. It ties all the systems together and runs the story.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZCpuError(Exception):
"General exception for Zcpu class"
... | #
# A class which represents the CPU itself, the brain of the virtual
# machine. It ties all the systems together and runs the story.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZCpuError(Exception):
"General exception for Zcpu class"
... | Make the CPU use lovely decorator syntax for registering opcode implementations. | Make the CPU use lovely decorator syntax for registering opcode implementations.
| Python | bsd-3-clause | sussman/zvm,sussman/zvm |
c2eccb4ce1259830dd641d19624358af83c09549 | webcomix/comic_spider.py | webcomix/comic_spider.py | from urllib.parse import urljoin
import scrapy
class ComicSpider(scrapy.Spider):
name = "My spider"
def __init__(self, *args, **kwargs):
self.start_urls = kwargs.get('start_urls') or []
self.next_page_selector = kwargs.get('next_page_selector', None)
self.comic_image_selector = kwarg... | from urllib.parse import urljoin
import click
import scrapy
class ComicSpider(scrapy.Spider):
name = "Comic Spider"
def __init__(self, *args, **kwargs):
self.start_urls = kwargs.get('start_urls') or []
self.next_page_selector = kwargs.get('next_page_selector', None)
self.comic_image_... | Copy logging from previous version and only yield item to pipeline if a comic image was found | Copy logging from previous version and only yield item to pipeline if a comic image was found
| Python | mit | J-CPelletier/webcomix,J-CPelletier/webcomix,J-CPelletier/WebComicToCBZ |
1a6344ea1fac51a8024e1803a0391662d4ab81e0 | pyeda/boolalg/vexpr.py | pyeda/boolalg/vexpr.py | """
Boolean Vector Logic Expressions
This module is deprecated.
The functionality has been superceded by the bfarray module.
Interface Functions:
bitvec
"""
from pyeda.boolalg import expr
from pyeda.boolalg import bfarray
def bitvec(name, *dims):
"""Return a new array of given dimensions, filled with Expres... | """
Boolean Vector Logic Expressions
This module is deprecated.
The functionality has been superceded by the bfarray module.
Interface Functions:
bitvec
"""
from warnings import warn
from pyeda.boolalg import expr
from pyeda.boolalg import bfarray
def bitvec(name, *dims):
"""Return a new array of given dim... | Add deprecation warning to bitvec function | Add deprecation warning to bitvec function
| Python | bsd-2-clause | pombredanne/pyeda,GtTmy/pyeda,karissa/pyeda,sschnug/pyeda,sschnug/pyeda,cjdrake/pyeda,sschnug/pyeda,cjdrake/pyeda,GtTmy/pyeda,GtTmy/pyeda,karissa/pyeda,pombredanne/pyeda,karissa/pyeda,cjdrake/pyeda,pombredanne/pyeda |
2339fa64974184c8174917be305c45a34013bae9 | easy/lowest_unique/lowest_unique.py | easy/lowest_unique/lowest_unique.py | import sys
def lowest_unique(int_list):
numbers = {}
for index in range(len(int_list)):
group = numbers.setdefault(int(int_list[index]), [])
group.append(index)
for number in numbers:
retval = numbers[number]
if len(retval) == 1:
return retval[0] + 1
return ... | import sys
def lowest_unique(int_list):
numbers = {}
for index, number in enumerate(int_list):
group = numbers.setdefault(int(number), [])
group.append(index)
for number in sorted(numbers.keys()):
retval = numbers[number]
if len(retval) == 1:
return retval[0] + ... | Improve solution by using enumerate | Improve solution by using enumerate
| Python | mit | MikeDelaney/CodeEval |
a5faf69efd3a53b937b0bd27d42ad0ca8b0af9a9 | centinel/backend.py | centinel/backend.py | import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
... | import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
... | Add ability to submit results | Add ability to submit results
| Python | mit | iclab/centinel,JASONews/centinel,lianke123321/centinel,Ashish1805/centinel,lianke123321/centinel,iclab/centinel,iclab/centinel,ben-jones/centinel,rpanah/centinel,lianke123321/centinel,rpanah/centinel,rpanah/centinel |
cd621061773b7eafcea9358c9b762663a070ccc5 | cc/license/jurisdiction.py | cc/license/jurisdiction.py | import RDF
import zope.interface
import interfaces
import rdf_helper
class Jurisdiction(object):
zope.interface.implements(interfaces.IJurisdiction)
def __init__(self, short_name):
'''@param short_name can be e.g. mx'''
model = rdf_helper.init_model(
rdf_helper.JURI_RDF_PATH)
... | import RDF
import zope.interface
import interfaces
import rdf_helper
class Jurisdiction(object):
zope.interface.implements(interfaces.IJurisdiction)
def __init__(self, short_name):
"""Creates an object representing a jurisdiction.
short_name is a (usually) two-letter code representing
... | Add documentation and make Jurisdiction calls not fail when some of the values aren't found. | Add documentation and make Jurisdiction calls not fail when some of the values aren't found.
| Python | mit | creativecommons/cc.license,creativecommons/cc.license |
9c39105f2dcb296590e895aaf35de5d4c3105ddb | ephypype/commands/tests/test_cli.py | ephypype/commands/tests/test_cli.py | """Test neuropycon command line interface"""
# Authors: Dmitrii Altukhov <daltuhov@hse.ru>
#
# License: BSD (3-clause)
import os
import os.path as op
from ephypype.commands import neuropycon
from click.testing import CliRunner
def test_input_linear():
"""Test input node with Linear plugin (serial workflow execu... | """Test neuropycon command line interface"""
# Authors: Dmitrii Altukhov <daltuhov@hse.ru>
#
# License: BSD (3-clause)
import matplotlib # noqa
matplotlib.use('Agg') # noqa; for testing don't use X server
import os
import os.path as op
from ephypype.commands import neuropycon
from click.testing import CliRunner
d... | FIX matplotlib backend problem in cli tests | FIX matplotlib backend problem in cli tests
| Python | bsd-3-clause | neuropycon/ephypype |
92d25e86620fcdc415e94d5867cc22a95f88ca3a | mint/rest/db/awshandler.py | mint/rest/db/awshandler.py | #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
... | #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from mint import amiperms
class AWSHandler(object):
def __init__(self, cfg, db):
self.db = db
self.amiPerms = amiperms.AMIPermissionsManager(cfg, db)
def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None):
... | Fix typo when setting up handler. | Fix typo when setting up handler.
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint |
09b2fe8b248e70300470fcf71f6df0741376c548 | misc/disassemble_linear.py | misc/disassemble_linear.py | import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines):
res = ''
for line in lines:
op = proc.CPU_CONF['parse_line'](line)
if op is None:
continue
res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassembl... | import argparse
import sys
import time
import bracoujl.processor.gb_z80 as proc
dis = proc.CPU_CONF['disassembler']()
def disassemble(lines, keep_logs=False):
res = []
for line in lines:
op, gline = proc.CPU_CONF['parse_line'](line), ''
if keep_logs:
gline += line + (' | DIS: ' if ... | Fix and enhance disassemble miscellaneous script. | Fix and enhance disassemble miscellaneous script.
| Python | bsd-3-clause | fmichea/bracoujl |
e0063c0d5604372c1a07a179f5206a0a27570817 | package_reviewer/check/repo/check_semver_tags.py | package_reviewer/check/repo/check_semver_tags.py | import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found. See http://semver.org."
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
m... | import re
from . import RepoChecker
class CheckSemverTags(RepoChecker):
def check(self):
if not self.semver_tags:
msg = "No semantic version tags found"
for tag in self.tags:
if re.search(r"(v|^)\d+\.\d+$", tag.name):
msg += " (semantic versio... | Change message of semver tag check | Change message of semver tag check
| Python | mit | packagecontrol/st_package_reviewer,packagecontrol/package_reviewer |
d3163d8a7695da9687f82d9d40c6767322998fc2 | python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_collections.py | python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_collections.py | # Add taintlib to PATH so it can be imported during runtime without any hassle
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__))))
from taintlib import *
# This has no runtime impact, but allows autocomplete to work
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..taintlib... | # Add taintlib to PATH so it can be imported during runtime without any hassle
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__))))
from taintlib import *
# This has no runtime impact, but allows autocomplete to work
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..taintlib... | Add iterable-unpacking in for test | Python: Add iterable-unpacking in for test
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql |
679abfdd2b6a3c4d18170d93bfd42d73c47ff9c5 | phasm/typing.py | phasm/typing.py | """
Several type aliases used througout PHASM
-----------------------------------------
This is a separate module to prevent circular imports.
"""
from typing import Mapping, Set, Callable, Union, Tuple, Iterable
# Pairwise local alignments
OrientedDNASegment = 'phasm.alignments.OrientedDNASegment'
OrientedRead = 'p... | """
Several type aliases used througout PHASM
-----------------------------------------
This is a separate module to prevent circular imports.
"""
from typing import Mapping, Set, Callable, Union, Tuple, Iterable
# Pairwise local alignments
OrientedDNASegment = 'phasm.alignments.OrientedDNASegment'
OrientedRead = 'p... | Change Node type a bit | Change Node type a bit
In a reconstructed assembly graph sometimes the nodes can be str
| Python | mit | AbeelLab/phasm,AbeelLab/phasm |
fea07e0fe53049963a744b52c38a9abdfeb1c09e | commands.py | commands.py | from os import path
import shutil
import sublime
import sublime_plugin
SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..'))
COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands')
COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH)
COMMANDS_SOURCE_FULL_FILEPATH... | from os import path
import shutil
import sublime
import sublime_plugin
SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..'))
COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands')
COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH)
COMMANDS_SOURCE_FULL_FILEPATH... | Revert "Started exploring using argument but realizing this is a rabbit hole" | Revert "Started exploring using argument but realizing this is a rabbit hole"
This reverts commit b899d5613c0f4425aa4cc69bac9561b503ba83d4.
| Python | unlicense | twolfson/sublime-edit-command-palette,twolfson/sublime-edit-command-palette,twolfson/sublime-edit-command-palette |
b21c5a1b0f8d176cdd59c8131a316f142540d9ec | materials.py | materials.py | import color
def parse(mat_node):
materials = []
for node in mat_node:
materials.append(Material(node))
class Material:
''' it’s a material
'''
def __init__(self, node):
for c in node:
if c.tag == 'ambient':
self.ambient_color = color.parse(c[0])
... | import color
def parse(mat_node):
materials = []
for node in mat_node:
materials.append(Material(node))
class Material:
''' it’s a material
'''
def __init__(self, node):
for c in node:
if c.tag == 'ambient':
self.ambient_color = color.parse(c[0])
... | Remove replacement of commas by points | Remove replacement of commas by points
| Python | mit | cocreature/pytracer |
2fe72f41b1b62cf770869b8d3ccefeef1096ea11 | conftest.py | conftest.py | # -*- coding: UTF-8 -*-
"""
Configure pytest environment.
Add project-specific information.
.. seealso::
* https://github.com/pytest-dev/pytest-html
"""
import behave
import pytest
@pytest.fixture(autouse=True)
def _annotate_environment(request):
"""Add project-specific information to test-run environment:
... | # -*- coding: UTF-8 -*-
"""
Configure pytest environment.
Add project-specific information.
.. seealso::
* https://github.com/pytest-dev/pytest-html
"""
import behave
import pytest
@pytest.fixture(autouse=True)
def _annotate_environment(request):
"""Add project-specific information to test-run environment:
... | FIX when pytest-html is not installed. | FIX when pytest-html is not installed.
| Python | bsd-2-clause | Abdoctor/behave,Abdoctor/behave,jenisys/behave,jenisys/behave |
6df2a6e82a04c6cb19a789c55f758d0958a9b690 | nipype/interfaces/setup.py | nipype/interfaces/setup.py | def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('interfaces', parent_package, top_path)
config.add_data_dir('tests')
config.add_data_dir('script_templates')
return config
if __name__ == '__main__':
from numpy.dist... | def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('interfaces', parent_package, top_path)
config.add_subpackage('fsl')
config.add_data_dir('tests')
config.add_data_dir('script_templates')
return config
if __name__ ... | Add fsl subpackage on install. | Add fsl subpackage on install.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1050 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| Python | bsd-3-clause | glatard/nipype,rameshvs/nipype,arokem/nipype,wanderine/nipype,wanderine/nipype,FredLoney/nipype,dmordom/nipype,arokem/nipype,Leoniela/nipype,blakedewey/nipype,wanderine/nipype,dmordom/nipype,FCP-INDI/nipype,FredLoney/nipype,gerddie/nipype,FCP-INDI/nipype,christianbrodbeck/nipype,iglpdc/nipype,mick-d/nipype,satra/NiPype... |
6267fa5d9a3ff2573dc33a23d3456942976b0b7e | cyder/base/models.py | cyder/base/models.py | from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTim... | from django.db import models
from django.utils.safestring import mark_safe
from cyder.base.utils import classproperty
class BaseModel(models.Model):
"""
Base class for models to abstract some common features.
* Adds automatic created and modified fields to the model.
"""
created = models.DateTim... | Add help_text to interface 'expire' field | Add help_text to interface 'expire' field
| Python | bsd-3-clause | OSU-Net/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,akeym/cyder |
f29a6b205a872d7df63e8c45b5829959c98de227 | comics/comics/pcweenies.py | comics/comics/pcweenies.py | from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'The PC Weenies'
language = 'en'
url = 'http://www.pcweenies.com/'
start_date = '1998-10-21'
rights = 'Krishna M. Sadasivam'
class Crawler(CrawlerBase):
history_c... | from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = 'The PC Weenies'
language = 'en'
url = 'http://www.pcweenies.com/'
start_date = '1998-10-21'
rights = 'Krishna M. Sadasivam'
class Crawler(CrawlerBase):
history_c... | Update CSS selector which matched two img elements | Update CSS selector which matched two img elements
| Python | agpl-3.0 | klette/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,klette/comics,datagutten/comics,datagutten/comics |
5f0f1da10ebc01d95bb8659f5dc7782e57365b53 | .conda/to_cargoport.py | .conda/to_cargoport.py | #!/usr/bin/env python
import sys
import yaml
def extDetect(url):
if url.endswith('.tar.gz'):
return '.tar.gz'
elif url.endswith('.tgz'):
return '.tar.gz'
elif url.endswith('.tar.bz2'):
return '.tar.bz2'
elif url.endswith('.tar.xz'):
return '.tar.xz'
else:
re... | #!/usr/bin/env python
import sys
import yaml
def extDetect(url):
if url.endswith('.tar.gz'):
return '.tar.gz'
elif url.endswith('.tgz'):
return '.tar.gz'
elif url.endswith('.tar.bz2'):
return '.tar.bz2'
elif url.endswith('.tar.xz'):
return '.tar.xz'
else:
gu... | Fix download issue for a few packages | Fix download issue for a few packages
| Python | mit | erasche/community-package-cache,erasche/community-package-cache,gregvonkuster/cargo-port,gregvonkuster/cargo-port,galaxyproject/cargo-port,galaxyproject/cargo-port,erasche/community-package-cache,gregvonkuster/cargo-port |
54f53815653f807c17c33e9d3262d9d3a31abfcf | scripts/fill_events.py | scripts/fill_events.py | #!/usr/bin/env python
import sys
import os
sys.path.append(os.path.join(os.path.dirname('__file__'), '..', 'src'))
from random import randint
from datetime import datetime, timedelta
from logsandra.model.client import CassandraClient
client = CassandraClient('test', 'localhost', 9160, 3)
today = datetime.now()
ke... | #!/usr/bin/env python
import sys
import os
sys.path.append(os.path.join(os.path.dirname('__file__'), '..', 'src'))
from random import randint
from datetime import datetime, timedelta
from logsandra.model.client import CassandraClient
client = CassandraClient('test', 'localhost', 9160, 3)
keywords = ['foo', 'bar', ... | Print info about keywords when loading sample data | Print info about keywords when loading sample data
| Python | mit | thobbs/logsandra |
6ad647899d044cb46be6172cbea9c93a369ddc78 | pymanopt/solvers/theano_functions/comp_diff.py | pymanopt/solvers/theano_functions/comp_diff.py | # Module containing functions to compile and differentiate Theano graphs.
import theano.tensor as T
import theano
# Compile objective function defined in Theano.
def compile(objective, argument):
return theano.function([argument], objective)
# Compute the gradient of 'objective' with respect to 'argument' and re... | # Module containing functions to compile and differentiate Theano graphs.
import theano.tensor as T
import theano
# Compile objective function defined in Theano.
def compile(objective, argument):
return theano.function([argument], objective)
# Compute the gradient of 'objective' with respect to 'argument' and re... | Use `compile` function for `gradient` function | Use `compile` function for `gradient` function
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
| Python | bsd-3-clause | j-towns/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,tingelst/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt |
48e4203bc87fda407d0e5f804c854b53f7bf54fc | lemon/publications/managers.py | lemon/publications/managers.py | from django.db import models
from lemon.publications.querysets import PublicationQuerySet
class PublicationManager(models.Manager):
def expired(self):
return self.get_query_set().expired()
def future(self):
return self.get_query_set().future()
def enabled(self):
return self... | from django.db import models
from lemon.publications.querysets import PublicationQuerySet
class PublicationManager(models.Manager):
def expired(self):
return self.get_query_set().expired()
def future(self):
return self.get_query_set().future()
def enabled(self):
return self... | Fix handling of the _db attribute on the PublicationManager in get_query_set | Fix handling of the _db attribute on the PublicationManager in get_query_set
| Python | bsd-3-clause | trilan/lemon,trilan/lemon,trilan/lemon |
3c4565dcf6222af0e3b7cabf5c52f9ab18488be2 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecut... | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import is_repo_url, expand_abbreviations
@pytest.fixture(params=[
'gitolite@server:team/repo',
'git@github.com:audreyr/cookiecutter.git',
'https://github.com/audreyr/cookiecutter.git',
'https://bitbucket.org/pokoli/cookiecutter.hg',
])
def... | Refactor tests for is_repo_url to be parametrized | Refactor tests for is_repo_url to be parametrized
| Python | bsd-3-clause | luzfcb/cookiecutter,terryjbates/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,dajose/cookiecutter,stevepiercy/cookiecutter,terryjbates/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,aud... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.