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 |
|---|---|---|---|---|---|---|---|---|---|
0fae7ce68a531b2c27e03a854fba3319d041ee45 | mezzanine/twitter/managers.py | mezzanine/twitter/managers.py |
from django.db.models import Manager
from mezzanine.utils.cache import cache_installed
class TweetManager(Manager):
"""
Manager that handles generating the initial ``Query`` instance
for a user, list or search term.
"""
def get_for(self, user_name=None, list_name=None, search_term=None):
... |
from django.db.models import Manager
class TweetManager(Manager):
"""
Manager that handles generating the initial ``Query`` instance
for a user, list or search term.
"""
def get_for(self, user_name=None, list_name=None, search_term=None):
"""
Create a query and run it for the giv... | Revert cache changes to Twitter queries - since authenticated users bypass the cache, and the Twitter call will generate a lot of queries. | Revert cache changes to Twitter queries - since authenticated users bypass the cache, and the Twitter call will generate a lot of queries.
| Python | bsd-2-clause | viaregio/mezzanine,promil23/mezzanine,biomassives/mezzanine,dekomote/mezzanine-modeltranslation-backport,sjuxax/mezzanine,AlexHill/mezzanine,dustinrb/mezzanine,ZeroXn/mezzanine,theclanks/mezzanine,theclanks/mezzanine,SoLoHiC/mezzanine,guibernardino/mezzanine,dekomote/mezzanine-modeltranslation-backport,emile2016/mezzan... |
2875a8e6c123d3d4f6039e7864ff66373c51daea | examples/signal_handlers/signal_handlers.py | examples/signal_handlers/signal_handlers.py | # -*- coding: utf-8 -*-
from riot.app import quit_app, run_tag
from riot.tags.style import parse_style
from riot.tags.tags import parse_tag_from_node
from riot.tags.utils import convert_string_to_node
from riot.virtual_dom import define_tag, mount
sig = define_tag('sig', '''
<sig>
<filler valign="top">
<pile>
... | # -*- coding: utf-8 -*-
from riot.app import quit_app, run_tag
from riot.tags.style import parse_style
from riot.tags.tags import parse_tag_from_node
from riot.tags.utils import convert_string_to_node
from riot.virtual_dom import define_tag, mount
sig = define_tag('sig', '''
<sig>
<filler valign="top">
<pile>
... | Remove useless code in signal handler example. | Remove useless code in signal handler example.
| Python | mit | soasme/riotpy |
79c0071b7aad2992011684428611701bc58a9bff | tests/__init__.py | tests/__init__.py | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import tornado.testing
import tornado.options
import celery
from flower.app import Flower
from flower.urls import handlers
from flower.events import Events
from flower.urls import settings
from flower import command # s... | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import tornado.testing
from tornado.options import options
import celery
import mock
from flower.app import Flower
from flower.urls import handlers
from flower.events import Events
from flower.urls import settings
from f... | Add an util funcion for mocking options | Add an util funcion for mocking options
| Python | bsd-3-clause | jzhou77/flower,asmodehn/flower,jzhou77/flower,asmodehn/flower,asmodehn/flower,jzhou77/flower |
4aad37d8186fab025ba29050620a929c167ca497 | pulsar/locks.py | pulsar/locks.py | try:
import lockfile
except ImportError:
lockfile = None
import threading
import logging
log = logging.getLogger(__name__)
NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, expect suboptimal Pulsar lock handling."
class LockManager():
def __init__(self, lockfile=lockfile):
if not lockfile:... | try:
import lockfile
except ImportError:
lockfile = None
import threading
import logging
log = logging.getLogger(__name__)
NO_PYLOCKFILE_MESSAGE = "pylockfile module not found, skipping experimental lockfile handling."
class LockManager():
def __init__(self, lockfile=lockfile):
if not lockfile... | Fix misleading message about pylockfile. | Fix misleading message about pylockfile.
| Python | apache-2.0 | ssorgatem/pulsar,natefoo/pulsar,natefoo/pulsar,ssorgatem/pulsar,galaxyproject/pulsar,galaxyproject/pulsar |
3f848be239d5fc4ae18d598250e90217b86e8fcf | pywikibot/_wbtypes.py | pywikibot/_wbtypes.py | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... | # -*- coding: utf-8 -*-
"""Wikibase data type classes."""
#
# (C) Pywikibot team, 2013-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import json
from pywikibot.tools import StringTypes
class WbRepresentation(object):
... | Add missing not-equal comparison for wbtypes | Add missing not-equal comparison for wbtypes
Bug: T158848
Change-Id: Ib6e992b7ed1c5b4b8feac205758bdbaebda2b09c
| Python | mit | hasteur/g13bot_tools_new,magul/pywikibot-core,jayvdb/pywikibot-core,Darkdadaah/pywikibot-core,happy5214/pywikibot-core,hasteur/g13bot_tools_new,magul/pywikibot-core,happy5214/pywikibot-core,wikimedia/pywikibot-core,npdoty/pywikibot,wikimedia/pywikibot-core,jayvdb/pywikibot-core,npdoty/pywikibot,Darkdadaah/pywikibot-cor... |
aa5bc77e78e82fbe63acf2fd8f6764a420f2e4e8 | simuvex/procedures/stubs/caller.py | simuvex/procedures/stubs/caller.py |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
def run(self, target_addr=None):
self.call(target_addr, [ ], self.after_call)
... |
import simuvex
######################################
# Caller
######################################
class Caller(simuvex.SimProcedure):
"""
Caller stub. Creates a Ijk_Call exit to the specified function
"""
NO_RET = True
def run(self, target_addr=None):
self.call(target_addr, [ ], se... | Make sure Caller does not return | Make sure Caller does not return
| Python | bsd-2-clause | axt/angr,chubbymaggie/angr,iamahuman/angr,tyb0807/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,iamahuman/angr,schieb/angr,angr/angr,angr/simuvex,iamahuman/angr,chubbymaggie/angr,axt/angr,angr/angr,chubbymaggie/simuvex,tyb0807/angr,angr/angr,f-prettyland/angr,f-prettyland/angr,axt/angr,schieb/angr,chubbymaggie/simuve... |
47348a032bf86aac563dca41703f1e39d03b2360 | aplpy/header.py | aplpy/header.py | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
crpixy = header['CRPIX%i' % iy]
cdelty = header['CDELT%i' % iy]
# Check for CRVAL2!... | from __future__ import absolute_import
def check(header, convention=None, dimensions=[0, 1]):
ix = dimensions[0] + 1
iy = dimensions[1] + 1
ctypex = header['CTYPE%i' % ix]
crvaly = header['CRVAL%i' % iy]
# Check for CRVAL2!=0 for CAR projection
if ctypex[4:] == '-CAR' and crvaly != 0:
... | Fix check for Wells/Calabretta convention | Fix check for Wells/Calabretta convention | Python | mit | mwcraig/aplpy,allisony/aplpy |
11abf077a8c429825c2ba55e42ffa590448da502 | examples/django_app/tests/test_settings.py | examples/django_app/tests/test_settings.py | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... | from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
... | Fix unit tests for Django 1.8 | Fix unit tests for Django 1.8
| Python | bsd-3-clause | vkosuri/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot |
9836c275d79851010654aacda379ccb78cea1b27 | chartflo/engine.py | chartflo/engine.py | import pandas as pd
from goerr import err
from dataswim import DataSwim
from django.db.models.query import QuerySet
from django_pandas.io import read_frame
class ChartFlo(DataSwim):
def __repr__(self):
"""
String representation of the object
"""
rows = str(len(self.df.columns))
... | from dataswim import DataSwim
class ChartFlo(DataSwim):
def __repr__(self):
"""
String representation of the object
"""
rows = str(len(self.df.columns))
return '<Chartflo object - ' + rows + " >"
cf = ChartFlo()
| Move the load_data method to the Dataswim lib | Move the load_data method to the Dataswim lib
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo |
b28dd26792be9125d2fd3d5657431bc6ee7a5470 | lobster/cmssw/actions.py | lobster/cmssw/actions.py | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | Add message in log with plotting process id. | Add message in log with plotting process id.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
6e76b51f5aa1c5ae54130f52e176195a992284aa | src/core/monkeypatch.py | src/core/monkeypatch.py | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the jo... | Update for janeway's monkey patch. | Update for janeway's monkey patch.
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway |
986b15b5f33ebf25b26f40645378174bb66f1898 | gerberlicious.py | gerberlicious.py |
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.ren... |
"""
gerberlicious, a python library for programmatically generating Gerber files
Example script.
"""
from gerberlicious.point import Point
from gerberlicious.layer import Layer
from gerberlicious.aperture import CircleAperture
from gerberlicious.drawable import PointList, ApertureFlash
from gerberlicious.ren... | Rename 'square' to 'path' in example script | Rename 'square' to 'path' in example script
| Python | mit | deveah/gerberlicious |
ed667175f4961bbc7cc823657a5dd80f35ed9593 | organizer/migrations/0002_tag_data.py | organizer/migrations/0002_tag_data.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
TAGS = (
# ( tag name, tag slug ),
("augmented reality", "augmented-reality"),
("big data", "big-data"),
("django", "django"),
("education", "education"),
("ipython", "ipython"),
("java... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
TAGS = (
# ( tag name, tag slug ),
("augmented reality", "augmented-reality"),
("big data", "big-data"),
("django", "django"),
("education", "education"),
("ipython", "ipython"),
("java... | Optimize addition of Tag data in migration. | Ch26: Optimize addition of Tag data in migration.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
cb17da3fbd819a386446bc2af42e38f8c95bc392 | blango/forms.py | blango/forms.py | from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the ... | from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the ... | Fix UserCommentForm(), which got broken in the previous commit. | Fix UserCommentForm(), which got broken in the previous commit.
| Python | bsd-3-clause | fiam/blangoblog,fiam/blangoblog,fiam/blangoblog |
c78d9c63238b5535b1881f4eee54700f5a138b04 | lupa/__init__.py | lupa/__init__.py |
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
import DLFCN
dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
except ImportError:
... | from __future__ import absolute_import
# We need to enable global symbol visibility for lupa in order to
# support binary module loading in Lua. If we can enable it here, we
# do it temporarily.
def _try_import_with_global_library_symbols():
try:
from os import RTLD_NOW, RTLD_GLOBAL
except ImportErr... | Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2. | Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
| Python | mit | pombredanne/lupa,pombredanne/lupa |
fc2c3ec6680e8c1102a336ec0f6bde7db32d2070 | tests/tools/assigner/test_arguments.py | tests/tools/assigner/test_arguments.py | import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err... | import inspect
import sys
import unittest
from contextlib import contextmanager
import kafka.tools.assigner.actions
from kafka.tools.assigner.arguments import set_up_arguments
from kafka.tools.assigner.modules import get_modules
from kafka.tools.assigner.plugins import PluginModule
@contextmanager
def redirect_err... | Call the CM to mask stderr output properly | Call the CM to mask stderr output properly
| Python | apache-2.0 | toddpalino/kafka-tools |
1cc044e601dc6b6d2a5f62c7557a6cd2d5b50986 | homepage/views.py | homepage/views.py | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
if not uid:
uid, data = api.create_new_user()
else:
data = api.get_saved_cities(uid)
resp... | from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api
def index(request):
uid = request.COOKIES.get("uid")
data = None
if not uid:
uid, _ = api.create_new_user()
else:
data = api.get_saved_cities(u... | Fix create user in homepage view. | Fix create user in homepage view.
api.create_new_user is returning the newly created user record, so we can't pass that as data to the template.
| Python | mit | c17r/tsace,c17r/tsace,c17r/tsace |
c755934a9bc9f15f1e7dcf6d337c3dd3acf4e824 | checks/check_solarize.py | checks/check_solarize.py | import imgaug as ia
import imgaug.augmenters as iaa
def main():
image = ia.quokka_square((128, 128))
images_aug = iaa.Solarize(1.0)(images=[image] * (5*5))
ia.imshow(ia.draw_grid(images_aug))
if __name__ == "__main__":
main()
| from __future__ import print_function, division, absolute_import
import imgaug as ia
import imgaug.augmenters as iaa
import timeit
def main():
for size in [64, 128, 256, 512, 1024]:
for threshold in [64, 128, 192]:
time_iaa = timeit.timeit(
"iaa.solarize(image, %d)" % (threshol... | Add performance comparison with PIL | Add performance comparison with PIL
| Python | mit | aleju/ImageAugmenter,aleju/imgaug,aleju/imgaug |
418be2bfa0f902183b607fa402da75c09bf7e6db | hug/decorators.py | hug/decorators.py | from functools import wraps
from collections import OrderedDict
import sys
def call(url, methods=('ALL', )):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('API_CALLS', OrderedDict())
for method in method... | from functools import wraps
from collections import OrderedDict
import sys
from falcon import HTTP_METHODS
def call(url, methods=HTTP_METHODS):
def decorator(api_function):
module = sys.modules[api_function.__name__]
api_definition = sys.modules['hug.hug'].__dict__.setdefault('HUG_API_CALLS', Ord... | Use falcon methods as HTTP methods | Use falcon methods as HTTP methods
| Python | mit | STANAPO/hug,shaunstanislaus/hug,shaunstanislaus/hug,timothycrosley/hug,philiptzou/hug,janusnic/hug,timothycrosley/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,jean/hug,giserh/hug,origingod/hug,janusnic/hug,yasoob/hug,gbn972/hug,MuhammadAlkarouri/hug,jean/hug,giserh/hug,timothycrosley/hug,gbn972/hug,alisaifee/hug,yas... |
edcf561564a8fe30c80bda750ec0770c5e854ce8 | Code/Python/Kamaelia/Examples/Backplane/Forwarding.py | Code/Python/Kamaelia/Examples/Backplane/Forwarding.py | #!/usr/bin/python
import time
import Axon
from Kamaelia.Util.Backplane import *
from Kamaelia.Util.Console import *
from Kamaelia.Chassis.Pipeline import Pipeline
class Source(Axon.ThreadedComponent.threadedcomponent):
value = 1
sleep = 1
def main(self):
while 1:
self.send(str(self.val... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ver... | Change license to Apache 2 | Change license to Apache 2 | Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia |
6610648c75dc90800655a3502d4cd24fb47ac406 | timpani/webserver/webserver.py | timpani/webserver/webserver.py | import flask
import os.path
import datetime
import urllib.parse
from .. import database
from .. import configmanager
from . import controllers
FILE_LOCATION = os.path.abspath(os.path.dirname(__file__))
STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static"))
CONFIG_PATH = os.path.abspath(os.path.join... | import flask
import os.path
import datetime
import urllib.parse
from .. import database
from .. import configmanager
from . import controllers
FILE_LOCATION = os.path.abspath(os.path.dirname(__file__))
STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static"))
CONFIG_PATH = os.path.abspath(os.path.join... | Remove session cookie print in teardown | Remove session cookie print in teardown
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani |
9793107fb218bdff796d8df55404156e299e33ea | website/apps/ts_om/check.py | website/apps/ts_om/check.py | import os
from django.conf import settings
__author__ = 'nreed'
url_dict = {
'validate': 'http://127.0.0.1:8000/om_validate/validate/',
'scenarios': '/home/nreed/scenarios/',
'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/'
}
def check_dir(local_dir, typ):
if local_dir is ... | import os
from django.conf import settings
__author__ = 'nreed'
url_dict = {
'validate': 'http://127.0.0.1:8000/om_validate/validate/',
'scenarios': getattr(settings, "PROJECT_ROOT", '') + '/scenarios/',
'openmalaria': getattr(settings, "PROJECT_ROOT", '') + '/om_validate/bin/'
}
def check_dir(local_di... | Set default scenarios directory to within root of project. | Set default scenarios directory to within root of project.
| Python | mpl-2.0 | vecnet/om,vecnet/om,vecnet/om,vecnet/om,vecnet/om |
b04a01f451b2fe0348af217e9eed905b552cf1cf | lc0201_bitwise_and_of_numbers_range.py | lc0201_bitwise_and_of_numbers_range.py | """Leetcode 201. Bitwise AND of Numbers Range
Medium
URL: https://leetcode.com/problems/bitwise-and-of-numbers-range/
Given a range [m, n] where 0 <= m <= n <= 2147483647,
return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
"""
class ... | """Leetcode 201. Bitwise AND of Numbers Range
Medium
URL: https://leetcode.com/problems/bitwise-and-of-numbers-range/
Given a range [m, n] where 0 <= m <= n <= 2147483647,
return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7]
Output: 4
Example 2:
Input: [0,1]
Output: 0
"""
class ... | Revise class name and add time/space complexity | Revise class name and add time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
d10344dce7d012de2d434cd205fb0f179e34113c | packages/syft/src/syft/core/tensor/types.py | packages/syft/src/syft/core/tensor/types.py | # relative
from .passthrough import AcceptableSimpleType # type: ignore
from .passthrough import PassthroughTensor # type: ignore
from .passthrough import SupportedChainType # type: ignore
| from .passthrough import AcceptableSimpleType # type: ignore # NOQA
from .passthrough import PassthroughTensor # type: ignore # NOQA
from .passthrough import SupportedChainType # type: ignore # NOQA
| Fix flake8 warning by adding flake annotation | Fix flake8 warning by adding flake annotation
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
c576acc020e60e704dad55f8cd281c4ebb26ad28 | plenario/apiary/views.py | plenario/apiary/views.py | from flask import Blueprint, request
from json import dumps, loads
from redis import Redis
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis(REDIS_HOST_SAFE)
@blueprint.route("/apiary/send_message", methods=["POST"])
def send_message():
try:
data = lo... | from collections import defaultdict
from json import dumps, loads
from traceback import format_exc
from flask import Blueprint, make_response, request
from redis import Redis
from plenario.auth import login_required
from plenario.settings import REDIS_HOST_SAFE
blueprint = Blueprint("apiary", __name__)
redis = Redis... | Add a rudimentary view for tracking mapper errors | Add a rudimentary view for tracking mapper errors
| Python | mit | UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario,UrbanCCD-UChicago/plenario |
6b6181f1c2f902f20da440eb3bedb5d02ecfbf16 | angr/engines/soot/expressions/cast.py | angr/engines/soot/expressions/cast.py |
from .base import SimSootExpr
from archinfo import ArchSoot
import logging
l = logging.getLogger("angr.engines.soot.expressions.cast")
class SimSootExpr_Cast(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Cast, self).__init__(expr, state)
def _execute(self):
if self.expr.... |
from .base import SimSootExpr
from archinfo import ArchSoot
import logging
l = logging.getLogger("angr.engines.soot.expressions.cast")
class SimSootExpr_Cast(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Cast, self).__init__(expr, state)
def _execute(self):
if self.expr.... | Use correct dict for the type sizes | Use correct dict for the type sizes
| Python | bsd-2-clause | iamahuman/angr,iamahuman/angr,iamahuman/angr,angr/angr,schieb/angr,schieb/angr,angr/angr,schieb/angr,angr/angr |
bb0fae91cc0ce067a0e331bc953c7130be4e41c8 | neuroimaging/externals/pynifti/nifti/__init__.py | neuroimaging/externals/pynifti/nifti/__init__.py |
from niftiimage import NiftiImage
| """
Nifti
=====
Python bindings for the nifticlibs. Access through the NiftiImage class.
See help for pyniftiio.nifti.NiftiImage
"""
from niftiimage import NiftiImage
| Add doc for pynifti package. | DOC: Add doc for pynifti package. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD |
2864441be365beb40e0396b444f8d96af8d7d92e | aleph/logic/documents.py | aleph/logic/documents.py | import os
import logging
from aleph.core import db, archive
from aleph.model import Document
from aleph.queues import ingest_entity
log = logging.getLogger(__name__)
def crawl_directory(collection, path, parent=None):
"""Crawl the contents of the given path."""
content_hash = None
if not path.is_dir():
... | import os
import logging
from servicelayer.jobs import Job
from aleph.core import db, archive
from aleph.model import Document
from aleph.queues import ingest_entity
log = logging.getLogger(__name__)
def crawl_directory(collection, path, parent=None, job_id=None):
"""Crawl the contents of the given path."""
... | Make stable job IDs in ingest runs | Make stable job IDs in ingest runs
| Python | mit | alephdata/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph |
ae2f1014bbe83d64f17fee6a9ebd2c12cdc9a1bf | app/main/errors.py | app/main/errors.py | from flask import render_template
from app.main import main
@main.app_errorhandler(400)
def bad_request(e):
return render_template("errors/500.html",
**main.config['BASE_TEMPLATE_DATA']), 400
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("errors/404.htm... | from flask import render_template
from app.main import main
from dmutils.apiclient import APIError
@main.app_errorhandler(APIError)
def api_error(e):
return _render_error_template(e.status_code)
@main.app_errorhandler(400)
def bad_request(e):
return _render_error_template(400)
@main.app_errorhandler(404)
... | Add APIError flask error handler | Add APIError flask error handler
This is modelled after the similar change in the supplier frontend
https://github.com/alphagov/digitalmarketplace-supplier-frontend/commit/233f8840d55cadb9fb7fe60ff12c53b0f59f23a5
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend |
3cf44a081f6dc824e1ff0639f424c0502fa6fe39 | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
help='Set the value for the fixture "bar".'
)
@pytest.fixture
def bar(request):
return re... | # -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store',
dest='foo',
default={{cookiecutter.year}},
help='Set the value for the fixture "bar".'
)
@pytest.... | Add a default to the foo option | Add a default to the foo option
| Python | mit | s0undt3ch/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin |
095d8d0136ff3942a9fcc76564a61e17dae56b71 | goldprice.py | goldprice.py | #!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it an... | #!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it an... | Fix breakage. The website is looking for user-agent header | Fix breakage. The website is looking for user-agent header
| Python | agpl-3.0 | sharuzzaman/sharuzzaman-code-repo.maybank-gia-rate |
a510d20cebe2aff86a6bf842d063b5df8937a7ec | raven/contrib/pylons/__init__.py | raven/contrib/pylons/__init__.py | """
raven.contrib.pylons
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from raven.middleware import Sentry as Middleware
from raven.base import Client
class Sentry(Middleware):
def __init__(self, app, config):
... | """
raven.contrib.pylons
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from raven.middleware import Sentry as Middleware
from raven.base import Client
def list_from_setting(config, setting):
value = config.get(setting)... | Update site and project names for pylons integration. Fix behavior of empty lists. Add DSN. | Update site and project names for pylons integration. Fix behavior of empty lists. Add DSN.
| Python | bsd-3-clause | tarkatronic/opbeat_python,tarkatronic/opbeat_python,inspirehep/raven-python,ticosax/opbeat_python,jbarbuto/raven-python,jmagnusson/raven-python,ronaldevers/raven-python,akalipetis/raven-python,collective/mr.poe,patrys/opbeat_python,arthurlogilab/raven-python,percipient/raven-python,inspirehep/raven-python,ronaldevers/r... |
a3570205c90dd8757a833aed4f4069fbd33028e0 | course/views.py | course/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from mainmodels.models import Category, Course, CourseInCategory
from django.contrib.auth.models import User
# Create your views here.
def createCourse(req):
if req.method == 'POST':
try:
courseName ... | from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from mainmodels.models import Category, Course, CourseInCategory
# Create your views here.
def createCourse(req):
if req.method == 'POST':
try:
courseName = req.POST['courseName']
courseC... | Remove fixed owner and make loged in user instead | Remove fixed owner and make loged in user instead
| Python | apache-2.0 | PNNutkung/Coursing-Field,PNNutkung/Coursing-Field,PNNutkung/Coursing-Field |
6f7890c8b29670f613b6a551ebac2b383f3a7a64 | tests/test_recipes.py | tests/test_recipes.py | import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
... | import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
from fixtures import yeast
class TestRecipe(unittest.TestCase):
def setUp(self):
... | Test units mismatch in recipe | Test units mismatch in recipe
| Python | mit | chrisgilmerproj/brewday,chrisgilmerproj/brewday |
931a858dc1cfde1652d21e1ccd60a82dde683ce3 | moxie/butterfield.py | moxie/butterfield.py | import os
import json
import asyncio
from butterfield.utils import at_bot
from aiodocker import Docker
from aiocore import Service
WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888")
@asyncio.coroutine
def events(bot):
docker = Docker()
events = docker.events
events.saferun()
stream... | import os
import json
import asyncio
from butterfield.utils import at_bot
from aiodocker import Docker
from aiocore import Service
WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888")
@asyncio.coroutine
def events(bot):
docker = Docker()
events = docker.events
events.saferun()
stream... | Add simple "yo" bot command | Add simple "yo" bot command
| Python | mit | paultag/moxie,loandy/moxie,mileswwatkins/moxie,mileswwatkins/moxie,paultag/moxie,loandy/moxie,loandy/moxie,paultag/moxie,rshorey/moxie,rshorey/moxie,rshorey/moxie,mileswwatkins/moxie |
69baf66b13331d5936e8c540a2bb7eccb1d64cb7 | invoice/views.py | invoice/views.py | from django.shortcuts import get_object_or_404
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
| from django.shortcuts import get_object_or_404
from invoice.models import Invoice
from invoice.pdf import draw_pdf
from invoice.utils import pdf_response
def pdf_view(request, pk):
invoice = get_object_or_404(Invoice, pk=pk)
return pdf_response(draw_pdf, invoice.file_name(), invoice)
def pdf_user_view(reque... | Add view for user to download invoice | Add view for user to download invoice
| Python | bsd-3-clause | Chris7/django-invoice,Chris7/django-invoice,simonluijk/django-invoice |
f7b351a43d99a6063c49dfdf8db60c654fd89b74 | scrapi/processing/postgres.py | scrapi/processing/postgres.py | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webview.settings")
import logging
from api.webview.models import Document
from scrapi import events
from scrapi.processing.base import BaseProcessor
logger = logging.getLogger(__name__)
class PostgresProcessor(BasePr... | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webview.settings")
import django
import logging
from api.webview.models import Document
from scrapi import events
from scrapi.processing.base import BaseProcessor
django.setup()
logger = logging.getLogger(__name__)
... | Add django setup for some initialization | Add django setup for some initialization
| Python | apache-2.0 | CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi,felliott/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi |
0ea1153438c1d98232a921c8d14d401a541e95fd | examples/regex/regex_parser.py | examples/regex/regex_parser.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from parser_base import RegexParser
import model
class RegexSemantics(object):
def __init__(self):
super(RegexSemantics, self).__init__()
self._count = 0
def START(self, ast):
re... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from parser_base import RegexParser
import model
class RegexSemantics(object):
def __init__(self):
super(RegexSemantics, self).__init__()
self._count = 0
def START(self, ast):
re... | Fix regex example, the model must not be a unicode string. | Fix regex example, the model must not be a unicode string.
| Python | bsd-2-clause | vmuriart/grako,frnknglrt/grako |
fcd85a1b15ca8b82f892bba171c21f9a1b4f6e4a | SOAPpy/tests/alanbushTest.py | SOAPpy/tests/alanbushTest.py | #!/usr/bin/env python
# Copyright (c) 2001 actzero, inc. All rights reserved.
import sys
sys.path.insert (1, '..')
import SOAP
ident = '$Id$'
SoapEndpointURL = 'http://www.alanbushtrust.org.uk/soap/compositions.asp'
MethodNamespaceURI = 'urn:alanbushtrust-org-uk:soap:methods'
SoapAction = MethodNamespaceURI + ... | #!/usr/bin/env python
# Copyright (c) 2001 actzero, inc. All rights reserved.
import sys
sys.path.insert (1, '..')
import SOAP
ident = '$Id$'
SoapEndpointURL = 'http://www.alanbushtrust.org.uk/soap/compositions.asp'
MethodNamespaceURI = 'urn:alanbushtrust-org-uk:soap.methods'
SoapAction = MethodNamespaceURI + ... | Correct URI and list categories | Correct URI and list categories
git-svn-id: c4afb4e777bcbfe9afa898413b708b5abcd43877@69 7150bf37-e60d-0410-b93f-83e91ef0e581
| Python | mit | acigna/pywez,acigna/pywez,acigna/pywez |
c5970991ed2d3285e6a3ef9badb6e73756ff876b | tests/test_session.py | tests/test_session.py | # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock... | # Local imports
from uplink import session
def test_base_url(uplink_builder_mock):
# Setup
uplink_builder_mock.base_url = "https://api.github.com"
sess = session.Session(uplink_builder_mock)
# Run & Verify
assert uplink_builder_mock.base_url == sess.base_url
def test_headers(uplink_builder_mock... | Fix `assert_called` usage for Python 3.5 build | Fix `assert_called` usage for Python 3.5 build
The `assert_called` method seems to invoke a bug caused by a type in the
unittest mock module. (The bug was ultimately tracked and fix here:
https://bugs.python.org/issue24656)
| Python | mit | prkumar/uplink |
d635fc9129bc4ccfd5384be6958ae1c14e9916ec | scripts/merge_translations.py | scripts/merge_translations.py | import sys
import yaml
def main(base_file, new_file, overwrite_language):
old = yaml.load(file(base_file).read())
new = yaml.load(file(new_file).read())
assert len(overwrite_language) == 2
for o, n in zip(old, new):
if overwrite_language in n['text']:
o['text'][overwrite_languag... | import sys
import yaml
def persona(old, new, overwrite_language):
old_t = old['translations']
new_t = new['translations']
for key in old_t:
if key in new_t and overwrite_language in new_t[key]:
old_t[key][overwrite_language] = new_t[key][overwrite_language]
def questions(old, new, ... | Add persona merging to translation merge script | Add persona merging to translation merge script | Python | mit | okfde/eucopyright,okfde/eucopyright,okfde/eucopyright |
03a78a509c0213f8f95223a7926a1bce547f05fe | rotterdam/proc.py | rotterdam/proc.py | import logging
import os
import signal
from setproctitle import setproctitle
class Proc(object):
signal_map = {}
def __init__(self):
self.logger = logging.getLogger(self.__module__)
self.pid = None
@property
def name(self):
return self.__class__.__name__.lower()
def s... | import logging
import os
import signal
from setproctitle import setproctitle
class Proc(object):
signal_map = {}
def __init__(self):
self.logger = logging.getLogger(self.__module__)
self.pid = None
self.parent_pid = None
@property
def name(self):
return self.__clas... | Initialize parent_pid in the Proc class init. | Initialize parent_pid in the Proc class init.
| Python | mit | wglass/rotterdam |
ce6a3a3833d498fa32a5317fd95e206cad9d5a83 | alg_gcd.py | alg_gcd.py | def gcd(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
"""
while n != 0:
m, n = n, m % n
return m
def main():
print(gcd(4, 2))
print(gcd(2, 4))
print(gcd(10, 4))
print(gcd(4, 10))
print(gcd(10, 1))
print(gcd(1, 10))
if _... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def gcd(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
"""
while n != 0:
m, n = n, m % n
return m
def main():
print('gcd(4, 2): {}'.f... | Add importing from __future__ & revise main() | Add importing from __future__ & revise main()
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
0b45ec48955f73a0e88422660af82ff6fd89333b | tools/crons/newwoz.py | tools/crons/newwoz.py | import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
print("NEW WOZZT TEST")
from museum_site.wozzt_queue import WoZZT_Queue # noqa: E402
def main():
entry = WoZZT_Queue.objects.all().order_by("-priority", "id")[0]
entry.send_tweet()
entry.delete_... | import os
import django
from datetime import datetime
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
from museum_site.wozzt_queue import WoZZT_Queue # noqa: E402
def main():
now = datetime.now()
if now.weekday() == 1: # Tuesday
entry = WoZZT_Queue.objects.filt... | Use Tuesday branch on Tuesdays | Use Tuesday branch on Tuesdays
| Python | mit | DrDos0016/z2,DrDos0016/z2,DrDos0016/z2 |
ed89c92ac56e89648bf965ea3aa8963e840e3a5c | tests/test_excuses.py | tests/test_excuses.py | # Copyright 2017 Starbot Discord Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2017 Starbot Discord Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Fix the unit test :) | Fix the unit test :)
| Python | apache-2.0 | StarbotDiscord/Starbot,dhinakg/BitSTAR,StarbotDiscord/Starbot,dhinakg/BitSTAR |
38749a0033c2acc6c9fd8971749c68f93cb9c0db | virtualenv/__init__.py | virtualenv/__init__.py | from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license... | from __future__ import absolute_import, division, print_function
from virtualenv.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
from virtualenv.core import create
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__aut... | Add virtualenv.create function to enable easy virtualenv creation | Add virtualenv.create function to enable easy virtualenv creation
| Python | mit | ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv |
e521b16844efc2853c0db9014098cb3e37f6eb04 | numpy/_array_api/_sorting_functions.py | numpy/_array_api/_sorting_functions.py | def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(r... | def argsort(x, /, *, axis=-1, descending=False, stable=True):
from .. import argsort
from .. import flip
# Note: this keyword argument is different, and the default is different.
kind = 'stable' if stable else 'quicksort'
res = argsort(x, axis=axis, kind=kind)
if descending:
res = flip(r... | Add missing returns to the array API sorting functions | Add missing returns to the array API sorting functions
| Python | bsd-3-clause | jakirkham/numpy,numpy/numpy,mhvk/numpy,seberg/numpy,pdebuyl/numpy,numpy/numpy,numpy/numpy,jakirkham/numpy,anntzer/numpy,charris/numpy,simongibbons/numpy,endolith/numpy,simongibbons/numpy,mhvk/numpy,seberg/numpy,mattip/numpy,mattip/numpy,jakirkham/numpy,mhvk/numpy,charris/numpy,seberg/numpy,simongibbons/numpy,pdebuyl/nu... |
f3cc2de83c88f01f7ec554ae6223132c284b4ad4 | kotti_site_gallery/__init__.py | kotti_site_gallery/__init__.py | from fanstatic import Library
from fanstatic import Resource
from kotti.resources import Image
import kotti.static as ks
lib_kotti_site_gallery = Library('kotti_site_gallery', 'static')
view_css = Resource(lib_kotti_site_gallery,
"kotti_site_gallery.css",
minified="kotti_site_g... | from __future__ import absolute_import
from fanstatic import Library
from fanstatic import Resource
from kotti.resources import Image
from kotti.fanstatic import view_css
from kotti.fanstatic import view_needed
lib_kotti_site_gallery = Library('kotti_site_gallery', 'static')
ksg_view_css = Resource(lib_kotti_site_ga... | Fix import for Kotti > 0.8x. | Fix import for Kotti > 0.8x.
| Python | bsd-2-clause | Kotti/kotti_site_gallery,Kotti/kotti_site_gallery |
a4c5782158e7d3fa696fc4532836355457f48cc0 | versebot/webparser.py | versebot/webparser.py | """
VerseBot for reddit
By Matthieu Grieger
parser.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 attrib... | """
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... | Add note about BibleGateway layout | Add note about BibleGateway layout
| Python | mit | Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot |
41b5a95a5c396c131d1426dd926e0a1a4beccc86 | mrp_workorder_sequence/models/mrp_production.py | mrp_workorder_sequence/models/mrp_production.py | # Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class MrpProduction(models.Model):
_inherit = "mrp.production"
def _reset_work_order_sequence(self):
for rec in self:
current_seque... | # Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class MrpProduction(models.Model):
_inherit = "mrp.production"
def _reset_work_order_sequence(self):
for rec in self:
current_seque... | Call method changed on v14 | [FIX] mrp_workorder_sequence: Call method changed on v14
| Python | agpl-3.0 | OCA/manufacture,OCA/manufacture |
54b147e59d1dfd4b65643a3f8a56098eb5a99451 | tests/kafka_cluster_manager/decommission_test.py | tests/kafka_cluster_manager/decommission_test.py | from __future__ import unicode_literals
from argparse import Namespace
import mock
import pytest
from kafka_utils.kafka_cluster_manager.cluster_info \
.partition_count_balancer import PartitionCountBalancer
from kafka_utils.kafka_cluster_manager.cmds import decommission
from tests.kafka_cluster_manager.helper im... | from __future__ import unicode_literals
from argparse import Namespace
import mock
import pytest
from kafka_utils.kafka_cluster_manager.cluster_info \
.partition_count_balancer import PartitionCountBalancer
from kafka_utils.kafka_cluster_manager.cmds import decommission
from tests.kafka_cluster_manager.helper im... | Add more default args so tests pass in py3+ | Add more default args so tests pass in py3+
| Python | apache-2.0 | Yelp/kafka-utils,Yelp/kafka-utils |
159aea1c97b8e8de45802cace031e7206c3c8fec | thecure/sprites/tile.py | thecure/sprites/tile.py | from thecure.resources import load_spritesheet_frame
from thecure.sprites import Sprite
class Tile(Sprite):
NAME = 'tile'
WIDTH = 64
HEIGHT = 64
NEED_TICKS = False
def __init__(self, filename, tile_offset):
super(Tile, self).__init__()
self.filename = filename
self.tile_... | from thecure.resources import load_spritesheet_frame
from thecure.sprites import Sprite
class Tile(Sprite):
NAME = 'tile'
WIDTH = 64
HEIGHT = 64
NEED_TICKS = False
def __init__(self, filename, tile_offset):
super(Tile, self).__init__()
self.filename = filename
self.tile_... | Add a __str__ for Tile. | Add a __str__ for Tile.
| Python | mit | chipx86/the-cure |
def66bc381f03970640a61d64b49ad5de9ef3879 | ocaml/build-in.py | ocaml/build-in.py | # Needed because ocamlbuild 3.12.1 doesn't support absolute pathnames (4.00.1 does)
import sys
import os
from os.path import relpath
ocaml_build_dir = relpath(sys.argv[1], '.')
os.execvp("make", ["make", 'OCAML_BUILDDIR=' + ocaml_build_dir, "ocaml"])
| # Needed because ocamlbuild 3.12.1 doesn't support absolute pathnames (4.00.1 does)
import sys
import os
from os.path import relpath
ocaml_build_dir = relpath(sys.argv[1], '.')
# Hack: when we can depend on a full OCaml feed with the build tools, we can remove this.
# Until then, we need to avoid trying to compile aga... | Remove OCAMLLIB from build environment | Remove OCAMLLIB from build environment
This is a temporary hack: when we can depend on a full OCaml feed with
the build tools, we can remove this. Until then, we need to avoid trying
to compile against the limited runtime environment.
| Python | lgpl-2.1 | 0install/0install,afb/0install,afb/0install,afb/0install,gasche/0install,bastianeicher/0install,bhilton/0install,fdopen/0install,gasche/0install,0install/0install,jaychoo/0install,dbenamy/0install,gfxmonk/0install,jaychoo/0install,dbenamy/0install,DarkGreising/0install,bastianeicher/0install,fdopen/0install,bhilton/0in... |
b297ad6b4d52b688a1c50ffc2a5574d8061c5ce0 | csvdiff/records.py | csvdiff/records.py | # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import csv
class InvalidKeyError(Exception):
pass
def load(file_or_stream):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
return csv.DictReader(istream)
def index(record_s... | # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import csv
from . import error
class InvalidKeyError(Exception):
pass
def load(file_or_stream):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
return _safe_iterator(csv.Dict... | Check for errors parsing the CSV as we go. | Check for errors parsing the CSV as we go.
When rows bleed into each other, we can get keys that are None in the records.
Now we get a user error in this case.
| Python | bsd-3-clause | larsyencken/csvdiff |
75e65f6144820ba216166eee4417912394f8cdca | tools/bundle.py | tools/bundle.py | #!/usr/bin/env python
import os
import sys
import glob
import getopt
def file_list(path):
files = []
if os.path.isfile(path):
return [path]
for f in os.listdir(path):
new_dir = os.path.join(path, f)
if os.path.isdir(new_dir) and not os.path.islink(new_dir):
files.extend(file_list(new_dir))
... | #!/usr/bin/env python
import os
import sys
import glob
import getopt
def file_list(path):
files = []
if os.path.isfile(path):
return [path]
for f in os.listdir(path):
new_dir = path + '/' + f
if os.path.isdir(new_dir) and not os.path.islink(new_dir):
files.extend(file_list(new_dir))
else... | Stop using os.path.join, because Visual Studio can actually handle forward slash style paths, and the os.path method was creating mixed \\ and / style paths, b0rking everything. | Stop using os.path.join, because Visual Studio can actually handle forward
slash style paths, and the os.path method was creating mixed \\ and /
style paths, b0rking everything.
| Python | apache-2.0 | kans/birgo,kans/birgo,kans/birgo,kans/birgo,kans/birgo |
e7356e6ca1968d930f4fd348b48dcdd1cb9a02ab | taggit/admin.py | taggit/admin.py | from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
extra = 0
class TagAdmin(admin.ModelAdmin):
inlines = [
TaggedItemInline
]
ordering = ['name']
admin.site.register(Tag, TagAdmin)
| from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
extra = 0
class TagAdmin(admin.ModelAdmin):
inlines = [
TaggedItemInline
]
ordering = ['name']
search_fields = ['name']
admin.site.register(Tag,... | Add ability to search tags by name | Add ability to search tags by name | Python | bsd-3-clause | theatlantic/django-taggit2,decibyte/django-taggit,theatlantic/django-taggit,decibyte/django-taggit,theatlantic/django-taggit,theatlantic/django-taggit2 |
3aba7e7f654e492fb689b8030615658cae93c2d1 | txircd/modules/umode_o.py | txircd/modules/umode_o.py | from txircd.modbase import Mode
class OperMode(Mode):
def checkSet(self, target, param):
return False # Should only be set by the OPER command; hence, reject any normal setting of the mode
def checkWhoFilter(self, user, targetUser, filters, fields, channel, udata):
if "o" in filters and no... | from txircd.modbase import Mode
class OperMode(Mode):
def checkSet(self, user, target, param):
user.sendMessage(irc.ERR_NOPRIVILEGES, ":Permission denied - User mode o may not be set")
return False # Should only be set by the OPER command; hence, reject any normal setting of the mode
def c... | Fix crashing when a user attempts to set usermode +o without /oper | Fix crashing when a user attempts to set usermode +o without /oper
| Python | bsd-3-clause | Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd |
c3b0cc681b06ab5b8d64612d5c35fb27da56beeb | spk/sabnzbd/src/app/sabnzbd.cgi.py | spk/sabnzbd/src/app/sabnzbd.cgi.py | #!/usr/local/sabnzbd/env/bin/python
import os
import configobj
config = configobj.ConfigObj('/usr/local/sabnzbd/var/config.ini')
protocol = 'https' if int(config['misc']['enable_https']) else 'http'
port = int(config['misc']['https_port']) if int(config['misc']['enable_https']) else int(config['misc']['port'])
print... | #!/usr/local/sabnzbd/env/bin/python
import os
import configobj
config = configobj.ConfigObj('/usr/local/sabnzbd/var/config.ini')
protocol = 'https' if int(config['misc']['enable_https']) else 'http'
https_port = int(config['misc']['port']) if len(config['misc']['https_port']) == 0 else int(config['misc']['https_port'... | Fix port number detection in sabnzbd | Fix port number detection in sabnzbd
Thanks DcR-NL
| Python | bsd-3-clause | Decipher/spksrc,astroganga/spksrc,mjoe/spksrc,markbastiaans/spksrc,Decipher/spksrc,mreppen/spksrc,saschpe/spksrc,schumi2004/spksrc,hadess/spksrc,mirweb/spksrc,mirweb/spksrc,jdierkse/spksrc,adrien-delhorme/spksrc,sea3pea0/spksrc,thunfischbrot/spksrc,mirweb/spksrc,Foncekar/spksrc,thunfischbrot/spksrc,lysin/spksrc,hmflash... |
550dee3e13a0ee80d0bd9338c281e51fefdcfdc8 | slack_log_handler/__init__.py | slack_log_handler/__init__.py | import traceback
from logging import Handler
from slacker import Chat
class SlackLogHandler(Handler):
def __init__(self, api_key, channel, stack_trace=False, username='Python logger', icon_url=None, icon_emoji=None):
Handler.__init__(self)
self.slack_chat = Chat(api_key)
self.channel = ch... | import json
import traceback
from logging import Handler
from slacker import Slacker
class SlackLogHandler(Handler):
def __init__(self, api_key, channel, stack_trace=False, username='Python logger', icon_url=None, icon_emoji=None):
Handler.__init__(self)
self.slack_chat = Slacker(api_key)
... | Add format with slack attachments. | Add format with slack attachments.
| Python | apache-2.0 | mathiasose/slacker_log_handler |
ed68bd18b88f349a7348006a2e14cdddbc993da7 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'afb4570ceee2ad10f3caf5a81335a2ee11ec68a5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'ea1a7e85a3de1878e5656110c76f4d2d8af41c6e'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Upgrade libchromiumcontent to Chrome 37. | Upgrade libchromiumcontent to Chrome 37.
| Python | mit | beni55/electron,gbn972/electron,chrisswk/electron,mrwizard82d1/electron,Andrey-Pavlov/electron,yan-foto/electron,roadev/electron,abhishekgahlot/electron,MaxWhere/electron,nicholasess/electron,Jonekee/electron,synaptek/electron,edulan/electron,tincan24/electron,faizalpribadi/electron,davazp/electron,tylergibson/electron... |
f20156beb47f860646f31b46ff69879e190d220d | scripts/postbuild.py | scripts/postbuild.py | #!/usr/bin/python3
import sys
import jenkins
from firebase import firebase
JENKINS_URL = '' # Enter Jenkins URL like http://localhost:8080
JENKINS_USERNAME = '' # Enter available Jenkins username
JENKINS_APITOKEN = '' # Enter Jenkins API token (or password if Jenkins < 1.5)
FIREBASE_DSN = '' # Enter your firebase ... | #!/usr/bin/python3
import sys
import jenkins
from firebase import firebase
JENKINS_URL = '' # Enter Jenkins URL like http://localhost:8080
JENKINS_USERNAME = '' # Enter available Jenkins username
JENKINS_APITOKEN = '' # Enter Jenkins API token (or password if Jenkins < 1.5)
FIREBASE_DSN = '' # Enter your firebase ... | Add job console output to firebase | Add job console output to firebase
| Python | mpl-2.0 | MDTsai/webcompat-system-addon-autotest |
374bd4881e00c2605f28ea816fa94468a76f2621 | jps/utils.py | jps/utils.py | import json
from .publisher import Publisher
from .common import DEFAULT_PUB_PORT
from .common import DEFAULT_HOST
from .env import get_master_host
class JsonMultiplePublisher(object):
'''publish multiple topics by one json message
Example:
>>> p = JsonMultiplePublisher()
>>> p.publish('{"topic1":... | import json
from .publisher import Publisher
from .common import DEFAULT_PUB_PORT
from .common import DEFAULT_HOST
from .env import get_master_host
class JsonMultiplePublisher(object):
'''publish multiple topics by one json message
Example:
>>> p = JsonMultiplePublisher()
>>> p.publish('{"topic1":... | Add MultiplePublisher to handle topic name suffix | Add MultiplePublisher to handle topic name suffix
| Python | apache-2.0 | OTL/jps |
937a5e32c77ca57917d60a891616fbcf19ab19f9 | respite/utils.py | respite/utils.py | from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model = _model
return Form
def parse_http_accept_header(header):
"""
Return ... | from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model = _model
return Form
def parse_http_accept_header(header):
"""
Return ... | Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly | Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite |
c9392a6578b0894dff7a5407410e8892e9f3ae6d | win_unc/validators.py | win_unc/validators.py | from win_unc.sanitizors import sanitize_username, sanitize_unc_path
def is_valid_drive_letter(string):
"""
Drive letters are one character in length and between "A" and "Z". Case does not matter.
"""
return (len(string) == 1
and string[0].isalpha())
def is_valid_unc_path(string):
"""... | from win_unc.internal.utils import take_while
from win_unc.sanitizors import sanitize_username, sanitize_unc_path
def is_valid_drive_letter(string):
"""
Drive letters are one character in length and between "A" and "Z". Case does not matter.
"""
return (len(string) == 1
and string[0].isalp... | Fix bad refactor of is_valid_unc_path | Fix bad refactor of is_valid_unc_path
| Python | mit | nithinphilips/py_win_unc,CovenantEyes/py_win_unc |
1d13bd71ff105d540c3af166056cb0b8731a3417 | wooey/migrations/0037_populate-jsonfield.py | wooey/migrations/0037_populate-jsonfield.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-03-04 23:14
from __future__ import unicode_literals
import json
from django.db import migrations
def populate_default(apps, schema_editor):
ScriptParameter = apps.get_model('wooey', 'ScriptParameter')
for obj in ScriptParameter.objects.all():
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-03-04 23:14
from __future__ import unicode_literals
import json
from django.db import migrations
def populate_default(apps, schema_editor):
ScriptParameter = apps.get_model('wooey', 'ScriptParameter')
for obj in ScriptParameter.objects.all():
... | Add reverse to data migration | Add reverse to data migration
| Python | bsd-3-clause | wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey |
fea2c0bc02a8323ad6c759ca63663499a538186e | onnx/__init__.py | onnx/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_ml_pb2 import * # noqa
from .version import version as __version__ # noqa
import sys
def load(obj):
'''
Loads a binary protobuf that stores onnx gr... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_ml_pb2 import * # noqa
from .version import version as __version__ # noqa
# Import common subpackages so they're available when you 'import onnx'
import onn... | Undo BC-breaking change, restore 'import onnx' providing submodules. | Undo BC-breaking change, restore 'import onnx' providing submodules.
Signed-off-by: Edward Z. Yang <dbd597f5635f432486c5d365e9bb585b3eaa1853@fb.com>
| Python | apache-2.0 | onnx/onnx,onnx/onnx,onnx/onnx,onnx/onnx |
81faa7704fb355dd16674d4ed089e0ced34c24c6 | rflo/start.py | rflo/start.py | import ioflo.app.run
import os
class Manager(object):
'''
Manage the main ioflo process
'''
def __init__(self):
self.behaviors = ['rflo.config', 'rflo.roads']
self.floscript = os.path.join(os.path.dirname(__file__), 'raft.flo')
def start(self):
ioflo.app.run.start(
... | import ioflo.app.run
import os
class Manager(object):
'''
Manage the main ioflo process
'''
def __init__(self):
self.behaviors = ['rflo.config', 'rflo.roads', 'rflo.router']
self.floscript = os.path.join(os.path.dirname(__file__), 'raft.flo')
def start(self):
ioflo.app.run... | Add router to the behaviors lookup | Add router to the behaviors lookup
| Python | apache-2.0 | thatch45/rflo |
da1a0f5e7ffcbe37cdee484b452b5376049dd1e5 | python/django.py | python/django.py | """
Django middleware that enables the MDK.
This is old-style (Django <1.10) middleware. Please see
https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-middleware
if you're using Django 1.10.
"""
import atexit
from traceback import format_exception_only
from mdk import start
class MDKSessionMi... | """
Django middleware that enables the MDK.
"""
import atexit
from traceback import format_exception_only
from mdk import start
# Django 1.10 new-style middleware compatibility:
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class MDKSessionMiddleware... | Work with Django 1.10 as well. | Work with Django 1.10 as well.
| Python | apache-2.0 | datawire/mdk,datawire/mdk,datawire/mdk,datawire/mdk |
a3357cd4bb0859f480fa91f50604a2f129431096 | eduid_signup/vccs.py | eduid_signup/vccs.py | from pwgen import pwgen
from re import findall
import vccs_client
def generate_password(settings, credential_id, email):
"""
Generate a new password credential and add it to the VCCS authentication backend.
The salt returned needs to be saved for use in subsequent authentications using
this password... | from pwgen import pwgen
from re import findall
import vccs_client
def generate_password(settings, credential_id, email):
"""
Generate a new password credential and add it to the VCCS authentication backend.
The salt returned needs to be saved for use in subsequent authentications using
this password... | Exclude upper case letters from generated passwords. | Exclude upper case letters from generated passwords.
12 character passwords from the set a-z0-9 have more bits of
entropy (62) than 10 character passwords from the set
a-zA-Z0-9 (60), and are probably perceived as nicer by the
users too (less ambiguity, easier to type on smartphones and
the like).
| Python | bsd-3-clause | SUNET/eduid-signup,SUNET/eduid-signup,SUNET/eduid-signup |
b03ed6307bd1354b931cdd993361d0a40a1d6850 | api/init/graphqlapi/proxy.py | api/init/graphqlapi/proxy.py | import graphqlapi.utils as utils
from graphql.parser import GraphQLParser
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphqlapi.exceptions import RequestException
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(pay... | import graphqlapi.utils as utils
from graphqlapi.exceptions import RequestException
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphql.parser import GraphQLParser
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(pay... | Reorder imports in alphabetical order | Reorder imports in alphabetical order
| Python | apache-2.0 | alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality |
f95aa5b36a354fe3cfd94b43d8f0f6346ec400de | soapypower/threadpool.py | soapypower/threadpool.py | import os, queue, concurrent.futures
class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor):
"""ThreadPoolExecutor which allows setting max. work queue size"""
def __init__(self, max_workers=0, thread_name_prefix='', max_queue_size=0):
super().__init__(max_workers or os.cpu_count() or 1, thre... | import os, queue, concurrent.futures
class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor):
"""ThreadPoolExecutor which allows setting max. work queue size"""
def __init__(self, max_workers=0, thread_name_prefix='', max_queue_size=0):
#super().__init__(max_workers or os.cpu_count() or 1, thr... | Disable setting thread_name_prefix in ThreadPoolExecutor (only supported in Python >= 3.6) | Disable setting thread_name_prefix in ThreadPoolExecutor (only supported in Python >= 3.6)
| Python | mit | xmikos/soapy_power,xmikos/soapy_power |
aed8a831bca72268ad9fbcd2f777d91af29d61b6 | message_view.py | message_view.py | import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""):
panel_view = self.window.cr... | import sublime
import sublime_plugin
PANEL_NAME = "SublimeLinter Messages"
OUTPUT_PANEL = "output." + PANEL_NAME
def plugin_unloaded():
for window in sublime.windows():
window.destroy_output_panel(PANEL_NAME)
class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand):
def run(self, msg=""... | Define const `OUTPUT_PANEL` for the panel name | Define const `OUTPUT_PANEL` for the panel name
| Python | mit | SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3 |
3fe0f73d9c9ca177cefd61636f10be77aa1261d0 | autoentrepreneur/forms.py | autoentrepreneur/forms.py | from django.forms import ModelForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from autoentrepreneur.models import UserProfile, AUTOENTREPRENEUR_ACTIVITY, \
AUTOENTREPRENEUR_PAYMENT_OPTION
class UserProfileForm(ModelForm):
company_name = forms.CharField(required=False, max_... | from django.forms import ModelForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from autoentrepreneur.models import UserProfile, AUTOENTREPRENEUR_ACTIVITY, \
AUTOENTREPRENEUR_PAYMENT_OPTION
class UserProfileForm(ModelForm):
company_name = forms.CharField(required=False, max_... | Remove bank information from form. | Remove bank information from form.
| Python | agpl-3.0 | fgaudin/aemanager,fgaudin/aemanager,fgaudin/aemanager |
969b2d322174392a85f6fa6fc92160cb18144594 | bulbs/content/serializers.py | bulbs/content/serializers.py | from django import forms
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Content, Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
... | from django import forms
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Content, Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
... | Allow for empty tags and authors on `ContentSerializer` | Allow for empty tags and authors on `ContentSerializer`
| Python | mit | theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs,pombredanne/django-bulbs,theonion/django-bulbs |
e0ddd80ea2d23f9b5fc32dd8a5ea13f9cb30da49 | app/packages/__init__.py | app/packages/__init__.py | from flask import Blueprint
packages = Blueprint('packages', __name__)
from . import views, models
from utils import github_data
def post_get_single(result=None, **kw):
result.update(result.pop("get_json"))
result.update(github_data(result['name'], result['author'], result['url']))
# runs for search requ... | from flask import Blueprint
packages = Blueprint('packages', __name__)
from . import views, models
from utils import github_data
def post_get_single(result=None, **kw):
result.update(result.pop("get_json"))
result.update(github_data(result['name'], result['author'], result['url']))
# runs for search requ... | Add api for package search based on name and keywords | Add api for package search based on name and keywords
| Python | bsd-2-clause | NikhilKalige/atom-website,NikhilKalige/atom-website,NikhilKalige/atom-website |
9bfe2dbd37fa18ed7915e82dc8dc8515d7fe9a76 | alfred_collector/__main__.py | alfred_collector/__main__.py | import argparse
import yaml
from .process import CollectorProcess
def get_config(path):
with open(path) as file:
return yaml.load(file)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('config')
args = parser.parse_args()
config = get_config(args.config)
processes... | import argparse
import signal
import yaml
from functools import partial
from .process import CollectorProcess
def get_config(path):
with open(path) as file:
return yaml.load(file)
def terminate_processes(processes, signum, frame):
for process in processes:
if process is not None and process.... | Terminate child processes on SIGTERM signal | Terminate child processes on SIGTERM signal
| Python | isc | alfredhq/alfred-collector |
692fe65ca9d24286d10e542c5028924a22036362 | tests/test_models.py | tests/test_models.py | import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
sted = turbasen.Sted.get('52407fb375049e561500004e')
... | # encoding: utf-8
from __future__ import unicode_literals
import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
... | Add encoding and unicode literals import | Add encoding and unicode literals import
| Python | mit | Turbasen/turbasen.py |
75080e6f0da4f699ef1eb89310847befeccfab40 | skimage/filter/tests/test_filter_import.py | skimage/filter/tests/test_filter_import.py | from skimage._shared.utils import all_warnings, skimage_deprecation
from numpy.testing import assert_warns
def import_filter():
from skimage import filter as F
assert('sobel' in dir(F))
def test_filter_import():
with all_warnings():
assert_warns(skimage_deprecation, import_filter)
| from numpy.testing import assert_warns
from warnings import catch_warnings, simplefilter
def test_import_filter():
with catch_warnings():
simplefilter('ignore')
from skimage import filter as F
assert('sobel' in dir(F))
| Check for deprecation on import is problematic. Rather just check that filter can be imported normally. | Check for deprecation on import is problematic. Rather just check that filter can be imported normally.
| Python | bsd-3-clause | michaelaye/scikit-image,warmspringwinds/scikit-image,juliusbierk/scikit-image,michaelpacer/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,pratapvardhan/scikit-image,robintw/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,youprofit/sciki... |
532c201053ae271544270035423f690b4774794a | swimlane/core/fields/usergroup.py | swimlane/core/fields/usergroup.py | from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def cast_to_pytho... | from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def set_swimlane(... | Fix multiselect user/group field when retrieving results from a report | Fix multiselect user/group field when retrieving results from a report
| Python | mit | Swimlane/sw-python-client |
53e8c14d774131503dbdefe6528cd1e26adbf30b | azure_nosetests.py | azure_nosetests.py | #!/usr/bin/env python
import os.path, nose, glob, sys
packages = [os.path.dirname(p) for p in glob.glob('azure*/setup.py')]
sys.path += packages
nose.main() | #!/usr/bin/env python
import os.path, nose, glob, sys, pkg_resources
packages = [os.path.dirname(p) for p in glob.glob('azure*/setup.py')]
sys.path += packages
# Declare it manually, because "azure-storage" is probably installed with pip
pkg_resources.declare_namespace('azure')
nose.main() | Allow Travis to load tests and use azure-storage installed from pip at the same time | Allow Travis to load tests and use azure-storage installed from pip at the same time
| Python | mit | Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,v-iam/azure-sdk-for-python,Azure/azure-sdk-for-python,AutorestCI/azure-sdk-for-python,lmazuel/azure-sdk-for-python,Azure/azure-sdk-for-python,SUSE/azure-sdk-for-python |
ed9294c7ab0abf574f076464274d83f1e39b53cd | paws/handler.py | paws/handler.py | from .request import Request
from .response import response
class Handler(object):
'''
Simple dispatcher class.
'''
def __init__(self, event, context):
self.request = Request(event, context)
def __call__(self, event, context):
func = getattr(self, self.event['httpMethod'], self.in... | from .request import Request
from .response import response, Response
import logging
log = logging.getLogger()
class Handler(object):
'''
Simple dispatcher class.
'''
def __init__(self, event, context):
self.request = Request(event, context)
def __call__(self, event, context):
fu... | Handle and log exceptions. Render Response objects. | Handle and log exceptions. Render Response objects.
| Python | bsd-3-clause | funkybob/paws |
b5afdd604831f985427880537d37eb7a35addaa1 | tests/functional/test_python_option.py | tests/functional/test_python_option.py | import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fsdecode(tmpdir / "venv")
env = EnvBuilder(with_pip=... | import json
import os
from pathlib import Path
from venv import EnvBuilder
from tests.lib import PipTestEnvironment, TestData
def test_python_interpreter(
script: PipTestEnvironment,
tmpdir: Path,
shared_data: TestData,
) -> None:
env_path = os.fspath(tmpdir / "venv")
env = EnvBuilder(with_pip=Fa... | Fix test to cater for packages leaked into venv | Fix test to cater for packages leaked into venv
| Python | mit | pfmoore/pip,pypa/pip,sbidoul/pip,pfmoore/pip,pradyunsg/pip,sbidoul/pip,pypa/pip,pradyunsg/pip |
4c986e7cedde18530745dca072e06659f1fb20a9 | numpy/compat/__init__.py | numpy/compat/__init__.py | """
Compatibility module.
This module contains duplicated code from Python itself or 3rd party
extensions, which may be included for the following reasons:
* compatibility
* we may only need a small subset of the copied library/module
"""
from . import _inspect
from . import _pep440
from . import py3k
from ._ins... | """
Compatibility module.
This module contains duplicated code from Python itself or 3rd party
extensions, which may be included for the following reasons:
* compatibility
* we may only need a small subset of the copied library/module
"""
from . import _inspect
from . import py3k
from ._inspect import getargspec... | Remove numpy.compat._pep440 from default imports | PERF: Remove numpy.compat._pep440 from default imports
The submoudle numpy.compat._pep440 is removed from the default import of
numpy to reduce the import time. See #22061
| Python | bsd-3-clause | endolith/numpy,numpy/numpy,numpy/numpy,mattip/numpy,endolith/numpy,mattip/numpy,mhvk/numpy,charris/numpy,charris/numpy,mattip/numpy,endolith/numpy,numpy/numpy,mhvk/numpy,mhvk/numpy,mhvk/numpy,charris/numpy,charris/numpy,endolith/numpy,mhvk/numpy,mattip/numpy,numpy/numpy |
0707d920f37edb82d16ccabe1e8413ec16c47c0b | backend/mcapi/mcdir.py | backend/mcapi/mcdir.py | import utils
from os import environ
import os.path
MCDIR = environ.get("MCDIR") or '/mcfs/data'
def for_uid(uidstr):
pieces = uidstr.split('-')
path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4])
utils.mkdirp(path)
return path
| import utils
from os import environ
import os.path
MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons'
def for_uid(uidstr):
pieces = uidstr.split('-')
path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4])
utils.mkdirp(path)
return path
| Change directory where data is written to. | Change directory where data is written to.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
f75a151b33635cad5604cb9d7f66fc043c4f972a | saleor/core/utils/json_serializer.py | saleor/core/utils/json_serializer.py | import json
from django.core.serializers.base import DeserializationError
from django.core.serializers.json import (
DjangoJSONEncoder, PythonDeserializer, Serializer as JsonSerializer)
from prices import Money
MONEY_TYPE = 'Money'
class Serializer(JsonSerializer):
def _init_options(self):
super()._... | import json
from django.core.serializers.base import DeserializationError
from django.core.serializers.json import (
DjangoJSONEncoder, PythonDeserializer, Serializer as JsonSerializer)
from prices import Money
MONEY_TYPE = 'Money'
class Serializer(JsonSerializer):
def _init_options(self):
super()._... | Fix except handler raises immediately | Fix except handler raises immediately
| Python | bsd-3-clause | UITools/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor |
f3fcddaf7aa4e081322db6779ce2ad6d7e0db10a | pytac/device.py | pytac/device.py | """The device class used to represent a particular function of an accelerator
element.
A physical element in an accelerator may have multiple devices: an example at
DLS is a sextupole magnet that contains also horizontal and vertical corrector
magnets and a skew quadrupole.
"""
class Device(object):
"""A represe... | """The device class used to represent a particular function of an accelerator
element.
A physical element in an accelerator may have multiple devices: an example at
DLS is a sextupole magnet that contains also horizontal and vertical corrector
magnets and a skew quadrupole.
"""
class Device(object):
"""A represe... | Add a code for a BasicDevice class. | Add a code for a BasicDevice class.
| Python | apache-2.0 | willrogers/pytac,willrogers/pytac |
8dbe3e9e418c120d59bb95aa6ff8fb3ab382aac2 | billjobs/tests/tests_export_account_email.py | billjobs/tests/tests_export_account_email.py | from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.as... | from django.test import TestCase
from django.contrib.admin.sites import AdminSite
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.as... | Test export_email has a short description | Test export_email has a short description
| Python | mit | ioO/billjobs |
3e71356de442e47bcb96ea311295bb447fd23341 | bin/ogcserver-local.py | bin/ogcserver-local.py | #!/usr/bin/env python
import os
import sys
import socket
from os import path
from pkg_resources import *
if not len(sys.argv) > 1:
sys.exit('Usage: %s <map.xml>' % os.path.basename(sys.argv[0]))
sys.path.insert(0,os.path.abspath('.'))
from ogcserver.wsgi import WSGIApp
import ogcserver
default_conf = resource_... | #!/usr/bin/env python
import os
import sys
import socket
from os import path
from pkg_resources import *
import argparse
parser = argparse.ArgumentParser(description='Runs the ogcserver as WMS server')
parser.add_argument('mapfile', type=str, help='''
A XML mapnik stylesheet
''')
args = parser.parse_args()
sys.pat... | Use ArgumentParser to read paramaters | Use ArgumentParser to read paramaters
| Python | bsd-3-clause | mapnik/OGCServer,pbabik/OGCServer,pbabik/OGCServer |
b855dbde90bfd5842ad292f5f424957df02c2fe0 | myflaskapp/myflaskapp/item/models.py | myflaskapp/myflaskapp/item/models.py | """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
pass
| """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
text = Column(db.String(80),nullable=True)
| Add text field to Item model | Add text field to Item model
| Python | mit | terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python |
cb22f18186262bffbfa78b47f1d6e7c2a060d5ff | gearhorn/cmd.py | gearhorn/cmd.py | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Add port specification to gearhorn CLI | Add port specification to gearhorn CLI
| Python | apache-2.0 | SpamapS/gearhorn |
6a68ef52ab9e762860087f701eee15e11786ca71 | k3d/__init__.py | k3d/__init__.py | from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unic... | from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unic... | Fix calling "display" method multiple times | Fix calling "display" method multiple times
| Python | mit | K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter |
bc2d57bb36373eded3ae1cd82cd4b91bd5649b57 | kyokai/route.py | kyokai/route.py | """
Module for Kyokai routes.
"""
import re
class Route(object):
"""
A route is simply a wrapped coroutine object for a request.
It takes in a regular expression as a matcher, for the path, and a list of accepted methods.
"""
def __init__(self, matcher: str, methods: list):
"""
C... | """
Module for Kyokai routes.
"""
import re
from kyokai.exc import HTTPClientException, HTTPException
class Route(object):
"""
A route is simply a wrapped coroutine object for a request.
It takes in a regular expression as a matcher, for the path, and a list of accepted methods.
"""
def __init_... | Make invoke() actually invoke the coroutine. | Make invoke() actually invoke the coroutine.
| Python | mit | SunDwarf/Kyoukai |
40db9d64d616d99ec2464aff6fe5960943584ac3 | rnacentral/apiv1/urls.py | rnacentral/apiv1/urls.py | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | """
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | Add a stable url for the current API version | Add a stable url for the current API version
| Python | apache-2.0 | RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode |
a5898f8e5b2b25af472f1e2e5ce02626b86db5f2 | tunneler/tests/test_models.py | tunneler/tests/test_models.py | from unittest import TestCase
from ..models import Tunnel
| from unittest import TestCase
from ..models import Tunnel
class TestModels(TestCase):
def test_defaults(self):
tunnel = Tunnel()
self.assertEquals(tunnel.name, 'unnamed')
self.assertEquals(tunnel.process, None)
self.assertEqual(tunnel.local_port, 0)
self.assertEqual(tunnel... | Add a basic test for models. | Add a basic test for models.
| Python | isc | xoliver/tunneler,xoliver/tunneler |
48bd50609fffb18dbab821522810ec587751434c | arguments.py | arguments.py | import argparse
from settings import HONEYPORT
"""
Here we define command line arguments.
`port` stands for port, to listen on.
`-v` to increase verbose of the server
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that... | import argparse
from settings import HONEYPORT
"""
Here we define command line arguments.
`port` stands for port, to listen on.
`-v` to increase verbose of the server
"""
def parse():
parser = argparse.ArgumentParser(
description='Serve some sweet honey to the ubiquitous bots!',
epilog='And that... | Add option to enable self updating | Add option to enable self updating
This is a customization option for more flexibility.
If you want to autoupdate, then you can give a -u option.
If not - don't.
| Python | mit | Zloool/manyfaced-honeypot |
9f8f929b8fdc0ebfdb609621f4613d31b73639b0 | sipa/utils/link_patch.py | sipa/utils/link_patch.py | import re
from flask import request
from markdown import Markdown
from markdown.extensions import Extension
from markdown.postprocessors import Postprocessor
def absolute_path_replacer(match):
"""Correct the url in a regex match prepending the absolute path"""
assert len(match.groups()) == 2
prefix = re... | import re
from flask import request
from markdown import Markdown
from markdown.extensions import Extension
from markdown.postprocessors import Postprocessor
def absolute_path_replacer(match):
"""Correct the url in a regex match prepending the absolute path"""
assert len(match.groups()) == 2
prefix = re... | Fix priority of link postprocessor | Fix priority of link postprocessor
Fixes #424
| Python | mit | agdsn/sipa,agdsn/sipa,agdsn/sipa,agdsn/sipa |
0a0d6b87aac75f298194b43cfcea67b0d1651a97 | knights/library.py | knights/library.py | from functools import partial
class Library:
'''
Container for registering tags and filters
'''
def __init__(self):
self.tags = {}
self.filters = {}
self.helpers = {}
def tag(self, func=None, name=None):
if func is None:
return partial(self.tag, name=na... | from functools import partial
class Library:
'''
Container for registering tags and helpers
'''
def __init__(self):
self.tags = {}
self.helpers = {}
def tag(self, func=None, name=None):
if func is None:
return partial(self.tag, name=name)
if name is No... | Remove another reference to filter | Remove another reference to filter
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
c56d9cded7190d524d3d4dbcd960a0b0fe8bf10c | apps/local_apps/account/middleware.py | apps/local_apps/account/middleware.py | from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on ... | from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on ... | Throw 500 error on multiple account in LocaleMiddleware so we can fix them. | Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
git-svn-id: 51ba99f60490c2ee9ba726ccda75a38950f5105d@1120 45601e1e-1555-4799-bd40-45c8c71eef50
| Python | mit | alex/pinax,amarandon/pinax,amarandon/pinax,alex/pinax,alex/pinax,amarandon/pinax,amarandon/pinax |
5da30efc6cbbc58db60ba29643c56448b5a79e77 | test/test_pipeline/components/test_base.py | test/test_pipeline/components/test_base.py | import unittest
from autosklearn.pipeline.components.base import find_components, \
AutoSklearnClassificationAlgorithm
class TestBase(unittest.TestCase):
def test_find_components(self):
c = find_components('dummy_components', 'dummy_components',
AutoSklearnClassificationA... | import os
import sys
import unittest
from autosklearn.pipeline.components.base import find_components, \
AutoSklearnClassificationAlgorithm
this_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(this_dir)
class TestBase(unittest.TestCase):
def test_find_components(self):
c = find_com... | FIX fix unit test by fixing import paths | FIX fix unit test by fixing import paths
| Python | bsd-3-clause | automl/auto-sklearn,automl/auto-sklearn |
22de9f9d45edbf5eddea2940549efc225c805f02 | tests/ext_i18n.py | tests/ext_i18n.py | from __future__ import unicode_literals
from unittest import TestCase
from wtforms import TextField, validators
from wtforms.ext.i18n.utils import get_translations
from wtforms.ext.i18n import form as i18n_form
class I18NTest(TestCase):
def test_failure(self):
self.assertRaises(IOError, get_translations,... | from __future__ import unicode_literals
from unittest import TestCase
from wtforms import TextField, validators
from wtforms.ext.i18n.utils import get_translations
from wtforms.ext.i18n import form as i18n_form
class I18NTest(TestCase):
def test_failure(self):
self.assertRaises(IOError, get_translations,... | Fix assert for python 2.6 compatibility | Fix assert for python 2.6 compatibility
| Python | bsd-3-clause | Xender/wtforms,Aaron1992/wtforms,jmagnusson/wtforms,pawl/wtforms,cklein/wtforms,pawl/wtforms,crast/wtforms,hsum/wtforms,Aaron1992/wtforms,skytreader/wtforms,wtforms/wtforms,subyraman/wtforms |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.