commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
26585bcc2a4da3a53b1b13d4d1728e2533b12140 | move_tab.py | move_tab.py | # -*- coding: utf-8 -*-
"""
Move Tab
Plugin for Sublime Text to move tabs around
Copyright (c) 2012 Frédéric Massart - FMCorz.net
Licensed under The MIT License
Redistributions of files must retain the above copyright notice.
http://github.com/FMCorz/MoveTab
"""
import sublime_plugin
class MoveTabCommand(sublime... | """
Move Tab
Plugin for Sublime Text to move tabs around
Copyright (c) 2012 Frédéric Massart - FMCorz.net
Licensed under The MIT License
Redistributions of files must retain the above copyright notice.
http://github.com/FMCorz/MoveTab
"""
import sublime_plugin
class MoveTabCommand(sublime_plugin.WindowCommand):
... | Remove outdated and redundant encoding specifier | Remove outdated and redundant encoding specifier
| Python | mit | SublimeText/MoveTab | ---
+++
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
"""
Move Tab
|
caaa59ca23d7405ff16726d509e3c0d4e659baec | djstripe/migrations/0023_auto_20170307_0937.py | djstripe/migrations/0023_auto_20170307_0937.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-07 09:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-07 09:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL)
class Migration(migrations.... | Fix migration 0023 subscriber model reference | Fix migration 0023 subscriber model reference
| Python | mit | pydanny/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,pydanny/dj-stripe,jleclanche/dj-stripe,jleclanche/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,kavdev/dj-stripe,dj-stripe/dj-stripe | ---
+++
@@ -4,6 +4,9 @@
from django.conf import settings
from django.db import migrations, models
+
+
+DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL)
class Migration(migrations.Migration):
@@ -17,7 +20,7 @@
migrations.AlterField(
mod... |
a55765af4af8646a3ec95de2e8274b1c5584ee10 | nova/policies/fixed_ips.py | nova/policies/fixed_ips.py | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | Add policy description for os-fixed-ips | Add policy description for os-fixed-ips
This commit adds policy doc for os-fixed-ips policies.
Partial implement blueprint policy-docs
Change-Id: Ief255af699cee217ebf963a2c36f9e819ef4ef90
| Python | apache-2.0 | openstack/nova,jianghuaw/nova,vmturbo/nova,gooddata/openstack-nova,Juniper/nova,rahulunair/nova,Juniper/nova,jianghuaw/nova,jianghuaw/nova,gooddata/openstack-nova,vmturbo/nova,vmturbo/nova,rahulunair/nova,klmitch/nova,mahak/nova,rahulunair/nova,vmturbo/nova,klmitch/nova,mikalstill/nova,Juniper/nova,phenoxim/nova,mahak/... | ---
+++
@@ -13,8 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
-from oslo_policy import policy
-
from nova.policies import base
@@ -22,9 +20,26 @@
fixed_ips_policies = [
- policy.RuleDefault(
- name=BASE_POLICY_NAME,
- chec... |
6d37cb94c13c26ae82bc3b67a7ff03c2a032d7fc | test/test_message.py | test/test_message.py | import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü'
def test_quopri_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
def test_... | from base64 import b64encode
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü\n'
# Something in the email module implicitly adds a newline to the body text if
# one isn't present, so we need to include one here lest the base64 encodings
# not match up.
TEXT_ENC = TEXT.encode('utf-8')
... | Make tests forwards-compatible with new email API | Make tests forwards-compatible with new email API
| Python | mit | jwodder/daemail | ---
+++
@@ -1,21 +1,26 @@
+from base64 import b64encode
import quopri
from daemail.message import DraftMessage
-TEXT = 'àéîøü'
+TEXT = 'àéîøü\n'
+# Something in the email module implicitly adds a newline to the body text if
+# one isn't present, so we need to include one here lest the base64 encoding... |
e9e3c474194393a0586709a9cc59b02cf8573b32 | gearstore/cmd.py | gearstore/cmd.py | # Copyright (c) 2015 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 applica... | # Copyright (c) 2015 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 applica... | Fix call to stock instead of run | Fix call to stock instead of run
| Python | apache-2.0 | SpamapS/gearstore | ---
+++
@@ -39,5 +39,5 @@
stkr.waitForServer()
while True:
- stkr.run()
+ stkr.stock()
stkr.ship() |
14d4bd44fda88ff512f0a2581539e41d51063744 | pyconde/checkin/templatetags/checkin_tags.py | pyconde/checkin/templatetags/checkin_tags.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from django.utils.html import format_html
from django.utils.encoding import force_text
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.simple_tag(takes_context=True)
def highli... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from django.utils.html import format_html
from django.utils.encoding import force_text
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.simple_tag(takes_context=True)
def highli... | Make highlight template tag case insensitive | Make highlight template tag case insensitive
| Python | bsd-3-clause | pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep | ---
+++
@@ -11,6 +11,6 @@
@register.simple_tag(takes_context=True)
def highlight(context, value):
- if any(term in force_text(value) for term in context['search_terms']):
+ if any(term.lower() in force_text(value).lower() for term in context['search_terms']):
value = format_html('<strong>{0}</stron... |
4af6e0b4c514b65c5bd9251398947e830ce9f26e | quickphotos/templatetags/quickphotos_tags.py | quickphotos/templatetags/quickphotos_tags.py | from django import template
from quickphotos.models import Photo
register = template.Library()
@register.assignment_tag
def get_latest_photos(*args, **kwargs):
limit = kwargs.pop('limit', None)
photos = Photo.objects.all()
if args:
photos = photos.filter(user__in=args)
if limit is not None... | from django import template
from quickphotos.models import Photo
register = template.Library()
@register.assignment_tag
def get_latest_photos(*args, **kwargs):
limit = kwargs.pop('limit', None)
liked_by = kwargs.pop('liked_by', None)
photos = Photo.objects.all()
if liked_by:
photos = photos... | Tag filtering by liked photos | Tag filtering by liked photos
| Python | bsd-3-clause | blancltd/django-quick-photos,kmlebedev/mezzanine-instagram-quickphotos | ---
+++
@@ -8,7 +8,11 @@
@register.assignment_tag
def get_latest_photos(*args, **kwargs):
limit = kwargs.pop('limit', None)
+ liked_by = kwargs.pop('liked_by', None)
photos = Photo.objects.all()
+
+ if liked_by:
+ photos = photos.filter(like__user=liked_by)
if args:
photos = p... |
9d846cf6d22eb7a577f09918c2e48f6484a75962 | tests/test__utils.py | tests/test__utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import numpy as np
import dask_distance._utils
@pytest.mark.parametrize("et, u, v", [
(ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)),
])
def test__bool_cmp_mtx_cnt_err(et, u, v):
with ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import numpy as np
import dask_distance._utils
@pytest.mark.parametrize("et, u, v", [
(ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)),
(ValueError, np.zeros((1, 2,), dtype=bool), np.zer... | Test non-1D array error in utils | Test non-1D array error in utils
Adds a test for `_bool_cmp_mtx_cnt` to make sure that both arrays are 1D
only. Will raise a `ValueError` if this is not the case.
| Python | bsd-3-clause | jakirkham/dask-distance | ---
+++
@@ -13,6 +13,8 @@
@pytest.mark.parametrize("et, u, v", [
(ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)),
+ (ValueError, np.zeros((1, 2,), dtype=bool), np.zeros((2,), dtype=bool)),
+ (ValueError, np.zeros((2,), dtype=bool), np.zeros((1, 2,), dtype=bool)),
])
def test__bool... |
c4153cc69238054ddbdb8b385325f5a8701e98f8 | taxiexpress/serializers.py | taxiexpress/serializers.py | from django.forms import widgets
from rest_framework import serializers
from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'anim... | from django.forms import widgets
from rest_framework import serializers
from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'anim... | Add filters to Customer serializer | Add filters to Customer serializer
| Python | mit | TaxiExpress/server,TaxiExpress/server | ---
+++
@@ -28,4 +28,4 @@
travel_set = TravelSerializer(many=True)
class Meta:
model = Customer
- fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'favlist', 'travel_set')
+ fields = ('email', 'phone', 'first_name', 'last_name', 'image', 'lastUpdate', 'fav... |
55dc2428796059cba22df71bde307d5621394979 | runtests.py | runtests.py | # python setup.py test
# or
# python runtests.py
import sys
from django.conf import settings
APP = 'djrill'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF=APP+'.urls',
INSTALLED_APPS=(
'djang... | # python setup.py test
# or
# python runtests.py
import sys
from django.conf import settings
APP = 'djrill'
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ROOT_URLCONF=APP+'.urls',
INSTALLED_APPS=(
'djang... | Fix tests in Django 1.7 | Fix tests in Django 1.7
Django 1.7 doesn't include session or auth middleware
in minimal default config. Djrill admin views require auth.
| Python | bsd-3-clause | idlweb/Djrill,barseghyanartur/Djrill,janusnic/Djrill,barseghyanartur/Djrill,idlweb/Djrill,brack3t/Djrill,janusnic/Djrill | ---
+++
@@ -21,6 +21,12 @@
'django.contrib.sessions',
'django.contrib.admin',
APP,
+ ),
+ MIDDLEWARE_CLASSES=(
+ 'django.middleware.common.CommonMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+... |
458fd49fdf73f5cc338c58b1e741fde42f2f7251 | exampleapp/models.py | exampleapp/models.py | from galleries.models import Gallery, ImageModel
from django.db import models
from imagekit.models import ImageSpec
from imagekit.processors.resize import Fit
class Photo(ImageModel):
thumbnail = ImageSpec([Fit(50, 50)])
full = ImageSpec([Fit(400, 200)])
caption = models.CharField(max_length=100)
class ... | from galleries.models import Gallery, ImageModel
from django.db import models
from imagekit.models import ImageSpec
from imagekit.processors import ResizeToFit
class Photo(ImageModel):
thumbnail = ImageSpec([ResizeToFit(50, 50)])
full = ImageSpec([ResizeToFit(400, 200)])
caption = models.CharField(max_len... | Use (not so) new processor class names | Use (not so) new processor class names
| Python | mit | hzdg/django-galleries,hzdg/django-galleries,hzdg/django-galleries | ---
+++
@@ -1,17 +1,17 @@
from galleries.models import Gallery, ImageModel
from django.db import models
from imagekit.models import ImageSpec
-from imagekit.processors.resize import Fit
+from imagekit.processors import ResizeToFit
class Photo(ImageModel):
- thumbnail = ImageSpec([Fit(50, 50)])
- full = ... |
c8ef27115ebe38d19efb857a05fe5a4e7910ee55 | website/addons/forward/model.py | website/addons/forward/model.py | # -*- coding: utf-8 -*-
from modularodm import fields
from modularodm.validators import (
URLValidator, MinValueValidator, MaxValueValidator
)
from modularodm.exceptions import ValidationValueError
from framework.mongo.utils import sanitized
from website.addons.base import AddonNodeSettingsBase
class ForwardNo... | # -*- coding: utf-8 -*-
from modularodm import fields
from modularodm.validators import (
URLValidator, MinValueValidator, MaxValueValidator
)
from modularodm.exceptions import ValidationValueError
from framework.mongo.utils import sanitized
from website.addons.base import AddonNodeSettingsBase
class ForwardNo... | Reset values of external link add-on to default when deleted. | Reset values of external link add-on to default when deleted.
| Python | apache-2.0 | cosenal/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,lyndsysimon/osf.io,dplorimer/osf,cldershem/osf.io,leb2dg/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,caseyrygt/osf.io,jmcarp/osf.io,SSJohns/osf.io,arpitar/osf.io,zamattiac/osf.io,RomanZWang/osf.io,alexschiller/osf.io,samchrisinger/osf.io,emetsger/osf.io,SSJohns/os... | ---
+++
@@ -27,6 +27,15 @@
def link_text(self):
return self.label if self.label else self.url
+ def on_delete(self):
+ self.reset()
+
+ def reset(self):
+ self.url = None
+ self.label = None
+ self.redirect_bool = True
+ self.redirect_secs = 15
+
@ForwardNod... |
ac9c8fe7519ff76b4f4002ae8c50e0185fa4bb88 | tools/test_filter.py | tools/test_filter.py | {
'bslmf_addreference': [ {'OS': 'Windows'} ],
'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bslalg_constructorproxy': [ {'OS': 'AIX', 'library': 'shared_library'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'cas... | {
'bslmf_addreference': [ {'OS': 'Windows'} ],
'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case... | Remove exception for bslalg_constructorproxy test driver on AIX shared library builds. | Remove exception for bslalg_constructorproxy test driver on AIX shared library builds.
| Python | apache-2.0 | abeels/bde,che2/bde,minhlongdo/bde,bloomberg/bde-allocator-benchmarks,bowlofstew/bde,bloomberg/bde-allocator-benchmarks,jmptrader/bde,abeels/bde,dharesign/bde,frutiger/bde,che2/bde,apaprocki/bde,RMGiroux/bde-allocator-benchmarks,idispatch/bde,gbleaney/Allocator-Benchmarks,bloomberg/bde-allocator-benchmarks,idispatch/bd... | ---
+++
@@ -2,7 +2,6 @@
'bslmf_addreference': [ {'OS': 'Windows'} ],
'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
- 'bslalg_constructorproxy': [ {'OS': 'AIX', 'library': 'shared_library'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'po... |
121bcbfc873ce45667ec67bc6f22387b43f3aa52 | openfisca_web_ui/uuidhelpers.py | openfisca_web_ui/uuidhelpers.py | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it ... | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it ... | Use uuid.hex instead of reinventing it. | Use uuid.hex instead of reinventing it.
| Python | agpl-3.0 | openfisca/openfisca-web-ui,openfisca/openfisca-web-ui,openfisca/openfisca-web-ui | ---
+++
@@ -30,4 +30,4 @@
def generate_uuid():
- return unicode(uuid.uuid4()).replace('-', '')
+ return unicode(uuid.uuid4().hex) |
2f1423eb57c21938ce85a07e3a3760901f2a852a | games/objects/basescript.py | games/objects/basescript.py |
import datetime
from mongoengine_models import Message
class Script(object):
'''This is a placeholder class used for doing object script things.
It's mostly just used for detecting if an object is really a script or not.
'''
def __init__(self, mongo_engine_object=None):
self.me_obj = mongo_en... |
import datetime
from mongoengine_models import Message
import os
import re
import random
from settings import MAX_DICE_AMOUNT
def parse(s):
result = re.search(r'^((?P<rolls>\d+)#)?(?P<dice>\d*)d(?P<sides>\d+)(?P<mod>[+-]\d+)?$', s)
return (result.group('rolls') or 0,
result.group('dice') or 1,
... | Add support for rolling dice for easy random number generation in scripts. | Add support for rolling dice for easy random number generation in scripts.
| Python | agpl-3.0 | cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO | ---
+++
@@ -2,6 +2,19 @@
import datetime
from mongoengine_models import Message
+
+import os
+import re
+import random
+
+from settings import MAX_DICE_AMOUNT
+
+def parse(s):
+ result = re.search(r'^((?P<rolls>\d+)#)?(?P<dice>\d*)d(?P<sides>\d+)(?P<mod>[+-]\d+)?$', s)
+ return (result.group('rolls') or 0,
... |
bc19d4d7d2181ee402aafcbb064070852151063c | IPython/html/tests/test_notebookapp.py | IPython/html/tests/test_notebookapp.py | """Test NotebookApp"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------... | """Test NotebookApp"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------... | Test for writing and removing server info files | Test for writing and removing server info files
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -14,6 +14,7 @@
import nose.tools as nt
import IPython.testing.tools as tt
+from IPython.html import notebookapp
#-----------------------------------------------------------------------------
# Test functions
@@ -23,3 +24,18 @@
"""ipython notebook --help-all works"""
tt.help_all_output_tes... |
53ce60063c8a308cbbe08eddd264dd1e30c93615 | jarbas/core/tests/test_loaddatasets_command.py | jarbas/core/tests/test_loaddatasets_command.py | from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_... | from django.test import TestCase
from jarbas.core.management.commands.loaddatasets import Command
class TestSerializer(TestCase):
def setUp(self):
self.command = Command()
def test_force_int(self):
self.assertEqual(self.command.force_int('1'), 1)
self.assertEqual(self.command.force_... | Add loaddatasets serializer tests for real | Add loaddatasets serializer tests for real
| Python | mit | marcusrehm/serenata-de-amor,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,rogeriochaves/jarbas,marcusrehm/serenata-de-amor,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,datasci... | ---
+++
@@ -13,3 +13,49 @@
self.assertEqual(self.command.force_int('1.0'), 1)
with self.assertRaises(ValueError):
self.command.force_int('abc')
+
+ def test_serializer(self):
+ expected = {
+ 'document_id': 1,
+ 'congressperson_id': 1,
+ 'congr... |
d91d16a53ee01cf384187dcda28f1c4ab6e46e1b | astropy/io/misc/asdf/tags/time/tests/test_timedelta.py | astropy/io/misc/asdf/tags/time/tests/test_timedelta.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import pytest
asdf = pytest.importorskip('asdf')
from asdf.tests.helpers import assert_roundtrip_tree
from astropy.time import Time, TimeDelta
@pytest.mark.parametrize('fmt', Time.FORMATS.keys())
def test_timedelta(fmt, tmpdir)... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import pytest
asdf = pytest.importorskip('asdf')
from asdf.tests.helpers import assert_roundtrip_tree
from astropy.time import Time, TimeDelta
@pytest.mark.parametrize('fmt', TimeDelta.FORMATS.keys())
def test_timedelta(fmt, tm... | Fix the ASDF test for TimeDelta formats | Fix the ASDF test for TimeDelta formats
| Python | bsd-3-clause | larrybradley/astropy,MSeifert04/astropy,saimn/astropy,bsipocz/astropy,stargaser/astropy,larrybradley/astropy,dhomeier/astropy,saimn/astropy,bsipocz/astropy,mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,mhvk/astropy,stargaser/astropy,MSeifert04/astropy,pllim/astropy,MSeifert04/astropy,astropy/astrop... | ---
+++
@@ -9,13 +9,13 @@
from astropy.time import Time, TimeDelta
-@pytest.mark.parametrize('fmt', Time.FORMATS.keys())
+@pytest.mark.parametrize('fmt', TimeDelta.FORMATS.keys())
def test_timedelta(fmt, tmpdir):
- t1 = Time(Time.now(), format=fmt)
- t2 = Time(Time.now(), format=fmt)
+ t1 = Time(Time... |
63a32acb6e2f9aadec015361f04283999f75be79 | examples/app/localmodule.py | examples/app/localmodule.py | def install_module(app):
"""Installs this localmodule."""
install_module
| class IndexResource(object):
def on_get(self, req, res):
res.body = 'Hello. This is app.'
def install_module(app):
"""Installs this localmodule."""
app.api.add_route('/', IndexResource())
| Add IndexResource to example module. | Add IndexResource to example module.
| Python | apache-2.0 | slinghq/sling | ---
+++
@@ -1,3 +1,9 @@
+class IndexResource(object):
+
+ def on_get(self, req, res):
+ res.body = 'Hello. This is app.'
+
+
def install_module(app):
"""Installs this localmodule."""
- install_module
+ app.api.add_route('/', IndexResource()) |
7b7f626c54694ec72166094ad568254ecfcdce8a | strictyaml/__init__.py | strictyaml/__init__.py | # The all important loader
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators impor... | # The all important loader
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators impor... | REFACTOR : Import YAMLError so it is usable as a generic exception. | REFACTOR : Import YAMLError so it is usable as a generic exception.
| Python | mit | crdoconnor/strictyaml,crdoconnor/strictyaml | ---
+++
@@ -19,9 +19,8 @@
from strictyaml.validators import UniqueSeq
# Exceptions
+from strictyaml.exceptions import YAMLError
from strictyaml.exceptions import StrictYAMLError
-
-# Validaton
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions |
a4e9198194e08b99e11802dd260bd5c203179211 | Mollie/API/Object/Customer.py | Mollie/API/Object/Customer.py | from .Base import Base
class Customer(Base):
@property
def id(self):
return self.getProperty('id')
@property
def name(self):
return self.getProperty('name')
@property
def email(self):
return self.getProperty('email')
@property
def locale(self):
return... | from .Base import Base
class Customer(Base):
@property
def id(self):
return self.getProperty('id')
@property
def name(self):
return self.getProperty('name')
@property
def email(self):
return self.getProperty('email')
@property
def locale(self):
return... | Remove forgotten if in customer.py | Remove forgotten if in customer.py
| Python | bsd-2-clause | mollie/mollie-api-python | ---
+++
@@ -20,8 +20,6 @@
@property
def metadata(self):
- if 'metadata' not in self:
- return None
return self.getProperty('metadata')
@property |
38b739941f9d002e8ad345388ff41418fe4160a4 | flexget/plugins/input/sonarr.py | flexget/plugins/input/sonarr.py | from __future__ import unicode_literals, division, absolute_import
import logging
import requests
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
log = logging.getLogger('sonarr')
class Sonarr(object):
schema = {
'type': 'object',
'properties': {
... | from __future__ import unicode_literals, division, absolute_import
import logging
import requests
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
log = logging.getLogger('sonarr')
class Sonarr(object):
schema = {
'type': 'object',
'properties': {
... | Fix PEP8 and add more data | Fix PEP8 and add more data
Added tvdb_id and tvrage_id entries to returned data
| Python | mit | grrr2/Flexget,ianstalk/Flexget,thalamus/Flexget,Pretagonist/Flexget,jacobmetrick/Flexget,ratoaq2/Flexget,offbyone/Flexget,oxc/Flexget,grrr2/Flexget,ibrahimkarahan/Flexget,crawln45/Flexget,sean797/Flexget,gazpachoking/Flexget,Flexget/Flexget,qk4l/Flexget,ianstalk/Flexget,offbyone/Flexget,xfouloux/Flexget,antivirtel/Flex... | ---
+++
@@ -8,6 +8,7 @@
log = logging.getLogger('sonarr')
+
class Sonarr(object):
schema = {
@@ -15,7 +16,7 @@
'properties': {
'base_url': {'type': 'string'},
'port': {'type': 'number'},
- 'api_key': {'type':'string'}
+ 'api_key': {'type': 'string'... |
e6f85eb50ea1de37ba0f2c4ad75997a9da3879a0 | changes/api/jobphase_index.py | changes/api/jobphase_index.py | from __future__ import absolute_import
from flask import Response
from sqlalchemy.orm import joinedload, subqueryload_all
from changes.api.base import APIView
from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer
from changes.models import Job, JobPhase, JobStep
class JobPhaseIndexAPIView(A... | from __future__ import absolute_import
from flask import Response
from sqlalchemy.orm import joinedload, subqueryload_all
from changes.api.base import APIView
from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer
from changes.models import Job, JobPhase, JobStep
class JobPhaseIndexAPIView(A... | Order JobPhase by date started, date created | Order JobPhase by date started, date created
| Python | apache-2.0 | bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes | ---
+++
@@ -22,7 +22,7 @@
subqueryload_all(JobPhase.steps, JobStep.node),
).filter(
JobPhase.job_id == job.id,
- ))
+ ).order_by(JobPhase.date_started.asc(), JobPhase.date_created.asc()))
return self.respond(self.serialize(phase_list, {
JobPhase... |
202f47bb5903786b0c6a09ea4e27ed558938d2da | dramadive/button_app.py | dramadive/button_app.py | #!/usr/bin/env python3
import os
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os.O_NONBLOCK)
... | #!/usr/bin/env python3
import os
import requests
from select import select
from sys import exit, stderr
from time import sleep
WRITE_BYTES = [0x0 for b in range(0, 8)]
WRITE_BYTES[0] = 0x08
WRITE_BYTES[7] = 0x02
CLOSED = 0x15
OPEN = 0x17
DOWN = 0x16
def main():
fd_id = os.open('/dev/big_red_button', os.O_RDWR|os... | Use vendor and product id for udev rules | Use vendor and product id for udev rules
| Python | apache-2.0 | 1stvamp/dramadive-client | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import os
+import requests
from select import select
from sys import exit, stderr
from time import sleep
@@ -25,14 +26,15 @@
data = fd.read(8)
if data is not None and data[0] != last:
if data[0] == CLOSED:
- ... |
c68a69beb03047d7ea388704fbb12074b32216bc | scenarios/UAS/alice_cfg.py | scenarios/UAS/alice_cfg.py | from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig
class AUTH_CREDS(AUTH_CREDS_orig):
enalgs = ('SHA-256', 'MD5-sess', None)
def __init__(self):
AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
| from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig
class AUTH_CREDS(AUTH_CREDS_orig):
enalgs = ('SHA-256', 'SHA-256-sess', 'MD5-sess', None)
def __init__(self):
AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
| Enable SHA-256-sess to see if it works or not. | Enable SHA-256-sess to see if it works or not.
| Python | bsd-2-clause | sippy/voiptests,sippy/voiptests | ---
+++
@@ -1,7 +1,7 @@
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig
class AUTH_CREDS(AUTH_CREDS_orig):
- enalgs = ('SHA-256', 'MD5-sess', None)
+ enalgs = ('SHA-256', 'SHA-256-sess', 'MD5-sess', None)
def __init__(self):
AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw... |
f577606a84deb5dac36aa95500b0d21529560868 | src/permission/conf.py | src/permission/conf.py | # coding=utf-8
"""
django-permission application configure
"""
__author__ = 'Alisue <lambdalisue@hashnote.net>'
__all__ = ('settings',)
from django.conf import settings
from appconf import AppConf
from permission.handlers import LogicalPermissionHandler
class PermissionConf(AppConf):
DEFAULT_PERMISSION_HANDLER = L... | # coding=utf-8
"""
django-permission application configure
"""
__author__ = 'Alisue <lambdalisue@hashnote.net>'
__all__ = ('settings',)
from django.conf import settings
from appconf import AppConf
from permission.handlers import LogicalPermissionHandler
class PermissionConf(AppConf):
DEFAULT_PERMISSION_HANDLER = L... | Add default permission of StaffPermissionLogic | Add default permission of StaffPermissionLogic
| Python | mit | lambdalisue/django-permission | ---
+++
@@ -33,6 +33,11 @@
DEFAULT_GIPL_CHANGE_PERMISSION = True
DEFAULT_GIPL_DELETE_PERMISSION = False
+ DEFAULT_SPL_ANY_PERMISSION = False
+ DEFAULT_SPL_ADD_PERMISSION = True
+ DEFAULT_SPL_CHANGE_PERMISSION = True
+ DEFAULT_SPL_DELETE_PERMISSION = False
+
AUTODISCOVER_ENABLE = True
... |
b8ec7503c71c43de8168a7d22cec4c2842382f2d | augur/datasources/downloads/test_downloads_routes.py | augur/datasources/downloads/test_downloads_routes.py | import os
import pytest
import requests
import augur.server
@pytest.fixture(scope="module")
def downloads_routes():
pass
| import os
import pytest
import requests
@pytest.fixture(scope="module")
def downloads_routes():
pass
| Remove uneccesary import in downloads API test | Remove uneccesary import in downloads API test
The test_downloads_routes.py module was uneccessarily importing augur.server
due to the remnants of the previous testing architecture. This import
was causing the build to error out, so it's been removed.
Signed-off-by: Carter Landis <ffc486ac0b21a34cfd7d1170183ed86b0f1b... | Python | mit | OSSHealth/ghdata,OSSHealth/ghdata,OSSHealth/ghdata | ---
+++
@@ -1,7 +1,6 @@
import os
import pytest
import requests
-import augur.server
@pytest.fixture(scope="module")
def downloads_routes(): |
033e6dbcbc735101164a7fa4c789e6704a6ee15a | aldryn_apphooks_config/models.py | aldryn_apphooks_config/models.py | # -*- coding: utf-8 -*-
from app_data import AppDataField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class AppHookConfig(models.Model):
"""
This is the generic (abstract) model ... | # -*- coding: utf-8 -*-
from app_data import AppDataField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class AppHookConfig(models.Model):
"""
This is the generic (abstract) model ... | Change the str representation of AppHookConfig by using the related CMSApp name instead of the type | Change the str representation of AppHookConfig by using the related CMSApp name instead of the type
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config | ---
+++
@@ -15,6 +15,8 @@
namespace = models.CharField(max_length=100)
app_data = AppDataField()
+ cmsapp = None
+
class Meta:
verbose_name = _(u'app-hook config')
verbose_name_plural = _(u'app-hook configs')
@@ -27,4 +29,7 @@
super(AppHookConfig, self).save(*args, **kwa... |
2d39aed3dcdb28acc61a6598cca9836665c2674e | cs251tk/student/markdownify/check_submit_date.py | cs251tk/student/markdownify/check_submit_date.py | import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and re... | import os
from dateutil.parser import parse
from ...common import run, chdir
def check_dates(spec_id, username, spec, basedir):
""" Port of the CheckDates program from C++
Finds the first submission date for an assignment
by comparing first commits for all files in the spec
and re... | Modify error check in check_dates() | Modify error check in check_dates()
| Python | mit | StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit | ---
+++
@@ -16,11 +16,11 @@
for file in spec['files']:
# Run a git log on each file with earliest commits listed first
- _, res, _ = run(['git', 'log', '--reverse', '--pretty=format:%ad', '--date=iso8601',
- os.path.join(basedir, file['filename'])])
+ ... |
ab72360da83e3b8d95030394f35a442943f53233 | domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py | domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
from control import lqr
import numpy as np
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.... | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self... | Remove some unused code that unnecessarily introduced depends | Remove some unused code that unnecessarily introduced depends
This should be regarded as an update to 9aa5b02e12a2287642a285541c43790a10d6444f
that removes unnecessary dependencies for the lqr.py example.
In the example provided by 9aa5b02e12a2287642a285541c43790a10d6444f
Python code was introduced that led to depend... | Python | bsd-3-clause | fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark | ---
+++
@@ -5,20 +5,11 @@
import rospy
from dynamaestro.msg import VectorStamped
-from control import lqr
-import numpy as np
-
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self.read_state)
self.int... |
4a3b39b55d129b2bad4772f8a477053bd33cb6c0 | masters/master.client.breakpad/master_site_config.py | masters/master.client.breakpad/master_site_config.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class Breakpad(Master.Master3):
project_name = 'Breakpad'
project_url = ('https://co... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class Breakpad(Master.Master3):
project_name = 'Breakpad'
project_url = ('https://co... | Change port for breakpad to available port. | Change port for breakpad to available port.
BUG=366164, 359557
R=johnw@google.com
Review URL: https://codereview.chromium.org/526553002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291789 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -10,7 +10,7 @@
project_name = 'Breakpad'
project_url = ('https://code.google.com/p/google-breakpad/wiki/'
'GettingStartedWithBreakpad')
- master_port = 8047
- slave_port = 8147
- master_port_alt = 8247
+ master_port = 8053
+ slave_port = 8153
+ master_port_alt = 8253
buildb... |
687592754a80397e4e44585f232e76b7d3360780 | pod_manager/db.py | pod_manager/db.py | import redis
from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
def get_client():
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
return client
| import pickle
import redis
from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
__all__ = [
'get_client',
'cache_object',
'get_object'
]
def get_client():
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
return client
def cache_object(client, key, obj, ttl=60):
... | Add cache_object and get_object functions. | Add cache_object and get_object functions.
| Python | apache-2.0 | racker/pod-manager | ---
+++
@@ -1,7 +1,33 @@
+import pickle
import redis
from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
+__all__ = [
+ 'get_client',
+ 'cache_object',
+ 'get_object'
+]
+
def get_client():
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
return client
+
+def... |
57d3f5a78385b07fb4d7f91ac97edb6e9dc850aa | waterbutler/providers/osfstorage/metadata.py | waterbutler/providers/osfstorage/metadata.py | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... | Use startswith in favor of indexing | Use startswith in favor of indexing
| Python | apache-2.0 | CenterForOpenScience/waterbutler,cosenal/waterbutler,icereval/waterbutler,chrisseto/waterbutler,RCOSDP/waterbutler,rafaeldelucena/waterbutler,Johnetordoff/waterbutler,TomBaxter/waterbutler,felliott/waterbutler,rdhyee/waterbutler,kwierman/waterbutler,Ghalko/waterbutler,hmoco/waterbutler | ---
+++
@@ -14,9 +14,9 @@
@property
def path(self):
- if self.raw['path'][0] != '/':
- return '/' + self.raw['path']
- return self.raw['path']
+ if self.raw['path'][0].startswith('/'):
+ return self.raw['path']
+ return '/' + self.raw['path']
@prope... |
c393aab91962a1623b36769856026a1a31527939 | settings.py | settings.py | from settings_common import *
PACKAGE_VERSION = "0.5"
DEBUG = TEMPLATE_DEBUG = True
DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp')
SERVE_STATIC_FILES = True
# the following is an idea from https://code.djangoproject.com/wi... | from settings_common import *
PACKAGE_VERSION = "0.5"
DEBUG = TEMPLATE_DEBUG = True
DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp')
SERVE_STATIC_FILES = True
LOGGING = {
'version': 1,
'disable_existing_loggers': Fal... | Add the setup for logging | Add the setup for logging
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | ---
+++
@@ -9,6 +9,51 @@
SERVE_STATIC_FILES = True
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'formatters': {
+ 'verbose': {
+ 'format': '%(asctime)s - %(levelname)s - %(name)s - %(filename)s:%(lineno)d %(funcName)s() %(message)s'
+ },
+ 'simp... |
3692d64332768a6a8bd85ac5dbfecaba5c364d4a | tests/util/test_platform.py | tests/util/test_platform.py | import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
if platform.system() != "L... | import pytest
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
@pytest.mark.skipif(
platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
)
def test_platfor... | Use Pytest's skipif decorator instead of returning to skip assert statements. | Use Pytest's skipif decorator instead of returning to skip assert statements.
| Python | mit | jaraco/keyring | ---
+++
@@ -1,3 +1,4 @@
+import pytest
import platform
from keyring.util.platform_ import (
@@ -10,19 +11,21 @@
)
+@pytest.mark.skipif(
+ platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
+)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on di... |
ae78135aed5c60c03c247677e9096ce5411b6635 | django_olcc/olcc/templatetags/olcc.py | django_olcc/olcc/templatetags/olcc.py | from django import template
from bs4 import BeautifulSoup
register = template.Library()
@register.tag(name='activehref')
def do_active_href(parser, token):
nodelist = parser.parse(('endactivehref',))
parser.delete_first_token()
return ActiveHref(nodelist)
class ActiveHref(template.Node):
"""
Thi... | from django import template
from bs4 import BeautifulSoup
register = template.Library()
@register.tag(name='activehref')
def do_active_href(parser, token):
nodelist = parser.parse(('endactivehref',))
parser.delete_first_token()
return ActiveHref(nodelist)
class ActiveHref(template.Node):
"""
Thi... | Update docstring for the ActiveHref template tag. | Update docstring for the ActiveHref template tag.
| Python | mit | twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc | ---
+++
@@ -15,6 +15,14 @@
This template tag will set an 'active' class attribute
on any anchor with an href value that matches part of the
current url path.
+
+ Sample template usage:
+
+ {% activehref %}
+ <li><a href="{% url products %}">Products</a></li>
+ <li><a href="{% url stores %}"... |
877378bd699b6d56ebc00b4df7d7a83523d470e7 | bugle/templatetags/bugle.py | bugle/templatetags/bugle.py | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('#[^\s]+')
@register.filter
def buglise(s):
s = unicode(s)
usernam... | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('\b#[^\s]+')
@register.filter
def buglise(s):
s = unicode(s)
usern... | Fix hash tag linking entities | Fix hash tag linking entities
| Python | bsd-2-clause | devfort/bugle,devfort/bugle,devfort/bugle,simonw/bugle_project,simonw/bugle_project | ---
+++
@@ -7,7 +7,7 @@
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
-hashtag_re = re.compile('#[^\s]+')
+hashtag_re = re.compile('\b#[^\s]+')
@register.filter
def buglise(s): |
5107ca17da0764257bc05488457a7a20f59fe76f | calicoctl/calico_ctl/__init__.py | calicoctl/calico_ctl/__init__.py | __version__ = "0.16.0-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
| __version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
| Update docs to version v0.16.1 | Update docs to version v0.16.1
| Python | apache-2.0 | Metaswitch/calico-docker,caseydavenport/calico-docker,insequent/calico-docker,TrimBiggs/calico-containers,projectcalico/calico-containers,projectcalico/calico-docker,caseydavenport/calico-containers,caseydavenport/calico-containers,projectcalico/calico-containers,projectcalico/calico-docker,Metaswitch/calico-docker,Tri... | ---
+++
@@ -1,4 +1,4 @@
-__version__ = "0.16.0-dev"
+__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev" |
1f11ca9f4e4d2560624fd159913d5b35d6bf12e7 | chainer/ya/utils/range_logger.py | chainer/ya/utils/range_logger.py | import logging
class rangelog:
logger = None
startlog = "--> Start: {name}"
endlog = "<-- End:" # noqa
@classmethod
def set_logger(cls, logger=None):
if logger is None:
cls.logger = logging.getLogger()
cls.logger.setLevel(getattr(logging, 'INFO'))
c... | import logging
class rangelog:
logger = None
startmsg = "--> Start: {name}"
endmsg = "<-- End:" # noqa
@classmethod
def set_logger(cls, logger=None):
if logger is None:
cls.logger = logging.getLogger()
cls.logger.setLevel(getattr(logging, 'INFO'))
c... | Add feature to set start/end messages | Add feature to set start/end messages
| Python | mit | yasuyuky/chainer-ya-utils | ---
+++
@@ -3,8 +3,8 @@
class rangelog:
logger = None
- startlog = "--> Start: {name}"
- endlog = "<-- End:" # noqa
+ startmsg = "--> Start: {name}"
+ endmsg = "<-- End:" # noqa
@classmethod
def set_logger(cls, logger=None):
@@ -15,14 +15,22 @@
elif isinstance(logger, ... |
9c45b422e3854551fd1ff3ae1d56ee20d3d6457d | mezzanine/settings/admin.py | mezzanine/settings/admin.py |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import Setting... |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import Setting... | Add a redirect on successful update of settings. | Add a redirect on successful update of settings.
| Python | bsd-2-clause | wyzex/mezzanine,ZeroXn/mezzanine,stephenmcd/mezzanine,tuxinhang1989/mezzanine,jerivas/mezzanine,cccs-web/mezzanine,damnfine/mezzanine,guibernardino/mezzanine,emile2016/mezzanine,gradel/mezzanine,biomassives/mezzanine,wrwrwr/mezzanine,geodesign/mezzanine,PegasusWang/mezzanine,theclanks/mezzanine,dsanders11/mezzanine,wbt... | ---
+++
@@ -33,6 +33,7 @@
settings_form = SettingsForm(request.POST or None)
if settings_form.is_valid():
settings_form.save()
+ return self.changelist_redirect()
extra_context["settings_form"] = settings_form
extra_context["title"] = _("Change %s" %
... |
210b24b1e04106745b5680d099f31f3a354446e8 | test/599-whitewater.py | test/599-whitewater.py | # node 2356117215
assert_has_feature(
16, 34003, 23060, 'pois',
{ 'kind': 'put_in' })
# way 308154534
assert_has_feature(
13, 2448, 2992, 'roads',
{ 'kind': 'portage_way' })
| # node 3134398100
assert_has_feature(
16, 19591, 23939, 'pois',
{ 'kind': 'put_in_egress' })
# way 308154534
assert_has_feature(
13, 2448, 2992, 'roads',
{ 'kind': 'portage_way' })
| Use test feature from North America | Use test feature from North America
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -1,7 +1,7 @@
-# node 2356117215
+# node 3134398100
assert_has_feature(
- 16, 34003, 23060, 'pois',
- { 'kind': 'put_in' })
+ 16, 19591, 23939, 'pois',
+ { 'kind': 'put_in_egress' })
# way 308154534
assert_has_feature( |
3c0bc3c382b3abe693b3871ee0c3d40723cb8f28 | comics/crawler/crawlers/bunny.py | comics/crawler/crawlers/bunny.py | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
ri... | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Bunny'
language = 'en'
url = 'http://bunny-comic.com/'
start_date = '2004-08-22'
history_capable_days = 14
schedule = 'Mo,Tu,We,Th,Fr'
time_zone = -8
ri... | Fix Bunny crawler crash on non-date image names | Fix Bunny crawler crash on non-date image names
| Python | agpl-3.0 | jodal/comics,klette/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics | ---
+++
@@ -23,7 +23,9 @@
url = pieces[i + 1]
break
image_name = url.replace('http://bunny-comic.com/strips/', '')
- if self.pub_date == self.string_to_date(image_name[:6], '%d%m%y'):
+ if (image_name[:6].isdigit()
+ and s... |
11efbbfb310e584ef4af01bf7d662216a3356d22 | wagtail/search/backends/database/sqlite/utils.py | wagtail/search/backends/database/sqlite/utils.py | import sqlite3
from django.db import OperationalError
def fts5_available():
# based on https://stackoverflow.com/a/36656216/1853523
if sqlite3.sqlite_version_info < (3, 19, 0):
# Prior to version 3.19, SQLite doesn't support FTS5 queries with
# column filters ('{column_1 column_2} : query'), ... | import sqlite3
from django.db import OperationalError
def fts5_available():
# based on https://stackoverflow.com/a/36656216/1853523
if sqlite3.sqlite_version_info < (3, 19, 0):
# Prior to version 3.19, SQLite doesn't support FTS5 queries with
# column filters ('{column_1 column_2} : query'), ... | Fix Sqlite FTS5 compatibility check | Fix Sqlite FTS5 compatibility check
As per https://github.com/wagtail/wagtail/issues/7798#issuecomment-1021544265 - the direct query against the sqlite3 library will fail with sqlite3.OperationalError, not django.db.OperationalError.
| Python | bsd-3-clause | torchbox/wagtail,torchbox/wagtail,torchbox/wagtail,torchbox/wagtail | ---
+++
@@ -14,7 +14,7 @@
tmp_db = sqlite3.connect(':memory:')
try:
tmp_db.execute('CREATE VIRTUAL TABLE fts5test USING fts5 (data);')
- except OperationalError:
+ except sqlite3.OperationalError:
return False
finally:
tmp_db.close() |
930ad35cee818e2d0b97f840ff0b3b772bd51af3 | post_office/management/commands/send_queued_mail.py | post_office/management/commands/send_queued_mail.py | import tempfile
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from ...lockfile import FileLock, FileLocked
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
default_lockfile = tempfile.gettempdir() + "/post_office... | import tempfile
import sys
from django.core.management.base import BaseCommand
from ...lockfile import FileLock, FileLocked
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
default_lockfile = tempfile.gettempdir() + "/post_office"
class Command(BaseCommand):
... | Switch to using the `add_arguments` method. | Switch to using the `add_arguments` method.
This is an alternative to using the `option_list` and
`optparse.make_option`. Django deprecated the use of `optparse` in
management commands in Django 1.8 and removed it in Django 1.10.
| Python | mit | jrief/django-post_office,ui/django-post_office,ui/django-post_office | ---
+++
@@ -1,6 +1,5 @@
import tempfile
import sys
-from optparse import make_option
from django.core.management.base import BaseCommand
@@ -14,15 +13,21 @@
class Command(BaseCommand):
-
- option_list = BaseCommand.option_list + (
- make_option('-p', '--processes', type='int',
- ... |
292277abac516c412d58f1454331d9e38ddda2b3 | ca_on_candidates/people.py | ca_on_candidates/people.py | from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv'
encoding = 'utf-8'
updated_at = date(2018, 1,... | from utils import CSVScraper
from datetime import date
class OntarioCandidatesPersonScraper(CSVScraper):
csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv'
encoding = 'utf-8'
... | Make CSV URL more specific | ca_on_candidates: Make CSV URL more specific
| Python | mit | opencivicdata/scrapers-ca,opencivicdata/scrapers-ca | ---
+++
@@ -4,7 +4,7 @@
class OntarioCandidatesPersonScraper(CSVScraper):
- csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv'
+ csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN... |
7111a61a66affcb3c60ea207084e537b2109da61 | mangaki/mangaki/management/commands/top.py | mangaki/mangaki/management/commands/top.py | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top'
def handle(self, *a... | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top'
def handle(self, *a... | Add ID to Artist in Top | Add ID to Artist in Top
| Python | agpl-3.0 | Mako-kun/mangaki,Elarnon/mangaki,Elarnon/mangaki,Mako-kun/mangaki,Mako-kun/mangaki,Elarnon/mangaki | ---
+++
@@ -24,5 +24,5 @@
c[contestant] += values.get(rating.choice, 0)
top = []
for i, (artist, score) in enumerate(c.most_common(20)):
- top.append(dict(rank=i + 1, name=str(artist), score=score, nb_ratings=nb_ratings[artist], nb_stars=nb_stars[artist]))
+ top.ap... |
355e0bab150f2e5c5c52b02714dfaef997dda856 | regparser/tree/xml_parser/flatsubtree_processor.py | regparser/tree/xml_parser/flatsubtree_processor.py | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | Allow images in EXTRACTs, etc. | Allow images in EXTRACTs, etc.
| Python | cc0-1.0 | tadhg-ohiggins/regulations-parser,eregs/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser | ---
+++
@@ -13,6 +13,7 @@
paragraph_processor.HeaderMatcher(),
paragraph_processor.SimpleTagMatcher('P', 'FP'),
us_code.USCodeMatcher(),
+ paragraph_processor.GraphicsMatcher(),
paragraph_processor.IgnoreTagMatcher('PRTPAGE')]
|
5e6d62ce7a567282a88530a2db80b775c9c4406e | swf/core.py | swf/core.py | # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attribu... | # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attribu... | Fix ConnectedSWFObject: restrict attributes set by constructor | Fix ConnectedSWFObject: restrict attributes set by constructor
- credentials: SETTINGS | kwargs
- region: SETTINGS | kwargs | boto.swf.layer1.Layer1.DefaultRegionName
- connection: kwargs
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | ---
+++
@@ -28,12 +28,15 @@
]
def __init__(self, *args, **kwargs):
- settings_ = {k: v for k, v in SETTINGS.iteritems()}
- settings_.update(kwargs)
+ settings_ = {key: SETTINGS.get(key, kwargs.get(key)) for key in
+ ('aws_access_key_id',
+ 'aws... |
0dde910ff5f44aaa265e9439d006effde3c68a3f | plugins/brian.py | plugins/brian.py | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | Add attribution to quotes in plugin | Add attribution to quotes in plugin
| Python | mit | kvchen/keffbot-py,kvchen/keffbot | ---
+++
@@ -30,6 +30,6 @@
def on_message(bot, channel, user, message):
- return '> {}'.format(generate_phrase(phrases, cache))
+ return '> {} ~brian'.format(generate_phrase(phrases, cache))
|
862c2bdeaab094afdd61db862be54a8c4b7c08f3 | corehq/apps/users/admin.py | corehq/apps/users/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django_digest.models import PartialDigest, UserNonce
from .models import DomainPermissionsMirror
class DDUserNonceAdmin(admin.ModelAdmin):
list_display = ('user', 'nonce', 'count', '... | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django_digest.models import PartialDigest, UserNonce
from .models import DomainPermissionsMirror, HQApiKey
class DDUserNonceAdmin(admin.ModelAdmin):
list_display = ('user', 'nonce', ... | Add ApiKey to Users page in Django Admin | Add ApiKey to Users page in Django Admin
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -4,7 +4,7 @@
from django_digest.models import PartialDigest, UserNonce
-from .models import DomainPermissionsMirror
+from .models import DomainPermissionsMirror, HQApiKey
class DDUserNonceAdmin(admin.ModelAdmin):
@@ -20,7 +20,17 @@
admin.site.register(PartialDigest, DDPartialDigestAdmin)
+cl... |
0470d1243ad2d7e7fd086c2b2f695dc431eaf2ea | pycroscopy/io/translators/df_utils/beps_gen_utils.py | pycroscopy/io/translators/df_utils/beps_gen_utils.py |
import numpy as np
def combine_in_out_field_loops(in_vec, out_vec):
"""
Parameters
----------
in_vec
out_vec
Returns
-------
"""
return np.vstack((in_vec, out_vec))
def build_loop_from_mat(loop_mat, num_steps):
"""
Parameters
----------
loop_mat
num_steps... |
import numpy as np
import os
beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images'))
def combine_in_out_field_loops(in_vec, out_vec):
"""
Parameters
----------
in_vec
out_vec
Returns
-------
"""
return np.vstack((in_vec, out_vec... | Define a path to the image folder for fake beps generator | Define a path to the image folder for fake beps generator
Path is defined in beps_gen_utils
Users can still provide their own images if they want. | Python | mit | anugrah-saxena/pycroscopy,pycroscopy/pycroscopy | ---
+++
@@ -1,6 +1,9 @@
import numpy as np
+import os
+
+beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images'))
def combine_in_out_field_loops(in_vec, out_vec):
""" |
8eaf39db81deeeddd9b9035caa1c249f68d1d96f | ioant/ioant/utils/utils.py | ioant/ioant/utils/utils.py | import os
import sys
import json
def open_file_as_string(filepath):
with open(filepath, 'r') as ftemp:
templateString = ftemp.read()
return templateString
def return_absolut_path(script_path, relative_path):
return os.path.realpath(os.path.join(script_path, relative_path))
def fetch_json_file_... | import os
import sys
import json
def open_file_as_string(filepath):
with open(filepath, 'r') as ftemp:
templateString = ftemp.read()
return templateString
def return_absolut_path(script_path, relative_path):
return os.path.realpath(os.path.join(script_path, relative_path))
def fetch_json_file_... | Add function for backward compability | Add function for backward compability
| Python | mit | ioants/pypi-packages,ioants/pypi-packages,ioants/pypi-packages | ---
+++
@@ -20,7 +20,19 @@
return json_dict
-
+def topic_to_dict(topic):
+ sub_topics_list = topic.split('/')
+ if len(sub_topics_list) is not 6:
+ return None
+ else:
+ topic_dict = {}
+ topic_dict['top'] = sub_topics_list[0]
+ topic_dict['global'] = sub_topics_list[1]
+... |
33bd09ba4c8658064f5b9134e6ffb1b4dfad7de0 | fridge/test/test_cas.py | fridge/test/test_cas.py | from fridge.cas import ContentAddressableStorage
from fridge.memoryfs import MemoryFS
class TestContentAddressableStorage(object):
def create_cas(self, fs=None, path='cas'):
if fs is None:
fs = MemoryFS()
return ContentAddressableStorage(path, fs)
def has_root_property(self):
... | from fridge.cas import ContentAddressableStorage
from fridge.memoryfs import MemoryFS
class TestContentAddressableStorage(object):
def create_cas(self, fs=None, path='cas'):
if fs is None:
fs = MemoryFS()
return ContentAddressableStorage(path, fs)
def has_root_property(self):
... | Test files stored in CAS are still readable. | Test files stored in CAS are still readable.
| Python | mit | jgosmann/fridge,jgosmann/fridge | ---
+++
@@ -25,5 +25,13 @@
content = f.read()
assert content == u'dummy content'
+ def test_file_can_still_be_accessed_after_store(self):
+ fs = MemoryFS()
+ cas = self.create_cas(fs)
+ with fs.open('testfile', 'w') as f:
+ f.write(u'dummy content')
+ ... |
a7fbed238216bd7a9110829e893c318099cc1e14 | anthemav/__main__.py | anthemav/__main__.py | import argparse
import asyncio
import logging
from .protocol import create_anthemav_reader
def console():
parser = argparse.ArgumentParser(description=console.__doc__)
parser.add_argument('--host', default='127.0.0.1', help='IP or FQDN of AVR')
parser.add_argument('--port', default='14999', help='Port of ... | import argparse
import asyncio
import logging
from .protocol import create_anthemav_reader
def console():
parser = argparse.ArgumentParser(description=console.__doc__)
parser.add_argument('--host', default='127.0.0.1', help='IP or FQDN of AVR')
parser.add_argument('--port', default='14999', help='Port of ... | Update callback to support two parameters | Update callback to support two parameters
| Python | mit | nugget/python-anthemav | ---
+++
@@ -20,12 +20,8 @@
loop = asyncio.get_event_loop()
- def print_callback(telegram):
- """Callback that prints telegram values."""
- for obiref, obj in telegram.items():
- if obj:
- print(obj.value, obj.unit)
- print()
+ def print_callback(callerobj,... |
ee0a0b492b5536e0cc8c8e561875254698416eb4 | lib/ansible/utils/string_functions.py | lib/ansible/utils/string_functions.py | def isprintable(instring):
#http://stackoverflow.com/a/3637294
import string
printset = set(string.printable)
isprintable = set(instring).issubset(printset)
return isprintable
def count_newlines_from_end(str):
i = len(str)
while i > 0:
if str[i-1] != '\n':
break
... | def isprintable(instring):
if isinstance(instring, str):
#http://stackoverflow.com/a/3637294
import string
printset = set(string.printable)
isprintable = set(instring).issubset(printset)
return isprintable
else:
return True
def count_newlines_from_end(str):
i... | Allow isprintable() util function to work with unicode | Allow isprintable() util function to work with unicode
Fixes #6842
| Python | mit | thaim/ansible,thaim/ansible | ---
+++
@@ -1,9 +1,12 @@
def isprintable(instring):
- #http://stackoverflow.com/a/3637294
- import string
- printset = set(string.printable)
- isprintable = set(instring).issubset(printset)
- return isprintable
+ if isinstance(instring, str):
+ #http://stackoverflow.com/a/3637294
+ im... |
e284968b7e234b30a8a593b298a96b78bb151c03 | pyscf/pbc/tdscf/rhf_slow.py | pyscf/pbc/tdscf/rhf_slow.py | """
This module is an alias for `pyscf.tdscf.rhf_slow`. It works with single k-point HF objects.
"""
from pyscf.tdscf.rhf_slow import * | """
This and other `_slow` modules implement the time-dependent Hartree-Fock procedure. The primary performance drawback is
that, unlike other 'fast' routines with an implicit construction of the eigenvalue problem, these modules construct
TDHF matrices explicitly via an AO-MO transformation, i.e. with a O(N^5) complex... | Extend a docstring in PBC-Gamma TDHF | Extend a docstring in PBC-Gamma TDHF
| Python | apache-2.0 | gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,gkc1000/pyscf | ---
+++
@@ -1,4 +1,18 @@
"""
-This module is an alias for `pyscf.tdscf.rhf_slow`. It works with single k-point HF objects.
+This and other `_slow` modules implement the time-dependent Hartree-Fock procedure. The primary performance drawback is
+that, unlike other 'fast' routines with an implicit construction of the ... |
01fa3a2ce4181629db2027fd9797e5592bdadada | python/balcaza/t2wrapper.py | python/balcaza/t2wrapper.py | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = ge... | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = ge... | Change wrapper code to use [] notation for attribute access | Change wrapper code to use [] notation for attribute access
| Python | lgpl-2.1 | jongiddy/balcazapy,jongiddy/balcazapy,jongiddy/balcazapy | ---
+++
@@ -18,8 +18,8 @@
type = ListType(String, depth)
# Copy any annotations
type.dict = port.type.dict
- setattr(self.input, port.name, type)
- getattr(self.input, port.name) >> getattr(nested.input, port.name)
+ self.input[port.name] = type
+ self.input[port.name] >> nested.input[port.name]
... |
ff4b241b33a5e2896110f4575e9aff41a3e04e72 | dimod/compatibility23.py | dimod/compatibility23.py | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.it... | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.it... | Move namedtuple definition outside of argspec function | Move namedtuple definition outside of argspec function
| Python | apache-2.0 | dwavesystems/dimod,dwavesystems/dimod | ---
+++
@@ -43,10 +43,10 @@
zip_longest = itertools.zip_longest
+ _ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
+
def getargspec(f):
- ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
+ argspec = inspect.getfullargspec(f)
+ ... |
fce5851733205a2b15e53971af13f56c42063eb3 | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Add 10 days only in the leap day case too. | Add 10 days only in the leap day case too.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | ---
+++
@@ -31,9 +31,8 @@
def date(self, year, month, day):
if day == 29 and month == 2 and self.is_julian_leap_year(year):
d = date(year, month, 28)
- d = d + timedelta(days=11)
else:
d = date(year, month, day)
- d = d + timedelta(days=10)
+ ... |
5fe53a31bd7f37f8d9bd4fbe3796c8a0fa85019a | storm/db.py | storm/db.py | import motor
import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, db=None):
self.host = host
self.port = port
self.db = db
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connectio... | import motor
import error
from tornado import gen
from bson.objectid import ObjectId
class Connection(object):
def __init__(self, host='localhost', port=None, db=None):
self.host = host
self.port = port
self.db = db
class Database(object):
def __init__(self, connection):
if n... | Make sure looking up by id works correctly | Make sure looking up by id works correctly
| Python | mit | ccampbell/storm,liujiantong/storm | ---
+++
@@ -1,6 +1,7 @@
import motor
import error
from tornado import gen
+from bson.objectid import ObjectId
class Connection(object):
@@ -33,15 +34,18 @@
self.is_connected = True
@gen.coroutine
- def select_one(self, table, **args):
+ def select_one(self, table, **kwargs):
sel... |
c7364a95e06e1743fdd0fef73367f458ec3630d7 | xqueue/aws_settings.py | xqueue/aws_settings.py | from settings import *
import json
from logsettings import get_logger_config
with open(ENV_ROOT / "env.json") as env_file:
ENV_TOKENS = json.load(env_file)
XQUEUES = ENV_TOKENS['XQUEUES']
XQUEUE_WORKERS_PER_QUEUE = ENV_TOKENS['XQUEUE_WORKERS_PER_QUEUE']
LOG_DIR = ENV_TOKENS['LOG_DIR']
local_loglevel = ENV_TOKENS... | from settings import *
import json
from logsettings import get_logger_config
with open(ENV_ROOT / "env.json") as env_file:
ENV_TOKENS = json.load(env_file)
XQUEUES = ENV_TOKENS['XQUEUES']
XQUEUE_WORKERS_PER_QUEUE = ENV_TOKENS['XQUEUE_WORKERS_PER_QUEUE']
LOG_DIR = ENV_TOKENS['LOG_DIR']
local_loglevel = ENV_TOKENS... | Use RABBIT_HOST in env.json if it exists | Use RABBIT_HOST in env.json if it exists
| Python | agpl-3.0 | edx/xqueue,EDUlib/xqueue,Marx86/xqueue,knehez/xqueue,EDUlib/xqueue,EDUlib/xqueue,Marx86/xqueue,nttks/xqueue,knehez/xqueue,knehez/xqueue,nttks/xqueue,edx/xqueue,edx/xqueue | ---
+++
@@ -9,13 +9,15 @@
XQUEUE_WORKERS_PER_QUEUE = ENV_TOKENS['XQUEUE_WORKERS_PER_QUEUE']
LOG_DIR = ENV_TOKENS['LOG_DIR']
-local_loglevel = ENV_TOKENS.get('LOCAL_LOGLEVEL','INFO')
+local_loglevel = ENV_TOKENS.get('LOCAL_LOGLEVEL', 'INFO')
LOGGING = get_logger_config(LOG_DIR,
logg... |
cfb42cd7ddbba5e197e0c2454e1a92ce913b6913 | calaccess_campaign_browser/management/commands/buildcalaccesscampaignbrowser.py | calaccess_campaign_browser/management/commands/buildcalaccesscampaignbrowser.py | from django.core.management import call_command
from calaccess_campaign_browser.management.commands import CalAccessCommand
class Command(CalAccessCommand):
help = 'Transforms and loads refined data from raw CAL-ACCESS source files'
def handle(self, *args, **options):
call_command("flushcalaccesscamp... | from django.core.management import call_command
from calaccess_campaign_browser.management.commands import CalAccessCommand
class Command(CalAccessCommand):
help = 'Transforms and loads refined data from raw CAL-ACCESS source files'
def handle(self, *args, **options):
call_command("flushcalaccesscamp... | Comment out expends until we get them cleaned up | Comment out expends until we get them cleaned up
| Python | mit | myersjustinc/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,california-civic-data-coalition/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,california-civic-data-coalition/django-calaccess-campaign-browser,myersjustinc/django-calaccess-campaign-browser | ---
+++
@@ -11,5 +11,5 @@
call_command("loadcalaccesscampaignfilings")
call_command("loadcalaccesscampaignsummaries")
call_command("loadcalaccesscampaigncontributions")
- call_command("loadcalaccesscampaignexpenditures")
+ #call_command("loadcalaccesscampaignexpenditures")
... |
b79f5173629cbe5dfe15633084e203d4a52c0b1b | pyxray/parser/test_wikipedia.py | pyxray/parser/test_wikipedia.py | #!/usr/bin/env python
""" """
# Standard library modules.
import unittest
import logging
# Third party modules.
# Local modules.
from pyxray.parser.wikipedia import WikipediaElementNameParser
# Globals and constants variables.
class TestWikipediaElementNameParser(unittest.TestCase):
def setUp(self):
u... | #!/usr/bin/env python
""" """
# Standard library modules.
import unittest
import logging
# Third party modules.
# Local modules.
from pyxray.parser.wikipedia import WikipediaElementNameParser
# Globals and constants variables.
class TestWikipediaElementNameParser(unittest.TestCase):
def setUp(self):
u... | Fix test (wikipedia entries seem to change) | Fix test (wikipedia entries seem to change) | Python | mit | openmicroanalysis/pyxray,ppinard/pyxray,openmicroanalysis/pyxray | ---
+++
@@ -24,7 +24,7 @@
def test__iter__(self):
props = list(self.parser)
- self.assertEqual(2819, len(props))
+ self.assertEqual(2820, len(props))
if __name__ == '__main__': #pragma: no cover
logging.getLogger().setLevel(logging.DEBUG) |
93cd0d5dc6388582bbcfdafe21c4f41793af75dc | hamlpy/template/utils.py | hamlpy/template/utils.py | import imp
from django.template import loaders
from os import listdir
from os.path import dirname, splitext
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.', 1)[1], loader)
for loader in get_submodules(load... | from importlib import machinery
from django.template import loaders
from os import listdir
from os.path import dirname, splitext
MODULE_EXTENSIONS = tuple(machinery.all_suffixes())
def get_django_template_loaders():
return [(loader.__name__.rsplit('.', 1)[1], loader)
for loader in get_submodules(loa... | Replace deprecated imp usage with importlib | Replace deprecated imp usage with importlib
| Python | mit | nyaruka/django-hamlpy,nyaruka/django-hamlpy | ---
+++
@@ -1,10 +1,10 @@
-import imp
+from importlib import machinery
from django.template import loaders
from os import listdir
from os.path import dirname, splitext
-MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
+MODULE_EXTENSIONS = tuple(machinery.all_suffixes())
def get_djan... |
2e88043e2f7a987469f1af5dffa1c4675368c667 | tests/schema-validator.py | tests/schema-validator.py | #!/usr/bin/python
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema")
import jsonschema
import jsonschema.exceptions
def main(argv):
if len(argv) < 3:
print "Usage: "
print "\t" + os.path.basename(__file__) + " <json file> <schema file... | #!/usr/bin/python
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema")
import jsonschema
import jsonschema.exceptions
def main(argv):
if len(argv) < 3:
print "Usage: "
print "\t" + os.path.basename(__file__) + " <json file> <schema file... | Replace true/false from JSON to python False/True | Replace true/false from JSON to python False/True
Signed-off-by: Vivek Galatage <bbe41406aa2af935662c4582fd181c8ca0156a8e@visteon.com>
| Python | mit | vivekgalatage/libtracing | ---
+++
@@ -14,10 +14,15 @@
jsonFile = open(argv[1])
jsonContents = jsonFile.read()
+ jsonContents = jsonContents.replace('false', 'False')
+ jsonContents = jsonContents.replace('true', 'True')
+
jsonFile.close()
schemaFile = open(argv[2])
jsonSchema = schemaFile.read()
+ jsonSch... |
b1dae11860d61e3b574c7bd6b332053819675ddb | tests/test_block_cache.py | tests/test_block_cache.py | import angr
import logging
l = logging.getLogger("angr.tests")
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
def test_block_cache():
p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True)
b = p.factory.blo... | import angr
import logging
l = logging.getLogger("angr.tests")
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
def test_block_cache():
p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True)
b = p.factory.blo... | Fix the test case for block cache. | Fix the test case for block cache.
| Python | bsd-2-clause | f-prettyland/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,schieb/angr,angr/angr,tyb0807/angr,tyb0807/angr,f-prettyland/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,iamahuman/angr,chubbymaggie/angr,chubbymaggie/angr,axt/angr,axt/angr,angr/angr | ---
+++
@@ -9,11 +9,11 @@
def test_block_cache():
p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True)
b = p.factory.block(p.entry)
- assert p.factory.block(p.entry) is b
+ assert p.factory.block(p.entry).vex is b.vex
p = angr.Project(os.path.join(test_lo... |
b5744150da20f9b3b0f37704eb91878de21072cf | deploy/scripts/upgrade-web.py | deploy/scripts/upgrade-web.py | #!/usr/bin/python3
import errno
import pathlib
import platform
import sys
import subprocess
def main():
dist = platform.dist()
if dist[0] != 'debian' and dist[0] != 'Ubuntu':
print('This script can only be run on Debian GNU/Linux or Ubuntu.')
sys.exit(errno.EPERM)
workdir = pathlib.Path(_... | #!/usr/bin/python3
import errno
import pathlib
import platform
import sys
import subprocess
def main():
dist = platform.dist()
if dist[0] != 'debian' and dist[0] != 'Ubuntu':
print('This script can only be run on Debian GNU/Linux or Ubuntu.')
sys.exit(errno.EPERM)
workdir = pathlib.Path(_... | Install uwsgi in venv on web upgrade | Install uwsgi in venv on web upgrade
| Python | mit | clicheio/cliche,clicheio/cliche,item4/cliche,clicheio/cliche,item4/cliche | ---
+++
@@ -13,14 +13,17 @@
sys.exit(errno.EPERM)
workdir = pathlib.Path(__file__).resolve().parent.parent
+ with (workdir / 'etc' / 'revision.txt').open('r') as revision_file:
+ revision = (revision_file.readline().strip())
+ venv_dir = pathlib.Path('/home/cliche/venv_{}'.format(revision... |
2179dee14cfbd58ab8d8779561ac3826fe8892dd | custom/enikshay/reports/views.py | custom/enikshay/reports/views.py | from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_prov... | from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import Choi... | Use LocationChoiceProvider in enikshay location view | Use LocationChoiceProvider in enikshay location view
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,10 +1,14 @@
+from collections import namedtuple
+
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
-from corehq.apps.locations.models imp... |
acaacbea4fbfdcc0f1f0c5e0aa9a837dee439d08 | saau/sections/image_provider.py | saau/sections/image_provider.py | import json
import inspect
from os.path import join, exists
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = frame_info.f_locals['self']
try:
msg += self.__name__ + '#' # for static/class methods
excep... | import inspect
import json
from os.path import exists, join
from pathlib import Path
from typing import Any, Union
from ..services import Services
PathOrStr = Union[str,Path]
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = fram... | Add types to ImageProvider and RequiresData | Add types to ImageProvider and RequiresData
| Python | mit | Mause/statistical_atlas_of_au | ---
+++
@@ -1,6 +1,12 @@
+import inspect
import json
-import inspect
-from os.path import join, exists
+from os.path import exists, join
+from pathlib import Path
+from typing import Any, Union
+
+from ..services import Services
+
+PathOrStr = Union[str,Path]
def not_implemented():
@@ -20,34 +26,32 @@
clas... |
6a10f2f08825480edc7b84ca00d84c36873cbdf4 | devs/tools/adapt-es-path.py | devs/tools/adapt-es-path.py | #!/usr/bin/env python3
"""
Use to apply patches from ES upstream with:
git apply --reject \
<(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py)
"""
import sys
def main():
for line in sys.stdin:
sys.stdout.write(
line
... | #!/usr/bin/env python3
"""
Use to apply patches from ES upstream with:
git apply --reject \
<(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py)
"""
import sys
def main():
for line in sys.stdin:
sys.stdout.write(
line
... | Update dev tool for applying ES patches | Update dev tool for applying ES patches
Adds path rewrite for `test/framework` -> `es/es-testing/` | Python | apache-2.0 | crate/crate,crate/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,crate/crate | ---
+++
@@ -17,6 +17,9 @@
.replace('diff --git a/server/', 'diff --git a/es/es-server/')
.replace('--- a/server/', '--- a/es/es-server/')
.replace('+++ b/server/', '+++ b/es/es-server/')
+ .replace('diff --git a/test/framework', 'diff --git a/es/es-testing/')
+ ... |
37be9141cbcafb51ebef4ba76a5c2f1dcd9449d1 | example/test1_autograder.py | example/test1_autograder.py | from nose.tools import eq_ as assert_eq
@score(problem="hello", points=0.5)
def grade_hello1():
"""Grade 'hello' with input 'Jessica'"""
msg = hello("Jessica")
assert_eq(msg, "Hello, Jessica!")
@score(problem="hello", points=0.5)
def grade_hello2():
"""Grade 'hello' with input 'Python'"""
msg = he... | from nose.tools import eq_ as assert_eq
@score(problem="Problem 1/Part A", points=0.5)
def grade_hello1():
"""Grade 'hello' with input 'Jessica'"""
msg = hello("Jessica")
assert_eq(msg, "Hello, Jessica!")
@score(problem="Problem 1/Part A", points=0.5)
def grade_hello2():
"""Grade 'hello' with input ... | Update example autograding code to use heading names | Update example autograding code to use heading names
| Python | mit | jhamrick/original-nbgrader,jhamrick/original-nbgrader | ---
+++
@@ -1,24 +1,28 @@
from nose.tools import eq_ as assert_eq
-@score(problem="hello", points=0.5)
+
+@score(problem="Problem 1/Part A", points=0.5)
def grade_hello1():
"""Grade 'hello' with input 'Jessica'"""
msg = hello("Jessica")
assert_eq(msg, "Hello, Jessica!")
-@score(problem="hello", p... |
271c234ce215c036f54928a7c2910ddda4cea360 | dbaas/dbaas/celeryconfig.py | dbaas/dbaas/celeryconfig.py | import os
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT)
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheB... | import os
REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379')
BROKER_URL = os.getenv(
'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT)
CELERYD_TASK_TIME_LIMIT = 10800
CELERY_TRACK_STARTED = True
CELERY_IGNORE_RESULT = False
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheB... | Add celeryd prefetch multiplier setting | Add celeryd prefetch multiplier setting
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -13,3 +13,4 @@
CELERYD_LOG_FORMAT = "[%(asctime)s: %(processName)s %(name)s %(levelname)s] %(message)s"
CELERY_ALWAYS_EAGER = False
CELERYD_LOG_COLOR = False
+CELERYD_PREFETCH_MULTIPLIER = 1 |
d346129fb33f84eaa61ed48f3d4b4f9570062241 | server/server/tests/__init__.py | server/server/tests/__init__.py | import pytest
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
pytestmark = pytest.mark.django_db(transaction=True)
@pytest.fixture
def fm_user():
user = User.objects.create_user('fuzzmanager', 'test@example.com', 'test')
user.password_raw = 'test'
(token, cr... | import pytest
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User, Permission
from rest_framework.authtoken.models import Token
from crashmanager.models import User as CMUser
pytestmark = pytest.mark.django_db(transaction=True)
@pytest.fixture
def fm_user():
use... | Fix Collector and EC2Reporter tests. Token user used for test now requires the correct permissions. | Fix Collector and EC2Reporter tests.
Token user used for test now requires the correct permissions.
| Python | mpl-2.0 | MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager | ---
+++
@@ -1,6 +1,8 @@
import pytest
-from django.contrib.auth.models import User
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.auth.models import User, Permission
from rest_framework.authtoken.models import Token
+from crashmanager.models import User as CMUser
pytestmark = py... |
1455da161123ea778d8e82c2f961fdcf85cd10aa | monitor-checker-http.py | monitor-checker-http.py | #!/usr/bin/env python
import pika
import json
import requests
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER))
channel = connection.channel()
channel.queue_declare(queue='http')
def callback(ch, method, properties, bod... | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(p... | Add credentials + code clean up | Add credentials + code clean up
| Python | mit | observer-hackaton/monitor-checker-http | ---
+++
@@ -2,13 +2,17 @@
import pika
import json
import requests
+import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
+RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
+RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
+
+credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.Bl... |
7b697cbcddf29412ac94a186817bd9db1880a0f2 | nbody/snapshots/util.py | nbody/snapshots/util.py | """Various utility functions, mostly dealing with input/output"""
import os
import numpy as np
def load_snapshots(directory_name, stack_coords=False):
"""Loads files by traversing a directory and reading in a filename sorted order"""
data = []
for root, dirs, files in os.walk(directory_name):
... | """Various utility functions, mostly dealing with input/output"""
import os
import numpy as np
def load_snapshots(directory_name, stack_coords=False):
"""Loads files by traversing a directory and reading in a filename sorted order"""
data = []
for root, dirs, files in os.walk(directory_name):
... | Fix csv saving for arbitrary parameter sets | Fix csv saving for arbitrary parameter sets
| Python | mit | kostassabulis/nbody-workshop-2015 | ---
+++
@@ -11,17 +11,13 @@
for file_name in sorted(files, key=lambda x: int(x.split(".")[-2])):
#This needs fixing, but I'll leave it like this until we unify our formats
if file_name.endswith("csv"):
- bodies = np.loadtxt(os.path.join(root, file_name), delimiter=","... |
5745f894840eaad666617a6f99a22b62d550373c | django/contrib/comments/feeds.py | django/contrib/comments/feeds.py | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... | Use correct m2m join table name in LatestCommentsFeed | Use correct m2m join table name in LatestCommentsFeed
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409089
| Python | bsd-3-clause | Belgabor/django,Belgabor/django,Belgabor/django | ---
+++
@@ -28,7 +28,7 @@
is_removed = False,
)
if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None):
- where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)']
+ where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE... |
dfe52966b8ab72cd17687c1f6d15fdadac4d72e2 | weasyprint/logger.py | weasyprint/logger.py | # coding: utf-8
"""
weasyprint.logging
------------------
Logging setup.
The rest of the code gets the logger through this module rather than
``logging.getLogger`` to make sure that it is configured.
Logging levels are used for specific purposes:
- errors are used for unreachable or unus... | # coding: utf-8
"""
weasyprint.logging
------------------
Logging setup.
The rest of the code gets the logger through this module rather than
``logging.getLogger`` to make sure that it is configured.
Logging levels are used for specific purposes:
- errors are used for unreachable or unus... | Set default logging level to WARNING | Set default logging level to WARNING
Fixes tests with pytest 3.3.0+
| Python | bsd-3-clause | Kozea/WeasyPrint,Kozea/WeasyPrint | ---
+++
@@ -26,4 +26,5 @@
import logging
LOGGER = logging.getLogger('weasyprint')
+LOGGER.setLevel(logging.WARNING)
LOGGER.addHandler(logging.NullHandler()) |
6f8efd5e6893491a7ee1c046513210c8ad1e7fc8 | sqliteschema/_logger/_logger.py | sqliteschema/_logger/_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "sqliteschema"
try:
from loguru import logger
logger.disable(MODULE_NAME)
except ImportEr... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import tabledata
from ._null_logger import NullLogger
MODULE_NAME = "sqliteschema"
_is_enable = False
try:
from loguru import logger
logger.disable(MODULE_NA... | Add check for logging state | Add check for logging state
| Python | mit | thombashi/sqliteschema | ---
+++
@@ -12,6 +12,7 @@
MODULE_NAME = "sqliteschema"
+_is_enable = False
try:
from loguru import logger
@@ -22,10 +23,17 @@
def set_logger(is_enable):
+ global _is_enable
+
+ if is_enable == _is_enable:
+ return
+
if is_enable:
logger.enable(MODULE_NAME)
else:
... |
0c30fe72179a125b41ffb88fec387862c78e6c7c | flaskrst/modules/atom.py | flaskrst/modules/atom.py | # -*- coding: utf-8 -*-
"""
flask-rst.modules.atom
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
from flask import Blueprint, request, current_app
from werkzeug.contrib.atom import AtomFeed, FeedEntry
from flaskrst.modules.blog import ... | # -*- coding: utf-8 -*-
"""
flask-rst.modules.atom
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
from flask import Blueprint, request, current_app
from werkzeug.contrib.atom import AtomFeed, FeedEntry
from flaskrst.modules.blog import ... | Add more information to the feed entry | Add more information to the feed entry
| Python | bsd-3-clause | jarus/flask-rst | ---
+++
@@ -20,8 +20,15 @@
feed_url=request.url, url=request.host_url,
subtitle=current_app.config.get('SITE_SUBTITLE', None))
for post in get_posts():
- entry = FeedEntry(post.title, url=post.external_url,
- updated=post.pub_date)
+ ... |
038bb5fe10a3b9df18f8c709cddd0c18b2ac694d | parsing/forum/mongo_forum_to_mongod.py | parsing/forum/mongo_forum_to_mongod.py | '''
Insert the edx discussion board .mongo files into mongodb database
'''
import pymongo
import sys
import json
def connect_to_db_collection(db_name, collection_name):
'''
Retrieve collection from given database name and collection name
'''
connection = pymongo.Connection('localhost', 27017)
db... | '''
Insert the edx discussion board .mongo files into mongodb database
'''
import pymongo
import sys
import json
def connect_to_db_collection(db_name, collection_name):
'''
Retrieve collection from given database name and collection name
'''
connection = pymongo.Connection('localhost', 27017)
db... | Add function to migrate forum data to mongodb | Add function to migrate forum data to mongodb
| Python | mit | andyzsf/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research | ---
+++
@@ -23,7 +23,17 @@
def migrate_form_to_mongodb(forum_mongo_file, collection):
- pass
+ with open(forum_mongo_file) as file_handler:
+ try:
+ for line in file_handler:
+ data = json.loads(line)
+ data = remove_dollar_sign(data)
+ collect... |
cc8cc05480e85c9a66450f1655083e87d00ba3f4 | usersettings/shortcuts.py | usersettings/shortcuts.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_usersettings_model():
"""
Returns the ``UserSettings`` model that is active in this project.
"""
from django.db.models import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL... | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_usersettings_model():
"""
Returns the ``UserSettings`` model that is active in this project.
"""
from django.db.models import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL... | Update 'get_current_usersettings' to catch 'DoesNotExist' error | Update 'get_current_usersettings' to catch 'DoesNotExist' error
| Python | bsd-3-clause | mishbahr/django-usersettings2,mishbahr/django-usersettings2 | ---
+++
@@ -26,5 +26,8 @@
the SITE_ID in the project's settings
"""
USERSETTINGS_MODEL = get_usersettings_model()
- current_usersettings = USERSETTINGS_MODEL.objects.get_current()
+ try:
+ current_usersettings = USERSETTINGS_MODEL.objects.get_current()
+ except USERSETTINGS_MODEL.DoesNo... |
eb9e2c3217ff0f19a28fc49b2fa5f14d295f32e2 | app/views.py | app/views.py | from flask import render_template, jsonify, request
from app import app
from app import evolver
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
def format_transcriptions(transcriptions):
'''Split the raw string of transcriptions into
the correct tuple rules.'''
... | from flask import render_template, jsonify, request
from app import app
from app import evolver
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
def format_transcriptions(transcriptions):
'''Split the raw string of transcriptions into
the correct tuple rules.'''
... | Fix bug when transcriptions are empty | Fix bug when transcriptions are empty
| Python | mit | kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve | ---
+++
@@ -12,7 +12,12 @@
def format_transcriptions(transcriptions):
'''Split the raw string of transcriptions into
the correct tuple rules.'''
- return [(pair.split(':')[0], pair.split(':')[1]) for pair in transcriptions.split('\n')]
+ clean_transcriptions = transcriptions.strip().lower()
+
+ if... |
87bdef439a3faf465bb8c23166beeb8a142400f7 | fapistrano/plugins/curl.py | fapistrano/plugins/curl.py | # -*- coding: utf-8 -*-
from fabric.api import cd, env, run
from .. import signal, configuration
def init():
configuration.setdefault('curl_url', '')
configuration.setdefault('curl_options', '')
signal.register('deploy.updating', download_artifact)
def download_artifact(**kwargs):
with cd(env.release... | # -*- coding: utf-8 -*-
from fabric.api import cd, env, run
from .. import signal, configuration
def init():
configuration.setdefault('curl_url', '')
configuration.setdefault('curl_options', '')
configuration.setdefault('curl_extract_tar', '')
configuration.setdefault('curl_postinstall_script', '')
... | Add extract_tar and post_install_script option. | Add extract_tar and post_install_script option.
| Python | mit | liwushuo/fapistrano | ---
+++
@@ -6,8 +6,15 @@
def init():
configuration.setdefault('curl_url', '')
configuration.setdefault('curl_options', '')
+ configuration.setdefault('curl_extract_tar', '')
+ configuration.setdefault('curl_postinstall_script', '')
signal.register('deploy.updating', download_artifact)
def dow... |
83e147ca35cbdc70a5b3e3e374a14a3ad4efdd17 | vumi_http_api/__init__.py | vumi_http_api/__init__.py | from .vumi_api import VumiApiWorker
__all__ = ['VumiApiWorker']
| from .vumi_api import VumiApiWorker
__version__ = "0.0.1a"
__all__ = ['VumiApiWorker']
| Add __version__ to vumi_http_api package. | Add __version__ to vumi_http_api package.
| Python | bsd-3-clause | praekelt/vumi-http-api,praekelt/vumi-http-api | ---
+++
@@ -1,3 +1,5 @@
from .vumi_api import VumiApiWorker
+__version__ = "0.0.1a"
+
__all__ = ['VumiApiWorker'] |
bd3cb20453d044882fc476e55e2aade8c5c81ea7 | 2/ConfNEP.py | 2/ConfNEP.py | """A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
from ILAMB.ilamblib import MakeComparable
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observation... | """A custom ILAMB confrontation for net ecosystem productivity (nep)."""
import os
import numpy as np
from ILAMB.Confrontation import Confrontation
from ILAMB.Variable import Variable
from ILAMB.ilamblib import MakeComparable
class ConfNEP(Confrontation):
"""Confront ``nep`` model outputs with ``nee`` observation... | Remove call to _checkRegions method | Remove call to _checkRegions method
At one point it was a method of the super (I believe), but it's
no longer there.
| Python | mit | permamodel/ILAMB-experiments | ---
+++
@@ -22,7 +22,6 @@
def stageData(self, m):
obs = Variable(filename=self.source,
variable_name=self.variable)
- self._checkRegions(obs)
obs.data *= -1.0 # Reverse sign of benchmark data.
mod = m.extractTimeSeries(self.variable, |
528759e6ba579de185616190e3e514938989a54e | tests/console/asciimatics/widgets/testcheckbox.py | tests/console/asciimatics/widgets/testcheckbox.py |
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox
class TestCheckBox(TestCase):
def test_checkbox(self):
"""
Test the checkbox
:return: void
"""
c... |
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox
class TestCheckBox(TestCase):
def test_checkbox(self):
"""
Test the checkbox
:return: void
"""
c... | Check if checkbox value has updated. | Check if checkbox value has updated.
| Python | apache-2.0 | LowieHuyghe/script-core | ---
+++
@@ -23,5 +23,6 @@
for value in [True, False, True]:
previous_count = len(changed_checkbox)
checkbox.value = value
+ self.assert_equal(value, checkbox.value)
self.assert_equal(previous_count + 1, len(changed_checkbox))
self.assert_equal(ch... |
d6b4024d502e189e67d9027a50e472b7c295a83f | misc/migrate_miro_vhs.py | misc/migrate_miro_vhs.py | #!/usr/bin/env python
# -*- encoding: utf-8
import boto3
def get_existing_records(dynamodb_client):
"""
Generates existing Miro records from the SourceData table.
"""
paginator = dynamodb_client.get_paginator('scan')
for page in paginator.paginate(TableName='SourceData'):
for item in page... | #!/usr/bin/env python
# -*- encoding: utf-8
import boto3
OLD_TABLE = 'SourceData'
OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
def get_existing_records(dynamodb_client):
"""
Generates existing Mi... | Copy the S3 object into the new bucket | Copy the S3 object into the new bucket
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api | ---
+++
@@ -2,6 +2,13 @@
# -*- encoding: utf-8
import boto3
+
+
+OLD_TABLE = 'SourceData'
+OLD_BUCKET = 'wellcomecollection-vhs-sourcedata'
+
+NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro'
+NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro'
def get_existing_records(dynamodb_client):
@@ -9,14 +16,31... |
89ccd37938fc4ca98b0683ecd8c93e48eef3bf35 | forms.py | forms.py | from django import forms
class RemoteSubscribeForm(forms.Form):
username = forms.CharField(max_length=64, label="Username")
profile_url = forms.URLField(label="OMB Compatable Profile URL")
AUTHORIZE_CHOICES = (
('on', 'Accept'),
('off', 'Reject')
)
class AuthorizeForm(forms.Form):
token = forms.C... | from django import forms
class RemoteSubscribeForm(forms.Form):
username = forms.CharField(max_length=64, label="Username")
profile_url = forms.URLField(label="OMB Compatable Profile URL")
AUTHORIZE_CHOICES = (
(1, 'Accept'),
(0, 'Reject')
)
class AuthorizeForm(forms.Form):
token = forms.CharFiel... | Use integer values for the remote subscribe form to comply with the django oauth_provider. | Use integer values for the remote subscribe form to comply with the django oauth_provider.
| Python | mit | skabber/django-omb | ---
+++
@@ -5,8 +5,8 @@
profile_url = forms.URLField(label="OMB Compatable Profile URL")
AUTHORIZE_CHOICES = (
- ('on', 'Accept'),
- ('off', 'Reject')
+ (1, 'Accept'),
+ (0, 'Reject')
)
class AuthorizeForm(forms.Form): |
df0d950747d80024f962216f17f2d3f967e4363b | source/hostel_huptainer/environment.py | source/hostel_huptainer/environment.py | """Inspects dictionary for desired keys and stores for later usage."""
from hostel_huptainer.errors import InputError
class Environment(object):
"""Searches ``environment`` for expected variables and stores them."""
def __init__(self, environment):
self.hostname = environment.get('CERTBOT_HOSTNAME')... | """Inspects dictionary for desired keys and stores for later usage."""
from hostel_huptainer.errors import InputError
class Environment(object):
"""Searches ``environment`` for expected variables and stores them."""
def __init__(self, environment):
self.hostname = environment.get('CERTBOT_HOSTNAME')... | Decrease line length for pycodestyle compliance | Decrease line length for pycodestyle compliance
A line exceeded 75 characters in length.
| Python | apache-2.0 | Jitsusama/hostel-huptainer | ---
+++
@@ -10,4 +10,5 @@
self.hostname = environment.get('CERTBOT_HOSTNAME')
if not self.hostname:
- raise InputError('CERTBOT_HOSTNAME environment variable is missing.')
+ raise InputError(
+ 'CERTBOT_HOSTNAME environment variable is missing.') |
7a7de7b7a44180f4ea3b6d5b3334ce406eb72b38 | discussion/migrations/0002_discussionthread_updated.py | discussion/migrations/0002_discussionthread_updated.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('discussion', '0001_initial'),
]
operations = [
migrations.AddField(
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
('discussion', '0001_initial'),
]
operations = [
migrations.AddField(
model_name... | Fix because we're not timezone aware. | Fix because we're not timezone aware.
| Python | mit | btomaszewski/webdoctor-server | ---
+++
@@ -2,8 +2,7 @@
from __future__ import unicode_literals
from django.db import models, migrations
-import datetime
-from django.utils.timezone import utc
+from django.utils import timezone
class Migration(migrations.Migration):
@@ -16,7 +15,7 @@
migrations.AddField(
model_name='d... |
bab10c6a1e9c8548fe778817595aa18baa5e3cdb | account_fiscal_position_no_source_tax/account.py | account_fiscal_position_no_source_tax/account.py | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... | FIX fiscal position no source tax | FIX fiscal position no source tax
| Python | agpl-3.0 | csrocha/account_journal_payment_subtype,csrocha/account_voucher_payline | ---
+++
@@ -9,9 +9,11 @@
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, context=context)
- taxes_without_src_ids = [
- x.tax_dest_id.id for x in fposition_id.tax_ids if not... |
5dec1db567ef7c2b6ea1cca3ddd02612cb9f7d8a | Lib/encodings/bz2_codec.py | Lib/encodings/bz2_codec.py | """ Python 'bz2_codec' Codec - bz2 compression encoding
Unlike most of the other codecs which target Unicode, this codec
will return Python string objects for both encode and decode.
Adapted by Raymond Hettinger from zlib_codec.py which was written
by Marc-Andre Lemburg (mal@lemburg.com).
"""
import ... | """ Python 'bz2_codec' Codec - bz2 compression encoding
Unlike most of the other codecs which target Unicode, this codec
will return Python string objects for both encode and decode.
Adapted by Raymond Hettinger from zlib_codec.py which was written
by Marc-Andre Lemburg (mal@lemburg.com).
"""
import ... | Revert previous change. MAL preferred the old version. | Revert previous change. MAL preferred the old version.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -8,20 +8,57 @@
"""
import codecs
-import bz2
+import bz2 # this codec needs the optional bz2 module !
-def encode(input, errors='strict'):
+### Codec APIs
+
+def bz2_encode(input,errors='strict'):
+
+ """ Encodes the object input and returns a tuple (output
+ object, length consumed).
+
+ ... |
090c485a6d6e0eb9b078ef5401ad0364f8c494d7 | StatCache.py | StatCache.py | import numpy as np
def circular_store(redis, stat_name, stat_value):
stat_value = np.average(np.append(np.asfarray(redis.lrange(stat_name, 0, 2)), stat_value))
redis.lpush(stat_name, stat_value)
redis.ltrim(stat_name, 0, 100)
def circular_all(redis, stat_name):
return np.asfarray(redis.lrange(stat_... | import numpy as np
def circular_store(redis, stat_name, stat_value):
stat_value = np.average(np.append(np.asfarray(redis.lrange(stat_name, 0, 1)), stat_value))
redis.lpush(stat_name, stat_value)
redis.ltrim(stat_name, 0, 100)
def circular_all(redis, stat_name):
return np.asfarray(redis.lrange(stat_... | Use moving average n=1 instead of n=2 | Use moving average n=1 instead of n=2
| Python | mit | nettube/mbtapuller,nettube/mbtapuller,nettube/mbtapuller | ---
+++
@@ -2,7 +2,7 @@
def circular_store(redis, stat_name, stat_value):
- stat_value = np.average(np.append(np.asfarray(redis.lrange(stat_name, 0, 2)), stat_value))
+ stat_value = np.average(np.append(np.asfarray(redis.lrange(stat_name, 0, 1)), stat_value))
redis.lpush(stat_name, stat_value)
... |
8e308f1928fed8713c5b18ada2032b92f4dceeff | blocker.py | blocker.py | import os
import sys
import json
import utils
from datetime import datetime
from experiments import *
RESULTS_DIR = "results"
DATA_DIR = "data"
EXPERIMENTS = {
"http_request" : http_request.HTTPRequestExperiment,
"tcp_connect" : tcp_connect.TCPConnectExperiment,
"turkey" : turkey.TurkeyExperime... | import os
import sys
import json
import utils
from datetime import datetime
from experiments import *
RESULTS_DIR = "results"
DATA_DIR = "data"
EXPERIMENTS = {
"http_request" : http_request.HTTPRequestExperiment,
"tcp_connect" : tcp_connect.TCPConnectExperiment,
"turkey" : turkey.TurkeyExperime... | Store json file as .json | Store json file as .json
| Python | mit | rpanah/centinel,rpanah/centinel,ben-jones/centinel,iclab/centinel,lianke123321/centinel,gsathya/centinel-client,iclab/centinel,gsathya/blocker,JASONews/centinel,Ashish1805/centinel,rpanah/centinel,lianke123321/centinel,gsathya/centinel-client,iclab/centinel,lianke123321/centinel | ---
+++
@@ -17,7 +17,7 @@
}
def get_result_file():
- result_file = "result-%s.txt" % (datetime.now().isoformat())
+ result_file = "result-%s.json" % (datetime.now().isoformat())
return os.path.join(RESULTS_DIR, result_file)
def get_input_file(experiment_name): |
cc29f43a351f1e0418edaceb830e5b189d31b3ad | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '99d263cbd842ba57331ddb975aad742470a4cff4'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Update libchromiumcontent to fix shared workers. | win: Update libchromiumcontent to fix shared workers.
| Python | mit | tinydew4/electron,mattotodd/electron,fritx/electron,kcrt/electron,RobertJGabriel/electron,lzpfmh/electron,sshiting/electron,leethomas/electron,fomojola/electron,Gerhut/electron,subblue/electron,dahal/electron,posix4e/electron,jsutcodes/electron,thingsinjars/electron,subblue/electron,Jacobichou/electron,aichingm/electro... | ---
+++
@@ -5,7 +5,7 @@
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d'
+LIBCHROMIUMCONTENT_COMMIT = '99d263cbd842ba57331ddb975aad742470a4cff4'
ARCH = {
'cygwin': '32bit', |
e0a34d86837b6d1e1a9d740fbc5f0b8e2a2ee4b1 | Lib/email/__init__.py | Lib/email/__init__.py | # Copyright (C) 2001 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '1.0'
__all__ = ['Encoders',
'Errors',
'Generator',
'Image',
'Iterators',
'MIMEBase',
... | # Copyright (C) 2001 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '1.0'
__all__ = ['Encoders',
'Errors',
'Generator',
'Iterators',
'MIMEAudio',
'MIMEBase',... | Fix __all__ to the current list of exported modules (must pass the tests in test_email.py). | Fix __all__ to the current list of exported modules (must pass the
tests in test_email.py).
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -9,13 +9,14 @@
__all__ = ['Encoders',
'Errors',
'Generator',
- 'Image',
'Iterators',
+ 'MIMEAudio',
'MIMEBase',
+ 'MIMEImage',
+ 'MIMEMessage',
+ 'MIMEText',
'Message',
- 'MessageRFC822'... |
36ce36541bbd6512feaaf8e385bcfa7e11251281 | infcommon/yaml_reader/factory.py | infcommon/yaml_reader/factory.py | # -*- coding: utf-8 -*-
from infcommon.factory import Factory
from infcommon.yaml_reader.yaml_reader import YamlReader
def yaml_reader(path=None):
return Factory.instance('yaml_reader', lambda: YamlReader(path))
| # -*- coding: utf-8 -*-
import os
from infcommon.factory import Factory
from infcommon.yaml_reader.yaml_reader import YamlReader
DEFAULT_PATH_ENVIRONMENT_VARIABLE_NAME = 'CONF_FILE'
def yaml_reader(path=None):
path = path or os.environ[DEFAULT_PATH_ENVIRONMENT_VARIABLE_NAME]
return Factory.instance('yaml_... | Use environment variable with deafult path when no path given | [FEATURE] Use environment variable with deafult path when no path given
| Python | mit | aleasoluciones/infcommon,aleasoluciones/infcommon | ---
+++
@@ -1,8 +1,15 @@
# -*- coding: utf-8 -*-
+
+import os
from infcommon.factory import Factory
from infcommon.yaml_reader.yaml_reader import YamlReader
+DEFAULT_PATH_ENVIRONMENT_VARIABLE_NAME = 'CONF_FILE'
+
+
def yaml_reader(path=None):
- return Factory.instance('yaml_reader', lambda: YamlReader(pa... |
1c05f5f88d84d90ca949bab6e3d48c5f1e35a909 | keystone/server/flask/request_processing/req_logging.py | keystone/server/flask/request_processing/req_logging.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 t... | # 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 t... | Make Request Logging a little better | Make Request Logging a little better
Use the flask.request properties instead of direct environ lookups,
as this is more representative of what is happening in the application.
Change-Id: Ic16c5ea26b2f526b51ef167e6f6977c72df1d06a
Partial-Bug: #1776504
| Python | apache-2.0 | openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,mahak/keystone,openstack/keystone | ---
+++
@@ -18,14 +18,12 @@
LOG = log.getLogger(__name__)
-_ENVIRON_KEYS = ('SCRIPT_NAME', 'PATH_INFO')
def log_request_info():
# Add in any extra debug logging about the request that is desired
# note that this is executed prior to routing the request to a resource
# so the data is somewhat ... |
ebc5831cf8cd3a87c6d663c28afb94a952f4e42f | mint/scripts/db2db/migrate.py | mint/scripts/db2db/migrate.py | #!/usr/bin/python
#
# Copyright (c) 2009 rPath, Inc.
#
# All rights reserved.
#
import logging
from conary import dbstore
from mint.scripts.db2db import db2db
log = logging.getLogger(__name__)
def switchToPostgres(cfg):
if cfg.dbDriver in ('postgresql', 'pgpool'):
return
sourceTuple = (cfg.dbDrive... | #!/usr/bin/python
#
# Copyright (c) 2009 rPath, Inc.
#
# All rights reserved.
#
import logging
from conary import dbstore
from mint.scripts.db2db import db2db
log = logging.getLogger(__name__)
def switchToPostgres(cfg):
if cfg.dbDriver in ('postgresql', 'pgpool'):
return
sourceTuple = (cfg.dbDrive... | Fix another use of the rbuilder postgres user | Fix another use of the rbuilder postgres user
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | ---
+++
@@ -18,8 +18,8 @@
return
sourceTuple = (cfg.dbDriver, cfg.dbPath)
- destTuple = ('postgresql', 'rbuilder@localhost:5439/mint')
- finalTuple = ('pgpool', 'rbuilder@localhost.localdomain:6432/mint')
+ destTuple = ('postgresql', 'postgres@localhost:5439/mint')
+ finalTuple = ('pgpool'... |
9a3d8a96ed9cf0d1d1f002bf324d57b099ddde0f | gateway/utils/testfinder.py | gateway/utils/testfinder.py | import os
import unittest
from gateway.utils.resourcelocator import ResourceLocator
from unittest import TestLoader
TEST_PATH = "tests"
verbosity = 1
test_loader = unittest.defaultTestLoader
def find_test_modules(test_modules=None):
test_locator = ResourceLocator.get_locator(TEST_PATH)
test_suite = test_lo... | import os
import unittest
from gateway.utils.resourcelocator import ResourceLocator
from unittest import TestLoader
TEST_PATH = "tests"
verbosity = 1
test_loader = unittest.defaultTestLoader
def find_test_modules(test_modules=None):
test_locator = ResourceLocator.get_locator(TEST_PATH)
test_suite = test_load... | Add documentation Clean duplicate code remove unused code | Add documentation
Clean duplicate code
remove unused code
| Python | mit | aceofwings/Evt-Gateway,aceofwings/Evt-Gateway | ---
+++
@@ -4,9 +4,7 @@
from unittest import TestLoader
TEST_PATH = "tests"
-
verbosity = 1
-
test_loader = unittest.defaultTestLoader
@@ -16,7 +14,13 @@
return test_suite
def run_tests(test_classes=None):
+ """
+ run_tests - runs a test suite with specified paramters
+ :param test_classes:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.