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 |
|---|---|---|---|---|---|---|---|---|---|
822cc689ce44b1c43ac118b2a13c6d0024d2e194 | tests/raw_text_tests.py | tests/raw_text_tests.py | from nose.tools import istest, assert_equal
from mammoth.raw_text import extract_raw_text_from_element
from mammoth import documents
@istest
def raw_text_of_text_element_is_value():
assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello")))
@istest
def raw_text_of_paragraph_is_terminated_wit... | from nose.tools import istest, assert_equal
from mammoth.raw_text import extract_raw_text_from_element
from mammoth import documents
@istest
def text_element_is_converted_to_text_content():
element = documents.Text("Hello.")
result = extract_raw_text_from_element(element)
assert_equal("Hello.", result)... | Make raw text tests consistent with mammoth.js | Make raw text tests consistent with mammoth.js
| Python | bsd-2-clause | mwilliamson/python-mammoth |
fd5387f1bb8ac99ed421c61fdff777316a4d3191 | tests/test_publisher.py | tests/test_publisher.py | import pytest
import pika
from mettle.settings import get_settings
from mettle.publisher import publish_event
def test_long_routing_key():
settings = get_settings()
conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url))
chan = conn.channel()
exchange = settings['state_exchange']
... | import pytest
import pika
from mettle.settings import get_settings
from mettle.publisher import publish_event
@pytest.mark.xfail(reason="Need RabbitMQ fixture")
def test_long_routing_key():
settings = get_settings()
conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url))
chan = conn.chann... | Mark test as xfail so that releases can be cut | Mark test as xfail so that releases can be cut
| Python | mit | yougov/mettle,yougov/mettle,yougov/mettle,yougov/mettle |
53636a17cd50d704b7b4563d0b23a474677051f4 | hub/prototype/config.py | hub/prototype/config.py | # put this into ~/.alphahub/config.py and make sure it's
# not readable by anyone else (it contains passwords!)
# the host we run on and want to receive packets on; note
# that "localhost" is probably the wrong thing here, you
# want your actual host name here so the sockets bind the
# right way and receive packets fr... | # put this into ~/.alphahub/config.py and make sure it's
# not readable by anyone else (it contains passwords!)
# the host we run on and want to receive packets on; note
# that "localhost" is probably the wrong thing here, you
# want your actual host name here so the sockets bind the
# right way and receive packets fr... | Make sure we give an example for two servers. | Make sure we give an example for two servers.
| Python | agpl-3.0 | madprof/alpha-hub |
d185407ac4caf5648ef4c12eab83fec81c307407 | tests/test_trackable.py | tests/test_trackable.py | # -*- coding: utf-8 -*-
"""
test_trackable
~~~~~~~~~~~~~~
Trackable tests
"""
import pytest
from utils import authenticate, logout
pytestmark = pytest.mark.trackable()
def test_trackable_flag(app, client):
e = 'matt@lp.com'
authenticate(client, email=e)
logout(client)
authenticate(clie... | # -*- coding: utf-8 -*-
"""
test_trackable
~~~~~~~~~~~~~~
Trackable tests
"""
import pytest
from utils import authenticate, logout
pytestmark = pytest.mark.trackable()
def test_trackable_flag(app, client):
e = 'matt@lp.com'
authenticate(client, email=e)
logout(client)
authenticate(clie... | Add mock X-Forwarded-For header in trackable tests | Add mock X-Forwarded-For header in trackable tests
| Python | mit | pawl/flask-security,reustle/flask-security,jonafato/flask-security,asmodehn/flask-security,quokkaproject/flask-security,LeonhardPrintz/flask-security-fork,dommert/flask-security,LeonhardPrintz/flask-security-fork,fuhrysteve/flask-security,CodeSolid/flask-security,simright/flask-security,inveniosoftware/flask-security-f... |
3bd9214465547ff6cd0f7ed94edf8dacf10135b5 | registration/backends/simple/urls.py | registration/backends/simple/urls.py | """
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... | """
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... | Clean up an import in simple backend URLs. | Clean up an import in simple backend URLs.
| Python | bsd-3-clause | dirtycoder/django-registration,ubernostrum/django-registration,myimages/django-registration,tdruez/django-registration,awakeup/django-registration |
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1 | easy_maps/geocode.py | easy_maps/geocode.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))`... | Resolve the 500 error when google send a no results info | Resolve the 500 error when google send a no results info
| Python | mit | duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps |
7c6f1bfca63ea0db8e07156b5122d0986b9cd1a5 | backend/breach/tests/test_sniffer.py | backend/breach/tests/test_sniffer.py | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')
@patch('breach.sniffer.request... | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
sniffer_params = {
'snifferendpoint': self.endpoint,
'sourceip': '147.102.239.229',
'host... | Update sniffer tests with new argument passing | Update sniffer tests with new argument passing
| Python | mit | dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafi... |
34e17142f565cfc27c15522212c4240944cb4001 | sauce/lib/helpers.py | sauce/lib/helpers.py | # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from tg import url as tgurl
from webhelpers import date, feedgenerator, html, number, misc, text
import re, textwrap
#log = logging.getLogger(__name__)
# shortcut for links
link_to = html.tags.link_to
def link(label, url='', **attrs):
... | # -*- coding: utf-8 -*-
"""WebHelpers used in SAUCE.
@author: moschlar
"""
from datetime import datetime
from tg import url as tgurl
#from webhelpers import date, feedgenerator, html, number, misc, text
import webhelpers as w
from webhelpers.html.tags import link_to
from webhelpers.text import truncate
from webhel... | Replace my own helper functions with webhelper ones | Replace my own helper functions with webhelper ones
| Python | agpl-3.0 | moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE |
25993238cb18212a2b83b2d6b0aa98939d38f192 | scripts/lwtnn-split-keras-network.py | scripts/lwtnn-split-keras-network.py | #!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-fi... | #!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-fi... | Remove Keras from network splitter | Remove Keras from network splitter
Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.
| Python | mit | lwtnn/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn |
3916efe4a017fe9e0fb1c5fe09b99f374d7a4060 | instana/__init__.py | instana/__init__.py | """
Instana sensor and tracer. It consists of two modules that can be used as entry points:
- sensor: activates the meter to collect and transmit all kind of built-in metrics
- tracer: OpenTracing tracer implementation. It implicitly activates the meter
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2016 ... | """
Instana sensor and tracer. It consists of two modules that can be used as entry points:
- sensor: activates the meter to collect and transmit all kind of built-in metrics
- tracer: OpenTracing tracer implementation. It implicitly activates the meter
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 ... | Update module init file; begin version stamping here. | Update module init file; begin version stamping here.
| Python | mit | instana/python-sensor,instana/python-sensor |
67fd73f8f035ac0e13a64971d9d54662df46a77f | karm/test/__karmutil.py | karm/test/__karmutil.py | import sys
import os
def dcopid():
'''Get dcop id of karm. Fail if more than one instance running.'''
id = stdin = stdout = None
try:
( stdin, stdout ) = os.popen2( "dcop" )
l = stdout.readline()
while l:
if l.startswith( "karm" ):
if not id: id = l
else: raise "Only one instan... | import sys
import os
class KarmTestError( Exception ): pass
def dcopid():
'''Get dcop id of karm. Fail if more than one instance running.'''
id = stdin = stdout = None
( stdin, stdout ) = os.popen2( "dcop" )
l = stdout.readline()
while l:
if l.startswith( "karm" ):
if not id: id = l
else: r... | Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. | Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
svn path=/trunk/kdepim/; revision=367066
| Python | lgpl-2.1 | lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi |
d237c121955b7249e0e2ab5580d2abc2d19b0f25 | noveltorpedo/models.py | noveltorpedo/models.py | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
contents = models.TextFie... | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
... | Allow a story to have many authors | Allow a story to have many authors
| Python | mit | NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo |
8b33c216b2da4a7bf480d79675325134777db9ae | wsme/release.py | wsme/release.py | name = "WSME"
version = "0.3"
description = "Web Services Made Easy"
author = "Christophe de Vienne"
email = "python-wsme@googlegroups.com"
url = "http://bitbucket.org/cdevienne/wsme"
license = "MIT"
| name = "WSME"
version = "0.3"
description = """Web Services Made Easy makes it easy to \
implement multi-protocol webservices."""
author = "Christophe de Vienne"
email = "python-wsme@googlegroups.com"
url = "http://bitbucket.org/cdevienne/wsme"
license = "MIT"
| Change a bit the short description to make it more explicit | Change a bit the short description to make it more explicit
| Python | mit | stackforge/wsme |
0ac053e9c27f8381bb1aceff0bfdb12fc9c952cb | tests/test_config.py | tests/test_config.py | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | Test default values for Riemann | Test default values for Riemann
| Python | mit | CodersOfTheNight/oshino |
d8b3e511b00c9b5a8c7951e16d06173fe93d6501 | engine/util.py | engine/util.py | import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x):
time.slee... | import json
import threading
import Queue
from datetime import datetime,date,timedelta
import time
import numpy
from tornado import gen
from tornado.ioloop import IOLoop
@gen.coroutine
def async_sleep(seconds):
yield gen.Task(IOLoop.instance().add_timeout, time.time() + seconds)
def delayed(seconds):
def f(x)... | Fix conditions in JSON encoder | Fix conditions in JSON encoder
| Python | apache-2.0 | METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,METASPACE2020/sm-engine,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed,SpatialMetabolomics/SM_distributed |
43905a102092bdd50de1f8997cd19cb617b348b3 | tests/cart_tests.py | tests/cart_tests.py | import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
c... | import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
c... | Use the reset adder from the banks properly | Use the reset adder from the banks properly
| Python | bsd-2-clause | pusscat/refNes |
f0e8999ad139a8da8d3762ee1d318f23928edd9c | tests/modelstest.py | tests/modelstest.py | # Copyright (C) 2010 rPath, Inc.
import testsuite
testsuite.setup()
from testrunner import testcase
from rpath_repeater import models
class TestBase(testcase.TestCaseWithWorkDir):
pass
class ModelsTest(TestBase):
def testModelToXml(self):
files = models.ImageFiles([
models.ImageFile(tit... | # Copyright (C) 2010 rPath, Inc.
import testsuite
testsuite.setup()
from testrunner import testcase
from rpath_repeater import models
class TestBase(testcase.TestCaseWithWorkDir):
pass
class ModelsTest(TestBase):
def testModelToXml(self):
files = models.ImageFiles([
models.ImageFile(tit... | Fix test after metadata changes | Fix test after metadata changes
| Python | apache-2.0 | sassoftware/rpath-repeater |
3a5fb18a385ffd0533da94632d917e3c0bcfb051 | tests/test_nulls.py | tests/test_nulls.py | from tests.models import EventWithNulls, EventWithNoNulls
import pytest
@pytest.mark.django_db
def test_recurs_can_be_explicitly_none_if_none_is_allowed():
# Check we can save None correctly
event = EventWithNulls.objects.create(recurs=None)
assert event.recurs is None
# Check we can deserialize None... | from recurrence import Recurrence
from tests.models import EventWithNulls, EventWithNoNulls
import pytest
@pytest.mark.django_db
def test_recurs_can_be_explicitly_none_if_none_is_allowed():
# Check we can save None correctly
event = EventWithNulls.objects.create(recurs=None)
assert event.recurs is None
... | Add a test for saving an empty recurrence object | Add a test for saving an empty recurrence object
I wasn't sure whether this would fail on models which don't
accept null values. Turns out it's allowed, so we should
make sure it stays allowed.
| Python | bsd-3-clause | linux2400/django-recurrence,linux2400/django-recurrence,django-recurrence/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,django-recurrence/django-recurrence |
cd2e4cce080413feb7685ec9a788327b8bca9053 | tests/test_style.py | tests/test_style.py | import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
flake8([])
except SystemExit as e:
if e.code != 0:
self.fa... | import logging
import pkg_resources
import unittest
class CodeStyleTestCase(unittest.TestCase):
def test_code_style(self):
logger = logging.getLogger('flake8')
logger.setLevel(logging.ERROR)
flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
try:
... | Decrease noise from code-style test | Decrease noise from code-style test
| Python | mit | ministryofjustice/bai2 |
59e47de06a175084538140481c7a702ff020e919 | libvcs/__about__.py | libvcs/__about__.py | __title__ = 'libvcs'
__package_name__ = 'libvcs'
__description__ = 'vcs abstraction layer'
__version__ = '0.3.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/libvcs'
__pypi__ = 'https://pypi.org/project/libvcs/'
__email__ = 'tony@git-pull.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 20... | __title__ = 'libvcs'
__package_name__ = 'libvcs'
__description__ = 'vcs abstraction layer'
__version__ = '0.3.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/vcs-python/libvcs'
__docs__ = 'https://libvcs.git-pull.com'
__tracker__ = 'https://github.com/vcs-python/libvcs/issues'
__pypi__ = 'https://pypi.o... | Add metadata for tracker and docs | Add metadata for tracker and docs
| Python | mit | tony/libvcs |
d8c1c7da47e2568cecc1fd6dff0fec7661b39125 | turbosms/routers.py | turbosms/routers.py |
class SMSRouter(object):
app_label = 'sms'
db_name = 'sms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self.app_label:
... |
class TurboSMSRouter(object):
app_label = 'turbosms'
db_name = 'turbosms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self... | Fix bug in sms router. | Fix bug in sms router.
| Python | isc | pmaigutyak/mp-turbosms |
5fade4bc26c2637a479a69051cee37a1a859c71a | load_hilma.py | load_hilma.py | #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import sys
import pymongo
from pathlib import Path
import argh
from xml2json import etree_to_dict
from hilma_conversion import get_handler
hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler)
def load_hilma_xml(inputfile, collection):
root = E... | #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import sys
import pymongo
from pathlib import Path
import argh
from xml2json import etree_to_dict
from hilma_conversion import get_handler
hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler)
def load_hilma_xml(inputfile, collection):
root = E... | Use the notice ID as priary key | Use the notice ID as priary key
Gentlemen, drop your DBs!
| Python | agpl-3.0 | jampekka/openhilma |
816874f692c7ef9de5aa8782fab1747e96199229 | moksha/live/flot.py | moksha/live/flot.py | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it... | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it... | Clean up some LiveFlotWidget params | Clean up some LiveFlotWidget params
| Python | apache-2.0 | ralphbean/moksha,lmacken/moksha,lmacken/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,pombredanne/moksha,ralphbean/moksha,lmacken/moksha |
8bc2b19e9aef410832555fb9962c243f0d4aef96 | brink/decorators.py | brink/decorators.py | def require_request_model(cls, *args, validate=True, **kwargs):
"""
Makes a handler require that a request body that map towards the given model
is provided. Unless the ``validate`` option is set to ``False`` the data will
be validated against the model's fields.
The model will be passed to the han... | import asyncio
def require_request_model(cls, *args, validate=True, **kwargs):
"""
Makes a handler require that a request body that map towards the given model
is provided. Unless the ``validate`` option is set to ``False`` the data will
be validated against the model's fields.
The model will be ... | Add decorator for using websocket subhandlers | Add decorator for using websocket subhandlers
| Python | bsd-3-clause | brinkframework/brink |
2501bb03e836ac29cc1defa8591446ff217771b2 | tests/test_model.py | tests/test_model.py | """Sample unittests."""
import unittest2 as unittest
from domain_models import model
from domain_models import fields
class User(model.DomainModel):
"""Example user domain model."""
id = fields.Int()
email = fields.String()
first_name = fields.Unicode()
last_name = fields.Unicode()
gender =... | """Sample unittests."""
import unittest2 as unittest
from domain_models import model
from domain_models import fields
class User(model.DomainModel):
"""Example user domain model."""
id = fields.Int()
email = fields.String()
first_name = fields.Unicode()
last_name = fields.Unicode()
gender =... | Fix of tests with unicode strings | Fix of tests with unicode strings
| Python | bsd-3-clause | ets-labs/domain_models,ets-labs/python-domain-models,rmk135/domain_models |
cb798ae8f7f6e810a87137a56cd04be76596a2dd | photutils/tests/test_psfs.py | photutils/tests/test_psfs.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from photutils.psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01,... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from ..psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01, 0.1, 1]
@... | Use relative imports for consistency; pep8 | Use relative imports for consistency; pep8
| Python | bsd-3-clause | larrybradley/photutils,astropy/photutils |
66df1b2719aa278c37f1c70ef550659c22d93d10 | tests/unit/fakes.py | tests/unit/fakes.py | # Copyright 2012 Intel Inc, OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | # Copyright 2012 Intel Inc, OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | Fix Copyright Headers - Rename LLC to Foundation | Fix Copyright Headers - Rename LLC to Foundation
One code change, rest are in headers
Change-Id: I73f59681358629e1ad74e49d3d3ca13fcb5c2eb1
| Python | apache-2.0 | openstack/oslo.i18n,varunarya10/oslo.i18n |
65fd070a88e06bb040e8c96babc6b4c86ca29730 | validatish/error.py | validatish/error.py | """
Module containing package exception classes.
"""
class Invalid(Exception):
def __init__(self, message, exceptions=None, validator=None):
Exception.__init__(self, message, exceptions)
self.message = message
self.exceptions = exceptions
self.validator = validator
def __str_... | """
Module containing package exception classes.
"""
class Invalid(Exception):
def __init__(self, message, exceptions=None, validator=None):
Exception.__init__(self, message, exceptions)
self.message = message
self.exceptions = exceptions
self.validator = validator
def __str_... | Hide Python 2.6 Exception.message deprecation warnings | Hide Python 2.6 Exception.message deprecation warnings
| Python | bsd-3-clause | ish/validatish,ish/validatish |
5c620a504327696b9cfe3ffc423ae7ae6e915e78 | dec02/dec02part1.py | dec02/dec02part1.py | # Advent of Code
# Dec 2, Part 1
# @geekygirlsarah
| # Advent of Code
# Dec 2, Part 1
# @geekygirlsarah
inputFile = "input.txt"
# Tracking vars
finalCode = ""
lastNumber = 5 # start here
tempNumber = 0
with open(inputFile) as f:
while True:
line = f.readline(-1)
if not line:
# print "End of file"
break
# print (... | Add 12/2 part 1 solution | Add 12/2 part 1 solution
| Python | mit | geekygirlsarah/adventofcode2016 |
356dd5294280db3334f86354202f0d68881254b9 | joerd/check.py | joerd/check.py | import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file.
"""
try:
zip_file = zipfile.ZipFile(tmp.name, 'r')
test_result = zip_file.test... | import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal
def is_zip(tmp):
"""
Returns True if the NamedTemporaryFile given as the argument appears to be
a well-formed Zip file.
"""
try:
zip_file = zipfile.ZipFile(tmp.name, 'r')
test_result = zip_file.test... | Return verifier function, not None. Also reset the temporary file to the beginning before verifying it. | Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
| Python | mit | mapzen/joerd,tilezen/joerd |
9353a5e2369e819c092c94d224b09c321f5b5ff0 | utils/get_collection_object_count.py | utils/get_collection_object_count.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... | Add option to count components | Add option to count components
| Python | bsd-3-clause | barbarahui/nuxeo-calisphere,barbarahui/nuxeo-calisphere |
d84e6aa022ef5e256807738c35e5069a0a1380d7 | app/main/forms/frameworks.py | app/main/forms/frameworks.py | from flask.ext.wtf import Form
from wtforms import BooleanField
from wtforms.validators import DataRequired, Length
from dmutils.forms import StripWhitespaceStringField
class SignerDetailsForm(Form):
signerName = StripWhitespaceStringField('Full name', validators=[
DataRequired(message="You must provide t... | from flask.ext.wtf import Form
from wtforms import BooleanField
from wtforms.validators import DataRequired, Length
from dmutils.forms import StripWhitespaceStringField
class SignerDetailsForm(Form):
signerName = StripWhitespaceStringField('Full name', validators=[
DataRequired(message="You must provide t... | Add form for accepting contract variation | Add form for accepting contract variation
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend |
f16994fd3722acba8a60157eed0630a5e2a3d387 | macdict/cli.py | macdict/cli.py | from __future__ import absolute_import
import sys
import argparse
from macdict.dictionary import lookup_word, ensure_unicode
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('word')
return parser.parse_args()
def abort(text):
sys.stderr.write(u'%s\n' % text)
sys.exit(1)... | from __future__ import absolute_import
import sys
import argparse
from macdict.dictionary import lookup_word, ensure_unicode
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('word')
return parser.parse_args()
def abort(text):
sys.stderr.write(u'%s\n' % text)
sys.exit(1)... | Fix unicode decoding on error messages | Fix unicode decoding on error messages
| Python | mit | tonyseek/macdict |
75171ed80079630d22463685768072ad7323e653 | boundary/action_installed.py | boundary/action_installed.py | ###
### Copyright 2014-2015 Boundary, Inc.
###
### Licensed under the Apache License, Version 2.0 (the "License");
### you may not use this file except in compliance with the License.
### You may obtain a copy of the License at
###
### http://www.apache.org/licenses/LICENSE-2.0
###
### Unless required by applicable... | #
# Copyright 2014-2015 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | Change code to be PEP-8 compliant | Change code to be PEP-8 compliant
| Python | apache-2.0 | boundary/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/boundary-api-cli,jdgwartney/pulse-api-cli,wcainboundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/pulse-api-cli |
57bc8b3c40bbafda6f69b23c230ad73750e881ab | hashable/helpers.py | hashable/helpers.py | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equality_comparable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equality_comparabl... | from .equals_builder import EqualsBuilder
from .hash_code_builder import HashCodeBuilder
__all__ = [
'hashable',
'equalable',
]
def hashable(cls=None, attributes=None, methods=None):
_validate_attributes_and_methods(attributes, methods)
def decorator(cls):
cls = equalable(cls, attributes, m... | Rename decorator equality_comparable to equalable | Rename decorator equality_comparable to equalable
| Python | mit | minmax/hashable |
4f6e27a6bbc2bbdb19c165f21d47d1491bffd70e | scripts/mc_check_lib_file.py | scripts/mc_check_lib_file.py | #!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assume... | #!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2021 The HERA Collaboration
# Licensed under the 2-clause BSD License
"""
Check that input files are safely in the librarian.
This script takes a list of input files and returns the list of those
found in the HERA_MC.lib_files table.
NOTE: Assume... | Move sessionmaker outside of loop | Move sessionmaker outside of loop
| Python | bsd-2-clause | HERA-Team/hera_mc,HERA-Team/hera_mc |
5436068e2a0974a932d59d51dd529af221832735 | test/vim_autopep8.py | test/vim_autopep8.py | """Run autopep8 on the selected buffer in Vim.
map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>
"""
import vim
if vim.eval('&syntax') == 'python':
encoding = vim.eval('&fileencoding')
source = '\n'.join(line.decode(encoding)
for line in vim.current.buffer) + '\n'
import autopep8
... | """Run autopep8 on the selected buffer in Vim.
map <C-I> :pyfile <path_to>/vim_autopep8.py<CR>
Replace ":pyfile" with ":py3file" if Vim is built with Python 3 support.
"""
from __future__ import unicode_literals
import sys
import vim
ENCODING = vim.eval('&fileencoding')
def encode(text):
if sys.version_in... | Support Python 3 in Vim usage example | Support Python 3 in Vim usage example
| Python | mit | vauxoo-dev/autopep8,Vauxoo/autopep8,vauxoo-dev/autopep8,hhatto/autopep8,SG345/autopep8,SG345/autopep8,MeteorAdminz/autopep8,Vauxoo/autopep8,hhatto/autopep8,MeteorAdminz/autopep8 |
c105d6f18a5a17b0a47fda5a2df2f8f47352b037 | setuptools/command/upload.py | setuptools/command/upload.py | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short cir... | Simplify logic by eliminating retries in password prompt and returning results directly. | Simplify logic by eliminating retries in password prompt and returning results directly.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
a3213788d0d8591b235359d4b17886ce3f50ab37 | tests/test_plugin.py | tests/test_plugin.py | import datajoint.errors as djerr
import datajoint.plugin as p
import pkg_resources
def test_check_pubkey():
base_name = 'datajoint'
base_meta = pkg_resources.get_distribution(base_name)
pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name))
with open('./datajoint.pub', "r") as f:
as... | import datajoint.errors as djerr
import datajoint.plugin as p
import pkg_resources
from os import path
def test_check_pubkey():
base_name = 'datajoint'
base_meta = pkg_resources.get_distribution(base_name)
pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name))
with open(path.join(path.abspa... | Make pubkey test more portable. | Make pubkey test more portable.
| Python | lgpl-2.1 | datajoint/datajoint-python,dimitri-yatsenko/datajoint-python |
bc5475bcc3608de75c42d24c5c74e416b41b873f | pages/base.py | pages/base.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 selenium.webdriver.common.by import By
from page import Page
class Base(Page):
_login_locator = (By.ID, 'lo... | # 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 selenium.webdriver.common.by import By
from page import Page
class Base(Page):
_login_locator = (By.ID, 'lo... | Make username and password required arguments | Make username and password required arguments
| Python | mpl-2.0 | mozilla/mozwebqa-examples,davehunt/mozwebqa-examples,mozilla/mozwebqa-examples,davehunt/mozwebqa-examples |
54bce2a224843ec9c1c8b7eb35cdc6bf19d5726b | expensonator/api.py | expensonator/api.py | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... | from tastypie.authorization import Authorization
from tastypie.fields import CharField
from tastypie.resources import ModelResource
from expensonator.models import Expense
class ExpenseResource(ModelResource):
tags = CharField()
def dehydrate_tags(self, bundle):
return bundle.obj.tags_as_string()
... | Fix key error when no tags are specified | Fix key error when no tags are specified
| Python | mit | matt-haigh/expensonator |
f02b6505f190011f06b37619ec4fdf9bda1e804e | cea/interfaces/dashboard/api/utils.py | cea/interfaces/dashboard/api/utils.py | from flask import current_app
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
try:
params['choices'] = p._choices
except AttributeError:
pass
if p.typename == 'WeatherPathParameter':
... | from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'Weath... | Add parameter deconstruction fro DatabasePathParameter | Add parameter deconstruction fro DatabasePathParameter
| Python | mit | architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS |
dfdeaf536466cfa8003af4cd5341d1d7127ea6b7 | py/_test_py2go.py | py/_test_py2go.py | #!/usr/bin/env python
import datetime
def return_true():
return True
def return_false():
return False
def return_int():
return 123
def return_float():
return 1.0
def return_string():
return "ABC"
def return_bytearray():
return bytearray('abcdefg')
def return_array():
return [1, 2, {"k... | #!/usr/bin/env python
import datetime
def return_true():
return True
def return_false():
return False
def return_int():
return 123
def return_float():
return 1.0
def return_string():
return "ABC"
def return_bytearray():
return bytearray('abcdefg')
def return_array():
return [1,... | Update python script for pep8 style | Update python script for pep8 style
| Python | mit | sensorbee/py,sensorbee/py |
caf9795cf0f775442bd0c3e06cd550a6e8d0206b | virtool/labels/db.py | virtool/labels/db.py | async def count_samples(db, label_id):
return await db.samples.count_documents({"labels": {"$in": [label_id]}})
| async def attach_sample_count(db, document, label_id):
document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
| Rewrite function for sample count | Rewrite function for sample count
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool |
51e7cd3bc5a9a56fb53a5b0a8328d0b9d58848dd | modder/utils/desktop_notification.py | modder/utils/desktop_notification.py | # coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, titl... | # coding: utf-8
import platform
if platform.system() == 'Darwin':
from Foundation import NSUserNotificationDefaultSoundName
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def desktop_notify(text, titl... | Fix title for desktop notification | Fix title for desktop notification
| Python | mit | JokerQyou/Modder2 |
8a7837a8ce7b35c3141374c6a5c99361261fa70a | Cura/avr_isp/chipDB.py | Cura/avr_isp/chipDB.py |
avrChipDB = {
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
return chip
return False
|
avrChipDB = {
'ATMega1280': {
'signature': [0x1E, 0x97, 0x03],
'pageSize': 128,
'pageCount': 512,
},
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
ret... | Add ATMega1280 chip to programmer chips. | Add ATMega1280 chip to programmer chips.
| Python | agpl-3.0 | MolarAmbiguity/OctoPrint,EZ3-India/EZ-Remote,JackGavin13/octoprint-test-not-finished,spapadim/OctoPrint,dragondgold/OctoPrint,hudbrog/OctoPrint,CapnBry/OctoPrint,Javierma/OctoPrint-TFG,chriskoz/OctoPrint,javivi001/OctoPrint,shohei/Octoprint,eddieparker/OctoPrint,MolarAmbiguity/OctoPrint,mayoff/OctoPrint,uuv/OctoPrint,C... |
ef96000b01c50a77b3500fc4071f83f96d7b2458 | mrbelvedereci/api/views/cumulusci.py | mrbelvedereci/api/views/cumulusci.py | from django.shortcuts import render
from mrbelvedereci.api.serializers.cumulusci import OrgSerializer
from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer
from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer
from mrbelvedereci.cumulusci.filters import OrgFilter
from mrbelved... | from django.shortcuts import render
from mrbelvedereci.api.serializers.cumulusci import OrgSerializer
from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer
from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer
from mrbelvedereci.cumulusci.filters import OrgFilter
from mrbelved... | Remove ServiceFilter from view since it's not needed. Service only has name and json | Remove ServiceFilter from view since it's not needed. Service only has
name and json
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci |
4f0dbf920a6867d8f3e16eb420391c8bcca43c44 | onirim/card/_door.py | onirim/card/_door.py | from onirim.card._base import ColorCard
class _Door(ColorCard):
def drawn(self, agent, content):
do_open = agent.ask("if open") if content.can_open(self) else False
if do_open:
content.discard(self)
else:
content.limbo(self)
def door(color):
return _Door(color)... | from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door may ... | Implement openable check for door card. | Implement openable check for door card.
| Python | mit | cwahbong/onirim-py |
24f0402e27ce7e51f370e82aa74c783438875d02 | oslo_db/tests/sqlalchemy/__init__.py | oslo_db/tests/sqlalchemy/__init__.py | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | # Copyright (c) 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Remove deprecation warning when loading tests/sqlalchemy | Remove deprecation warning when loading tests/sqlalchemy
/home/sam/Work/ironic/.tox/py27/local/lib/python2.7/site-packages/oslo_db/tests/sqlalchemy/__init__.py:20:
DeprecationWarning: Function
'oslo_db.sqlalchemy.test_base.optimize_db_test_loader()' has moved to
'oslo_db.sqlalchemy.test_fixtures.optimize_package_test_... | Python | apache-2.0 | openstack/oslo.db,openstack/oslo.db |
db6cb95d5d4261780482b4051f556fcbb2d9f237 | rest_api/forms.py | rest_api/forms.py | from django.forms import ModelForm
from rest_api.models import Url
class UrlForm(ModelForm):
class Meta:
model = Url
| from django.forms import ModelForm
from gateway_backend.models import Url
class UrlForm(ModelForm):
class Meta:
model = Url
| Remove Url model from admin | Remove Url model from admin
| Python | bsd-2-clause | victorpoluceno/shortener_frontend,victorpoluceno/shortener_frontend |
3410fba1c8a39156def029eac9c7ff9f779832e6 | dev/ci.py | dev/ci.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import site
import sys
from . import build_root, requires_oscrypto
from ._import import _preload
deps_dir = os.path.join(build_root, 'modularcrypto-deps')
if os.path.exists(deps_dir):
site.addsitedir(dep... | Fix CI to ignore system install of asn1crypto | Fix CI to ignore system install of asn1crypto
| Python | mit | wbond/oscrypto |
502d99042428175b478e796c067e41995a0ae5bf | picoCTF-web/api/apps/v1/__init__.py | picoCTF-web/api/apps/v1/__init__.py | """picoCTF API v1 app."""
from flask import Blueprint, jsonify
from flask_restplus import Api
from api.common import PicoException
from .achievements import ns as achievements_ns
from .problems import ns as problems_ns
from .shell_servers import ns as shell_servers_ns
from .exceptions import ns as exceptions_ns
from... | """picoCTF API v1 app."""
from flask import Blueprint, jsonify
from flask_restplus import Api
from api.common import PicoException
from .achievements import ns as achievements_ns
from .problems import ns as problems_ns
from .shell_servers import ns as shell_servers_ns
from .exceptions import ns as exceptions_ns
from... | Fix PicoException response code bug | Fix PicoException response code bug
| Python | mit | royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF |
5d71215645683a059a51407a3768054c9ea77406 | pisite/logs/forms.py | pisite/logs/forms.py | from django import forms
from logs.models import Log
class LineCountForm(forms.Form):
linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) | from django import forms
from logs.models import Log
class LineCountForm(forms.Form):
linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow) | Add to the label that 0 lines will result in the entire file being downloaded | Add to the label that 0 lines will result in the entire file being downloaded
| Python | mit | sizlo/RPiFun,sizlo/RPiFun |
94dad4c56a4b6a1968fa15c20b8482fd56774f32 | optimize/py/main.py | optimize/py/main.py | from scipy import optimize as o
import clean as c
def minimize(func, guess):
return o.minimize(func, guess)
def minimize_scalar(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
retu... | from scipy import optimize as o
import numpy as np
import clean as c
def minimize_scalar(func, options):
bracket = options['bracket']
bounds = options['bounds']
method = options['method']
tol = options['tol']
options = options['options']
try:
return o.minimize_scalar(func, bracke... | Add non negative least squares scipy functionality | Add non negative least squares scipy functionality
| Python | mit | acjones617/scipy-node,acjones617/scipy-node |
a389f20c7f2c8811a5c2f50c43a9ce5c7f3c8387 | jobs_backend/vacancies/serializers.py | jobs_backend/vacancies/serializers.py | from rest_framework import serializers
from .models import Vacancy
class VacancySerializer(serializers.HyperlinkedModelSerializer):
"""
Common vacancy model serializer
"""
class Meta:
model = Vacancy
fields = (
'id', 'url', 'title', 'description', 'created_on', 'modified_o... | from rest_framework import serializers
from .models import Vacancy
class VacancySerializer(serializers.ModelSerializer):
"""
Common vacancy model serializer
"""
class Meta:
model = Vacancy
fields = (
'id', 'url', 'title', 'description', 'created_on', 'modified_on'
... | Fix for correct resolve URL | jobs-010: Fix for correct resolve URL
| Python | mit | pyshopml/jobs-backend,pyshopml/jobs-backend |
441a1b85f6ab954ab89f32977e4f00293270aac6 | sphinxcontrib/multilatex/__init__.py | sphinxcontrib/multilatex/__init__.py |
import directive
import builder
#===========================================================================
# Node visitor functions
def visit_passthrough(self, node):
pass
def depart_passthrough(self, node):
pass
passthrough = (visit_passthrough, depart_passthrough)
#=================... |
import directive
import builder
#===========================================================================
# Node visitor functions
def visit_passthrough(self, node):
pass
def depart_passthrough(self, node):
pass
passthrough = (visit_passthrough, depart_passthrough)
#=================... | Set LaTeX builder to skip latex_document nodes | Set LaTeX builder to skip latex_document nodes
This stops Sphinx' built-in LaTeX builder from complaining about unknown
latex_document node type.
| Python | apache-2.0 | t4ngo/sphinxcontrib-multilatex,t4ngo/sphinxcontrib-multilatex |
5c11a65af1d51794133895ebe2de92861b0894cf | flask_limiter/errors.py | flask_limiter/errors.py | """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
werkzeug_exception = None
werkzeug_version = get_distribution("werkzeug").version
if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pra... | """errors and exceptions."""
from distutils.version import LooseVersion
from pkg_resources import get_distribution
from six import text_type
from werkzeug import exceptions
class RateLimitExceeded(exceptions.TooManyRequests):
"""exception raised when a rate limit is hit.
The exception results in ``abort(429... | Remove backward compatibility hack for exception subclass | Remove backward compatibility hack for exception subclass
| Python | mit | alisaifee/flask-limiter,alisaifee/flask-limiter |
b3979a46a7bcd71aa9b40892167910fdeed5ad97 | frigg/projects/admin.py | frigg/projects/admin.py | from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
... | from django.contrib import admin
from django.template.defaultfilters import pluralize
from .forms import EnvironmentVariableForm
from .models import EnvironmentVariable, Project
class EnvironmentVariableMixin:
form = EnvironmentVariableForm
@staticmethod
def get_readonly_fields(request, obj=None):
... | Return empty tuple in get_readonly_fields | fix: Return empty tuple in get_readonly_fields
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq |
0d7c0b045c4a2e930fe0d7aa68b96d5a99916a34 | scripts/document_path_handlers.py | scripts/document_path_handlers.py | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
from nikola import nikola
n = nikola.Nikola()
n.init_plugins()
print(""".. title: Path Handlers for Nikola
.. slug: path-handlers
.. author: The Nikola Team
Nikola supports special links with the syntax ``link://kind/name``. Here is
the de... | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
from nikola import nikola
n = nikola.Nikola()
n.init_plugins()
print(""".. title: Path Handlers for Nikola
.. slug: path-handlers
.. author: The Nikola Team
Nikola supports special links with the syntax ``link://kind/name``. Here is
the de... | Make path handlers list horizontal | Make path handlers list horizontal
Signed-off-by: Chris Warrick <de6f931166e131a07f31c96c765aee08f061d1a5@gmail.com>
| Python | mit | s2hc-johan/nikola,wcmckee/nikola,gwax/nikola,x1101/nikola,okin/nikola,masayuko/nikola,xuhdev/nikola,wcmckee/nikola,gwax/nikola,knowsuchagency/nikola,atiro/nikola,andredias/nikola,gwax/nikola,xuhdev/nikola,atiro/nikola,x1101/nikola,okin/nikola,knowsuchagency/nikola,wcmckee/nikola,okin/nikola,getnikola/nikola,masayuko/ni... |
c6d50c3feed444f8f450c5c140e8470c6897f2bf | societies/models.py | societies/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | # -*- coding: utf-8 -*-
from django.db import models
from django_countries.fields import CountryField
class GuitarSociety(models.Model):
"""
Represents a single guitar society.
.. versionadded:: 0.1
"""
#: the name of the society
#: ..versionadded:: 0.1
name = models.CharField(max_lengt... | Make the Guitar Society __str__ Method a bit more Logical | Make the Guitar Society __str__ Method a bit more Logical
| Python | bsd-3-clause | chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org |
c7a209d2c4455325f1d215ca1c12074b394ae00e | gitdir/host/__init__.py | gitdir/host/__init__.py | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not s... | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not s... | Add status messages to `gitdir update` | Add status messages to `gitdir update`
| Python | mit | fenhl/gitdir |
11278ec546cf1c84a6aefff7ed4e5a677203d008 | index_addresses.py | index_addresses.py | import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Elasticsearch(... | import sys
import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Ela... | Change index to OpenAddresses schema | Change index to OpenAddresses schema
| Python | mit | codeforamerica/streetscope,codeforamerica/streetscope |
932ee2737b822742996f234c90b715771fb876bf | tests/functional/api/view_pdf_test.py | tests/functional/api/view_pdf_test.py | import pytest
from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-st... | from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-store"]
)... | Fix lint errors after adding missing __init__ files | Fix lint errors after adding missing __init__ files
| Python | bsd-2-clause | hypothesis/via,hypothesis/via,hypothesis/via |
50f2cd076aae183376ab14d31594c104ac210738 | shivyc.py | shivyc.py | #!/usr/bin/env python3
"""Main executable for ShivyC compiler
For usage, run "./shivyc.py --help".
"""
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args... | #!/usr/bin/env python3
"""Main executable for ShivyC compiler
For usage, run "./shivyc.py --help".
"""
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args... | Rename file_name argument on command line | Rename file_name argument on command line
| Python | mit | ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC |
d7149d8ea09c897fb954652beeef3bf008448d9e | mopidy/__init__.py | mopidy/__init__.py | import sys
if not (2, 6) <= sys.version_info < (3,):
sys.exit(u'Mopidy requires Python >= 2.6, < 3')
from subprocess import PIPE, Popen
VERSION = (0, 4, 0)
def get_git_version():
process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
if process.wait() != 0:
raise Exception('Execution of "... | import sys
if not (2, 6) <= sys.version_info < (3,):
sys.exit(u'Mopidy requires Python >= 2.6, < 3')
from subprocess import PIPE, Popen
VERSION = (0, 4, 0)
def get_git_version():
process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
if process.wait() != 0:
raise EnvironmentError('Executi... | Raise EnvironmentError instead of Exception to make pylint happy | Raise EnvironmentError instead of Exception to make pylint happy
| Python | apache-2.0 | pacificIT/mopidy,swak/mopidy,jodal/mopidy,vrs01/mopidy,swak/mopidy,woutervanwijk/mopidy,tkem/mopidy,rawdlite/mopidy,jodal/mopidy,mokieyue/mopidy,rawdlite/mopidy,jmarsik/mopidy,bacontext/mopidy,mokieyue/mopidy,quartz55/mopidy,ZenithDK/mopidy,dbrgn/mopidy,priestd09/mopidy,mopidy/mopidy,quartz55/mopidy,glogiotatidis/mopid... |
66a9d140feb3a0bd332031853fb1038622fd5c5b | oidc_apis/utils.py | oidc_apis/utils.py | from collections import OrderedDict
def combine_uniquely(iterable1, iterable2):
"""
Combine unique items of two sequences preserving order.
:type seq1: Iterable[Any]
:type seq2: Iterable[Any]
:rtype: list[Any]
"""
result = OrderedDict.fromkeys(iterable1)
for item in iterable2:
... | from collections import OrderedDict
import django
from oidc_provider import settings
from django.contrib.auth import BACKEND_SESSION_KEY
from django.contrib.auth import logout as django_user_logout
from users.models import LoginMethod, OidcClientOptions
from django.contrib.auth.views import redirect_to_login
def comb... | Implement current session auth method check | Implement current session auth method check
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo |
23ca8b449a075b4d8ebee19e7756e39f327e9988 | dwitter/user/urls.py | dwitter/user/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<url_username>\w+)$',
views.user_feed, {'page_nr': '1', 'sort': 'new'}, name='user_feed'),
url(r'^(?P<url_username>\w+)/(?P<sort>hot|new|top)$',
views.user_feed, {'page_nr': '1'}, name='user_sort_feed'),
url(r'^(... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<url_username>[\w.@+-]+)$',
views.user_feed, {'page_nr': '1', 'sort': 'new'}, name='user_feed'),
url(r'^(?P<url_username>[\w.@+-]+)/(?P<sort>hot|new|top)$',
views.user_feed, {'page_nr': '1'}, name='user_sort_feed'),
... | Fix url lookup error for usernames certain special characters | Fix url lookup error for usernames certain special characters
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter |
bca736ac15b06263c88d0265339b93b8c2b20d79 | test/settings/gyptest-settings.py | test/settings/gyptest-settings.py | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('settings.gyp')
test.build('test.gyp', test.AL... | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
# 'settings' is only supported for make and scons (and will be removed there as
# we... | Make new settings test not run for xcode generator. | Make new settings test not run for xcode generator.
TBR=evan
Review URL: http://codereview.chromium.org/7472006 | Python | bsd-3-clause | witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp |
9ec80ed117ca393a63bf7eb739b4702bfbc0884e | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | Add function to schedule later | Add function to schedule later | Python | mit | waltermoreira/tartpy |
b552d550ca7e4468d95da9a3005e07cbd2ab49d6 | tests/test_stock.py | tests/test_stock.py | import cutplanner
import unittest
class TestStock(unittest.TestCase):
def setUp(self):
self.stock = cutplanner.Stock(120)
def test_cut(self):
self.stock.assign_cut(20)
self.assertEqual(self.stock.remaining_length, 100)
if __name__ == '__main__':
unittest.main()
| import cutplanner
import unittest
class TestStock(unittest.TestCase):
def setUp(self):
self.stock = cutplanner.Stock(120)
self.piece = cutplanner.Piece(1, 20)
def test_cut(self):
self.stock.cut(self.piece)
self.assertEqual(self.stock.remaining_length, 100)
def test_used_l... | Add some initial tests for Stock. | Add some initial tests for Stock.
| Python | mit | alanc10n/py-cutplanner |
54eb7862d6b17f4e86a380004f6e682452fbebce | git_gutter_change.py | git_gutter_change.py | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def run(self):
view = self.window.active_view()
inserted, modified, ... | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
... | Make lines jumps only jump to blocks over changes | Make lines jumps only jump to blocks over changes
Instead of every line in a block of modifications which is tedious
| Python | mit | tushortz/GitGutter,biodamasceno/GitGutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,natecavanaugh/GitGutter,natecavanaugh/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,natecavanaugh/GitGutter,biodamasceno/GitGutter,akpersad/GitGutter,akpersad/GitGutter,robfrawley/sublime-git-gutter,natecavanaugh/... |
a36fe5002bbf5dfcf27a3251cfed85c341e2156d | cbcollections.py | cbcollections.py | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | Save generated value for defaultdict | MB-6867: Save generated value for defaultdict
Instead of just returning value, keep it in dict.
Change-Id: I2a9862503b71f2234a4a450c48998b5f53a951bc
Reviewed-on: http://review.couchbase.org/21602
Tested-by: Bin Cui <ed18693fff32c00e22495f4877a3b901bed09041@gmail.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a... | Python | apache-2.0 | couchbase/couchbase-cli,couchbaselabs/couchbase-cli,membase/membase-cli,membase/membase-cli,couchbase/couchbase-cli,membase/membase-cli,couchbaselabs/couchbase-cli,couchbaselabs/couchbase-cli |
b27a51f19ea3f9d13672a0db51f7d2b05f9539f0 | kitten/validation.py | kitten/validation.py | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS = {
'core': CORE_SCHEMA
}
def validate(request, schema_na... | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
'address': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS ... | Add 'address' field to core schema | Add 'address' field to core schema
| Python | mit | thiderman/network-kitten |
fb0b956563efbcd22af8300fd4341e3cb277b80a | app/models/user.py | app/models/user.py | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | Add avatar_url and owner field for User | Add avatar_url and owner field for User
| Python | agpl-3.0 | lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger |
f42e62005ea4cc3e71cf10dda8c0bace029014c5 | kubespawner/utils.py | kubespawner/utils.py | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurable, ThreadPool... | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurab... | Add random jitter to the exponential backoff function | Add random jitter to the exponential backoff function
| Python | bsd-3-clause | yuvipanda/jupyterhub-kubernetes-spawner,jupyterhub/kubespawner |
9f6d4d9e82ef575164535a8fb9ea80417458dd6b | website/files/models/dataverse.py | website/files/models/dataverse.py | import requests
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, F... | from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, Folder):
pass
... | Move override logic into update rather than touch | Move override logic into update rather than touch
| Python | apache-2.0 | Johnetordoff/osf.io,mluke93/osf.io,SSJohns/osf.io,chrisseto/osf.io,hmoco/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,acshi/osf.io,alexschiller/osf.io,caseyrollins/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,alexschiller/osf.io,adlius/osf.... |
06d210cdc811f0051a489f335cc94a604e99a35d | werobot/session/mongodbstorage.py | werobot/session/mongodbstorage.py | # -*- coding: utf-8 -*-
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | # -*- coding: utf-8 -*-
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | Use new pymongo API in MongoDBStorage | Use new pymongo API in MongoDBStorage
| Python | mit | whtsky/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot,whtsky/WeRoBot,weberwang/WeRoBot,weberwang/WeRoBot |
841ca9cfbdb8faac9d8deb47b65717b5fb7c8eb4 | mfh.py | mfh.py | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfh... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
client = create_process("client", mfhclient.main, args, update_event)
serv = c... | Move all the process creation in a new function | Move all the process creation in a new function
This reduces the size of code.
| Python | mit | Zloool/manyfaced-honeypot |
5f128bbfc61169ac6b5f0e9f4dc6bcd05092382c | requests_cache/serializers/pipeline.py | requests_cache/serializers/pipeline.py | """
.. automodsumm:: requests_cache.serializers.pipeline
:classes-only:
:nosignatures:
"""
from typing import Any, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
def __init__(self, obj: An... | """
.. automodsumm:: requests_cache.serializers.pipeline
:classes-only:
:nosignatures:
"""
from typing import Any, Callable, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods
Args:
obj: ... | Allow Stage objects to take functions instead of object + method names | Allow Stage objects to take functions instead of object + method names
| Python | bsd-2-clause | reclosedev/requests-cache |
657741f3d4df734afef228e707005dc21d540e34 | post-refunds-back.py | post-refunds-back.py | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wi... | #!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchange... | Update post-back script for Braintree | Update post-back script for Braintree
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com |
022062c409ee06a719b5687ea1feb989c5cad627 | app/grandchallenge/pages/sitemaps.py | app/grandchallenge/pages/sitemaps.py | from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False
)
| from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False, hidden=False,
)
| Remove hidden public pages from sitemap | Remove hidden public pages from sitemap
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
c5239c6bbb40ede4279b33b965c5ded26a78b2ae | app/tests/manual/test_twitter_api.py | app/tests/manual/test_twitter_api.py | # -*- coding: utf-8 -*-
"""
Twitter API test module.
Local test to check that Twitter credentials are valid connect to Twitter
API and that the auth functions can be used to do this.
s"""
from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(T... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Twitter API test module.
Local test to check that Twitter credentials are valid connect to Twitter
API and that the auth functions can be used to do this.
"""
from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# A... | Update Twitter auth test to run directly | test: Update Twitter auth test to run directly
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse |
c6862c5f864db4e77dd835f074efdd284667e6fd | util/ldjpp.py | util/ldjpp.py | #! /usr/bin/env python
from __future__ import print_function
import argparse
import json
parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
parser.add_argument('--indent', metavar='N', type=int, default=2,
dest='indent', help='indentation for pretty-printing')
parser.add_argument... | #! /usr/bin/env python
from __future__ import print_function
import click
import json
from collections import OrderedDict
def json_loader(sortkeys):
def _loader(line):
if sortkeys:
return json.loads(line)
else:
# if --no-sortkeys, let's preserve file order
retu... | Use click instead of argparse | Use click instead of argparse
| Python | mit | mhyfritz/goontools,mhyfritz/goontools,mhyfritz/goontools |
b7decb588f5b6e4d15fb04fa59aa571e5570cbfe | djangae/contrib/contenttypes/apps.py | djangae/contrib/contenttypes/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | Fix up for Django 1.9 | Fix up for Django 1.9
| Python | bsd-3-clause | grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae |
dfd3bff4560d1711624b8508795eb3debbaafa40 | changes/api/snapshotimage_details.py | changes/api/snapshotimage_details.py | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | Mark snapshots as inactive if any are not valid | Mark snapshots as inactive if any are not valid
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes |
f8b4b1a860b5c0a3ff16dbb8bbf83010bd9a1009 | feincms3/plugins/__init__.py | feincms3/plugins/__init__.py | # flake8: noqa
from . import html
from . import snippet
try:
from . import external
except ImportError: # pragma: no cover
pass
try:
from . import image
except ImportError: # pragma: no cover
pass
try:
from . import richtext
except ImportError: # pragma: no cover
pass
try:
from . import... | # flake8: noqa
from . import html
from . import snippet
try:
import requests
except ImportError: # pragma: no cover
pass
else:
from . import external
try:
import imagefield
except ImportError: # pragma: no cover
pass
else:
from . import image
try:
import feincms3.cleanse
except ImportErr... | Stop hiding local import errors | feincms3.plugins: Stop hiding local import errors
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 |
b2eebbdcc14dd47d6ad8bb385966f13ed13890c1 | superdesk/coverages.py | superdesk/coverages.py | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | Fix data relation not working for custom Guids | Fix data relation not working for custom Guids
| Python | agpl-3.0 | plamut/superdesk,sivakuna-aap/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk,mugurrus/superdesk,ioanpocol/superdesk,pavlovicnemanja/superdesk,Aca-jov/superdesk,akintolga/superdesk,vied12/superdesk,gbbr/superdesk,fritzSF/superdesk,ancafarcas/superd... |
4147e6f560889c75abbfd9c8e85ea38ffe408550 | suelta/mechanisms/facebook_platform.py | suelta/mechanisms/facebook_platform.py | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | Work around Python3's byte semantics. | Work around Python3's byte semantics.
| Python | mit | dwd/Suelta |
1dbe7acc945a545d3b18ec5025c19b26d1ed110f | test/test_sparql_construct_bindings.py | test/test_sparql_construct_bindings.py | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://github.com/RDFLib/rdflib/issu... | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
from nose.tools import eq_
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://gi... | Fix unit tests for python2 | Fix unit tests for python2
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib |
2ebbe2f9f23621d10a70d0817d83da33b002299e | rest_surveys/urls.py | rest_surveys/urls.py | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | Set a default api path | Set a default api path
| Python | mit | danxshap/django-rest-surveys |
1cbd56988478320268838f77e8cc6237d95346fd | test/dunya/conn_test.py | test/dunya/conn_test.py | import unittest
from compmusic.dunya.conn import _make_url
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
url = _make_url("path", **params)
self.assertEqual(url, 'http://dunya.compmusic.upf.edu/path?first=%25%5Egrt%C3%A0') | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
import unittest
from compmusic.dunya.conn import _make_url
class ConnTest(unittest.TestCase):
def test_make_url(self):
params = {"first": "%^grtà"}
url = _make_url("path", **params)
self.assertEqual(url, 'http://dunya.compmusic.upf.edu/path?... | Declare the encoding of conn.py as utf-8 | Declare the encoding of conn.py as utf-8
| Python | agpl-3.0 | MTG/pycompmusic |
a7437e657f55cd708baba83421941e67d474daf7 | tests/test_utilities.py | tests/test_utilities.py | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name') == 'name'
assert camelize('very_long_variable_name... | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize, deep_copy
from folium import Map, FeatureGroup, Marker
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name'... | Add test for deep_copy function | Add test for deep_copy function
| Python | mit | python-visualization/folium,ocefpaf/folium,ocefpaf/folium,python-visualization/folium |
fe05b5f694671a46dd3391b9cb6561923345c4b7 | rpi_gpio_http/app.py | rpi_gpio_http/app.py | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | Disable warnings in GPIO lib | Disable warnings in GPIO lib
| Python | mit | voidpp/rpi-gpio-http |
378f55687131324bb5c43e3b50f9db5fe3b39662 | zaqar_ui/__init__.py | zaqar_ui/__init__.py | # Copyright 2015 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | # Copyright 2015 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | Fix Zaqar-ui with wrong reference pbr version | Fix Zaqar-ui with wrong reference pbr version
Change-Id: I84cdb865478a232886ba1059febf56735a0d91ba
| Python | apache-2.0 | openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui |
d659c685f40de7eb7b2ccd007888177fb158e139 | tests/integration/players.py | tests/integration/players.py | #!/usr/bin/env python
import urllib.parse
import urllib.request
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
data = urllib.parse.urlencode(values)
data = dat... | #!/usr/bin/env python
import requests
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
r = requests.post(url, params=values, verify=False)
r.raise_for_status()... | Switch to requests library instead of urllib | Switch to requests library instead of urllib
| Python | mit | dropshot/dropshot-server |
eeeba609afe732b8e95aa535e70d4cdd2ae1aac7 | tests/unit/test_cufflinks.py | tests/unit/test_cufflinks.py | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | Remove some cruft from the cufflinks test. | Remove some cruft from the cufflinks test.
| Python | mit | vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,verdurin/bcbio-nextgen,fw1121/bcbio-nextgen,gifford-lab/bcbio-nextgen,chapmanb/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,verdurin/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantan... |
c956fbbbc6e4dbd713728c1feda6bce2956a0894 | runtime/Python3/src/antlr4/__init__.py | runtime/Python3/src/antlr4/__init__.py | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA import DFA
from... | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import... | Allow importing StdinStream from antlr4 package | Allow importing StdinStream from antlr4 package
| Python | bsd-3-clause | parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr... |
14c22be85b9c9b3d13cad1130bb8d8d83d69d68a | selenium_testcase/testcases/content.py | selenium_testcase/testcases/content.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .utils import dom_contains, wait_for
class ContentTestMixin:
def should_see_immediately(self, text):
""" Assert that DOM contains the given text. """
self.assertTrue(dom_contains(self.browser, text))
@wait_for
def shou... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .utils import wait_for
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
class ContentTestMixin:
content_search_list = (
(By.XPATH,
'//*[contains(normalize-space(.), "{}... | Update should_see_immediately to use local find_element method. | Update should_see_immediately to use local find_element method.
This commit adds a content_search_list and replaces dom_contains
with our local version of find_element. It adds an attribute
called content_search_list that can be overridden by the derived
TestCase class as necessary for corner cases.
| Python | bsd-3-clause | nimbis/django-selenium-testcase,nimbis/django-selenium-testcase |
7947d474da8bb086493890d81a6788d76e00b108 | numba/cuda/tests/__init__.py | numba/cuda/tests/__init__.py | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
suite.add... | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
if cuda.i... | Fix tests on machine without CUDA | Fix tests on machine without CUDA
| Python | bsd-2-clause | sklam/numba,numba/numba,seibert/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,gmarkall/numba,cpcloud/numba,IntelLabs/numba,gmarkall/numba,jriehl/numba,cpcloud/numba,sklam/numba,cpcloud/numba,numba/numba,stonebig/numba,stefanseefeld/numba,sklam/numba,cpcloud/numba,seibert/numba,sklam/numba,gmarkall/numba,stefanseefe... |
910d1288adddd0c8dd500c1be5e488502c1ed335 | localflavor/nl/forms.py | localflavor/nl/forms.py | # -*- coding: utf-8 -*-
"""NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch... | # -*- coding: utf-8 -*-
"""NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch... | Fix the wikipedia link and include a warning | Fix the wikipedia link and include a warning
| Python | bsd-3-clause | django/django-localflavor,rsalmaso/django-localflavor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.