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 |
|---|---|---|---|---|---|---|---|---|---|
fb41f01360423d176864a4846d0e769d4df03978 | penchy/tests/test_compat.py | penchy/tests/test_compat.py | from hashlib import sha1
from tempfile import TemporaryFile
from contextlib import contextmanager
from penchy.compat import unittest, nested, update_hasher
class NestedTest(unittest.TestCase):
def test_reraising_exception(self):
e = Exception('reraise this')
with self.assertRaises(Exception) as r... | from hashlib import sha1
from tempfile import TemporaryFile
from contextlib import contextmanager
from penchy.compat import unittest, nested, update_hasher, unicode_
class NestedTest(unittest.TestCase):
def test_reraising_exception(self):
e = Exception('reraise this')
with self.assertRaises(Excep... | Replace control hasher with constant hexdigest. | tests: Replace control hasher with constant hexdigest.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy |
36d8243712b5be7f7f7449abcd9640024cee0f19 | src/tpn/data_io.py | src/tpn/data_io.py | #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
d... | #!/usr/bin/env python
import zipfile
import cPickle
import numpy as np
"""
track_obj: {
frames: 1 by n numpy array,
anchors: 1 by n numpy array,
features: m by n numpy array,
scores: c by n numpy array,
boxes: 4 by n numpy array,
rois: 4 by n numpy array
}
"""
d... | Simplify save_track_proto_to_zip to save all keys in track_proto. | Simplify save_track_proto_to_zip to save all keys in track_proto.
| Python | mit | myfavouritekk/TPN |
0c6825ce8b5d1e3b15505c5bcac847c6a57a782e | statirator/main.py | statirator/main.py | import argparse
from . import commands
VALID_ARGS = ('init', 'compile', 'serve')
def create_options():
"Add options to tornado"
parser = argparse.ArgumentParser(
'Staitrator - Static multilingual site and blog generator')
parser.add_argument('command', choices=VALID_ARGS)
init = pars... | import argparse
from . import commands
def create_options():
"Add options to tornado"
parser = argparse.ArgumentParser(
'Staitrator - Static multilingual site and blog generator')
sub_parsers = parser.add_subparsers(help='Sub Commands help')
init = sub_parsers.add_parser('init', help=... | Move arguments to sub parsers | Move arguments to sub parsers
| Python | mit | MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator |
e192a0d29c0b082458bf0a6f37df86978bfa0032 | setup.py | setup.py | from distutils.core import setup
setup(
name='cstypo',
version='0.1.1',
author='Juda Kaleta',
author_email='juda.kaleta@gmail.com',
packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'],
scripts=['bin/cstypo'],
url='https://github.com/yetty/cstypo',
license=open('LICENSE').read(),
... | from distutils.core import setup
setup(
name='cstypo',
version='0.1.1',
author='Juda Kaleta',
author_email='juda.kaleta@gmail.com',
packages=['cstypo', 'cstypo.templatetags', 'cstypo.tests'],
scripts=['bin/cstypo'],
url='https://github.com/yetty/cstypo',
license=open('LICENSE').read(),
... | Add docopt to required packages | Add docopt to required packages
| Python | mit | yetty/cstypo |
d0163cb608b299733ad47111f0ef6b982d1a9a1c | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name="sbd",
version="0.1",
description="Iridium Short Burst Data DirectIP handling",
author="Pete Gadomski",
author_email="pete.gadomski@gmail.com",
url="https://github.com/gadomski/sbd",
scripts=["bin/iridiumd"],
i... | #!/usr/bin/env python
from distutils.core import setup
setup(name="sbd",
version="0.1",
description="Iridium Short Burst Data DirectIP handling",
author="Pete Gadomski",
author_email="pete.gadomski@gmail.com",
url="https://github.com/gadomski/sbd",
packages=["sbd"],
scripts=[... | Add sbd package to install | Add sbd package to install
| Python | mit | gadomski/sbd |
a5f9abc3f2de2bca89a5c3e5c35a8d7e223be4dd | setup.py | setup.py | from distutils.core import setup
setup(
name='nipype-pbs-workflows',
version='1.0',
author='https://www.ctsi.ufl.edu/research/study-development/informatics-consulting/',
author_email='ctsit@ctsi.ufl.edu',
description='Neuroimaging workflows writtten in nipype with a focus on PBS job scheduler',
lon... | from distutils.core import setup
setup(
name='nipype-pbs-workflows',
version='1.0.1',
author='https://www.ctsi.ufl.edu/research/study-development/informatics-consulting/',
author_email='ctsit@ctsi.ufl.edu',
description='Neuroimaging workflows writtten in nipype with a focus on PBS job scheduler',
... | Install scripts into the correct location | Install scripts into the correct location
| Python | bsd-3-clause | ctsit/nipype-pbs-workflows |
b668e1ab2c2fbd973f3bf8865db79f0a7b37141f | tasks.py | tasks.py |
import re
from invoke import task
def get_version():
return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version')
@task
def release(c):
version = get_version()
c.run("git tag -a aiodns-{0} -m \"aiodns {0} release\"".format(ver... |
import re
from invoke import task
def get_version():
return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version')
@task
def release(c):
version = get_version()
c.run("git tag -a aiodns-{0} -m \"aiodns {0} release\"".format(ver... | Build universal wheels when releasing | Build universal wheels when releasing
| Python | mit | saghul/aiodns |
4291d80377e970e02fb95afa6f9f85246cb9c498 | DjangoLibrary/tests/factories.py | DjangoLibrary/tests/factories.py | import datetime
from django.template.defaultfilters import slugify
from factory import DjangoModelFactory, lazy_attribute
from random import randint
from .models import Author
from .models import Book
class UserFactory(DjangoModelFactory):
class Meta:
model = 'auth.User'
django_get_or_create = ('u... | import datetime
from django.template.defaultfilters import slugify
from factory import DjangoModelFactory, lazy_attribute
from random import randint
class UserFactory(DjangoModelFactory):
class Meta:
model = 'auth.User'
django_get_or_create = ('username',)
first_name = 'John'
last_name = ... | Revert "Add AuthorFactory and BookFactory." | Revert "Add AuthorFactory and BookFactory."
This reverts commit 8cde42f87a82206cf63b3a5e4b0ec6c38d66d3a7.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary |
be6143f06df194150683eceafa63bb2ea5f33d05 | paytm.py | paytm.py | import selenium.webdriver as webdriver
import bs4 as bs
import pyisbn
import re
def paytm(isbn):
if len(isbn) == 10:
p_link = 'https://paytm.com/shop/search/?q='+pyisbn.Isbn10(isbn).convert(code='978')+'&sort_price=1'
else:
p_link = 'https://paytm.com/shop/search/?q='+isbn+'&sort_price=1'
# print p_link
driv... | import selenium.webdriver as webdriver
import bs4 as bs
import pyisbn
import re
def paytm(isbn):
if len(isbn) == 10:
p_link = 'https://paytm.com/shop/search/?q='+pyisbn.Isbn10(isbn).convert(code='978')+'&sort_price=1'
else:
p_link = 'https://paytm.com/shop/search/?q='+isbn+'&sort_price=1'
# print p_link
driv... | Fix typo in return during exception while loading page | Fix typo in return during exception while loading page
| Python | mit | GingerNinja23/bookbargain |
32ddc769bffed640e83e99e2657f20bbb3ef5e38 | mopidy_soundcloud/__init__.py | mopidy_soundcloud/__init__.py | from __future__ import unicode_literals
import os
from mopidy import ext, config
from mopidy.exceptions import ExtensionError
__version__ = '1.0.18'
__url__ = 'https://github.com/mopidy/mopidy-soundcloud'
class SoundCloudExtension(ext.Extension):
dist_name = 'Mopidy-SoundCloud'
ext_name = 'soundcloud'
... | from __future__ import unicode_literals
import os
from mopidy import ext, config
from mopidy.exceptions import ExtensionError
__version__ = '1.0.18'
__url__ = 'https://github.com/mopidy/mopidy-soundcloud'
class SoundCloudExtension(ext.Extension):
dist_name = 'Mopidy-SoundCloud'
ext_name = 'soundcloud'
... | Remove env check as Mopidy checks deps automatically | ext: Remove env check as Mopidy checks deps automatically
| Python | mit | mopidy/mopidy-soundcloud,yakumaa/mopidy-soundcloud |
4f5fe3002f3244f5ce6b90303def86c1763c8afb | wafer/users/tests/test_models.py | wafer/users/tests/test_models.py | # -*- coding: utf-8 -*-
# vim:fileencoding=utf-8 ai ts=4 sts=4 et sw=4
"""Tests for wafer.user.models"""
from django.contrib.auth import get_user_model
from django.test import TestCase
import sys
PY2 = sys.version_info[0] == 2
class UserModelTestCase(TestCase):
def test_str_method_issue192(self):
"""Te... | # -*- coding: utf-8 -*-
# vim:fileencoding=utf-8 ai ts=4 sts=4 et sw=4
"""Tests for wafer.user.models"""
from django.contrib.auth import get_user_model
from django.test import TestCase
import sys
class UserModelTestCase(TestCase):
def test_str_method_issue192(self):
"""Test that str(user) works correct... | Remove python2 logic from test | Remove python2 logic from test
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
a75e2b6c42ded44202e1fef53047c325566466f0 | stella/llvm.py | stella/llvm.py | from llvm import *
from llvm.core import *
from llvm.ee import *
import logging
tp_int = Type.int(64)
tp_float = Type.float()
def py_type_to_llvm(tp):
if tp == int:
return tp_int
elif tp == float:
return tp_float
else:
raise TypeError("Unknown type " + tp)
def get_generic_value(tp... | from llvm import *
from llvm.core import *
from llvm.ee import *
import logging
tp_int = Type.int(64)
#tp_float = Type.float() # Python always works with double precision
tp_double = Type.double()
def py_type_to_llvm(tp):
if tp == int:
return tp_int
elif tp == float:
return tp_double
else... | Use double precision for floats | Use double precision for floats
| Python | apache-2.0 | squisher/stella,squisher/stella,squisher/stella,squisher/stella |
6f80a7e5f8dea031db1c7cc676f8c96faf5fc458 | test/test_links.py | test/test_links.py | import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/... | import pytest
@pytest.mark.parametrize("name, linked_to", [
("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"),
("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"),
("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"),
("/home/wicksy/.aws", "/git/... | Change test function as existing method deprecated | Change test function as existing method deprecated
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build |
ed2dc3478691592cb38a1f1923a39bed4bcf423c | tests/test_main.py | tests/test_main.py | # -*- coding:utf-8 -*-
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
from os.path import devnull
from subprocess import check_call
from sys import version
from pytest import fixture, raises
from csft import __main__ as main, __version__
@fixture
def null():
with open(devnull, ... | # -*- coding:utf-8 -*-
from os.path import devnull
from subprocess import check_call
from pytest import fixture, raises
from csft import __main__ as main
@fixture
def null():
with open(devnull, 'w') as fobj:
yield fobj
def test_call(null):
check_call(['python', '-m', 'csft', 'csft'], stdout=null,... | Use capsys instead of redirect_stderr | Use capsys instead of redirect_stderr
| Python | mit | yanqd0/csft |
8b7fa42c7cd080f7faebbfaf782fa639104cb96a | pgcli/packages/expanded.py | pgcli/packages/expanded.py | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
sep = u"-[ RECORD {0} ]-------------------------\n"
padded_headers = [pad... | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
sep = u"-[ RECORD {0} ]-------------------------\n"
padded_headers = [pad... | Remove any whitespace from values | Remove any whitespace from values
| Python | bsd-3-clause | dbcli/pgcli,w4ngyi/pgcli,darikg/pgcli,koljonen/pgcli,d33tah/pgcli,koljonen/pgcli,d33tah/pgcli,w4ngyi/pgcli,darikg/pgcli,dbcli/pgcli |
a037843f62a3d6b1124f8b62517463ef92cd793f | tvsort_sl/fcntl.py | tvsort_sl/fcntl.py | # coding=utf-8
from __future__ import unicode_literals
def fcntl(fd, op, arg=0):
return 0
def ioctl(fd, op, arg=0, mutable_flag=True):
if mutable_flag:
return 0
else:
return ""
def flock(fd, op):
return
def lockf(fd, operation, length=0, start=0, whence=0):
return
| # coding=utf-8
from __future__ import unicode_literals
# Variables with simple values
FASYNC = 64
FD_CLOEXEC = 1
F_DUPFD = 0
F_FULLFSYNC = 51
F_GETFD = 1
F_GETFL = 3
F_GETLK = 7
F_GETOWN = 5
F_RDLCK = 1
F_SETFD = 2
F_SETFL = 4
F_SETLK = 8
F_SETLKW = 9
F_SETOWN = 6
F_UNLCK = 2
F_WRLCK = 3
LOCK_EX = 2
LOCK_NB = 4
LO... | Add missing variables to cntl | Add missing variables to cntl
| Python | mit | shlomiLan/tvsort_sl |
cb52e7b1a507ca7b6065c6994d11d3c07a41e6f1 | uniqueids/tasks.py | uniqueids/tasks.py | from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.... | from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.... | Make auto gen ID's strings on save to Identity | Make auto gen ID's strings on save to Identity
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration |
8d7d058480f909ef3bc22aa9f8ee76179b346784 | arthur/exercises.py | arthur/exercises.py | """
UI tools related to exercise search and selection.
"""
import urwid
from arthur.ui import DIVIDER
class SearchTool(object):
name = u"Mission search"
position = ("relative", 20), 30, "middle", 10
def __init__(self):
title = urwid.Text(u"Mission search")
search = urwid.Edit(u"Search te... | """
UI tools related to exercise search and selection.
"""
from arthur.ui import Prompt
class SearchTool(Prompt):
position = ("relative", 20), 30, "middle", 10
def __init__(self):
Prompt.__init__(self, u"Mission search", u"Search terms: ")
| Refactor search tool in terms of prompt | Refactor search tool in terms of prompt
| Python | isc | crypto101/arthur |
394f5832c6d3ff3efefbc5c21163adcdedd9a9bb | sale_stock_availability/__openerp__.py | sale_stock_availability/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on sale orders and other to see only if o... | # -*- coding: utf-8 -*-
{
'name': 'Stock availability in sales order line',
'version': '0.1',
'category': 'Tools',
'description': """
Stock availability in sales order line
======================================
* Add two groups. One for seeing stock on sale orders and other to see only if or not availa... | FIX sale stock availa.. description | FIX sale stock availa.. description
| Python | agpl-3.0 | syci/ingadhoc-odoo-addons,HBEE/odoo-addons,jorsea/odoo-addons,adhoc-dev/odoo-addons,bmya/odoo-addons,bmya/odoo-addons,levkar/odoo-addons,bmya/odoo-addons,dvitme/odoo-addons,ClearCorp/account-financial-tools,jorsea/odoo-addons,sysadminmatmoz/ingadhoc,ingadhoc/account-payment,HBEE/odoo-addons,ingadhoc/stock,adhoc-dev/acc... |
6ec97d78930b7ed77af34869face1a45895950f1 | sensor/core/models/event.py | sensor/core/models/event.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.db import models
VALUE_MAX_LEN = 128
class GenericEvent(models.Model):
"""Represents a measuremen... | Add sensor field to Event model in sensor.core | Add sensor field to Event model in sensor.core
| Python | mpl-2.0 | HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site,HeisenbergPeople/weather-station-site |
3a87b03ed42232f7daa96242142f48872bf26634 | readthedocs/gold/models.py | readthedocs/gold/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
LEVEL_CHOICES = (
('v1-org-5', '$5/mo'),
('v1-org-10', '$10/mo'),
('v1-org-15', '$15/mo'),
('v1-org-20', '$20/mo'),
('v1-org-50', '$50/mo'),
('v1-org-100', '$100/mo'),
)
class GoldUser(models.Model):
pub_... | from django.db import models
from django.utils.translation import ugettext_lazy as _
LEVEL_CHOICES = (
('v1-org-5', '$5/mo'),
('v1-org-10', '$10/mo'),
('v1-org-15', '$15/mo'),
('v1-org-20', '$20/mo'),
('v1-org-50', '$50/mo'),
('v1-org-100', '$100/mo'),
)
class GoldUser(models.Model):
pub_... | Add nicer string rep for gold user | Add nicer string rep for gold user
| Python | mit | jerel/readthedocs.org,CedarLogic/readthedocs.org,sunnyzwh/readthedocs.org,sils1297/readthedocs.org,rtfd/readthedocs.org,espdev/readthedocs.org,raven47git/readthedocs.org,sunnyzwh/readthedocs.org,safwanrahman/readthedocs.org,takluyver/readthedocs.org,fujita-shintaro/readthedocs.org,sid-kap/readthedocs.org,laplaceliu/rea... |
bc6d8d6789fb6275587e119eea7d39941ea4c749 | loadFeatures.py | loadFeatures.py | from numpy import *
from mnist import *
from util import Counter
# def loadData():
# images, labels = load_mnist('training')
def defineFeatures(imageList, n):
imageList = imageList[0:]
featureList = []
for image in imageList:
imgFeature = Counter()
for i in range(len(image)):
... | from mnist import *
from util import Counter
def loadData():
"""
loadData() pulls data from MNIST training set, splits it into training and
validation data, then parses the data into features
"""
# load data from MNIST files
images, labels = load_mnist('training')
# find out where to split ... | Split training and validation data | Split training and validation data
| Python | mit | chetaldrich/MLOCR,chetaldrich/MLOCR |
178b39611ec6bc32e4bb0ccd481660a0364872d7 | src/tests/test_utils.py | src/tests/test_utils.py | import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = ... | import numpy as np
import skimage.filter as filters
def generate_linear_structure(size, with_noise=False):
"""Generate a basic linear structure, optionally with noise"""
linear_structure = np.zeros(shape=(size,size))
linear_structure[:,size/2] = np.ones(size)
if with_noise:
linear_structure = ... | Add testing function for blobs | Add testing function for blobs
| Python | mit | samueljackson92/major-project,samueljackson92/major-project,samueljackson92/major-project,samueljackson92/major-project |
f10d443eda1e8727c48439cc7c9491178a1ac4c8 | performance_testing/result.py | performance_testing/result.py | import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
name = '%d-%d-%d_%d-%d-%d' % (
date.year,
date.month,
date.day,
date.hour,
date.minute,
... | import os
from datetime import datetime
from time import time
class Result:
def __init__(self, directory):
date = datetime.fromtimestamp(time())
self.file = File(directory, date.strftime('%Y-%m-%d_%H-%M-%S'))
class File:
def __init__(self, directory, name):
if not os.path.exists(dire... | Use date-format function for file-name | Use date-format function for file-name
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing |
a3975cc9d4a388789fcdaf07ece011b01801f162 | hilbert/decorators.py | hilbert/decorators.py | from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
from django.utils.log import getLogger
logger = getLogger('django-hilbert')
def ajax_login_required(view_func):
@wra... | from functools import wraps
from django import http
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.utils.decorators import available_attrs
def ajax_login_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(reque... | Remove logging to preserve 1.2 compatability. | Remove logging to preserve 1.2 compatability.
| Python | bsd-2-clause | mlavin/django-hilbert,mlavin/django-hilbert |
398d16aaa8f1239c2bb08c45af9cde218f21ab68 | was/photo/views.py | was/photo/views.py | from django.shortcuts import render
from .forms import UploadPhotoForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from .models import Photo
@login_required
def upload_photo_artist(request):
if request.method == 'POST':
print('nsm')
form =... | from django.shortcuts import render
from .forms import UploadPhotoForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from .models import Photo
@login_required
def upload_photo_artist(request):
if request.method == 'POST':
form = UploadPhotoForm(requ... | Add request.FILES in form construction in order to pass it to the form. | Add request.FILES in form construction in order to pass it to the form.
| Python | mit | KeserOner/where-artists-share,KeserOner/where-artists-share |
76b5d00a4f936c38036270ef37465fd2621db71c | TelegramLogHandler/handler.py | TelegramLogHandler/handler.py | import logging
class TelegramHandler(logging.Handler):
"""
A handler class which sends a Telegram message for each logging event.
"""
def __init__(self, token, ids):
"""
Initialize the handler.
Initialize the instance with the bot's token and a list of chat_id(s)
of the... | import logging
class TelegramHandler(logging.Handler):
"""
A handler class which sends a Telegram message for each logging event.
"""
def __init__(self, token, ids):
"""
Initialize the handler.
Initialize the instance with the bot's token and a list of chat_id(s)
of the... | Fix infinite loop caused by requests library's logging | Fix infinite loop caused by requests library's logging
| Python | mit | simonacca/TelegramLogHandler |
285cd06243fdd7aacb65628f390876be3b7ca098 | setup.py | setup.py | #!/usr/bin/env python
"""Setup for cppclean."""
from __future__ import unicode_literals
from distutils import core
with open('README') as readme:
core.setup(name='cppclean',
description='Find problems in C++ source that slow development '
'of large code bases.',
... | #!/usr/bin/env python
"""Setup for cppclean."""
from distutils import core
with open('README') as readme:
core.setup(name='cppclean',
description='Find problems in C++ source that slow development '
'of large code bases.',
long_description=readme.read(),
... | Make this work on Python 2 | Make this work on Python 2
http://bugs.python.org/issue13943
| Python | apache-2.0 | myint/cppclean,myint/cppclean,myint/cppclean,myint/cppclean |
557eaa0d0c15ab57f9b8773486098b14a9bcc89f | setup.py | setup.py | #! /usr/bin/env python
import os, glob
from distutils.core import setup
NAME = 'bacula_configuration'
VERSION = '0.1'
WEBSITE = 'http://gallew.org/bacula_configuration'
LICENSE = 'GPLv3 or later'
DESCRIPTION = 'Bacula configuration management tool'
LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no w... | #! /usr/bin/env python
import os, glob
from distutils.core import setup
NAME = 'bacula_configuration'
VERSION = '0.1'
WEBSITE = 'http://gallew.org/bacula_configuration'
LICENSE = 'GPLv3 or later'
DESCRIPTION = 'Bacula configuration management tool'
LONG_DESCRIPTION = 'Bacula is a great backup tool, but ships with no w... | Add dependencies, update for module name change | Add dependencies, update for module name change
| Python | bsd-3-clause | BrianGallew/bacula_configuration |
f622569041c3aae25a243029609d63606b29015f | start.py | start.py | try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import hopscotch
vx.default_start()
| try:
import rc
except ImportError:
import vx
# which keybinding do we want
from keybindings import concat
vx.default_keybindings = concat.load
vx.default_start()
| Change default keybindings to concat since these are the only ones that work | Change default keybindings to concat since these are the only ones that work
At least for now
| Python | mit | philipdexter/vx,philipdexter/vx |
5ab07a72a5a9e9e147e782301d55ed5c7c844978 | tasks.py | tasks.py | import invoke
def run(*args, **kwargs):
kwargs.update(echo=True)
return invoke.run(*args, **kwargs)
@invoke.task
def clean():
run("rm -rf .tox/")
run("rm -rf dist/")
run("rm -rf pyservice.egg-info/")
run("find . -name '*.pyc' -delete")
run("find . -name '__pycache__' -delete")
@invoke.tas... | import invoke
def run(*args, **kwargs):
kwargs.update(echo=True)
return invoke.run(*args, **kwargs)
@invoke.task
def clean():
run("rm -rf .tox/")
run("rm -rf dist/")
run("rm -rf pyservice.egg-info/")
run("find . -name '*.pyc' -delete")
run("find . -name '__pycache__' -delete")
run("rm ... | Add .coverage to clean task | Add .coverage to clean task
| Python | mit | numberoverzero/pyservice |
63c4997dbe712a4260c0ebe1f2c4c82416b39901 | account_import_line_multicurrency_extension/__openerp__.py | account_import_line_multicurrency_extension/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Vincent Renaville (Camptocamp)
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lice... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Vincent Renaville (Camptocamp)
# Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lice... | Remove list of conflicting module. Both modules can be installed and will work in parallele. Thought the workflow logic is different. | Remove list of conflicting module. Both modules can be installed and will work in parallele. Thought the workflow logic is different.
| Python | agpl-3.0 | syci/bank-payment,sergiocorato/bank-payment,ndtran/bank-payment,CompassionCH/bank-payment,Antiun/bank-payment,damdam-s/bank-payment,syci/bank-payment,sergiocorato/bank-payment,David-Amaro/bank-payment,diagramsoftware/bank-payment,acsone/bank-payment,Antiun/bank-payment,damdam-s/bank-payment,CompassionCH/bank-payment,Da... |
2c92d844b01458e74bd7163d755518f7947e87ec | 31-trinity/tf-31.py | 31-trinity/tf-31.py | #!/usr/bin/env python
import sys, re, operator, collections
#
# Model
#
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
stopwords = set(open('../stop_words.txt... | #!/usr/bin/env python
import sys, re, operator, collections
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
self.update(path_to_file)
def update(self, path... | Make the mvc example interactive | Make the mvc example interactive
| Python | mit | placrosse/exercises-in-programming-style,aaron-goshine/exercises-in-programming-style,jw0201/exercises-in-programming-style,bgamwell/exercises-in-programming-style,rajanvenkataguru/exercises-in-programming-style,bgamwell/exercises-in-programming-style,aaron-goshine/exercises-in-programming-style,emil-mi/exercises-in-pr... |
3bf8790a0a8bd5464cedcb4f2acb92f758bc01b4 | apgl/data/ExamplesGenerator.py | apgl/data/ExamplesGenerator.py | '''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain nu... | '''
A simple class which can be used to generate test sets of examples.
'''
#import numpy
import numpy.random
class ExamplesGenerator():
def __init__(self):
pass
def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4):
"""
Generate a certain nu... | Make sure labels are ints. | Make sure labels are ints. | Python | bsd-3-clause | charanpald/APGL |
f2baef5e4b3b1c1d64f62a84625136befd4772ba | osOps.py | osOps.py | import os
def createDirectory(directoryPath):
return None
def createFile(filePath):
try:
createdFile = open(filePath, 'w+')
createdFile.close()
except IOError:
print "Error: could not create file at location: " + filePath
def getFileContents(filePath):
return None
def deleteF... | import os
def createDirectory(directoryPath):
if os.path.isdir(directoryPath) is False and os.path.exists(directoryPath) is False:
try:
os.makedirs(directoryPath)
except OSError:
print 'Error: Could not create directory at location: ' + directoryPath
def createFile(filePath... | Implement logic for directory creation | Implement logic for directory creation
| Python | apache-2.0 | AmosGarner/PyInventory |
775d9a5d1b38b8973357a1a861da04848a7f39ad | osOps.py | osOps.py | import os
def createDirectory(directoryPath):
if os.path.isdir(directoryPath) is False and os.path.exists(directoryPath) is False:
try:
os.makedirs(directoryPath)
except OSError:
print 'Error: Could not create directory at location: ' + directoryPath
def createFile(filePath... | import os
def createDirectory(directoryPath):
if os.path.isdir(directoryPath) is False and os.path.exists(directoryPath) is False:
try:
os.makedirs(directoryPath)
except OSError:
print 'Error: Could not create directory at location: ' + directoryPath
def createFile(filePath... | Implement open file and get file contents functionality | Implement open file and get file contents functionality
| Python | apache-2.0 | AmosGarner/PyInventory |
b902c32237febd976ae899bea41195adc58920d0 | tests/context.py | tests/context.py | from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
@patch('invoke.context.run')
def honors_warn_state(self, run):
Context(run={'warn': True}).run('x')
run.assert_called_with('x', warn=True)
| from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
def _honors(self, kwarg, value):
with patch('invoke.context.run') as run:
Context(run={kwarg: value}).run('x')
run.assert_called_with('x', **{kwarg... | Refactor + add test for run(hide) | Refactor + add test for run(hide)
| Python | bsd-2-clause | pyinvoke/invoke,mattrobenolt/invoke,pfmoore/invoke,tyewang/invoke,pyinvoke/invoke,frol/invoke,kejbaly2/invoke,mkusz/invoke,frol/invoke,mkusz/invoke,kejbaly2/invoke,pfmoore/invoke,singingwolfboy/invoke,sophacles/invoke,mattrobenolt/invoke |
bd8c4e3640649cb9253f7a10088d8e879afc5b4f | st2client/st2client/models/keyvalue.py | st2client/st2client/models/keyvalue.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Add back code which is needed. | Add back code which is needed.
| Python | apache-2.0 | StackStorm/st2,nzlosh/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2 |
240ae629ba54d79d9306227fa9a88e8bc93324ea | tests/extractor_test.py | tests/extractor_test.py | import os
import shutil
from nose.tools import *
import beastling.beastxml
import beastling.configuration
import beastling.extractor
def test_extractor():
config = beastling.configuration.Configuration(configfile="tests/configs/embed_data.conf")
config.process()
xml = beastling.beastxml.BeastXml(config)
... | import os
import shutil
from nose.tools import *
import beastling.beastxml
import beastling.configuration
import beastling.extractor
_test_dir = os.path.dirname(__file__)
def test_extractor():
config = beastling.configuration.Configuration(configfile="tests/configs/embed_data.conf")
config.process()
xml... | Clean up afterwards, even if test fails. | Clean up afterwards, even if test fails.
| Python | bsd-2-clause | lmaurits/BEASTling |
ba1de19895b001069966a10d9c72b8485c4b4195 | tests/testapp/views.py | tests/testapp/views.py | from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.utils.html import format_html, mark_safe
from content_editor.contents import contents_for_mptt_item
from content_editor.renderer import PluginRenderer
from .models import Page, RichText, Image, Snippet, Externa... | from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render
from django.utils.html import format_html
from content_editor.contents import contents_for_mptt_item
from content_editor.renderer import PluginRenderer
from feincms3 import plugins
from .models import Page, RichText, Imag... | Use render_richtext in test suite | Use render_richtext in test suite
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 |
7b1773d5c3fa07899ad9d56d4ac488c1c2e2014e | dope_cherry.py | dope_cherry.py | #!/usr/bin/env python
# coding=utf8
# This is an example of how to run dope (or any other WSGI app) in CherryPy.
# Running it will start dope at the document root, and the server on port 80.
#
# Assuming a virtual environment in which cherrypy is installed, this would be
# the way to run it:
#
# $ /path/to/virtualenv/... | #!/usr/bin/env python
# coding=utf8
# This is an example of how to run dope (or any other WSGI app) in CherryPy.
# Running it will start dope at the document root, and the server on port 80.
#
# Assuming a virtual environment in which cherrypy is installed, this would be
# the way to run it:
#
# $ /path/to/virtualenv/... | Set server.max_request_body_size in cherrypy settings to allow more then 100M uploads. | Set server.max_request_body_size in cherrypy settings to allow more then 100M uploads.
| Python | mit | mbr/dope,mbr/dope |
fd14dc0cd191b4060562a83fad29ab852044f1fc | subscriptions/management/commands/add_prepend_next_to_subscriptions.py | subscriptions/management/commands/add_prepend_next_to_subscriptions.py | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call servic... | from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call service.")
def add_arguments(self, parser):
par... | Remove unused ObjectDoesNotExist exception import | Remove unused ObjectDoesNotExist exception import
| Python | bsd-3-clause | praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-staged-based-messaging |
b42d762acd30a19b5035b536a8d3c059b74dc5ed | setup.py | setup.py | from distutils.core import setup
setup(
name = 'pybenchmark',
packages = ['pybenchmark'], # this must be the same as the name above
version = '0.0.4',
description = 'A benchmark utility used in performance tests.',
author = 'Eugene Duboviy',
author_email = 'eugene.dubovoy@gmail.com',
url = 'https://github... | from distutils.core import setup
setup(
name = 'pybenchmark',
packages = ['pybenchmark'], # this must be the same as the name above
version = '0.0.5',
description = 'A benchmark utility used in performance tests.',
author = 'Eugene Duboviy',
author_email = 'eugene.dubovoy@gmail.com',
url = 'https://github... | Add new PyPI release version | Add new PyPI release version
| Python | mit | duboviy/pybenchmark |
a80a875a62f3cf4e73eb47934b7589b00042d369 | staticmodel/django/__init__.py | staticmodel/django/__init__.py | """
******************
Django integration
******************
**Static Model** provides two custom Django model fields in the
``staticmodel.django.fields`` module:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelIntegerField`` (sub-class of ``django.db.models.IntegerField``)
... | """
************************
Django model integration
************************
**Static Model** provides custom Django model fields in the
``staticmodel.django.models`` package:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelTextField`` (sub-class of ``django.db.models.TextF... | Fix django model field docstring. | Fix django model field docstring.
| Python | mit | wsmith323/staticmodel |
117de7c9ff56388ae7e33fb05f146710e423f174 | setup.py | setup.py | from distutils.core import setup
setup(
name='Decouple',
version='1.2.1',
packages=['Decouple', 'Decouple.BatchPlugins'],
license='LICENSE',
description='Decouple and recouple.',
long_description=open('README.md').read(),
author='Sven Kreiss, Kyle Cranmer',
author_email='sk@svenkreiss.... | from distutils.core import setup
setup(
name='Decouple',
version='1.2.2',
packages=['Decouple', 'Decouple.BatchPlugins', 'scripts'],
license='LICENSE',
description='Decouple and recouple.',
long_description=open('README.md').read(),
author='Sven Kreiss, Kyle Cranmer',
author_email='sk@... | Include 'scripts' as module in package. | Include 'scripts' as module in package.
| Python | mit | svenkreiss/decouple |
ccb9aebb5f2338e12d8aa79d65fa1a6e972e76c2 | todobackend/__init__.py | todobackend/__init__.py | from logging import getLogger, basicConfig, INFO
from os import getenv
from aiohttp import web
from .middleware import cors_middleware_factory
from .views import (
IndexView,
TodoView,
)
IP = '0.0.0.0'
PORT = getenv('PORT', '8000')
basicConfig(level=INFO)
logger = getLogger(__name__)
async def init(loop):
... | from logging import getLogger, basicConfig, INFO
from os import getenv
from aiohttp import web
from .middleware import cors_middleware_factory
from .views import (
IndexView,
TodoView,
)
IP = getenv('IP', '0.0.0.0')
PORT = getenv('PORT', '8000')
basicConfig(level=INFO)
logger = getLogger(__name__)
async de... | Allow users to specify IP | MOD: Allow users to specify IP
| Python | mit | justuswilhelm/todobackend-aiohttp |
8fe31c3fbf3853d679f29b6743d05478cc1413f9 | tests/unit/utils/test_utils.py | tests/unit/utils/test_utils.py | # coding=utf-8
'''
Test case for utils/__init__.py
'''
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pytest = None
import salt.utils
@skipIf(pytest is None, 'PyTest is missing... | # coding=utf-8
'''
Test case for utils/__init__.py
'''
from __future__ import unicode_literals, print_function, absolute_import
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pyt... | Add unit test to check if the environment returns a correct type | Add unit test to check if the environment returns a correct type
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
774915b91358b2e8ec7f665826b3dde4be1b5607 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='1.1.0',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.6-3.',
long_description=open(joi... | #!/usr/bin/env python
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='1.1.0',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.6-3.',
long_description=open(joi... | Extend list of supported python versions | Extend list of supported python versions
| Python | mit | davidaurelio/hashids-python |
7a393502b36567dce93df718d716373414e2e674 | test_noise_addition.py | test_noise_addition.py | # #!/usr/bin python
#Test Noise Addition:
import numpy as np
import matplotlib.pyplot as plt
def add_noise(flux, SNR):
"Using the formulation mu/sigma"
mu = np.mean(flux)
sigma = mu / SNR
# Add normal distributed noise at the SNR level.
noisey_flux = flux + np.random.normal(0, sigma, len(flux))
... | #!/usr/bin/env python
#Test Noise Addition:
import numpy as np
import matplotlib.pyplot as plt
def add_noise(flux, SNR):
"Using the formulation mu/sigma"
mu = np.mean(flux)
sigma = mu / SNR
# Add normal distributed noise at the SNR level.
noisey_flux = flux + np.random.normal(0, sigma, len(flux))... | Fix noise calculation, add printing to check SNR value of data | Fix noise calculation, add printing to check SNR value of data
| Python | mit | jason-neal/companion_simulations,jason-neal/companion_simulations |
bcf7b9a670b2ad1ad1962879de2009453e98a315 | setup.py | setup.py | from distutils.core import setup
import skyfield # to learn the version
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst').read(),
license='MIT',
author='Brandon Rhodes',
author_email='brandon@rhodesmill... | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst').read(),
license='MIT',
author='Brandon Rhodes',
... | Make it clearer when import could be a bad idea | Make it clearer when import could be a bad idea
| Python | mit | skyfielders/python-skyfield,exoanalytic/python-skyfield,ozialien/python-skyfield,GuidoBR/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,GuidoBR/python-skyfield |
fcef30a09d24ade495085fc281c334da0098f727 | tests/test_commands.py | tests/test_commands.py | from pim.commands.init import _defaults, _make_package
from pim.commands.install import install
from pim.commands.uninstall import uninstall
from click.testing import CliRunner
def _create_test_package():
d = _defaults()
d['description'] = 'test package'
_make_package(d, True)
return d
def test_insta... | from pim.commands.init import _defaults, _make_package
from pim.commands.install import install
from pim.commands.uninstall import uninstall
from click.testing import CliRunner
def _create_test_package():
"""Helper function to create a test package"""
d = _defaults()
d['description'] = 'test package'
... | Add docstring to test functions | DOC: Add docstring to test functions
| Python | mit | freeman-lab/pim |
6c488d267cd5919eb545855a522d5cd7ec7d0fec | molly/utils/management/commands/generate_cache_manifest.py | molly/utils/management/commands/generate_cache_manifest.py | import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
... | import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
... | Revert "Don't cache markers, admin files or uncompressed JS/CSS" | Revert "Don't cache markers, admin files or uncompressed JS/CSS"
This reverts commit 357d4053e80e433b899ecacc15fba2a04cd6032b.
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
aa3a79f3e733e65e354e0c1c63bf3efe0f128fc1 | contentcuration/contentcuration/views/json_dump.py | contentcuration/contentcuration/views/json_dump.py | import json
from rest_framework.renderers import JSONRenderer
"""
Format data such that it can be safely loaded by JSON.parse in javascript
1. create a JSON string
2. second, correctly wrap the JSON in quotes for inclusion in JS
Ref: https://github.com/learningequality/kolibri/issues/6044
"""
def _json_dumps(v... | import json
from rest_framework.renderers import JSONRenderer
"""
Format data such that it can be safely loaded by JSON.parse in javascript
1. create a JSON string
2. second, correctly wrap the JSON in quotes for inclusion in JS
Ref: https://github.com/learningequality/kolibri/issues/6044
"""
def _json_dumps(v... | Update json bootstrapping code for Py3. | Update json bootstrapping code for Py3.
| Python | mit | DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation |
e647731ecd2f7c3d68744137e298143529962693 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='Splango',
version='0.1',
description='Split (A/B) testing library for Django',
author='Shimon Rura',
author_email='shimon@rura.org',
url='http://github.com/shimon/Splango',
packages=['splango','splango.templatetags'... | #!/usr/bin/env python
from distutils.core import setup
setup(name='Splango',
version='0.1',
description='Split (A/B) testing library for Django',
author='Shimon Rura',
author_email='shimon@rura.org',
url='http://github.com/shimon/Splango',
packages=['splango','splango.templatetags'... | Make sure templates get included | Make sure templates get included
| Python | mit | shimon/Splango |
1e1430d89d0cbd5f1de04194ac394b703c86693d | virtool/api/genbank.py | virtool/api/genbank.py | """
Provides request handlers for managing and viewing analyses.
"""
import aiohttp
import aiohttp.web
import virtool.genbank
import virtool.http.proxy
import virtool.http.routes
from virtool.api.utils import bad_gateway, json_response, not_found
routes = virtool.http.routes.Routes()
@routes.get("/api/genbank/{acc... | """
Provides request handlers for managing and viewing analyses.
"""
import aiohttp
import aiohttp.client_exceptions
import virtool.genbank
import virtool.http.proxy
import virtool.http.routes
from virtool.api.utils import bad_gateway, json_response, not_found
routes = virtool.http.routes.Routes()
@routes.get("/ap... | Return 502 when NCBI unavailable | Return 502 when NCBI unavailable
| Python | mit | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool |
057aecebb701810c57cac5b8e44a5d5d0a03fa12 | virtool/error_pages.py | virtool/error_pages.py | import os
import sys
from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
@web.middleware
async def middleware(req, handler):
is_api_call = req.path.startswith("/api")
try:
response = await handler(req)
if not is_api_call and response.status =... | import os
import sys
from aiohttp import web
from mako.template import Template
from virtool.utils import get_static_hash
from virtool.handlers.utils import json_response
@web.middleware
async def middleware(req, handler):
is_api_call = req.path.startswith("/api")
try:
response = await handler(req)
... | Return json error response for ALL api errors | Return json error response for ALL api errors
HTML responses were being returned for non-existent endpoints. This was resulting on some uncaught exceptions. | Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool |
2721a3d5c8bfcf3a6945e8744e4887688578ce9f | tests/test_emailharvesterws.py | tests/test_emailharvesterws.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
import pytest
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
print(emails_found)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
| Revert "Revert "Fix a codacy issue"" | Revert "Revert "Fix a codacy issue""
This reverts commit 6551c882745b13d5b9be183e83f379e34b067921.
| Python | mit | avidot/Botanick |
e7e2c68a147adc9e7d0da69740d4698b7c100796 | micro.py | micro.py | #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def parse_function(tokens):
return 'test', (23, None), tokens[-1... | #!/usr/bin/env python
from sys import argv
from operator import add, sub, mul, div
from uuid import uuid4
functions = { \
'+': (2, add), \
'-': (2, sub), \
'*': (2, mul), \
'/': (2, div) \
}
def get_code():
return argv[1]
def get_tokens(code):
return code.split(' ')
def generate_name():
return str(uuid4())
... | Add a parsing of a function name. | Add a parsing of a function name.
| Python | mit | thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro |
f46526a5a42ec324de4925a208c23a46c48658c9 | pages/views.py | pages/views.py | from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.... | from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.... | Fix a bug with an empty database | Fix a bug with an empty database | Python | bsd-3-clause | pombreda/django-page-cms,google-code-export/django-page-cms,pombreda/django-page-cms,google-code-export/django-page-cms,google-code-export/django-page-cms,Alwnikrotikz/django-page-cms,odyaka341/django-page-cms,Alwnikrotikz/django-page-cms,Alwnikrotikz/django-page-cms,PiRSquared17/django-page-cms,pombreda/django-page-cm... |
7e15c50628f5d0a03b5407923a1dc2db99932ba3 | partner_company_group/models/res_partner.py | partner_company_group/models/res_partner.py | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class Contact(models.Model):
_inherit = "res.partner"
company_group_id = fields.Many2one(
"res.partner", "Company group", domain=[("is_company", "=", True)]
)
... | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class Contact(models.Model):
_inherit = "res.partner"
company_group_id = fields.Many2one(
"res.partner", "Company group", domain=[("is_company", "=", True)]
)
c... | Add one2many counterpart for company_group_id TT34815 | [IMP] partner_company_group: Add one2many counterpart for company_group_id
TT34815
| Python | agpl-3.0 | OCA/partner-contact,OCA/partner-contact |
2124c66d11e46878492970e73700e3e0028a3f1e | mopidy/internal/gi.py | mopidy/internal/gi.py | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, GObject, Gst
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
... | from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GLib, GObject, Gst
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
... | Set GLib prgname and application name | Set GLib prgname and application name
This makes Mopidy properly show up in pulseaudio as "Mopidy" instead of
"python*"
| Python | apache-2.0 | adamcik/mopidy,kingosticks/mopidy,mopidy/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,mopidy/mopidy,adamcik/mopidy,jcass77/mopidy,adamcik/mopidy,jcass77/mopidy,jodal/mopidy,kingosticks/mopidy,jodal/mopidy,jcass77/mopidy |
e7e043884244cc6bf38027db99a14e184cd1eda2 | gapipy/resources/flights/flight_status.py | gapipy/resources/flights/flight_status.py | from ..base import Resource
from .flight_segment import FlightSegment
class FlightStatus(Resource):
_as_is_fields = [
'current_segment',
'departure_service_action',
'flags',
'href',
'id',
'internal',
'segments_order',
'state',
]
@property
... | from ..base import Resource
from .flight_segment import FlightSegment
class FlightStatus(Resource):
_resource_name = 'flight_statuses'
_as_is_fields = [
'current_segment',
'departure_service_action',
'flags',
'href',
'id',
'internal',
'segments_order',... | Add resource name to FlightStatus | Add resource name to FlightStatus
| Python | mit | gadventures/gapipy |
af010c5e924a779a37495905efc32aecdfd358ea | whalelinter/commands/common.py | whalelinter/commands/common.py | #!/usr/bin/env python3
import re
from whalelinter.app import App
from whalelinter.dispatcher import Dispatcher
from whalelinter.commands.command import ShellCommand
from whalelinter.commands.apt import Apt
@Dispatcher.register(token='run', command='cd')
class Cd(ShellCommand):
def ... | #!/usr/bin/env python3
import re
from whalelinter.app import App
from whalelinter.dispatcher import Dispatcher
from whalelinter.commands.command import ShellCommand
from whalelinter.commands.apt import Apt
@Dispatcher.register(token='run', command='cd')
class Cd(ShellCommand):
def ... | Fix line addressing issue on 'cd' command | Fix line addressing issue on 'cd' command
| Python | mit | jeromepin/whale-linter |
d327b6651234c33549f35d5d5411012d2419634b | anillo/middlewares/cors.py | anillo/middlewares/cors.py | import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):
def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.... | import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):
def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.... | Add the ability to use the middleware decorator without arguments. | Add the ability to use the middleware decorator without arguments.
| Python | bsd-2-clause | jespino/anillo,hirunatan/anillo,jespino/anillo,hirunatan/anillo |
298d9fc5264fc80089034c4770369d65e898e3e0 | anillo/middlewares/cors.py | anillo/middlewares/cors.py | import functools
def wrap_cors(
func=None,
*,
allow_origin='*',
allow_headers=set(["Origin", "X-Requested-With", "Content-Type", "Accept"])):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.
This middlware accept... | import functools
DEFAULT_HEADERS = frozenset(["origin", "x-requested-with", "content-type", "accept"])):
def wrap_cors(func=None, *, allow_origin='*', allow_headers=DEFAULT_HEADERS):
"""
A middleware that allow CORS calls, by adding the
headers Access-Control-Allow-Origin and Access-Control-Allow-Headers.... | Put default headers as constant and make it immutable. | Put default headers as constant and make it immutable.
With additional cosmetic fixes.
| Python | bsd-2-clause | jespino/anillo,hirunatan/anillo,jespino/anillo,hirunatan/anillo |
7e7be00f696bd9fea2e9f18e126d27b6e9e1882d | jarn/mkrelease/python.py | jarn/mkrelease/python.py | import sys
from exit import err_exit
class Python(object):
"""Python interpreter abstraction."""
def __init__(self, python=None, version_info=None):
self.python = sys.executable
self.version_info = sys.version_info
if python is not None:
self.python = python
if ve... | import sys
from exit import err_exit
class Python(object):
"""Python interpreter abstraction."""
def __init__(self, python=None, version_info=None):
self.python = python or sys.executable
self.version_info = version_info or sys.version_info
def __str__(self):
return self.python
... | Use terser idiom for initialization. | Use terser idiom for initialization.
| Python | bsd-2-clause | Jarn/jarn.mkrelease |
012235fd93e77de19065a0e906554887e27580fd | kitsune/sumo/models.py | kitsune/sumo/models.py | from django.conf import settings
from django.db import models
class ModelBase(models.Model):
"""Base class for SUMO models.
* Adds objects_range class method.
* Adds update method.
"""
class Meta:
abstract = True
@classmethod
def objects_range(cls, before=None, after=None):
... | from django.conf import settings
from django.db import models
class ModelBase(models.Model):
"""Base class for SUMO models.
* Adds objects_range class method.
* Adds update method.
"""
class Meta:
abstract = True
@classmethod
def objects_range(cls, before=None, after=None):
... | Use Django's default update method | Use Django's default update method
| Python | bsd-3-clause | mozilla/kitsune,mozilla/kitsune,mozilla/kitsune,mozilla/kitsune |
be5ffde03bd08a613353c876fd91b35f8a38d76a | oidc_provider/urls.py | oidc_provider/urls.py | from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.views import *
urlpatterns = patterns('',
url(r'^authorize/?$', AuthorizeView.as_view(), name='authorize'),
url(r'^token/?$', csrf_exempt(TokenView.as_view()), name='token'),
url(r'... | from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from oidc_provider.views import *
urlpatterns = [
url(r'^authorize/?$', AuthorizeView.as_view(), name='authorize'),
url(r'^token/?$', csrf_exempt(TokenView.as_view()), name='token'),
url(r'^userinfo/?... | Remove patterns which will be deprecated in 1.10 | Remove patterns which will be deprecated in 1.10
| Python | mit | torreco/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oidc-provider,bunnyinc/django-oidc-provider,torreco/django-oidc-provider,bunnyinc/django-oidc-provider,juanifioren/django-oidc-provider,juanifioren/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oi... |
96d7a2a3a3250993084c1847436711ceaea988fc | app/database.py | app/database.py | from app import app
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, prompt_bool
from datetime import datetime
db = SQLAlchemy(app)
manager = Manager(usage="Manage the database")
@manager.command
def create():
"Create the database"
db.create_all()
@manager.command
def drop()... | from app import app
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, prompt_bool
from datetime import datetime
db = SQLAlchemy(app)
manager = Manager(usage="Manage the database")
@manager.command
def create():
"Create the database"
db.create_all()
@manager.command
def drop()... | Change unuique keys to MySQL varchar | Change unuique keys to MySQL varchar
| Python | mit | taeram/idiocy,taeram/idiocy,taeram/idiocy |
9a0cab561ea76a3d54cd410bacbe13a4f5e9f35b | server/admin.py | server/admin.py | from django.contrib import admin
from server.models import *
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
admin.site.register(UserProfile)
admin.site.register(BusinessUnit)
admin.site.register(MachineGroup... | from django.contrib import admin
from server.models import *
class ApiKeyAdmin(admin.ModelAdmin):
list_display = ('name', 'public_key', 'private_key')
class MachineAdmin(admin.ModelAdmin):
list_display = ('hostname', 'serial')
class MachineGroupAdmin(admin.ModelAdmin):
readonly_fields = ('key',)
ad... | Sort registrations. Separate classes of imports. Add API key display. | Sort registrations. Separate classes of imports. Add API key display.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal |
569cc559e32f31d3256ff2df3a491a55384e5c27 | lib/pylprof/imports.py | lib/pylprof/imports.py | from line_profiler import LineProfiler
lp = LineProfiler()
profile = lp.runcall
| from line_profiler import LineProfiler
lp = LineProfiler()
lp.enable_profile_all()
profile = lp.runcall
| Use new version of line profiler | [pylprof] Use new version of line profiler
| Python | mit | iddl/pprofile,iddl/pprofile |
236eaa669027199c2bc53e225b8ffcc6427e78cd | CodeFights/simpleComposition.py | CodeFights/simpleComposition.py | #!/usr/local/bin/python
# Code Fights Simple Composition Problem
from functools import reduce
import math
def compose(f, g):
return lambda x: f(g(x))
def simpleComposition(f, g, x):
return compose(eval(f), eval(g))(x)
# Generic composition of n functions:
def compose_n(*functions):
return reduce(lamb... | #!/usr/local/bin/python
# Code Fights Simple Composition Problem
import math
def compose(f, g):
return lambda x: f(g(x))
def simpleComposition(f, g, x):
return compose(eval(f), eval(g))(x)
def main():
tests = [
["math.log10", "abs", -100, 2],
["math.sin", "math.cos", 34.4, math.sin(ma... | Remove generic function composition example - didn't work | Remove generic function composition example - didn't work
| Python | mit | HKuz/Test_Code |
d085f8de9d428d0c84d281ad6782d86f4bb0d242 | photutils/conftest.py | photutils/conftest.py | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | Remove h5py from pytest header | Remove h5py from pytest header | Python | bsd-3-clause | larrybradley/photutils,astropy/photutils |
2c64ba2bf9e67d6fb3e12a16489900ae7319ca33 | RasPi/VR/VR_split_image_v0.1.py | RasPi/VR/VR_split_image_v0.1.py | #! /usr/bin/env python
import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
# read input image
img = cv2.imread('/home/pi/OCR/VR/tempImg.jpg')
# Extract only those image areas where VR information will exist
# Assumes that Rover positioning while imaging is perfect
# left_img = img... | #! /usr/bin/env python
import sys
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
# set the current working directory
os.chdir('/home/pi/OCR/VR/')
# read input image
img = cv2.imread('tempImg.jpg')
# Extract only those image areas where VR information will exist
# Assumes t... | Set current working directory to unify hardcoded paths | Set current working directory to unify hardcoded paths | Python | apache-2.0 | ssudheen/Watson-Rover,ssudheen/Watson-Rover,ssudheen/Watson-Rover,ssudheen/Watson-Rover |
a0ba91395dc02f92e58395e41db77af12439a507 | arrow/__init__.py | arrow/__init__.py | # -*- coding: utf-8 -*-
from ._version import __version__
from .api import get, now, utcnow
from .arrow import Arrow
from .factory import ArrowFactory
| # -*- coding: utf-8 -*-
from ._version import __version__
from .api import get, now, utcnow
from .arrow import Arrow
from .factory import ArrowFactory
from .parser import ParserError
| Add ParserError to the module exports. | Add ParserError to the module exports.
Adding ParserError to the module exports allows users to easily catch that specific error. It also eases lookup of that error for tools like PyCharm. | Python | apache-2.0 | crsmithdev/arrow |
8244d43bb87a2ea88ab1ee0c9cedee77eeb994ba | plumbium/artefacts.py | plumbium/artefacts.py | import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self.filename = filename
self._ext_length = len(extension)
def checksum(self):
return file_sha1sum(s... | import os.path
from utils import file_sha1sum
class Artefact(object):
def __init__(self, filename, extension):
if not filename.endswith(extension):
raise ValueError
self._filename = filename
self._ext_length = len(extension)
self._abspath = os.path.abspath(filename)
... | Add abspath and exists methods to Artefact | Add abspath and exists methods to Artefact
| Python | mit | jstutters/Plumbium |
e04123ce0b368b19015270b1fc1bd1f706c765cf | pwm/_compat.py | pwm/_compat.py | """
pwm._compat
~~~~~~~~~~~
Micro compatiblity library. Or superlight six, if you want. Like a five, or something.
"""
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection... | """
pwm._compat
~~~~~~~~~~~
Micro compatiblity library. Or superlight six, if you want. Like a five, or something.
"""
# pylint: disable=unused-import
import sys
PY2 = sys.version_info[0] == 2
if PY2: # pragma: no cover
from ConfigParser import RawConfigParser
from httplib import HTTPConnection... | Fix python 3 input compatiblity | Fix python 3 input compatiblity
| Python | mit | thusoy/pwm,thusoy/pwm |
5e2dbeab75501254da598c6c401cbbd8446f01a5 | util/timeline_adjust.py | util/timeline_adjust.py | #!/usr/bin/python
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float... | #!/usr/bin/python
from __future__ import print_function
import argparse
import re
time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")
def adjust_lines(lines, adjust):
for line in lines:
match = re.match(time_re, line)
if match:
time = float... | Fix timeline adjust not being able to load Windows files | Fix timeline adjust not being able to load Windows files
| Python | apache-2.0 | quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot |
1ceea35669fd8e6eff5252ef6607289619f0f3c2 | certbot/tests/main_test.py | certbot/tests/main_test.py | """Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def _call(self, args):
plugins = plugins_disco.... | """Tests for certbot.main."""
import unittest
import mock
from certbot import cli
from certbot import configuration
from certbot.plugins import disco as plugins_disco
class ObtainCertTest(unittest.TestCase):
"""Tests for certbot.main.obtain_cert."""
def setUp(self):
self.get_utility_patch = mock.... | Improve obtain_cert no pause test | Improve obtain_cert no pause test
| Python | apache-2.0 | lmcro/letsencrypt,jsha/letsencrypt,dietsche/letsencrypt,letsencrypt/letsencrypt,stweil/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,wteiken/letsencrypt,bsmr-misc-forks/letsencrypt,lmcro/letsencrypt,stweil/letsencrypt,jtl999/certbot,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,DavidGarciaCat/letsenc... |
14a085f787f5fe80a0737d97515b71adaf05d1cd | checker/checker/contest.py | checker/checker/contest.py | #!/usr/bin/python3
from checker.abstract import AbstractChecker
import base64
import sys
import codecs
class ContestChecker(AbstractChecker):
def __init__(self, tick, team, service, ip):
AbstractChecker.__init__(self, tick, team, service, ip)
def _rpc(self, function, *args):
sys.stdout.write... | #!/usr/bin/python3
from checker.abstract import AbstractChecker
import base64
import sys
import codecs
class ContestChecker(AbstractChecker):
def __init__(self, tick, team, service, ip):
AbstractChecker.__init__(self, tick, team, service, ip)
def _rpc(self, function, *args):
sys.stdout.write... | Fix double-encoding of binary blobs | Fix double-encoding of binary blobs
| Python | isc | fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver |
424a5da1e867b5b77fe5f241ef0a825988157811 | moksha/config/app_cfg.py | moksha/config/app_cfg.py | from tg.configuration import AppConfig, Bunch
import moksha
from moksha import model
from moksha.lib import app_globals, helpers
base_config = AppConfig()
base_config.package = moksha
# Set the default renderer
base_config.default_renderer = 'mako'
base_config.renderers = []
base_config.renderers.append('mako')
# @... | from tg.configuration import AppConfig, Bunch
import moksha
from moksha import model
from moksha.lib import app_globals, helpers
base_config = AppConfig()
base_config.package = moksha
# Set the default renderer
base_config.default_renderer = 'mako'
base_config.renderers = []
base_config.renderers.append('genshi')
ba... | Load up the genshi renderer | Load up the genshi renderer
| Python | apache-2.0 | lmacken/moksha,ralphbean/moksha,pombredanne/moksha,pombredanne/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha |
c35c11fb546123d0aada37fe7d7ab1829a6fa9f0 | graphenebase/transactions.py | graphenebase/transactions.py | from collections import OrderedDict
from binascii import hexlify, unhexlify
from calendar import timegm
from datetime import datetime
import json
import struct
import time
from .account import PublicKey
from .chains import known_chains
from .signedtransactions import Signed_Transaction
from .operations import Operatio... | from collections import OrderedDict
from binascii import hexlify, unhexlify
from calendar import timegm
from datetime import datetime
import json
import struct
import time
from .account import PublicKey
from .chains import known_chains
from .signedtransactions import Signed_Transaction
from .operations import Operatio... | Revert "[TaPOS] link to the last irreversible block instead of headblock" | Revert "[TaPOS] link to the last irreversible block instead of headblock"
This reverts commit 05cec8e450a09fd0d3fa2b40860760f7bff0c125.
| Python | mit | xeroc/python-graphenelib |
2e723dc3244d1d485fa7c27f06807fa39f62f5d1 | account_fiscal_position_no_source_tax/account.py | account_fiscal_position_no_source_tax/account.py | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v8 # noqa
def map_tax(self, taxes):
result = super(account_fiscal_position, self).map_tax(taxes)
taxes_without_src_ids = [
x.tax_dest_id.id for x... | from openerp import models, api, fields
class account_fiscal_position(models.Model):
_inherit = 'account.fiscal.position'
@api.v7
def map_tax(self, cr, uid, fposition_id, taxes, context=None):
result = super(account_fiscal_position, self).map_tax(
cr, uid, fposition_id, taxes, contex... | FIX fiscal position no source tax on v7 api | FIX fiscal position no source tax on v7 api
| Python | agpl-3.0 | csrocha/account_check,csrocha/account_check |
debb751e42229c702fe93430a44cb5674d9aacde | app/events/forms.py | app/events/forms.py | """Forms definitions."""
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
"""Form for EventCreateView."""
class Meta: # noqa
model = Event
fields = (
'title',
'date',
'venue',
'description',
'fb_... | """Forms definitions."""
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
"""Form for EventCreateView."""
class Meta: # noqa
model = Event
fields = (
'title',
'date',
'venue',
'description',
'fb_... | Add image upload to event form | Add image upload to event form
| Python | mit | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx |
27d083727e3ca8d0264fc08e96a15f1cdc6a5acc | orderedmodel/models.py | orderedmodel/models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not ... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, default=1)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not se... | Remove uniqueness of the order field | Remove uniqueness of the order field
This make possible adding the application in existing project
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel |
174e36358df2522f39154a47f3f79b7dffadb3fd | app/services/updater_service.py | app/services/updater_service.py | from app.system.updater import check_updates, do_upgrade, run_ansible
from app.system.updater import do_reboot
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().... | from os.path import basename
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.system.updater import do_reboot
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, ob... | Use base Repo name in updating UI. | Use base Repo name in updating UI.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer |
d64a171dfde57106a5abd7d46990c81c6250b965 | whitespaceterminator.py | whitespaceterminator.py | # coding: utf8
# Copyright © 2011 Kozea
# Licensed under a 3-clause BSD license.
"""
Strip trailing whitespace before saving.
"""
from gi.repository import GObject, Gedit
class WhiteSpaceTerminator(GObject.Object, Gedit.WindowActivatable):
"""Strip trailing whitespace before saving."""
window = GObject.pro... | # coding: utf8
# Copyright © 2011 Kozea
# Licensed under a 3-clause BSD license.
"""
Strip trailing whitespace before saving.
"""
from gi.repository import GObject, Gedit
class WhiteSpaceTerminator(GObject.Object, Gedit.WindowActivatable):
"""Strip trailing whitespace before saving."""
window = GObject.pro... | Connect on existing tabs when activating the plugin. | Connect on existing tabs when activating the plugin.
| Python | bsd-3-clause | Kozea/Gedit-WhiteSpace-Terminator |
f4f439f24dceb0c68f05a90196b3e4b525d1aa7a | setup.py | setup.py | #!/usr/bin/env python
import distutils.core
distutils.core.setup(
name='sunburnt',
version='0.4',
description='Python interface to Solr',
author='Toby White',
author_email='toby@timetric.com',
packages=['sunburnt'],
requires=['httplib2', 'lxml', 'pytz'],
license='WTFPL',
)
| #!/usr/bin/env python
import distutils.core
distutils.core.setup(
name='sunburnt',
version='0.4',
description='Python interface to Solr',
author='Toby White',
author_email='toby@timetric.com',
packages=['sunburnt'],
requires=['httplib2', 'lxml', 'pytz'],
license='WTFPL',
classifier... | Add some trove classifiers to the package metadata | Add some trove classifiers to the package metadata
| Python | mit | rlskoeser/sunburnt,pixbuffer/sunburnt-spatial,anmar/sunburnt,rlskoeser/sunburnt,pixbuffer/sunburnt-spatial,qmssof/sunburnt,tow/sunburnt,anmar/sunburnt |
00ca7bed25582d16cc47ecaa3908226ff7d56b0d | moocng/wsgi.py | moocng/wsgi.py | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | Allow it to run with runserver if you don't have the VIRTUALENV variable set | Allow it to run with runserver if you don't have the VIRTUALENV variable set
| Python | apache-2.0 | GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,OpenMOOC/moocng,GeographicaGS/moocng |
5e9619556d4d3403a314dba0aa0975b0ed5c7205 | setup.py | setup.py | from distutils.core import setup
setup(
name='txZMQ',
version=open('VERSION').read().strip(),
packages=['txzmq', 'txzmq.test'],
license='GPLv2',
author='Andrey Smirnov',
author_email='me@smira.ru',
url='https://github.com/smira/txZMQ',
description='Twisted bindings for ZeroMQ',
long... | import io
from distutils.core import setup
setup(
name='txZMQ',
version=io.open('VERSION', encoding='utf-8').read().strip(),
packages=['txzmq', 'txzmq.test'],
license='GPLv2',
author='Andrey Smirnov',
author_email='me@smira.ru',
url='https://github.com/smira/txZMQ',
description='Twiste... | Use io.open when reading UTF-8 encoded file for Python3 compatibility. | Use io.open when reading UTF-8 encoded file for Python3 compatibility.
This way both Python2 and Python3 can use setup.py to handle the package.
| Python | mpl-2.0 | smira/txZMQ |
7acd0f07522aa1752585f519109129f9e9b8687e | h2o-py/tests/testdir_algos/deeplearning/pyunit_iris_basic_deeplearning.py | h2o-py/tests/testdir_algos/deeplearning/pyunit_iris_basic_deeplearning.py | from builtins import range
import sys, os
sys.path.insert(1, os.path.join("..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
def deeplearning_basic():
iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"))
hh = H2ODeepL... | from builtins import range
import sys, os
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
def deeplearning_basic():
iris_hex = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"))
hh = H2ODeepLearningEstim... | Make sure pyuni_iris_basic_deeplearning can also run locally | Make sure pyuni_iris_basic_deeplearning can also run locally
| Python | apache-2.0 | jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,m... |
548329d5366e9b0f037a1df59efaeb6b36b5987d | aux2mongodb/auxservices/base.py | aux2mongodb/auxservices/base.py | from astropy.table import Table
import os
class AuxService:
renames = {}
ignored_columns = []
transforms = {}
basename = 'AUX_SERVICE'
def __init__(self, auxdir='/fact/aux'):
self.auxdir = auxdir
self.filename_template = os.path.join(
self.auxdir, '{date:%Y}', '{date... | from astropy.table import Table
import os
class AuxService:
renames = {}
ignored_columns = []
transforms = {}
basename = 'AUX_SERVICE'
def __init__(self, auxdir='/fact/aux'):
self.auxdir = auxdir
self.filename_template = os.path.join(
self.auxdir, '{date:%Y}', '{date... | Add method to read from filename | Add method to read from filename
| Python | mit | fact-project/aux2mongodb |
4b0a51dcfb1b71975d0064f0ce58d68660d45a13 | manage.py | manage.py | from os.path import abspath
from flask import current_app as app
from app import create_app
# from app.model import init_db
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '--cfgfile', dest='co... | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '--cfgfile', dest... | Add restdb function and db variable | Add restdb function and db variable | Python | mit | nerevu/prometheus-api,nerevu/prometheus-api,nerevu/prometheus-api |
aae5c02f8642eec08e87c102b7d255fb74b86c94 | pyluos/modules/led.py | pyluos/modules/led.py | from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
if new_color... | from .module import Module, interact
class Led(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'LED', id, alias, robot)
self.color = (0, 0, 0)
@property
def color(self):
return self._value
@color.setter
def color(self, new_color):
new_color = ... | Make sur the rgb values are within [0, 255] range. | Make sur the rgb values are within [0, 255] range.
| Python | mit | pollen/pyrobus |
29f6e1c46179257b6604a4314855b0347bc312ad | src/config.py | src/config.py | import json
import jsoncomment
class Config:
def __init_config_from_file(self, path):
with open(path) as f:
for k, v in jsoncomment.JsonComment(json).loads(f.read()).items():
self.__config[k] = v
def __init__(self, config):
self.__config = config
def __getitem... | import json
import jsoncomment
class Config:
def __init_config_from_file(self, path):
with open(path) as f:
for k, v in jsoncomment.JsonComment(json).loads(f.read()).items():
self.__config[k] = v
def __init__(self, config):
self.__config = config
def __getitem... | Remove 'fallback_path' handling from Config class | Remove 'fallback_path' handling from Config class
| Python | mit | sbobek/achievement-unlocked |
45da9e9d3eb2d8bba089c9a064e1a7c259da131a | bayespy/__init__.py | bayespy/__init__.py | ######################################################################
# Copyright (C) 2011-2013 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | ######################################################################
# Copyright (C) 2011-2013 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | Add plot module to automatically loaded modules | ENH: Add plot module to automatically loaded modules
| Python | mit | fivejjs/bayespy,bayespy/bayespy,jluttine/bayespy,SalemAmeen/bayespy |
72b660a9d71e1b29aa10a704e918c0c49dde8d86 | pygotham/admin/events.py | pygotham/admin/events.py | """Admin for event-related models."""
import wtforms
from pygotham.admin.utils import model_view
from pygotham.events import models
__all__ = ('EventModelView',)
CATEGORY = 'Events'
EventModelView = model_view(
models.Event,
'Events',
CATEGORY,
column_list=('name', 'slug', 'begins', 'ends', 'activ... | """Admin for event-related models."""
import wtforms
from pygotham.admin.utils import model_view
from pygotham.events import models
__all__ = ('EventModelView',)
CATEGORY = 'Events'
EventModelView = model_view(
models.Event,
'Events',
CATEGORY,
column_list=('name', 'slug', 'begins', 'ends', 'activ... | Exclude volunteers from the event admin | Exclude volunteers from the event admin
Showing many-to-many relationships in the admin can cause a page to take
a while to load. Plus the event admin isn't really the place to manage
volunteers.
Closes #198
| Python | bsd-3-clause | pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,PyGotham/pygotham,PyGotham/pygotham |
c01d29b4b2839976fd457a1e950ed5800150b315 | setup.py | setup.py | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"updat... | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"updat... | Update dependencies so installation is simpler. | Update dependencies so installation is simpler.
The pull request, and a new release of py-moneyed has occurred.
| Python | bsd-3-clause | recklessromeo/django-money,AlexRiina/django-money,iXioN/django-money,iXioN/django-money,rescale/django-money,recklessromeo/django-money,pjdelport/django-money,tsouvarev/django-money,tsouvarev/django-money |
935a44b454d83452e302130114c1f40d934bf2ed | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name = "f.lux indicator applet",
version = "1.1.8",
description = "f.lux indicator applet - better lighting for your computer",
author = "Kilian Valkhof, Michael and Lorna Herf, Josh Winters",
author_email = "kilian@kilianvalkhof.com",
u... | #!/usr/bin/env python
from distutils.core import setup
data_files=[('share/icons/hicolor/scalable/apps', ['fluxgui.svg', 'fluxgui-light.svg', 'fluxgui-dark.svg']),
('share/applications', ['desktop/fluxgui.desktop'])]
import os
if os.path.exists("xflux"):
data_files.append( ('bin', ['xflux']) )
setup(nam... | Drop xflux binary from debian package | Drop xflux binary from debian package
| Python | mit | NHellFire/f.lux-indicator-applet,esmail/f.lux-indicator-applet |
bb2c92732ee7cf834d937025a03c87d7ee5bc343 | tests/modules/test_traffic.py | tests/modules/test_traffic.py | import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_mi... | import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_mi... | Fix tests for module traffic | [tests/traffic] Fix tests for module traffic
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.