commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
bea43337d9caa4e9a5271b66d951ae6547a23c80 | DjangoLibrary/middleware.py | DjangoLibrary/middleware.py | from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['a... | from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['a... | Add a comment to py3 byte string decode. | Add a comment to py3 byte string decode.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary |
7e5777c7b09780d7cde1a94e58dd022f98051168 | scrapple/utils/config.py | scrapple/utils/config.py | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
def traverse_next(page, next, results):
"""
Recursive generator to traverse through the next attribute and \
crawl through the links to be followed
"""
... | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
from colorama import init, Fore, Back
init()
def traverse_next(page, next, results):
"""
Recursive generator to traverse through the next attribute and \
craw... | Modify stdout logging in crawler run | Modify stdout logging in crawler run
| Python | mit | AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,scrappleapp/scrapple,AlexMathew/scrapple |
cc8f1507c90261947d9520859922bff44ef9c6b4 | observatory/lib/InheritanceQuerySet.py | observatory/lib/InheritanceQuerySet.py | from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o)... | from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.core.exceptions import ObjectDoesNotExist
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.mod... | Fix the feed to work with new versions of django | Fix the feed to work with new versions of django
| Python | isc | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory |
48acf57692a2a0eb03a3d616507cae2d5f619ded | yunity/models/relations.py | yunity/models/relations.py | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | Add default value for date | Add default value for date
with @NerdyProjects
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core |
074520d7de93db9b83d8d20dd03640146609eeb2 | critical_critiques/submission/forms.py | critical_critiques/submission/forms.py | from django.forms import ModelForm
from .models import Submission
class SubmissionForm(ModelForm):
class Meta:
model = Submission
fields = ('url',)
| from urlparse import urlparse
from django import forms
from .models import Submission
class SubmissionForm(forms.ModelForm):
class Meta:
model = Submission
fields = ('url',)
def clean_url(self):
url = self.cleaned_data['url']
parsed_url = urlparse(url)
if not (parse... | Validate that the submission URLs are for GitHub | Validate that the submission URLs are for GitHub
| Python | mit | team-stroller/critical_critiques,team-stroller/critical_critiques,team-stroller/critical_critiques |
4b8b4a295e5b9f9674d351e60ffac74f85eae0d3 | WebIntegration/MatchData.py | WebIntegration/MatchData.py | '''
Created on Mar 28, 2017
@author: Jack Rausch
'''
import http.client
import json
import ssl
import tbapy
#import requests
URL = "http://www.thebluealliance.com/api/v2/"
HEADER_KEY = "X-TBA-App-Id"
HEADER_VAL = 'frc4215:data-analysis:.1'
#I was thinking that we should turn this into a class so that we can have an ... | #!/usr/bin/python3
# -*- encoding: utf8 -*-
'''
Created on Mar 28, 2017
@author: Jack Rausch
'''
import http.client
import json
import ssl
import tbapy
#import requests
URL = "http://www.thebluealliance.com/api/v2/"
HEADER_KEY = "X-TBA-App-Id"
HEADER_VAL = 'frc4215:data-analysis:.1'
#I was thinking that we should t... | Add sufficient leading lines to indicate the launching program of this script. | Add sufficient leading lines to indicate the launching program of this script.
| Python | mit | TrinityTrihawks/BluePython |
a600543515c286ed7bcba2bad5a0746588b62f9a | app/views.py | app/views.py | import logging
import hashlib
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
for app in ap... | import logging
import hashlib
import hmac
import json
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from app.models import SocialNetworkApp
logger = logging.getLogger(__name__)
def _get_facebook_app():
apps = SocialNetworkApp.objects.all()
f... | Modify function that calculate the expected signature | Modify function that calculate the expected signature
| Python | mit | rebearteta/social-ideation,joausaga/social-ideation,rebearteta/social-ideation,joausaga/social-ideation,joausaga/social-ideation,rebearteta/social-ideation,rebearteta/social-ideation,joausaga/social-ideation |
2fdf0366819c2d1cbc9ff6987797eca5acd8de5a | config/freetype2/__init__.py | config/freetype2/__init__.py | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('freetype-config --cflags')
except OSError... | import os
from SCons.Script import *
def configure(conf):
env = conf.env
conf.CBCheckHome('freetype2',
inc_suffix=['/include', '/include/freetype2'])
if not 'FREETYPE2_INCLUDE' in os.environ:
try:
env.ParseConfig('pkg-config freetype2 --cflags')
except OS... | Use pkg-config for freetype2 include discovery. | Use pkg-config for freetype2 include discovery.
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang |
f9b1418c7ea46d3d69fac027f097c5c1ace62f74 | django_cradmin/viewhelpers/__init__.py | django_cradmin/viewhelpers/__init__.py | from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . import detail # noqa
from . import listbuilderview # noqa
from . import multiselect # noqa
from . impo... | from . import mixins # noqa
from . import generic # noqa
from . import formbase # noqa
from . import crudbase # noqa
from . import create # noqa
from . import update # noqa
from . import delete # noqa
from . import detail # noqa
from . import listbuilderview # noqa
| Remove import for multiselect and objecttable. | viewhelpers: Remove import for multiselect and objecttable.
| Python | bsd-3-clause | appressoas/django_cradmin,appressoas/django_cradmin,appressoas/django_cradmin |
9deeb98a05483bfa262db59319c55eec78e900db | tests/test_stock.py | tests/test_stock.py | import unittest
from datetime import datetime
from stock import Stock
class StockTest(unittest.TestCase):
def test_new_stock_price(self):
"""A new stock should have a price that is None.
"""
stock = Stock("GOOG")
self.assertIsNone(stock.price)
def test_stock_update(self):
... | import unittest
from datetime import datetime
from stock import Stock
class StockTest(unittest.TestCase):
def test_new_stock_price(self):
"""A new stock should have a price that is None.
"""
stock = Stock("GOOG")
self.assertIsNone(stock.price)
def test_stock_update(self):
... | Add negative price exception test. | Add negative price exception test.
| Python | mit | bsmukasa/stock_alerter |
de88382029a01c036a3601c40cacc342f5212080 | api/base/views.py | api/base/views.py | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
... | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
... | Use request.version instead of hardcoding | Use request.version instead of hardcoding
| Python | apache-2.0 | KAsante95/osf.io,Johnetordoff/osf.io,petermalcolm/osf.io,mluo613/osf.io,saradbowman/osf.io,emetsger/osf.io,jmcarp/osf.io,Ghalko/osf.io,jinluyuan/osf.io,mluke93/osf.io,monikagrabowska/osf.io,hmoco/osf.io,chennan47/osf.io,zachjanicki/osf.io,acshi/osf.io,rdhyee/osf.io,jeffreyliu3230/osf.io,acshi/osf.io,mfraezz/osf.io,slor... |
e11166ed27b49250ee914c1227b3022ef7659e15 | curator/script.py | curator/script.py | import hashlib
from redis.exceptions import NoScriptError
class LuaScript(object):
def __init__(self, redis, template, cache):
self.redis = redis
self.template = template
self.cache = cache
self.script = self._render_template(template)
def _render_template(self, template):
... | import hashlib
from redis.exceptions import ResponseError
class LuaScript(object):
def __init__(self, redis, template, cache):
self.redis = redis
self.template = template
self.cache = cache
self.script = self._render_template(template)
def _render_template(self, template):
... | Use ResponseError instead of NoScriptError to be compatible with earlier versions of the redis client | Use ResponseError instead of NoScriptError to be compatible with earlier versions of the redis client
| Python | mit | eventbrite/curator |
4b459a367c67b40561b170b86c2df8882880d2be | test/test_examples.py | test/test_examples.py | # coding=utf-8
import os
import pytest
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment varia... | # coding=utf-8
import os
import pytest
import json as json_import
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'discovery_v1.ipynb', '__init__.py']
# examples path. /examples
examples_path = join(d... | Exclude tests if there are no credentials in VCAP_SERVICES | Exclude tests if there are no credentials in VCAP_SERVICES
| Python | apache-2.0 | ehdsouza/python-sdk,ehdsouza/python-sdk,ehdsouza/python-sdk |
c88171bef919dc02bf5796b1bc9318d60a680a8f | test/test_scraping.py | test/test_scraping.py | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
self.assertIs(type(time),... | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
assert type(time) is date... | Fix for assertIs method not being present in Python 2.6. | Fix for assertIs method not being present in Python 2.6.
| Python | mit | alanmcintyre/btce-api,CodeReclaimers/btce-api,lromanov/tidex-api |
61d71b27111f255c3dad3f974e6c7e0ace0c2ce9 | karld/iter_utils.py | karld/iter_utils.py | from functools import partial
from itertools import imap
from itertools import islice
from itertools import izip_longest
from itertools import ifilter
from operator import itemgetter
from operator import is_not
def yield_getter_of(getter_maker, iterator):
"""
Iteratively map iterator over the result of getter... | from functools import partial
from itertools import imap
from itertools import islice
from operator import itemgetter
def yield_getter_of(getter_maker, iterator):
"""
Iteratively map iterator over the result of getter_maker.
:param getter_maker: function that returns a getter function.
:param iterato... | Remove grouper and grouper based batchers | Remove grouper and grouper based batchers
I prefer to not use the filter fill value method to
batch. I don't like the need to allocate room for
the fill value object.
| Python | apache-2.0 | johnwlockwood/stream_tap,johnwlockwood/karl_data,johnwlockwood/iter_karld_tools,johnwlockwood/stream_tap |
6d2255b6f44a18bae0b50fb528564c6767683c68 | src/bindings/python/test/test.py | src/bindings/python/test/test.py | #ckwg +4
# Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception... | #ckwg +4
# Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
# KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
# Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
def test_error(msg):
import sys
sys.stderr.write('Error: %s\n' % msg)
def expect_exception... | Update Python expect_exception to be like C++'s | Update Python expect_exception to be like C++'s
| Python | bsd-3-clause | Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,Kitware/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit |
285f4e21190d28e4e3b26dc62b9fd396de1db24e | keyring/__init__.py | keyring/__init__.py | from __future__ import absolute_import
import logging
logger = logging.getLogger('keyring')
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
try:
import pkg_resources
__version__ = pk... | from __future__ import absolute_import
import logging
logger = logging.getLogger('keyring')
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
try:
import pkg_resources
__version__ = pk... | Define __all__ to suppress lint warnings. | Define __all__ to suppress lint warnings.
| Python | mit | jaraco/keyring |
2733cf558a7455eb017ec4690307a2ee18afbd8b | blogtrans.py | blogtrans.py | from blogtrans.ui.MainWindow import *
import sys, traceback
import getopt
import wx
# Importers / Exporters
from blogtrans.wretch.WretchImporter import WretchImporter
from blogtrans.mt import *
from blogtrans.blogger.BloggerExporter import *
from blogtrans.blogger.BloggerImporter import *
def trap_error(func) :
... | from blogtrans.ui.MainWindow import *
import sys, traceback
import getopt
import wx
# Importers / Exporters
from blogtrans.wretch.WretchImporter import WretchImporter
from blogtrans.mt import *
from blogtrans.blogger.BloggerExporter import *
from blogtrans.blogger.BloggerImporter import *
def trap_error(func) :
... | Load blog data from command line | Load blog data from command line
| Python | mit | miaout17/blogtrans,miaout17/blogtrans |
a8a257ef2bfb63d175f7db1cb91924adae125b5c | sympy/core/tests/test_compatibility.py | sympy/core/tests/test_compatibility.py | from sympy.core.compatibility import default_sort_key, as_int, ordered
from sympy.core.singleton import S
from sympy.utilities.pytest import raises
from sympy.abc import x
def test_default_sort_key():
func = lambda x: x
assert sorted([func, x, func], key=default_sort_key) == [func, func, x]
def test_as_int... | from sympy.core.compatibility import default_sort_key, as_int, ordered
from sympy.core.singleton import S
from sympy.utilities.pytest import raises
from sympy.abc import x
def test_default_sort_key():
func = lambda x: x
assert sorted([func, x, func], key=default_sort_key) == [func, func, x]
def test_as_int... | Change docstring to inline comment | Change docstring to inline comment
This is in response to comment from smichr
modified: sympy/core/tests/test_compatibility.py
| Python | bsd-3-clause | Mitchkoens/sympy,Sumith1896/sympy,kaichogami/sympy,sunny94/temp,jamesblunt/sympy,pbrady/sympy,Vishluck/sympy,Titan-C/sympy,jaimahajan1997/sympy,kevalds51/sympy,yukoba/sympy,kevalds51/sympy,abhiii5459/sympy,debugger22/sympy,kumarkrishna/sympy,lindsayad/sympy,Vishluck/sympy,souravsingh/sympy,debugger22/sympy,yashsharan/s... |
ce23775d3a76b0b8ecf349733454c0709cfe53d8 | opentreemap/treemap/templatetags/paging.py | opentreemap/treemap/templatetags/paging.py | from django import template
register = template.Library()
@register.filter
def four_before_page(page_range, page):
"""Returns 4 or fewer pages before the given (1-based) page number"""
return page_range[max(page-5, 0):max(page-1, 0)]
@register.filter
def four_after_page(page_range, page):
"""Returns 4 ... | from django import template
register = template.Library()
@register.filter
def four_before_page(page_range, page):
"""Returns 4 or fewer pages before the given (1-based) page number"""
return list(page_range)[max(page-5, 0):max(page-1, 0)]
@register.filter
def four_after_page(page_range, page):
"""Retu... | Support Paginator.page_range returning an iterator or list | Support Paginator.page_range returning an iterator or list
Paginator.page_range will return an iterator in Django 1.9+
| Python | agpl-3.0 | maurizi/otm-core,maurizi/otm-core,maurizi/otm-core,maurizi/otm-core |
56b85e7f995eb460a5e6fedb9f2296e430d17e96 | listener.py | listener.py | # Listener Class Override
import time
import json
from tweepy.streaming import StreamListener
import sys
class Listener(StreamListener):
def __init__(self, twitter_api, start_time=time.time()):
self.time = start_time
self.api = twitter_api
def on_data(self, data):
# uids we are current... | # Listener Class Override
import time
import json
from tweepy.streaming import StreamListener
import sys
class Listener(StreamListener):
def __init__(self, twitter_api, start_time=time.time()):
self.time = start_time
self.api = twitter_api
def on_data(self, data):
# uids we are current... | Remove text to make tweet unique for testing | Remove text to make tweet unique for testing
| Python | mit | robot-overlord/syriarightnow |
10db07f1fc432f6f3e1e530d28cfbfd6ada0a321 | versebot/webparser.py | versebot/webparser.py | """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations att... | """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations att... | Rename translations to translations_select, switch to HTTPS | Rename translations to translations_select, switch to HTTPS
| Python | mit | Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot |
6d660b0c27029817bc20406454ba565d09cfa31d | wagtail/core/forms.py | wagtail/core/forms.py | from django import forms
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
class PasswordViewRestrictionForm(forms.Form):
password = forms.CharField(label=gettext_lazy("Password"), widget=forms.PasswordInput)
return_url = forms.CharField(widget=forms.HiddenInp... | from django import forms
from django.utils.crypto import constant_time_compare
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
class PasswordViewRestrictionForm(forms.Form):
password = forms.CharField(label=gettext_lazy("Password"), widget=forms.PasswordInput)
... | Use constant_time_compare for view restriction password checks | Use constant_time_compare for view restriction password checks
| Python | bsd-3-clause | zerolab/wagtail,takeflight/wagtail,rsalmaso/wagtail,gasman/wagtail,thenewguy/wagtail,takeflight/wagtail,gasman/wagtail,mixxorz/wagtail,kaedroho/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,wagtail/wagtail,thenewguy/wagtail,rsalmaso/wagtail,takeflight/wagtail,wagtail/wagtail,jnns/wagtail,torchbox/wagtail,mixxorz/wagtail,m... |
ef4bd591abc794211624c0723d15cfa311370bb2 | examples/chatserver/views.py | examples/chatserver/views.py | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from django.views.decorators.csrf import csrf_exempt
import redis
from ws4redis import settings as redis_settings
class BaseTemplateView(TemplateView):
def ge... | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from django.views.decorators.csrf import csrf_exempt
import redis
from ws4redis import settings as redis_settings
class BaseTemplateView(TemplateView):
def ge... | Use META.SERVER_NAME in template view. | Use META.SERVER_NAME in template view.
We may want to access this example from a different machine.
| Python | mit | schinckel/django-websocket-redis |
c8c858cd26031178a8be30c3824577e0832806dc | bookworm/settings_mobile.py | bookworm/settings_mobile.py | from settings import *
import settings
TEMPLATE_DIRS_BASE = TEMPLATE_DIRS
TEMPLATE_DIRS = (
'%s/library/templates/mobile/auth' % ROOT_PATH,
'%s/library/templates/mobile' % ROOT_PATH,
)
TEMPLATE_DIRS += TEMPLATE_DIRS_BASE
MOBILE = True
| from settings import *
import settings
TEMPLATE_DIRS_BASE = TEMPLATE_DIRS
TEMPLATE_DIRS = (
'%s/library/templates/mobile/auth' % ROOT_PATH,
'%s/library/templates/mobile' % ROOT_PATH,
)
TEMPLATE_DIRS += TEMPLATE_DIRS_BASE
MOBILE = True
SESSION_COOKIE_NAME = 'bookworm_mobile'
| Change cookie name for mobile setting | Change cookie name for mobile setting
--HG--
extra : convert_revision : svn%3Ae08d0fb5-4147-0410-a205-bba44f1f51a3/trunk%40553
| Python | bsd-3-clause | erochest/threepress-rdfa,erochest/threepress-rdfa,erochest/threepress-rdfa,erochest/threepress-rdfa |
d883208fa4084e06aa0f19ba7031566f33260e23 | lib/web/web.py | lib/web/web.py | import os, os.path
import random
import string
import json
import cherrypy
from . import get_pic
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
... | import os, os.path
import random
import string
import json
import cherrypy
from . import get_pic
class StringGenerator(object):
@cherrypy.expose
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
... | Add sample urls to json.dump | Add sample urls to json.dump
| Python | mit | DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat,DexterLB/bookrat |
fc3f64de95554a66e2ec64804acf9c6032dd7e7b | test/rsrc/convert_stub.py | test/rsrc/convert_stub.py | #!/usr/bin/env python
"""A tiny tool used to test the `convert` plugin. It copies a file and appends
a specified text tag.
"""
import sys
def convert(in_file, out_file, tag):
"""Copy `in_file` to `out_file` and append the string `tag`.
"""
with open(out_file, 'wb') as out_f:
with open(in_file, '... | #!/usr/bin/env python
"""A tiny tool used to test the `convert` plugin. It copies a file and appends
a specified text tag.
"""
import sys
def convert(in_file, out_file, tag):
"""Copy `in_file` to `out_file` and append the string `tag`.
"""
# On Python 3, encode the tag argument as bytes.
if not isin... | Convert stub: Python 3 compatibility | Convert stub: Python 3 compatibility
Important for systems where `python` is 3.x, like Arch, even when beets itself
is running on Python 2.
| Python | mit | madmouser1/beets,jcoady9/beets,jcoady9/beets,xsteadfastx/beets,madmouser1/beets,diego-plan9/beets,Kraymer/beets,jackwilsdon/beets,sampsyo/beets,beetbox/beets,MyTunesFreeMusic/privacy-policy,shamangeorge/beets,pkess/beets,Kraymer/beets,mosesfistos1/beetbox,Kraymer/beets,sampsyo/beets,lengtche/beets,pkess/beets,xsteadfas... |
901868b42f98b8b25bc49e0930e0eb4bb56f26d1 | lib/rapidsms/tests/test_backend_irc.py | lib/rapidsms/tests/test_backend_irc.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestLog(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = Backend(... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import unittest
from harness import MockRouter
class TestBackendIRC(unittest.TestCase):
def test_backend_irc (self):
router = MockRouter()
try:
import irclib
from rapidsms.backends.irc import Backend
backend = B... | Rename test class (sloppy cut n' paste job) | Rename test class (sloppy cut n' paste job)
| Python | bsd-3-clause | rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy |
9dad4f997371011ee7fe9f6ecd0c1a58cbba6d27 | html_parse.py | html_parse.py | from bs4 import BeautifulSoup
def parse(html):
soup = BeautifulSoup(html, features="html.parser")
return soup.get_text() | import imp
import logging
log = logging.getLogger(__name__)
def module_exists(module_name):
try:
imp.find_module(module_name)
return True
except ImportError:
return False
if module_exists("bs4"):
log.info("Parsing HTML using beautifulsoup4")
from bs4 import BeautifulSoup
... | Add support for html2text or no parser Will still prefer beautifulsoup4 if installed | Add support for html2text or no parser
Will still prefer beautifulsoup4 if installed
| Python | mit | idiotandrobot/heathergraph |
ebafc242445e1a8413cd6afd45ae53d989850f9e | subprocrunner/error.py | subprocrunner/error.py | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import subprocess
import sys
from typing import Optional
from .typing import Command
class CommandError(Exception):
@property
def cmd(self) -> Optional[Command]:
return self.__cmd
@property
def errno(self) -> Optional[... | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
# keep the following line for backward compatibility
from subprocess import CalledProcessError # noqa
from typing import Optional
from .typing import Command
class CommandError(Exception):
@property
def cmd(self) -> Optional[Command]:... | Remove a class definition that no longer needed | Remove a class definition that no longer needed
| Python | mit | thombashi/subprocrunner,thombashi/subprocrunner |
c21fe453911af190f3cbd93356396d4f5e65195e | mopidy/backends/gstreamer.py | mopidy/backends/gstreamer.py | import logging
import gst
from mopidy import config
from mopidy.backends import BaseBackend
from mopidy.models import Artist, Album, Track, Playlist
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self)._... | import logging
import gst
from mopidy import config
from mopidy.backends import BaseBackend
from mopidy.models import Artist, Album, Track, Playlist
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self)._... | Clean play code for GStreamer | Clean play code for GStreamer
| Python | apache-2.0 | vrs01/mopidy,bacontext/mopidy,vrs01/mopidy,quartz55/mopidy,priestd09/mopidy,swak/mopidy,liamw9534/mopidy,hkariti/mopidy,pacificIT/mopidy,ZenithDK/mopidy,hkariti/mopidy,dbrgn/mopidy,kingosticks/mopidy,ZenithDK/mopidy,diandiankan/mopidy,vrs01/mopidy,hkariti/mopidy,pacificIT/mopidy,ali/mopidy,SuperStarPL/mopidy,adamcik/mo... |
454ee9051bd8d949eb290fb4d3a622941c9ccc74 | test/python/test_binarycodec.py | test/python/test_binarycodec.py | '''Unit tests for CODA binary serialization'''
import io
import unittest
from coda import descriptors
from coda.io.binarycodec import BinaryCodec
from coda.runtime.descdata import BoolValue
class BinaryCodecTest(unittest.TestCase):
def setUp(self):
self.buffer = io.BytesIO()
# self.encoder = BinaryCodec.crea... | '''Unit tests for CODA binary serialization'''
import io
import unittest
from coda import descriptors
from coda.io.binarycodec import BinaryCodec
from coda.runtime.descdata import BoolValue
class BinaryCodecTest(unittest.TestCase):
def setUp(self):
self.buffer = io.BytesIO()
# self.encoder = BinaryCodec.crea... | Disable debug mode in python unit test. | Disable debug mode in python unit test.
| Python | apache-2.0 | viridia/coda,viridia/coda,viridia/coda |
22f01c8727377fcbeb68489c9658443dd9e367dc | flask-app/nickITAPI/app.py | flask-app/nickITAPI/app.py | from flask import Flask, Response, request, jsonify
from ldap3 import Server, Connection, ALL
import json
import re
app = Flask(__name__) # create the application instance :)
@app.route('/')
def hello_world():
return 'Hello, World!'
def parse_query(query):
nick_list = re.compile('\s*[,]+\s*').split(query)
... | from flask import Flask, Response, request, jsonify, abort, render_template
from ldap3 import Server, Connection, ALL
import json
import re
app = Flask(__name__) # create the application instance :)
@app.route('/')
def hello_world():
return 'Hello, World!'
def parse_query(query):
nick_list = re.compile('\s*[... | Add handling of an empty search | Add handling of an empty search
| Python | mit | cthit/nickIT,cthit/nickIT,cthit/nickIT |
bbcbcefedcbff4cfd7a16cbfa904b42462f1ee88 | python/ql/test/query-tests/Variables/unused/type_annotation_fp.py | python/ql/test/query-tests/Variables/unused/type_annotation_fp.py | # FP Type annotation counts as redefinition
# See https://github.com/Semmle/ql/issues/2652
def type_annotation(x):
foo = 5
if x:
foo : int
do_stuff_with(foo)
else:
foo : float
do_other_stuff_with(foo)
| # FP Type annotation counts as redefinition
# See https://github.com/Semmle/ql/issues/2652
def type_annotation(x):
foo = 5
if x:
foo : int
do_stuff_with(foo)
else:
foo : float
do_other_stuff_with(foo)
def type_annotation_fn():
# False negative: the value of `bar` is nev... | Add false negative test case. | Python: Add false negative test case.
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql |
4889f26d51cafca6e36d29e6bcf62f4af6c6712d | openfisca_country_template/entities.py | openfisca_country_template/entities.py | # -*- coding: utf-8 -*-
# This file defines the entities needed by our legislation.
from openfisca_core.entities import build_entity
Household = build_entity(
key = "household",
plural = "households",
label = u'Household',
roles = [
{
'key': 'parent',
'plural': 'parent... | # -*- coding: utf-8 -*-
# This file defines the entities needed by our legislation.
from openfisca_core.entities import build_entity
Household = build_entity(
key = "household",
plural = "households",
label = u'Household',
roles = [
{
'key': 'parent',
'plural': 'parent... | Add docstring on every entity | Add docstring on every entity | Python | agpl-3.0 | openfisca/country-template,openfisca/country-template |
00f270137c460361537f979adc9da18a38324f2f | openremote-server-python/openremote.py | openremote-server-python/openremote.py | #!/usr/bin/env python
import sys
import re
import subprocess
import urlparse
import platform
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class OpenRemoteHandler(BaseHTTPRequestHandler):
def do_GET(self):
url = ''
try:
request_url = urlparse.urlsplit(self.path)
... | #!/usr/bin/env python
import re
import webbrowser
import urlparse
import platform
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class OpenRemoteHandler(BaseHTTPRequestHandler):
def do_GET(self):
url = ''
try:
request_url = urlparse.urlsplit(self.path)
if re.... | Use the webserver module, which means the script is now cross-platform. Hooray, Python\! | Use the webserver module, which means the script is now cross-platform. Hooray, Python\!
| Python | mit | chuckbjones/openremote,chuckbjones/openremote,chuckbjones/openremote,chuckbjones/openremote |
d4070aaee0e086b934912982d77126af53e9ade8 | src/core/tests.py | src/core/tests.py | # -*- coding: utf-8 -*-
from django.test import TestCase
from .models import Session
from .models import Spec
# if self.name == '':
# names = Session.objects.filter(name__startswith=self.UNTITLED_PREFIX, user=self.user).only('name')
# name_suffix = 1
# if len(names):
# names = [x.name for x in nam... | # -*- coding: utf-8 -*-
from django.test import TestCase
from .models import Session
from .models import Spec
# if self.name == '':
# names = Session.objects.filter(name__startswith=self.UNTITLED_PREFIX, user=self.user).only('name')
# name_suffix = 1
# if len(names):
# names = [x.name for x in nam... | Create 'Untitled 2' session name. | Create 'Untitled 2' session name. | Python | mit | uxebu/tddbin-backend,uxebu/tddbin-backend |
57f3141bf61fe74cc4ba3472f42640e0fada0f44 | tests/spin_one_half_gen_test.py | tests/spin_one_half_gen_test.py | """Tests for the general model with explicit one-half spin."""
import pytest
from drudge import UP, DOWN, SpinOneHalfGenDrudge
@pytest.fixture(scope='module')
def dr(spark_ctx):
"""The fixture with a general spin one-half drudge."""
return SpinOneHalfGenDrudge(spark_ctx)
def test_spin_one_half_general_dru... | """Tests for the general model with explicit one-half spin."""
import pytest
from sympy import IndexedBase, symbols, Rational
from drudge import CR, AN, UP, DOWN, SpinOneHalfGenDrudge
@pytest.fixture(scope='module')
def dr(spark_ctx):
"""The fixture with a general spin one-half drudge."""
return SpinOneHal... | Add test for restricted HF theory | Add test for restricted HF theory
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge |
7f0097d240c4a231029222fdd2bf507ca7d5b2ed | tests/v6/exemplar_generators.py | tests/v6/exemplar_generators.py | from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Integer(100, 200),
]
EXEMPLAR_DERIVED_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS | from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Integer(100, 200),
HashDigest(length=8),
FakerGenerator(method="name"),
]
EXEMPLAR_DERIVED_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_G... | Add exemplar generators for HashDigest, FakerGenerator | Add exemplar generators for HashDigest, FakerGenerator
| Python | mit | maxalbert/tohu |
fd5f3875d0d7e0fdb7b7ef33a94cf50d1d2b5fa4 | tests/write_to_stringio_test.py | tests/write_to_stringio_test.py | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
import pycurl
import unittest
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def... | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
import pycurl
import unittest
import sys
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
... | Add a test for writing to StringIO which is now different and does not work | Add a test for writing to StringIO which is now different and does not work
| Python | lgpl-2.1 | pycurl/pycurl,pycurl/pycurl,pycurl/pycurl |
c3e88993964f1c775829fc2f14aea2e84d33c099 | tests/frontends/mpd/protocol/audio_output_test.py | tests/frontends/mpd/protocol/audio_output_test.py | from __future__ import unicode_literals
from tests.frontends.mpd import protocol
class AudioOutputHandlerTest(protocol.BaseTestCase):
def test_enableoutput(self):
self.sendRequest('enableoutput "0"')
self.assertInResponse('OK')
def test_disableoutput(self):
self.sendRequest('disableo... | from __future__ import unicode_literals
from tests.frontends.mpd import protocol
class AudioOutputHandlerTest(protocol.BaseTestCase):
def test_enableoutput(self):
self.core.playback.mute = True
self.sendRequest('enableoutput "0"')
self.assertInResponse('OK')
self.assertEqual(sel... | Test that output enabling/disabling unmutes/mutes audio | mpd: Test that output enabling/disabling unmutes/mutes audio
| Python | apache-2.0 | jmarsik/mopidy,mopidy/mopidy,priestd09/mopidy,hkariti/mopidy,rawdlite/mopidy,adamcik/mopidy,vrs01/mopidy,ZenithDK/mopidy,ali/mopidy,bacontext/mopidy,kingosticks/mopidy,jcass77/mopidy,bacontext/mopidy,mopidy/mopidy,glogiotatidis/mopidy,bacontext/mopidy,woutervanwijk/mopidy,diandiankan/mopidy,bencevans/mopidy,dbrgn/mopid... |
de09310ebfd932cd725954e9c05f5a1ce78311e0 | news/management/commands/sync_newsletters.py | news/management/commands/sync_newsletters.py | from django.conf import settings
from django.core.management import BaseCommand
from synctool.functions import sync_data
DEFAULT_SYNC_DOMAIN = 'basket.mozilla.org'
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-d', '--domain',
default=geta... | from django.conf import settings
from django.core.management import BaseCommand
from synctool.functions import sync_data
from news.newsletters import clear_newsletter_cache, clear_sms_cache
DEFAULT_SYNC_DOMAIN = 'basket.mozilla.org'
class Command(BaseCommand):
def add_arguments(self, parser):
parser.a... | Add cache clear to sync command | Add cache clear to sync command
| Python | mpl-2.0 | glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket |
7226e9ae349eadba10d8f23f81df0b4d70adb6a2 | detectem/plugins/helpers.py | detectem/plugins/helpers.py | def meta_generator(name):
return '//meta[@name="generator" and contains(@content, "{}")]' \
'/@content'.format(name)
| def meta_generator(name):
return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \
'/@content'.format(name)
| Update meta_generator to match case insensitive | Update meta_generator to match case insensitive
| Python | mit | spectresearch/detectem |
dbf8d75c0e4105570676af0bde50d2a4c43e6dd3 | ain7/organizations/autocomplete_light_registry.py | ain7/organizations/autocomplete_light_registry.py | # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2016 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of ... | # -*- coding: utf-8
"""
ain7/annuaire/autocomplete_light_registry.py
"""
#
# Copyright © 2007-2016 AIn7 Devel Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of ... | Add a link to add a company in user profile | Add a link to add a company in user profile
When a user change its experience, s⋅he can add an organization (not an
office) if it does not exist yet.
Link to autocomplete-light module's doc:
http://django-autocomplete-light.readthedocs.io/en/2.3.1/addanother.html#autocompletes.
Fix #3
| Python | lgpl-2.1 | ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org,ain7/www.ain7.org |
ac7c04f76ad4276c34e000a065b6bc900f941ee5 | girder/utility/__init__.py | girder/utility/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc.
#
# 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 ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc.
#
# 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 ... | Send timestamps as ISO8601 format | Send timestamps as ISO8601 format
| Python | apache-2.0 | msmolens/girder,salamb/girder,jbeezley/girder,Kitware/girder,data-exp-lab/girder,sutartmelson/girder,opadron/girder,Xarthisius/girder,manthey/girder,essamjoubori/girder,Kitware/girder,sutartmelson/girder,Xarthisius/girder,essamjoubori/girder,kotfic/girder,RafaelPalomar/girder,sutartmelson/girder,kotfic/girder,Kitware/g... |
99daef4c39d89ac41c02533e8c6becd67f5c76b5 | docs/conf.py | docs/conf.py | from crate.theme.rtd.conf.python import *
if "sphinx.ext.intersphinx" not in extensions:
extensions += ["sphinx.ext.intersphinx"]
if "intersphinx_mapping" not in globals():
intersphinx_mapping = {}
intersphinx_mapping.update({
'reference': ('https://crate.io/docs/crate/reference/', None),
'sa': ('... | from crate.theme.rtd.conf.python import *
if "sphinx.ext.intersphinx" not in extensions:
extensions += ["sphinx.ext.intersphinx"]
if "intersphinx_mapping" not in globals():
intersphinx_mapping = {}
intersphinx_mapping.update({
'reference': ('https://crate.io/docs/crate/reference/en/latest/', None),
... | Fix documentation checks by adjusting intersphinx mapping | Fix documentation checks by adjusting intersphinx mapping | Python | apache-2.0 | crate/crate-python,crate/crate-python |
a303d4d0491abf91c8f2856527d0b3566f704b90 | tracestack/__init__.py | tracestack/__init__.py | import sys, urllib, webbrowser
def tracestack():
try:
last_error = sys.last_value
except:
raise Exception("No error message available.")
error_query = urllib.urlencode("[python] " + str(last_error))
search_url = "http://stackoverflow.com/search?q=" + error_query
webbrowser.open(sear... | import sys, urllib, webbrowser
def tracestack():
try:
last_error = "{0} {1}".format(sys.last_type, sys.last_value)
except:
raise Exception("No error message available.")
error_query = urllib.urlencode({"q": "[python] " + last_error})
search_url = "http://stackoverflow.com/search?q=" + e... | Fix bugs thanks to Aaron | Fix bugs thanks to Aaron | Python | mit | kod3r/tracestack,danrobinson/tracestack |
57f4b34a70a3506f1fb1e1842b3e75dc977bfe18 | flask_app.py | flask_app.py | from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +
'</head>... | from flask import abort
from flask import Flask
from flask_caching import Cache
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/')
def display_available():
content = ('<html>' +
'<head>' +
'<title>Restaurant Menu Parser</title>' +... | Add import of abort function. | Add import of abort function.
| Python | bsd-3-clause | talavis/kimenu |
00b31f3025493942c0ce7eb03c7cc09abf0eb8d0 | txlege84/core/views.py | txlege84/core/views.py | from django.views.generic import ListView
from topics.models import Topic, TopIssue
class LandingView(ListView):
model = Topic
template_name = 'landing.html'
def get_context_data(self, **kwargs):
context = super(LandingView, self).get_context_data(**kwargs)
context['top_issues'] = TopIss... | from django.views.generic import ListView
from topics.models import Topic, TopIssue
class LandingView(ListView):
model = Topic
template_name = 'landing.html'
def get_context_data(self, **kwargs):
context = super(LandingView, self).get_context_data(**kwargs)
context['top_issues'] = TopIss... | Print statement snuck in there | Print statement snuck in there
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 |
a9bc4d98e8b61b63c14a2a5f1e11c85d91747f30 | analysis/data_process/uk_2017/config.py | analysis/data_process/uk_2017/config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_fil... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Config file for the cleaning - plotting and notebook process"""
class CleaningConfig:
# Unprocessed dataset
raw_data = './dataset/raw_results-survey245554.csv'
# load the different answers to questions to classify questions based on that
question_fil... | Add options in the plot | Add options in the plot
| Python | bsd-3-clause | softwaresaved/international-survey |
e99196e14cd258960ad188875723178579b4dbf4 | src/rf/apps/workers/image_validator.py | src/rf/apps/workers/image_validator.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf import settings
import os
import uuid
from boto.s3.key import Key
from boto.s3.connection import S3Connection
from osgeo import gdal
def ensure_band_count(key_string... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf import settings
import os
import uuid
from boto.s3.key import Key
from boto.s3.connection import S3Connection
from osgeo import gdal
def ensure_band_count(key_string... | Use new temp file directory. | Use new temp file directory.
We created a new scratch directory that matches EC2 mounted temp space and
supplied this as a setting in commit 21916b. This switches temporary images to
be downloaded there rather than at /tmp.
| Python | apache-2.0 | aaronxsu/raster-foundry,aaronxsu/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,kdeloa... |
f73775980e37b51882bfbd21f609ddfda807b8c8 | tests/test_datafeed_fms_teams.py | tests/test_datafeed_fms_teams.py | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | import unittest2
import datetime
from google.appengine.ext import testbed
from datafeeds.datafeed_fms import DatafeedFms
class TestDatafeedFmsTeams(unittest2.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_urlfetch_stub()
se... | Speed up test by breaking out of a for loop if match found | Speed up test by breaking out of a for loop if match found
| Python | mit | phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance... |
f863f37a05855180dce40181a27e7925f0662647 | djangoautoconf/management/commands/dump_settings.py | djangoautoconf/management/commands/dump_settings.py | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... | Fix int float setting issue. | Fix int float setting issue.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf |
e778a2da7938dcf565282635e395dc410ef989d6 | terraform-gce/worker/generate-certs.py | terraform-gce/worker/generate-certs.py | #!/usr/bin/env python
import os.path
import subprocess
import argparse
import shutil
cl_parser = argparse.ArgumentParser()
args = cl_parser.parse_args()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if not os.path.exists('assets/certificates'):
os.makedirs('assets/certificates')
os.chdir('assets/certific... | #!/usr/bin/env python
import os.path
import subprocess
import argparse
import shutil
cl_parser = argparse.ArgumentParser()
args = cl_parser.parse_args()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if not os.path.exists('assets/certificates'):
os.makedirs('assets/certificates')
os.chdir('assets/certific... | Copy cert auth from master | Copy cert auth from master
| Python | apache-2.0 | aknuds1/contrib,aknuds1/contrib,aknuds1/contrib,aknuds1/contrib,aknuds1/contrib,aknuds1/contrib |
ffdd45d798eaf1349e12fc061789daacdefcd05c | membership.py | membership.py | """Manage society membership by checking member IDs and adding new members"""
import sqlite3
class MemberDatabase:
def __init__(self, dbFile = 'members.db', safe = True):
self.__connection = sqlite3.connect(dbFile)
self.__safe = safe
def __del__(self):
self.__connection.commit() # her... | """Manage society membership by checking member IDs and adding new members"""
import sqlite3
class MemberDatabase:
def __init__(self, dbFile = 'members.db', safe = True):
self.__connection = sqlite3.connect(dbFile)
self.__safe = safe
def __del__(self):
self.__connection.commit() # her... | Update last_attended when checking member | Update last_attended when checking member
| Python | mit | NullInfinity/socman,NullInfinity/society-event-manager |
c6346fa2c026318b530dbbdc90dbaee8310b6b05 | robot/Cumulus/resources/locators_50.py | robot/Cumulus/resources/locators_50.py | from locators_51 import *
import copy
npsp_lex_locators = copy.deepcopy(npsp_lex_locators)
npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]'
npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//lab... | from locators_51 import *
import copy
npsp_lex_locators = copy.deepcopy(npsp_lex_locators)
# current version (Sravani's )
npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]'
npsp_lex_locators['object']['field']= "//div[con... | Revert "Revert "changes in locator_50 file (current and old versions)"" | Revert "Revert "changes in locator_50 file (current and old versions)""
This reverts commit 7537387aa80109877d6659cc54ec0ee7aa6496bd.
| Python | bsd-3-clause | SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus |
356c9cd23ebf4953af169f38126fd521b49ca6c4 | recipe_scrapers/_abstract.py | recipe_scrapers/_abstract.py | from urllib import request
from bs4 import BeautifulSoup
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.u... | from urllib import request
from bs4 import BeautifulSoup
class AbstractScraper():
def __init__(self, url, test=False):
if test:
# when testing, we simply load a file
self.soup = BeautifulSoup(url.read(), "html.parser")
else:
self.soup = BeautifulSoup(request.u... | Add docstring to the methods structure in the abstract class | Add docstring to the methods structure in the abstract class
| Python | mit | hhursev/recipe-scraper |
d371c92e999aa90df39887a33901fdaa58f648f1 | test/gui/test_messages.py | test/gui/test_messages.py | import sys
from sequana.gui import messages
from PyQt5 import QtWidgets as QW
app = QW.QApplication(sys.argv)
def test_warning():
w = messages.WarningMessage("test")
def test_critical():
w = messages.CriticalMessage("test", details="test")
| from sequana.gui import messages
def test_warning(qtbot):
w = messages.WarningMessage("test")
def test_critical(qtbot):
w = messages.CriticalMessage("test", details="test")
| Fix test that caused a pytest hang | Fix test that caused a pytest hang
| Python | bsd-3-clause | sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana |
631983a14f941fa745b6e7f4b32fe1ef697d5703 | tests/mixers/denontest.py | tests/mixers/denontest.py | import unittest
import os
from mopidy.mixers.denon import DenonMixer
class DenonMixerDeviceMock(object):
def __init__(self):
self._open = True
self.ret_val = bytes('00')
def write(self, x):
pass
def read(self, x):
return self.ret_val
def isOpen(self):
return se... | import unittest
import os
from mopidy.mixers.denon import DenonMixer
class DenonMixerDeviceMock(object):
def __init__(self):
self._open = True
self.ret_val = bytes('MV00\r')
def write(self, x):
if x[2] != '?':
self.ret_val = bytes(x)
def read(self, x):
return s... | Update denon device mock to reflect mixer changes | Update denon device mock to reflect mixer changes
| Python | apache-2.0 | mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,tkem/mopidy,bacontext/mopidy,priestd09/mopidy,ZenithDK/mopidy,tkem/mopidy,quartz55/mopidy,bencevans/mopidy,vrs01/mopidy,priestd09/mopidy,jodal/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,rawdlite/mopidy,dbrgn/mopidy,bencevans/mopidy,abarisain/mopidy,jmarsik/mopidy,ali... |
4636c2deb451c284ffdfc44c744cf025a9f87377 | scribeui_pyramid/modules/plugins/__init__.py | scribeui_pyramid/modules/plugins/__init__.py | import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
plug... | import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
plug... | Fix load_plugin loop loading only one plugin | Fix load_plugin loop loading only one plugin
| Python | mit | mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui |
d8f6938649acd4a72a53d47c26a1b16adb0e8fe3 | jupyterlab_gitsync/jupyterlab_gitsync/__init__.py | jupyterlab_gitsync/jupyterlab_gitsync/__init__.py | from notebook.utils import url_path_join
from jupyterlab_gitsync.handlers import *
from jupyterlab_gitsync.version import VERSION
__version__ = VERSION
def _jupyter_server_extension_paths():
return [{'module': 'jupyterlab_gitsync'}]
def load_jupyter_server_extension(nb_server_app):
"""
Called when the ext... | from notebook.utils import url_path_join
from jupyterlab_gitsync.handlers import *
from jupyterlab_gitsync.version import VERSION
__version__ = VERSION
def _jupyter_server_extension_paths():
return [{'module': 'jupyterlab_gitsync'}]
def load_jupyter_server_extension(nb_server_app):
"""
Called when the exten... | Fix indentation to pass tests | Fix indentation to pass tests | Python | apache-2.0 | GoogleCloudPlatform/jupyter-extensions,GoogleCloudPlatform/jupyter-extensions,GoogleCloudPlatform/jupyter-extensions,GoogleCloudPlatform/jupyter-extensions |
d47ba3167b60710efe07e40113150b53c88e7d85 | tests/test_highlighter.py | tests/test_highlighter.py | import pytest
from rich.highlighter import NullHighlighter
def test_wrong_type():
highlighter = NullHighlighter()
with pytest.raises(TypeError):
highlighter([])
| """Tests for the higlighter classes."""
import pytest
from rich.highlighter import NullHighlighter, ReprHighlighter
from rich.text import Span, Text
def test_wrong_type():
highlighter = NullHighlighter()
with pytest.raises(TypeError):
highlighter([])
@pytest.mark.parametrize(
"style_name, test_... | Add tests for EUI-48 and EUI-64 in ReprHighlighter | Add tests for EUI-48 and EUI-64 in ReprHighlighter
| Python | mit | willmcgugan/rich |
6d930e7f29e12cd677cce07c7c1accc66ae594c8 | tests/test_zz_jvm_kill.py | tests/test_zz_jvm_kill.py | from cellom2tif import cellom2tif
import pytest
cfile = 'test-data/d1/MFGTMP_120628160001_C18f00d0.C01'
def test_read_image():
im = cellom2tif.read_image(cfile)
assert im.shape == (512, 512)
def test_done():
cellom2tif.done()
assert cellom2tif.VM_KILLED
def test_vm_killed_error():
cellom2tif... | from cellom2tif import cellom2tif
import bioformats as bf
import pytest
cfile = 'test-data/d1/MFGTMP_120628160001_C18f00d0.C01'
def test_read_image():
im = cellom2tif.read_image(cfile)
assert im.shape == (512, 512)
def test_read_image_from_reader():
rdr = bf.ImageReader(cfile)
im = cellom2tif.read... | Test reading from bf.ImageReader directly | Test reading from bf.ImageReader directly
| Python | bsd-3-clause | jni/cellom2tif |
351bc14c66962e5ef386b6d41073697993c95236 | greengraph/test/test_map.py | greengraph/test/test_map.py | from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
import yaml
def test_green():
size = (10,10)
zoom = 10
lat = 50
lon = 50
satellite = True
testMap = Map(lat,lon,satellite,zoom,size)
threshold = 1
trueArray = np.ones(size,dtype=bool)
falseArray =... | from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
from mock import patch
import os
@patch('requests.get')
@patch('matplotlib.image.imread')
@patch('StringIO.StringIO')
def test_green(mock_get,mock_imread,mock_StringIO):
def assert_images_equal(r,g,b,checkArray):
testMap... | Add patch decorator to test_green() function | Add patch decorator to test_green() function
| Python | mit | MikeVasmer/GreenGraphCoursework |
95da47010839da430223700345e07078b2157131 | evewspace/account/models.py | evewspace/account/models.py | from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save
# Create your models here.
class UserProfile(models.Model):
"""UserProfile defines custom fields tied to each User record in the Django auth DB."... | from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save
# Create your models here.
class PlayTime(models.Model):
"""PlayTime represents a choice of play times for use in several forms."""
fromtime = ... | Add PlayTime class and tie it to user profiles | Add PlayTime class and tie it to user profiles
Created a PlayTime class in account with from and to times.
Added ManyToManyField to UserProfile to keep track of play times.
| Python | apache-2.0 | evewspace/eve-wspace,Maarten28/eve-wspace,proycon/eve-wspace,gpapaz/eve-wspace,Unsettled/eve-wspace,acdervis/eve-wspace,Unsettled/eve-wspace,marbindrakon/eve-wspace,hybrid1969/eve-wspace,Unsettled/eve-wspace,acdervis/eve-wspace,marbindrakon/eve-wspace,Maarten28/eve-wspace,mmalyska/eve-wspace,acdervis/eve-wspace,nyrocro... |
09052d05c27921bc87b0c968de02b244b4e5a56b | cryptchat/test/test_networkhandler.py | cryptchat/test/test_networkhandler.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Run from Cryptchat
# python3 -m unittest discover
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
def setUp(self):... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Run from Cryptchat
# python3 -m unittest discover
import unittest
from ..network.networkhandler import NetworkHandler
from ..crypto.aes import AESCipher
from ..crypto.diffiehellman import DiffieHellman
class testNetworkHandler(unittest.TestCase):
@classmethod
... | Set up server/client once for the netcode test | Set up server/client once for the netcode test
| Python | mit | djohsson/Cryptchat |
83831a3434cdaf0a5ca214dfc4bd7fec65d4ffac | fastai/vision/models/tvm.py | fastai/vision/models/tvm.py | from torchvision.models import ResNet,resnet18,resnet34,resnet50,resnet101,resnet152
from torchvision.models import SqueezeNet,squeezenet1_0,squeezenet1_1
from torchvision.models import densenet121,densenet169,densenet201,densenet161
from torchvision.models import vgg11_bn,vgg13_bn,vgg16_bn,vgg19_bn,alexnet
| from torchvision.models import *
import types as _t
_g = globals()
for _k, _v in list(_g.items()):
if (
isinstance(_v, _t.ModuleType) and _v.__name__.startswith("torchvision.models")
) or (callable(_v) and _v.__module__ == "torchvision.models._api"):
del _g[_k]
del _k, _v, _g, _t
| Add latest TorchVision models on fastai | Add latest TorchVision models on fastai | Python | apache-2.0 | fastai/fastai |
45bdff8fbd19a74bf04aead7d134511605df99d5 | test/settings/gyptest-settings.py | test/settings/gyptest-settings.py | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('settings.gyp')
test.build('test.gyp', test.AL... | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
# 'settings' is only supported for make and scons (and will be removed there as
# we... | Make new settings test not run for xcode generator. | Make new settings test not run for xcode generator.
TBR=evan
Review URL: http://codereview.chromium.org/7472006
git-svn-id: e7e1075985beda50ea81ac4472467b4f6e91fc78@970 78cadc50-ecff-11dd-a971-7dbc132099af
| Python | bsd-3-clause | carlTLR/gyp,mistydemeo/gyp,msc-/gyp,okumura/gyp,Omegaphora/external_chromium_org_tools_gyp,channing/gyp,erikge/watch_gyp,ryfx/gyp,trafi/gyp,IllusionRom-deprecated/android_platform_external_chromium_org_tools_gyp,lukeweber/gyp-override,Phuehvk/gyp,duanhjlt/gyp,cchamberlain/gyp,Jack-Q/GYP-copy,clar/gyp,clar/gyp,openpeer/... |
7f0ab829f677a5d91d5b24dc6181a2519e25a934 | notes/managers.py | notes/managers.py | #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This... | #
# Copyright (c) 2009 Brad Taylor <brad@getcoded.net>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This... | Support hiding note and notebook template notes | Support hiding note and notebook template notes
| Python | agpl-3.0 | syskill/snowy,NoUsername/PrivateNotesExperimental,GNOME/snowy,jaredjennings/snowy,jaredjennings/snowy,sandyarmstrong/snowy,jaredjennings/snowy,NoUsername/PrivateNotesExperimental,widox/snowy,syskill/snowy,leonhandreke/snowy,leonhandreke/snowy,jaredjennings/snowy,widox/snowy,GNOME/snowy,sandyarmstrong/snowy |
cd5c56583c84b2b0fd05d743578193b7b681151c | nn/embedding/embeddings.py | nn/embedding/embeddings.py | import tensorflow as tf
from ..flags import FLAGS
from ..variable import variable
def embeddings(*, id_space_size, embedding_size, name=None):
return variable([id_space_size, embedding_size], name=name)
def word_embeddings(name="word_embeddings"):
if FLAGS.word_embeddings is None:
return embeddings(id_spa... | import tensorflow as tf
from ..flags import FLAGS
from ..variable import variable
from ..util import func_scope
@func_scope()
def embeddings(*, id_space_size, embedding_size, name=None):
return variable([id_space_size, embedding_size], name=name)
@func_scope()
def word_embeddings(name="word_embeddings"):
if F... | Add func_scope to embedding functions | Add func_scope to embedding functions
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten |
fa418ed5a6769a369d4b5cddfc6e215f551c57cf | events/cms_app.py | events/cms_app.py | from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class EventsApphook(CMSApp):
name = _("Events Apphook")
urls = ["events.urls"]
app_name = "events"
apphook_pool.register(EventsApphook)
| from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class EventsApphook(CMSApp):
name = _("Events Apphook")
urls = ["events.urls"]
app_name = "events"
namespace = "events"
apphook_pool.register(EventsApphook)
| Add namespace to support djangoCMS v3 | Add namespace to support djangoCMS v3
| Python | bsd-3-clause | theherk/django-theherk-events |
c0b3a482b8ef5284070da1398350acf936e50121 | rplugin/python3/deoplete/sources/LanguageClientSource.py | rplugin/python3/deoplete/sources/LanguageClientSource.py | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
return re.sub(r'(?<!\\)\$\d+', '', snip)
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = "LanguageClient"
self.mark = "[LC]"... | import re
from .base import Base
CompleteResults = "g:LanguageClient_completeResults"
def simplify_snippet(snip: str) -> str:
snip = re.sub(r'(?<!\\)\$(?P<num>\d+)', '<`\g<num>`>', snip)
return re.sub(r'(?<!\\)\${(?P<num>\d+):(?P<desc>.+?)}',
'<`\g<num>:\g<desc>`>', snip)
class Source(Ba... | Replace placeholders in completion text | Replace placeholders in completion text
In deoplete source, replace the placeholders with the neosnippet format.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... |
5b3d38821517f10f9b9da31f28af19e7302de954 | dimod/reference/composites/structure.py | dimod/reference/composites/structure.py | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
todo
... | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
"""
# ... | Update Structure composite to use the new abc | Update Structure composite to use the new abc
| Python | apache-2.0 | oneklc/dimod,oneklc/dimod |
9d7beff62a3555aa4be51cefb2f54681070d1305 | ircstat/plugins/__init__.py | ircstat/plugins/__init__.py | # Copyright 2013 John Reese
# Licensed under the MIT license
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name app... | # Copyright 2013 John Reese
# Licensed under the MIT license
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name app... | Make sure plugins' .name property gets set | Make sure plugins' .name property gets set
| Python | mit | jreese/ircstat,jreese/ircstat |
ad8f54f7a2532b0ad643790d061b4e488ac7849d | patchboard/tests/functional/trivial_example_test.py | patchboard/tests/functional/trivial_example_test.py | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... | # trivial_example.py
#
# Copyright 2014 BitVault.
#
# Reproduces the tests in trivial_example.rb
from __future__ import print_function
import pytest
from random import randint
from patchboard.tests.fixtures import (trivial_net_pb,
trivial_net_resources,
... | Remove xfail from working test | Remove xfail from working test
| Python | mit | patchboard/patchboard-py |
1e79cc27ae0025d9ba51eff2828cc25247c08d3c | ssbench/worker.py | ssbench/worker.py | import yaml
from ssbench.constants import *
class Worker:
def __init__(self, queue):
queue.use(STATS_TUBE)
self.queue = queue
def go(self):
job = self.queue.reserve()
while job:
job.delete() # avoid any job-timeout nonsense
self.handle_job(job)
... | import yaml
from ssbench.constants import *
class Worker:
def __init__(self, queue):
queue.use(STATS_TUBE)
self.queue = queue
def go(self):
job = self.queue.reserve()
while job:
job.delete() # avoid any job-timeout nonsense
self.handle_job(job)
... | Raise error on unknown job type | Raise error on unknown job type
| Python | apache-2.0 | charz/ssbench,swiftstack/ssbench,charz/ssbench,swiftstack/ssbench |
0be21659f1190e41db9b9818dd694015d94f78cc | zerodb/models/__init__.py | zerodb/models/__init__.py | import persistent
import indexable
import exceptions
class Model(persistent.Persistent):
"""
Data model to easily create indexable persistent objects.
If an object declares a property from indexable, this property is indexed.
*All* other properties are stored but unindexed
Example:
>>> cl... | import persistent
import indexable
import exceptions
class Model(persistent.Persistent):
"""
Data model to easily create indexable persistent objects.
If an object declares a property from indexable, this property is indexed.
*All* other properties are stored but unindexed
Example:
>>> cl... | Set model instance attributes based on fields | Set model instance attributes based on fields
| Python | agpl-3.0 | zerodb/zerodb,zero-db/zerodb,zero-db/zerodb,zerodb/zerodb |
b378102284bbbcc9ad909a7393dfffa24377ce27 | ginga/__init__.py | ginga/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""See LONG_DESC.txt"""
# Set up the version
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
__version__ = 'unknown... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""See LONG_DESC.txt"""
# Packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import * # noqa
# ------------------... | Fix version import and test runner | BUG: Fix version import and test runner
| Python | bsd-3-clause | pllim/ginga,pllim/ginga,ejeschke/ginga,naojsoft/ginga,ejeschke/ginga,ejeschke/ginga,pllim/ginga,naojsoft/ginga,naojsoft/ginga |
5bc8ad66b59312d7459ec9c4d58d89bee0038a48 | conference_scheduler/scheduler.py | conference_scheduler/scheduler.py | import pulp
from typing import Sequence
import conference_scheduler.parameters as params
def is_valid_schedule(schedule):
"""Validate an existing schedule against a problem
Parameters
---------
schedule : iterable
of resources.ScheduledItem
Returns
-------
bool
True if sc... | import pulp
from typing import Sequence
import conference_scheduler.parameters as params
def is_valid_schedule(schedule):
"""Validate an existing schedule against a problem
Parameters
---------
schedule : iterable
of resources.ScheduledItem
Returns
-------
bool
True if sc... | Correct order of constraint assignment and problem solution | Correct order of constraint assignment and problem solution
| Python | mit | PyconUK/ConferenceScheduler |
58b46dbc62c98372ed300eeb20b5ecb80a11ddb3 | test/test-mime.py | test/test-mime.py | from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
... | from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
... | Test getting comment for Mime type | Test getting comment for Mime type
| Python | lgpl-2.1 | 0312birdzhang/pyxdg |
f61c0a33a79fa4670874f4469e7ceb76c644bf4b | lambda_local/environment_variables.py | lambda_local/environment_variables.py | import json
import os
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json... | import json
import os
def export_variables(environment_variables):
for env_name, env_value in environment_variables.items():
os.environ[str(env_name)] = str(env_value)
def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind t... | Split the parsing of input and the exporting of the variables for reuse | Split the parsing of input and the exporting of the variables for
reuse
| Python | mit | HDE/python-lambda-local,HDE/python-lambda-local |
3598b974ecc078f34e54a32b06e16af8ccaf839b | opps/core/admin/__init__.py | opps/core/admin/__init__.py | # -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
| # -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
| Add source admin in Admin Opps Core | Add source admin in Admin Opps Core
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps |
83406db629abd389da85666dc79925f8e03a22f4 | lms/djangoapps/courseware/__init__.py | lms/djangoapps/courseware/__init__.py | #pylint: disable=missing-docstring
from __future__ import absolute_import
import warnings
if __name__ == 'courseware':
warnings.warn("Importing 'lms.djangoapps.courseware' as 'courseware' is no longer supported", DeprecationWarning)
| #pylint: disable=missing-docstring
from __future__ import absolute_import
import inspect
import warnings
if __name__ == 'courseware':
# pylint: disable=unicode-format-string
# Show the call stack that imported us wrong.
stack = "\n".join("%30s : %s:%d" % (t[3], t[1], t[2]) for t in inspect.stack()[:0:-1])... | Add more diagnostics to the courseware import warning | Add more diagnostics to the courseware import warning
| Python | agpl-3.0 | angelapper/edx-platform,angelapper/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,mitocw/edx-platform,edx/edx-platform,cpennington/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,edx-solutions/edx-platform,stvstnfrd/edx-platform,a... |
3beea9e3800f5c1e68f869d46d137162016a5276 | zc-list.py | zc-list.py | #!/usr/bin/env python
import sys
import client_wrap
def get_keys(client):
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
sys.exit()
return keys
def print_keys(client, keys):
for key in keys:
value = client.ReadLong(key)
print "%... | #!/usr/bin/env python
import sys
import argparse
import client_wrap
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--type", help="type of the cached data", default="double")
parser.add_argument("-c", "--connection", help="connection string", default="ipc:///var/run/zero-ca... | Add the parsing arguments function | Add the parsing arguments function
| Python | agpl-3.0 | ellysh/zero-cache-utils,ellysh/zero-cache-utils |
cab4ec885d3101775ac16532d46f6f47700d1134 | IATISimpleTester/views/uploader.py | IATISimpleTester/views/uploader.py | import os.path
from flask import request, jsonify, redirect, url_for
from IATISimpleTester import app, db
from IATISimpleTester.models import SuppliedData
@app.route('/upload', methods=['GET', 'POST'])
def upload():
resp = {}
source_url = request.args.get('source_url')
file = request.files.get('file')
... | import os.path
from flask import abort, request, jsonify, redirect, url_for
from IATISimpleTester import app, db
from IATISimpleTester.models import SuppliedData
@app.route('/upload', methods=['GET', 'POST'])
def upload():
source_url = request.args.get('source_url')
file = request.files.get('file')
raw_... | Tidy up upload response a bit | Tidy up upload response a bit
| Python | mit | pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester |
2aab542cc74fdc0cf060518241f01fd74d91ecb5 | byceps/services/user/transfer/models.py | byceps/services/user/transfer/models.py | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from attr import attrs
from ....typing import UserID
@attrs(auto_attribs=True, frozen=True, slots=True)
class User:
id: UserID
screen... | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from attr import attrs
from ....typing import UserID
@attrs(auto_attribs=True, frozen=True, slots=True)
class Us... | Fix type hint for avatar URL in user DTO | Fix type hint for avatar URL in user DTO
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps |
1c4e75c243205ad47cd2e47a3d836c6c9e516db4 | pika/amqp_object.py | pika/amqp_object.py | """Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
def __repr__(self):
items = list()
fo... | """Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
INDEX = None
def __repr__(self):
items = ... | Add a few base attributes | Add a few base attributes
| Python | bsd-3-clause | reddec/pika,shinji-s/pika,fkarb/pika-python3,renshawbay/pika-python3,zixiliuyue/pika,skftn/pika,vitaly-krugl/pika,vrtsystems/pika,hugoxia/pika,knowsis/pika,Tarsbot/pika,Zephor5/pika,jstnlef/pika,benjamin9999/pika,pika/pika |
5830f5590ed185116dd4807f6351ad3afeb0dd5d | plugins/postgres/dbt/adapters/postgres/relation.py | plugins/postgres/dbt/adapters/postgres/relation.py | from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres... | from dbt.adapters.base import Column
from dataclasses import dataclass
from dbt.adapters.base.relation import BaseRelation
from dbt.exceptions import RuntimeException
@dataclass(frozen=True, eq=False, repr=False)
class PostgresRelation(BaseRelation):
def __post_init__(self):
# Check for length of Postgres... | Tweak error message, reformat for flake8 | Tweak error message, reformat for flake8
| Python | apache-2.0 | analyst-collective/dbt,analyst-collective/dbt |
82155f3caad1220eeb2ee718142c5aace8600f87 | django-jquery-file-upload/urls.py | django-jquery-file-upload/urls.py | from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'upload.views.home', name='home'),
url(r'^$', lamb... | from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'upload.views.home', name='home'),
url(r'^$', lamb... | Fix serve media files path | Fix serve media files path
| Python | mit | minhlongdo/django-jquery-file-upload,Imaginashion/cloud-vision,vaniakov/django-jquery-file-upload,indrajithi/mgc-django,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision,minhlongdo/django-jquery-file-upload,Imaginashion/cloud-vision,vaniakov/django-jquery-file-upload,Imaginashion/cloud-vision,sigurdga/django... |
67ab4b7374d739719700f84f0f5726f1b0c476d8 | cybox/test/objects/mutex_test.py | cybox/test/objects/mutex_test.py | import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
... | import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
... | Fix some more unittest assert methods for Python 2.6 | Fix some more unittest assert methods for Python 2.6
| Python | bsd-3-clause | CybOXProject/python-cybox |
578fe6f7403de0f93b3ca2776092e5dfe8dbfa73 | twisted/plugins/docker_xylem_plugin.py | twisted/plugins/docker_xylem_plugin.py | import yaml
from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.web import server
from docker_xylem import service
class Options(usage.Options):
optP... | import yaml
from zope.interface import implements
from twisted.python import filepath, usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.web import server
from docker_xylem import service
class Options(usage.Options)... | Create /run/docker/plugins before using it. (@bearnard) | Create /run/docker/plugins before using it. (@bearnard)
| Python | mit | praekeltfoundation/docker-xylem,praekeltfoundation/docker-xylem |
45ead09898275154919ab9589abb610d42049782 | website/apps/ts_om/views/ScenarioValidationView.py | website/apps/ts_om/views/ScenarioValidationView.py | import requests
from django.conf import settings
from django.http import HttpResponse
from django.views.generic.base import View
from website.apps.ts_om.check import check_url
def rest_validate(f):
validate_url = check_url(getattr(settings, "TS_OM_VALIDATE_URL", None), "validate")
response = requests.post(... | import requests
from django.conf import settings
from django.http import HttpResponse
from django.views.generic.base import View
from website.apps.ts_om.check import check_url
def rest_validate(f):
validate_url = check_url(getattr(settings, "TS_OM_VALIDATE_URL", None), "validate")
response = requests.post(... | Remove invalid staticmethod decorator from post method. | Fix: Remove invalid staticmethod decorator from post method.
| Python | mpl-2.0 | vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om |
861f2ea86e26fe27ba3f2f283c32ed0a9931c5fb | ce/analysis/core.py | ce/analysis/core.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s =... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s =... | Add preliminary ErrorAnalysis test case | Add preliminary ErrorAnalysis test case
| Python | mit | admk/soap |
e4345634ea6a4c43db20ea1d3d33134b6ee6204d | alembic/versions/151b2f642877_text_to_json.py | alembic/versions/151b2f642877_text_to_json.py | """text to JSON
Revision ID: 151b2f642877
Revises: aee7291c81
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'aee7291c81'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN info... | """text to JSON
Revision ID: 151b2f642877
Revises: ac115763654
Create Date: 2015-06-12 14:40:56.956657
"""
# revision identifiers, used by Alembic.
revision = '151b2f642877'
down_revision = 'ac115763654'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = 'ALTER TABLE project ALTER COLUMN in... | Fix alembic revision after merge master | Fix alembic revision after merge master
| Python | agpl-3.0 | OpenNewsLabs/pybossa,PyBossa/pybossa,PyBossa/pybossa,Scifabric/pybossa,jean/pybossa,geotagx/pybossa,OpenNewsLabs/pybossa,jean/pybossa,Scifabric/pybossa,geotagx/pybossa |
7e47ce789c9eb363f941ead2b3b199152dffff1c | pushmanager/tests/test_bookmarklet.py | pushmanager/tests/test_bookmarklet.py | import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
... | import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
... | Test added for the ticket tracker url. | Test added for the ticket tracker url.
The automatic test now checks also the ticket tracker url (just tests that
the javascript contains the word %TICKET%).
| Python | apache-2.0 | Yelp/pushmanager,YelpArchive/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,Yelp/pushmanager |
e5bec10f3788e435af63970158e35cb3f2ad4f2a | simple_faq/views.py | simple_faq/views.py | from django.views.generic import TemplateView
from simple_faq.models import Topic
class Topics(TemplateView):
template_name = "topics.html"
context_object_name = "topics"
model = Topic | from django.views.generic import ListView
from simple_faq.models import Topic
class Topics(ListView):
template_name = "topics.html"
context_object_name = "topics"
model = Topic | Fix father class of topics view | Fix father class of topics view
@15m
| Python | mit | devartis/django-simple-faq,devartis/django-simple-faq |
3fcdb9e64ef955fd0a7e5b2fda481d351dfb4d18 | spotify/__init__.py | spotify/__init__.py | from __future__ import unicode_literals
import os
import weakref
import cffi
__version__ = '2.0.0a1'
_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#in... | from __future__ import unicode_literals
import logging
import os
import weakref
import cffi
__version__ = '2.0.0a1'
# Log to nowhere by default. For details, see:
# http://docs.python.org/2/howto/logging.html#library-config
logging.getLogger('spotify').addHandler(logging.NullHandler())
_header_file = os.path.jo... | Add NullHandler to the 'spotify' logger | Add NullHandler to the 'spotify' logger
| Python | apache-2.0 | jodal/pyspotify,mopidy/pyspotify,kotamat/pyspotify,jodal/pyspotify,kotamat/pyspotify,felix1m/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,jodal/pyspotify |
65655186f22f1cdc4699cfbddb8b11ccf3ad292a | apps/challenge/forms.py | apps/challenge/forms.py | from django import forms
from django.contrib.admin import widgets
# Smrtr
from network.models import Network
from challenge.models import Challenge
# External
from haystack.forms import SearchForm
class ChallengeForm(forms.ModelForm):
class Meta:
model = Challenge
... | from django import forms
from django.contrib.admin import widgets
# Smrtr
from network.models import Network
from challenge.models import Challenge
# External
from haystack.forms import SearchForm
class ChallengeForm(forms.ModelForm):
class Meta:
model = Challenge
... | Improve search ordering in challenges (+packages) | Improve search ordering in challenges (+packages)
| Python | bsd-3-clause | mfitzp/smrtr,mfitzp/smrtr |
95bd5b96fcbc62133aac4045a77ed7b7e7d342a5 | pyhprof/__init__.py | pyhprof/__init__.py | from pyhprof import *
from pyhprof import __doc__
from pyhprof import __all__
| '''Library for parsing and analyzing Java hprof files
'''
from .parsers import HProfParser, HeapDumpParser | Include parsers in top level module | Include parsers in top level module
| Python | apache-2.0 | matthagy/pyhprof |
761ba162338b86bc16aa4b642cc51a297d5491d6 | games/notifier.py | games/notifier.py | from games import models
def get_unpublished_installers(count=10):
return models.Installer.objects.filter(published=False).order_by('?')[:count]
def get_unpublished_screenshots(count=10):
return models.Screenshot.objects.filter(published=False).order_by('?')[:count]
def get_unreviewed_game_submissions(cou... | from games import models
DEFAULT_COUNT = 12
def get_unpublished_installers(count=DEFAULT_COUNT):
return models.Installer.objects.filter(published=False).order_by('?')[:count]
def get_unpublished_screenshots(count=DEFAULT_COUNT):
return models.Screenshot.objects.filter(published=False).order_by('?')[:count]... | Set the default number of items to 12 because it fits more nicely on the email | Set the default number of items to 12 because it fits more nicely on the email
| Python | agpl-3.0 | lutris/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.