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 |
|---|---|---|---|---|---|---|---|---|---|
86fa8271b5788aadcbbde3decbcd413b9d22871c | util/namespace.py | util/namespace.py | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
... | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
super(Namespace, self).__init__()
self.__dict__.update... | Call super __init__ from Namespace.__init__ | util: Call super __init__ from Namespace.__init__
| Python | unknown | embox/mybuild,abusalimov/mybuild,embox/mybuild,abusalimov/mybuild |
253daeb2e826a9fe87cd93c9bc1a2060d9b8fead | tests/project/settings.py | tests/project/settings.py | DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
}
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
]
INSTALLED_APPS = [
'fandjango',
'south',
'tests.project.app'
]
ROOT_URLCONF = 'tests.project.urls'
FACEBOOK_APPLICATION_ID = 1812597119252... | DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
}
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
]
INSTALLED_APPS = [
'fandjango',
'south',
'tests.project.app'
]
SOUTH_TESTS_MIGRATE = False
ROOT_URLCONF = 'tests.project.urls'
FACEBOOK_A... | Disable South migrations for tests. | Disable South migrations for tests.
| Python | mit | jgorset/fandjango,jgorset/fandjango |
9771381323e4eb44a13ffc8742615fba61ad2b85 | lino/modlib/notify/consumers.py | lino/modlib/notify/consumers.py | from channels import Group
def ws_echo(message):
Group(str(message.content['text'])).add(message.reply_channel)
message.reply_channel.send({
"text": message.content['text'],
})
| import json
from channels import Channel
from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
from django.utils import timezone
from lino.modlib.notify.models import Notification
# This decorator copies the user from the HTTP session (only available in
# websocket... | Update receive and send functions according to the new requirements | Update receive and send functions according to the new requirements
| Python | unknown | lsaffre/lino,lsaffre/lino,khchine5/lino,khchine5/lino,khchine5/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,lsaffre/lino,lino-framework/lino,lino-framework/lino,lsaffre/lino,khchine5/lino,khchine5/lino,lino-framework/lino |
cd996486b25ab35369994a4470f795ae31e06a9c | unit_tests/test_ccs.py | unit_tests/test_ccs.py | #!/usr/bin/env python3
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_nothing(self):
... | #!/usr/bin/env python3
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_parse_line(self):
... | Add first test for ccs | Add first test for ccs
| Python | mit | ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData |
9a52024ff5b8175ee8b8d4665d3c8c667003019b | glitter/blocks/redactor/tests.py | glitter/blocks/redactor/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.contrib.auth import get_user_model
from django.contrib.conte... | Add test for redactor block creation | Add test for redactor block creation
| Python | bsd-3-clause | developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter |
0fa002e66f82eff593514c2249c4229604ec0f0a | server.py | server.py | import web
import cPickle as pickle
import json
urls = (
'/latest', 'latest',
'/history', 'history'
)
class latest:
def GET(self):
try:
latest = pickle.load(open("latest.p", "r"))
return json.dumps(latest)
except:
return "Could not read latest data"
cla... | import web
import cPickle as pickle
import json
urls = (
'/latest', 'latest',
'/history', 'history'
)
class latest:
def GET(self):
try:
with open("latest.p", 'r') as f:
latest = pickle.load(f)
return json.dumps(latest)
except:
return "Cou... | Make sure to close the file afterwards | Make sure to close the file afterwards
| Python | mit | martindisch/SensorTag,martindisch/SensorTag,martindisch/SensorTag,martindisch/SensorTag |
d936f53ae422fab360f5e1cd62f7114d91ba270c | extra_plots.py | extra_plots.py | """
Generate nice plots providing additional information
"""
import sys
import numpy as np
import matplotlib.pylab as plt
def neural_spike():
""" Plot various neural spikes
"""
def do_plot(cell_evo):
""" Plot [cAMP] for single cell over time
"""
plt.plot(range(len(cell_evo)), cell... | """
Generate nice plots providing additional information
"""
import sys
import numpy as np
import matplotlib.pylab as plt
from singularity_finder import compute_tau
def neural_spike():
""" Plot various neural spikes
"""
def do_plot(cell_evo):
""" Plot [cAMP] for single cell over time
"""... | Add lagged phase space plot | Add lagged phase space plot
| Python | mit | kpj/PyWave |
7316d1cb953812ae0286d59d1abc014b2f90794b | locust/__init__.py | locust/__init__.py | from .user.sequential_taskset import SequentialTaskSet
from .user.task import task, TaskSet
from .user.users import HttpUser, User
from .event import Events
from .wait_time import between, constant, constant_pacing
events = Events()
__version__ = "1.0b1"
| from .user.sequential_taskset import SequentialTaskSet
from .user.task import task, TaskSet
from .user.users import HttpUser, User
from .user.wait_time import between, constant, constant_pacing
from .event import Events
events = Events()
__version__ = "1.0b1"
| Move wait_time.py into user module | Move wait_time.py into user module | Python | mit | locustio/locust,mbeacom/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust,mbeacom/locust,locustio/locust |
71eeb919373787569034225e8047079075df5569 | Challenges/chall_06.py | Challenges/chall_06.py | #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt:
welcome to my zipped list.
... | #!/usr/local/bin/python3
# Python Challenge - 6
# http://www.pythonchallenge.com/pc/def/channel.html
# http://www.pythonchallenge.com/pc/def/channel.zip
# Keyword: hockey -> oxygen
import re
import zipfile
def main():
'''
Hint: zip, now there are pairs
In the readme.txt:
welcome to my zipped list.
... | Add print statements for clarity | Add print statements for clarity
| Python | mit | HKuz/PythonChallenge |
3d1521892ba17120ca4461335713b9d2254311fe | marble/tests/test_clustering.py | marble/tests/test_clustering.py | """ Tests for the clustering computation """
from nose.tools import *
import marble as mb
# Test c = 0 in the checkerboard case
# Test c = 1 in the fully clustered case
# Test an intermediate situation with known result
| """ Tests for the clustering computation """
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
#
# Synthetic data for tests
#
def grid():
""" Areal units arranged in a grid """
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = {a:Polygo... | Add tests for the clustering of cities | Add tests for the clustering of cities
| Python | bsd-3-clause | walkerke/marble,scities/marble |
610fb9c9ac6a225df10ec770d44564e61af53ce0 | polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py | polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py | import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
... | import os
import glob
from django.apps import apps
from django.db import connection
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Turn off auto system check for all apps
We will maunally run system checks only for the
'addressbase' and 'pollingstations' apps
... | Use abspath for COPY command | Use abspath for COPY command
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
b556bffeb5ed48812258b452e05cc00cfb160453 | girder/app/app/configuration.py | girder/app/app/configuration.py | from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource, RestException
from girder.constants import AccessType, TokenScope
from girder.models.setting import Setting
from .constants import Features, Deployment, Branding
class Configuration(Resou... | from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource, RestException
from girder.constants import AccessType, TokenScope
from girder.models.setting import Setting
from .constants import Features, Deployment, Branding
class Configuration(Resou... | Fix up settings for upstream Girder change | Fix up settings for upstream Girder change
| Python | bsd-3-clause | OpenChemistry/mongochemserver |
b382c57e84d239f3f239f9e2587a3559e704f071 | mozcal/events/api.py | mozcal/events/api.py | from tastypie.resources import ModelResource
from models import Event
from mozcal.base.serializers import MozcalSerializer
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
}
allowed_methods = ['get']
serializer = Mozca... | from tastypie.resources import ModelResource
from models import Event
from mozcal.base.serializers import MozcalSerializer
class EventResource(ModelResource):
class Meta:
queryset = Event.objects.all()
filtering = {
"title": ('startswith',),
}
allowed_methods = ['get']
include_resource_ur... | Exclude uri fields from EventResource | Exclude uri fields from EventResource
| Python | bsd-3-clause | yvan-sraka/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents |
6c922f593dba7f3604763bbb489a910dee4c915a | .vim/templates/argparse.py | .vim/templates/argparse.py | import argparse
parser = argparse.ArgumentParser(description='A useful description of this script (might want to set this to __doc__)', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-x', metavar='nameofx', nargs='+', type=float, default=32*32*32, help='Helpful message about this argument... | import argparse
parser = argparse.ArgumentParser(description='A useful description of this script (might want to set this to __doc__)', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('strarg', type=str, help='A string argument')
parser.add_argument('numarg', type=float, help='A numerical a... | Add typed positional argument examples | Add typed positional argument examples
| Python | mit | SnoopJeDi/dotfiles,SnoopJeDi/dotfiles,SnoopJeDi/dotfiles |
0377db272c5535b478732fbf045a73b30a5eac00 | migrations/versions/849170064430_.py | migrations/versions/849170064430_.py | """add enqueue_job column to smtpserver table
Revision ID: 849170064430
Revises: a63df077051a
Create Date: 2018-11-22 10:04:00.330101
"""
# revision identifiers, used by Alembic.
revision = '849170064430'
down_revision = 'a63df077051a'
from alembic import op
import sqlalchemy as sa
def upgrade():
try:
... | """add enqueue_job column to smtpserver table
Revision ID: 849170064430
Revises: a63df077051a
Create Date: 2018-11-22 10:04:00.330101
"""
# revision identifiers, used by Alembic.
revision = '849170064430'
down_revision = '48ee74b8a7c8'
from alembic import op
import sqlalchemy as sa
def upgrade():
try:
... | Update down-revision of queue migration script | Update down-revision of queue migration script
| Python | agpl-3.0 | privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea |
dfbae8fd2f2346ecf7bb1e04c9c43c18e4da234d | src/encoded/authorization.py | src/encoded/authorization.py | from sqlalchemy.orm.exc import NoResultFound
from .storage import (
DBSession,
UserMap,
)
def groupfinder(login, request):
if ':' not in login:
return None
namespace, localname = login.split(':', 1)
if namespace == 'mailto':
session = DBSession()
query = session.query(... | from sqlalchemy.orm.exc import NoResultFound
from .storage import (
DBSession,
UserMap,
)
def groupfinder(login, request):
if ':' not in login:
return None
namespace, localname = login.split(':', 1)
if namespace == 'mailto':
session = DBSession()
model = session.query(... | Simplify the groupfinder a little. In general we should try to use session.query(...).get() rather than .filter(). | Simplify the groupfinder a little. In general we should try to use session.query(...).get() rather than .filter().
| Python | mit | kidaa/encoded,philiptzou/clincoded,ENCODE-DCC/snovault,T2DREAM/t2dream-portal,hms-dbmi/fourfront,hms-dbmi/fourfront,ClinGen/clincoded,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,T2DREAM/t2dream-portal,4dn-dcic/fourfront,kidaa/encoded,kidaa/encoded,T2DREAM/t2dream... |
b7bb3b0782fcece12531b90a17eda98c4ae59be0 | notes/templatetags/note_tags.py | notes/templatetags/note_tags.py | from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------... | from django.template import Library, Node, TemplateSyntaxError
from django.utils.html import escape
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from notes.models import Note
from castle.models import Profile
register = Library()
#-----------------------------------------------... | Update to display notes count bubble only when new notes are available | Update to display notes count bubble only when new notes are available
| Python | agpl-3.0 | ficlatte/main,HSAR/Ficlatte,stitzelj/Ficlatte,ficlatte/main,HSAR/Ficlatte,stitzelj/Ficlatte |
c4880ef0350d7cf58d9dff344f98f3b3096f2613 | this_app/models.py | this_app/models.py | from werkzeug.security import generate_password_hash, check_password_hash
class User(object):
"""represents a user who can CRUD his own bucketlists"""
users = {}
def __init__(self, email, username, password):
"""Constructor class to initialize class"""
self.email = email
self.use... | from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class User(UserMixin):
"""Represents a user who can Create, Read, Update & Delete his own bucketlists"""
counter = 0
users = {}
def __init__(self, email, username, password):
"""Constru... | Update User model class with flask-login methods | Update User model class with flask-login methods
| Python | mit | borenho/flask-bucketlist,borenho/flask-bucketlist |
1c07b3b29c18147578c94a21abf6c34647a7185d | tests/test_parse.py | tests/test_parse.py | import pytest
from skidl import *
from .setup_teardown import *
def test_parser_1():
netlist_to_skidl(r'C:\xesscorp\KiCad\tools\skidl\tests\Arduino_Uno_R3_From_Scratch.net')
| import pytest
from skidl import *
from .setup_teardown import *
def test_parser_1():
netlist_to_skidl(get_filename('Arduino_Uno_R3_From_Scratch.net'))
| Fix remaining absolute path in tests | Fix remaining absolute path in tests
| Python | mit | xesscorp/skidl,xesscorp/skidl |
192c7b01a34c3b9200005744790b63bcd7a7333c | pytablereader/loadermanager/_base.py | pytablereader/loadermanager/_base.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def format... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def format... | Add an interface to change loading encoding for File/URL loaders | Add an interface to change loading encoding for File/URL loaders
| Python | mit | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader |
8b916c0d4b45427f4820bb63fcccc085375c405a | jsplot/plot.py | jsplot/plot.py | data = []
def plot(x, y, label=None):
d = {
"data": zip(x, y),
}
if label:
d["label"] = label
data.append(d)
def show():
from plotserver.runserver import main
main()
def grid(*args, **kwargs):
pass
def legend(*args, **kwargs):
pass
| data = []
def plot(x, y, format=None, label=None, lw=None):
d = {
"data": zip(x, y),
}
if label:
d["label"] = label
data.append(d)
def show():
from plotserver.runserver import main
main()
def grid(*args, **kwargs):
pass
def legend(*args, **kwargs):
pass
| Add format and lw kwargs | Add format and lw kwargs
| Python | mit | certik/jsplot,certik/jsplot |
85db14b8584995da667c92cda6a44e2b3395250e | greenlight/views/__init__.py | greenlight/views/__init__.py | from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, reques... | from three import Three
from django.core.urlresolvers import reverse
from django.http import Http404
from .base import APIView
QC_three = Three(
endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/",
format = "json",
jurisdiction = "ville.quebec.qc.ca",
)
class ServicesView(APIView):
def get(self, reques... | Fix a bug when the open311 API returns an error. | Fix a bug when the open311 API returns an error.
| Python | mit | ironweb/lesfeuxverts-backend |
7fc58c651ea4d2d9db8b37a9f9768cecc834b225 | primestg/__init__.py | primestg/__init__.py | try:
__version__ = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
__version__ = 'unknown'
| import os
try:
__version__ = __import__('pkg_resources') \
.get_distribution(__name__).version
except Exception, e:
__version__ = 'unknown'
_ROOT = os.path.abspath(os.path.dirname(__file__))
def get_data(path):
filename = isinstance(path, (list, tuple)) and path[0] or path
return os.path.joi... | Add function to get relative path in repository | Add function to get relative path in repository
| Python | agpl-3.0 | gisce/primestg |
57170909979d89c6887fde80510855c2ea4770e9 | django_prometheus/__init__.py | django_prometheus/__init__.py | """Django-Prometheus
https://github.com/korfuri/django-prometheus
"""
# Import all files that define metrics. This has the effect that
# `import django_prometheus` will always instanciate all metric
# objects right away.
import django_prometheus.middleware
import django_prometheus.models
# Import pip_prometheus to e... | """Django-Prometheus
https://github.com/korfuri/django-prometheus
"""
# Import all files that define metrics. This has the effect that
# `import django_prometheus` will always instanciate all metric
# objects right away.
import django_prometheus.middleware
import django_prometheus.models
# Import pip_prometheus to e... | Make the use of pip-prometheus optional. | Make the use of pip-prometheus optional.
| Python | apache-2.0 | obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,korfuri/django-prometheus |
55d372b4887bc9461d9e5ea958a5703ed19bdcae | frontend/checkFrontend.py | frontend/checkFrontend.py | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = config file
#
# Author:
# Igor Sfiligoi Jul 17th 2008
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
config_dict={}
try:
execfile(sys.argv[1],config_dict)
... | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = work_dir
#
# Author:
# Igor Sfiligoi
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
try:
work_dir=sys.argv[1]
frontend_pid=glideinFrontendPidLib.get_fr... | Rewrite based on factory one | Rewrite based on factory one
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS |
ef8452020c95b08fa8aed9840a7e0cb94eaec514 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | Change url of the website | Change url of the website
| Python | agpl-3.0 | xcgd/document_attachment |
fae501041857f1e4eea2b5157feb94a3f3c84f18 | pinax/__init__.py | pinax/__init__.py | VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
return version
__version__ = get_versi... | import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PI... | Support development versions using an environment variable | Support development versions using an environment variable
| Python | mit | amarandon/pinax,amarandon/pinax,amarandon/pinax,amarandon/pinax |
ab3b2e9a681740159897ef8592c4f891df791119 | publisher_test_project/manage.py | publisher_test_project/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python3
import os
import sys
print("sys.real_prefix:", getattr(sys, "real_prefix", "-"))
print("sys.prefix:", sys.prefix)
if __name__ == "__main__":
if "VIRTUAL_ENV" not in os.environ:
raise RuntimeError(" *** ERROR: Virtual env not activated! *** ")
os.environ.setdefault("DJANGO_SETT... | Raise error if virtualenv not activated | Raise error if virtualenv not activated
| Python | bsd-3-clause | wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai |
daeda47aa33abad38f8f93ef9dde261809171c9b | podcasts/models.py | podcasts/models.py | from django.db import models
class Podcast(models.Model):
title = models.CharField(max_length=100, blank=True)
link = models.URLField(blank=True)
feed = models.URLField()
description = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.title
def title_or_unna... | from django.db import models
class Podcast(models.Model):
title = models.CharField(max_length=100, blank=True)
link = models.URLField(blank=True)
feed = models.URLField()
description = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.title
def title_or_unna... | Make so an episode link isn't mandatory | Make so an episode link isn't mandatory
| Python | mit | matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik |
e49cd7aeaf81ed12490d82b8a65ca93088ec916e | spacy/__init__.py | spacy/__init__.py | # coding: utf8
from __future__ import unicode_literals
from .cli.info import info as cli_info
from .glossary import explain
from .deprecated import resolve_load_name
from .about import __version__
from . import util
def load(name, **overrides):
name = resolve_load_name(name, **overrides)
return util.load_mod... | # coding: utf8
from __future__ import unicode_literals
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from . import util
def load(name, **overrides):
from .deprecated import resolve_load_name
name = resolve_load_name(name, **overrides)
return util.load... | Move import into load to avoid circular imports | Move import into load to avoid circular imports
| Python | mit | aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,honnibal/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaC... |
c54240e6d9f6393370fe94f2cd05476680cf17f2 | pygtfs/__init__.py | pygtfs/__init__.py | from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__
| import warnings
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
try:
from ._version import version as __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
| Allow usage directly from the code (fix the _version import) | Allow usage directly from the code (fix the _version import)
| Python | mit | jarondl/pygtfs |
215746e2fd7e5f78b6dae031aae6a935ab164dd1 | pyjokes/pyjokes.py | pyjokes/pyjokes.py | from __future__ import absolute_import
import random
import importlib
def get_joke(category='neutral', language='en'):
"""
Parameters
----------
category: str
Choices: 'neutral', 'explicit', 'chuck', 'all'
lang: str
Choices: 'en', 'de', 'es'
Returns
-------
joke: str
... | from __future__ import absolute_import
import random
from .jokes_en import jokes as jokes_en
from .jokes_de import jokes as jokes_de
from .jokes_es import jokes as jokes_es
all_jokes = {
'en': jokes_en,
'de': jokes_de,
'es': jokes_es,
}
class LanguageNotFoundError(Exception):
pass
class CategoryN... | Use dict not if/else, add exceptions | Use dict not if/else, add exceptions
| Python | bsd-3-clause | borjaayerdi/pyjokes,birdsarah/pyjokes,pyjokes/pyjokes,bennuttall/pyjokes,trojjer/pyjokes,gmarkall/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes |
b4fbb4784b61001cc29c311e3b50c3fad3c60ef0 | nipap/setup.py | nipap/setup.py | #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__aut... | #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__aut... | Change installation path for nipap-passwd | Change installation path for nipap-passwd
This really is a "admin tool" and so we put it in /usr/sbin instead!
Fixes #196
| Python | mit | SpriteLink/NIPAP,garberg/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,fredsod/NIPAP,fredsod/NIPAP,bbaja42/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,SoundGoof/NIPAP,SpriteLink/NIPAP,ettrig/NIPAP,garberg/NIPAP,SpriteLink/NIPAP,garberg/NIPAP,plajjan/NIPAP,plajjan/NIPAP,SoundGoof/NIPAP,plajjan/NIPAP,bbaja42/NIPAP,bbaja42... |
2e941cf1f6208b9ac2f6039681c24502b324ab5f | planner/models.py | planner/models.py | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugF... | import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugF... | Add Semester str method for admin interface. | Add Semester str method for admin interface.
Fixes #149
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp |
fd5810c86f5998c2e2a7b96f09e82b40fbe2cc11 | string/first-str-substr-occr.py | string/first-str-substr-occr.py | # Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1
def find_substring(string, substr):
string_len = len(... | # Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1
def find_substring(string, substr):
string_len = len(... | Return -1 if no substring is found | Return -1 if no substring is found
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
0994fb6a8c924e907151764f9c1eaa19f2c3aea7 | salt/returners/syslog_return.py | salt/returners/syslog_return.py | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... | Remove redundant text from syslog returner | Remove redundant text from syslog returner
The implicit call to syslog.openlog will already add salt-minion (technically `sys.argv[0]`) to the syslog.syslog call. It's redundant (and not technically correct) to have salt-minion here.
Can also be applied to 2015.8 and develop without issue.
Fixes #27756 | Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
2fc13f58d8deba0f34c1e33ed78884630e8a7804 | pages/tests.py | pages/tests.py | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed correctly
"""
c = Client()
c.login(... | from django.test import TestCase
from pages.models import *
from django.test.client import Client
class PagesTestCase(TestCase):
fixtures = ['tests.json']
def test_01_add_page(self):
"""
Test that the add admin page could be displayed via the admin
"""
c = Client()
c.l... | Add a create page test | Add a create page test
git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@300 439a9e5f-3f3e-0410-bc46-71226ad0111b
| Python | bsd-3-clause | akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,ba... |
ed71dc1e9163c5a7a7b0f623ea75393286804138 | dbsettings/utils.py | dbsettings/utils.py | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... | def set_defaults(app, *defaults):
"Installs a set of default values during syncdb processing"
from django.core.exceptions import ImproperlyConfigured
from django.db.models import signals
from dbsettings.loading import get_setting_storage, set_setting_value
if not defaults:
raise Impr... | Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals. | Fix bug with registering local methods that got garbage collected due to django's weakref handling in signals.
| Python | bsd-3-clause | johnpaulett/django-dbsettings,nwaxiomatic/django-dbsettings,MiriamSexton/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,nwaxiomatic/django-dbsettings,sciyoshi/django-dbsettings,helber/django-dbsettings,DjangoAdminHackers/django-dbsettings,helber/django-dbsettings,zlorf/django-dbsettings,... |
2bf5809b651bc85e922c853d2dab27d35fee85b8 | test/bibliopixel/threads/sub_test.py | test/bibliopixel/threads/sub_test.py | import functools, time, unittest
from bibliopixel.util.threads import sub
WAIT_FOR_SUB = 0.1
def pause(delay=0.01):
time.sleep(delay)
def run(input, output, *arg, **kwds):
pause()
output.put('first')
if arg != (1, 2, 3):
raise ValueError('1 2 3')
if kwds != dict(a=1):
raise V... | import functools, time, unittest
from bibliopixel.util.threads import sub
from .. import mark_tests
WAIT_FOR_SUB = 0.1
def pause(delay=0.01):
time.sleep(delay)
def run(input, output, *arg, **kwds):
pause()
output.put('first')
if arg != (1, 2, 3):
raise ValueError('1 2 3')
if kwds != ... | Disable one test in windows-only | Disable one test in windows-only
| Python | mit | ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel |
77136f1c7dc6159a040c17cf5143bea14e9462b3 | housing/listings/forms.py | housing/listings/forms.py | from django import forms
from .models import Listing, HousingUser
class ListingForm(forms.ModelForm):
furnished_details = forms.CharField(widget=forms.Textarea(attrs={
"placeholder": "Example: bed and desk only"}))
additional_lease_terms = forms.CharField(required=False,
widget=forms.Textarea(a... | from django import forms
from .models import Listing, HousingUser
class ListingForm(forms.ModelForm):
furnished_details = forms.CharField(required=False, widget=forms.Textarea(attrs={
"placeholder": "Example: bed and desk only"}))
additional_lease_terms = forms.CharField(required=False,
widget=... | Update newListing no longer require furnishing detail | Update newListing no longer require furnishing detail
| Python | mit | xyb994/housing,xyb994/housing,xyb994/housing,xyb994/housing |
a1bfb35bb5865cc45aded58b7cffab6da7cc0baf | pykeg/settings.py | pykeg/settings.py | # Pykeg main settings file.
# Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in
# common_settings.py.example.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.... | # Pykeg main settings file.
# Note: YOU SHOULD NOT NEED TO EDIT THIS FILE. Instead, see the instructions in
# common_settings.py.example.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.... | Add twitter to default apps. | Add twitter to default apps.
| Python | mit | Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server |
509ca9c2cad65b47e1a2a16a0c169434620b8c74 | mla_game/apps/transcript/management/commands/scrape_archive.py | mla_game/apps/transcript/management/commands/scrape_archive.py | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup arc... | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from popuparchive.client import Client
from ...models import Transcript
from ...tasks import process_transcript
logger = logging.getLogger('pua_scraper')
class Command(BaseCommand):
help = 'scrapes the popup arc... | Test for transcript before scraping from PUA | Test for transcript before scraping from PUA
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt |
eeaa4251234cfbbefc8f24e7cba22d330d98eefc | cloudbaseinit/shell.py | cloudbaseinit/shell.py | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | Make the multithreaded coinitialize only on 64bit | Make the multithreaded coinitialize only on 64bit
Change-Id: I5d44efb634051f00cd3ca54b99ce0dea806543be
| Python | apache-2.0 | alexpilotti/cloudbase-init,ader1990/cloudbase-init,stefan-caraiman/cloudbase-init,cmin764/cloudbase-init,openstack/cloudbase-init,stackforge/cloudbase-init |
56a76b9dc0745d22d9b1eac54348d6109dc3c0e1 | src/funding/urls.py | src/funding/urls.py | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.CurrentView.as_view(), name='funding_current'),
path('teraz/', vi... | # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.urls import path, include
from annoy.utils import banner_exempt
from . import views
urlpatterns = [
path('', banner_exempt(views.CurrentView.as_vi... | Disable banners on funding pages. | Disable banners on funding pages.
| Python | agpl-3.0 | fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury |
4927a1c29d258b1ab7c70ffecff6904b808480eb | bokeh/validation/warnings.py | bokeh/validation/warnings.py | ''' Define standard warning codes and messages for Bokeh validation checks.
1000 : *MISSING_RENDERERS*
A |Plot| object has no renderers configured (will result in a blank plot).
1001 : *NO_GLYPH_RENDERERS*
A |Plot| object has no glyph renderers (will result in an empty plot frame).
1002 : *EMPTY_LAYOUT*
... | ''' Define standard warning codes and messages for Bokeh validation checks.
1000 : *MISSING_RENDERERS*
A |Plot| object has no renderers configured (will result in a blank plot).
1001 : *NO_GLYPH_RENDERERS*
A |Plot| object has no glyph renderers (will result in an empty plot frame).
1002 : *EMPTY_LAYOUT*
... | Add module level documentation for colon warning | Add module level documentation for colon warning
| Python | bsd-3-clause | ericmjl/bokeh,timsnyder/bokeh,draperjames/bokeh,philippjfr/bokeh,mindriot101/bokeh,aavanian/bokeh,aavanian/bokeh,phobson/bokeh,daodaoliang/bokeh,KasperPRasmussen/bokeh,rothnic/bokeh,dennisobrien/bokeh,phobson/bokeh,DuCorey/bokeh,timsnyder/bokeh,jplourenco/bokeh,ericdill/bokeh,srinathv/bokeh,bokeh/bokeh,srinathv/bokeh,j... |
d8a46686f12de76381bf9c2cfde0e9482acc2259 | Toolkit/PlayPen/rooster.py | Toolkit/PlayPen/rooster.py | import os
import sys
import math
def main():
# do while len(spot.xds) > 100 (say)
# index, no unit cell / symmetry set
# copy out indexed spots, orientation matrix
# done
# compare list of orientation matrices - how are they related?
# graphical representation?
| import os
import sys
import math
import shutil
def split_spot_file(j):
'''Split the spot file into those which have been indexed (goes to SPOT.j)
and those which have not, which gets returned to SPOT.XDS. Returns number
of unindexed reflections.'''
spot_j = open('SPOT.%d' % j, 'w')
spot_0 = open('... | Make a start on the recursive reindexing | Make a start on the recursive reindexing | Python | bsd-3-clause | xia2/xia2,xia2/xia2 |
2e1d1e5914d853a4da55dd0c8ea534df396697a0 | coop_cms/forms/__init__.py | coop_cms/forms/__init__.py | # -*- coding: utf-8 -*-
# This can be imported directly from coop_cms.forms
from coop_cms.forms.articles import ArticleForm, ArticleSettingsForm, NewArticleForm
from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm
__all__ = ['ArticleForm', 'ArticleSettingsForm', 'NewArticleForm', 'NewsletterF... | # -*- coding: utf-8 -*-
# This can be imported directly from coop_cms.forms
from coop_cms.forms.articles import (
ArticleForm, ArticleAdminForm, ArticleSettingsForm, NewArticleForm, BaseArticleAdminForm
)
from coop_cms.forms.newsletters import NewsletterForm, NewsletterSettingsForm
__all__ = [
'ArticleForm', ... | Add more forms to the publics | Add more forms to the publics
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms |
e3ae701be163ccff7e2f64721752b0374dffdfc1 | rosie/chamber_of_deputies/tests/test_dataset.py | rosie/chamber_of_deputies/tests/test_dataset.py | import os.path
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
temp_path = mkdtemp()
... | import shutil
import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
self.temp_path = mkdtemp()
fixtures = os.path.join('rosi... | Fix companies path in Chamber of Deputies dataset test | Fix companies path in Chamber of Deputies dataset test
| Python | mit | marcusrehm/serenata-de-amor,datasciencebr/rosie,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor |
8aeee881bb32935718e767114256179f9c9bf216 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/test_drf_views.py | import pytest
from django.test import RequestFactory
from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet
from {{ cookiecutter.project_slug }}.users.models import User
pytestmark = pytest.mark.django_db
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
... | import pytest
from django.test import RequestFactory
from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet
from {{ cookiecutter.project_slug }}.users.models import User
pytestmark = pytest.mark.django_db
class TestUserViewSet:
def test_get_queryset(self, user: User, rf: RequestFactory):
... | Remove email from User API Test | Remove email from User API Test | Python | bsd-3-clause | ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-djang... |
8f3fb41b8001c3f2dffc6086e89e782a9a46f79a | draftjs_exporter/constants.py | draftjs_exporter/constants.py | from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
return name
# https://github.com/draft-js-utils/draft-js-utils/blob/master/src... | from __future__ import absolute_import, unicode_literals
# http://stackoverflow.com/a/22723724/1798491
class Enum(object):
def __init__(self, tuple_list):
self.tuple_list = tuple_list
def __getattr__(self, name):
if name not in self.tuple_list:
raise AttributeError("'Enum' has no ... | Fix Enum returning invalid elements | Fix Enum returning invalid elements
| Python | mit | springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter |
87079b55d17edc4cc8bbcb2a7af80adf5799608e | swingtime/urls.py | swingtime/urls.py | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/(?P<year>\d{4})/$',
views.year_view,
name='swingtime-yearly-view'
... | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.today_view,
name='swingtime-today'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime-calendar-json'... | Remove whitespace, and also add JSON url | Remove whitespace, and also add JSON url
| Python | mit | jonge-democraten/mezzanine-fullcalendar |
e264d00fa37dd1b326f1296badd74fa4ab599a45 | project/runner.py | project/runner.py | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
class CustomTestRunner(DiscoverRunner):
"""
Same as the default Django test runner, except it also runs our node
server as a subprocess so we can render React components.
"""
def setup_test_environment(self, **kwargs... | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
from django.conf import settings
from react.render_server import render_server
TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1')
TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008)
... | Use separate node server when running the tests | Use separate node server when running the tests
| Python | mit | jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015,jphalip/django-react-djangocon2015 |
84fa71e639bc1b6fda246ddfd321f0f777b86216 | tasks/__init__.py | tasks/__init__.py | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftes... | Add notifiers to task list | Add notifiers to task list
| Python | apache-2.0 | BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest |
6c3d18e8f2a242f9de79679c4cccafbca5066bb6 | runners/serializers.py | runners/serializers.py | from rest_framework import serializers
from .models import Runner, RunnerVersion
class RunnerVersionSerializer(serializers.ModelSerializer):
class Meta(object):
model = RunnerVersion
fields = ('version', 'url')
class RunnerSerializer(serializers.ModelSerializer):
versions = RunnerVersionSeri... | from rest_framework import serializers
from .models import Runner, RunnerVersion
class RunnerVersionSerializer(serializers.ModelSerializer):
class Meta(object):
model = RunnerVersion
fields = ('version', 'architecture', 'url')
class RunnerSerializer(serializers.ModelSerializer):
versions = R... | Add architecture to runner version serializer | Add architecture to runner version serializer
| Python | agpl-3.0 | lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website |
2f635e890414f777fbe3ddde1aea74ab13558313 | llvmlite/tests/test_dylib.py | llvmlite/tests/test_dylib.py | import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def test_bad_library(self)... | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... | Add tests to check loading library. | Add tests to check loading library.
| Python | bsd-2-clause | m-labs/llvmlite,pitrou/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,markdewing/llvmlite,pitrou/llvmlite,numba/llvmlite,markdewing/llvmlite,sklam/llvmlite,sklam/llvmlite,pitrou/llvmlite,numba/llvmlite,ssarangi/llvmlite,markdewing/llvmlite,squisher/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,numba/llvmlite,numba/llvmlite,sq... |
77f975b9f19fad319708f19c4602ab4fd7ad8260 | scripts/ben10_build.py | scripts/ben10_build.py | from __future__ import unicode_literals
from aasimar.shared_commands import BuildCommand
from ben10.foundation.decorators import Override
#===================================================================================================
# Ben10BuildCommand
#=========================================================... | from __future__ import unicode_literals
from aasimar.shared_commands import BuildCommand
from ben10.foundation.decorators import Override
#===================================================================================================
# Ben10BuildCommand
#=========================================================... | Fix build issues when sharedscripts10 is not available. | Fix build issues when sharedscripts10 is not available.
By calling project.install with --no-spawn, we can avoid an error that
happened during build:
[ben10] Resource not found "sharedscripts10".
| Python | lgpl-2.1 | Kaniabi/ben10,ESSS/ben10,Kaniabi/ben10,ESSS/ben10 |
f5922951bcabac81c41fd52e2ed5cd9b67c9a920 | src/gramcore/features/tests/test_descriptors.py | src/gramcore/features/tests/test_descriptors.py | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many valu... | """Tests for module gramcore.features.descriptors"""
import numpy
from nose.tools import assert_equal
from gramcore.features import descriptors
def test_hog_size():
"""Create a fixture and check hog result size
There are already enough tests in skimage for this, just adding so to
document how many valu... | Add comment on HOG calculations | Add comment on HOG calculations
| Python | mit | cpsaltis/pythogram-core |
8aca599083f69fbc4427f608554d4035c7d2dccf | social/apps/pyramid_app/views.py | social/apps/pyramid_app/views.py | from pyramid.view import view_config
from social.utils import module_member
from social.actions import do_auth, do_complete, do_disconnect
from social.apps.pyramid_app.utils import psa, login_required
@view_config(route_name='social.auth', request_method='GET')
@psa('social.complete')
def auth(request):
return d... | from pyramid.view import view_config
from social.utils import module_member
from social.actions import do_auth, do_complete, do_disconnect
from social.apps.pyramid_app.utils import psa, login_required
@view_config(route_name='social.auth', request_method=('GET', 'POST'))
@psa('social.complete')
def auth(request):
... | Allow POST requests for auth method so OpenID forms could use it that way. | Allow POST requests for auth method so OpenID forms could use it that way.
| Python | bsd-3-clause | fearlessspider/python-social-auth,cjltsod/python-social-auth,python-social-auth/social-app-django,tobias47n9e/social-core,python-social-auth/social-core,python-social-auth/social-app-django,python-social-auth/social-storage-sqlalchemy,fearlessspider/python-social-auth,python-social-auth/social-app-cherrypy,cjltsod/pyth... |
cbdc24aeef9ffbd8e7400ab43112409509b3337d | reviewday/util.py | reviewday/util.py | import os
import shutil
import html_helper
from Cheetah.Template import Template
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
if os.path.exists(out_dir):
print 'WARNING: output directory "%s" already exists' % ... | import os
import html_helper
from Cheetah.Template import Template
from distutils.dir_util import copy_tree
def prep_out_dir(out_dir='out_report'):
src_dir = os.path.dirname(__file__)
report_files_dir = os.path.join(src_dir, 'report_files')
copy_tree(report_files_dir, out_dir)
def create_report(name_spa... | Remove warning for existing output directory. | Remove warning for existing output directory.
In our configuration puppet will manage the output directory, so it
is expected behavior for it to exist, removing warning. Also
switching to distutils.dir_util copy_tree since that allows for
copying of required supporting files into an existing output
directory.
Change-... | Python | mit | openstack-infra/reviewday,openstack-infra/reviewday,dprince/reviewday |
4ed64168541993e2ea85e7ea47139550d1daa206 | backdrop/write/config/development_environment_sample.py | backdrop/write/config/development_environment_sample.py | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | # Copy this file to development_environment.py
# and replace OAuth credentials your dev credentials
TOKENS = {
'_foo_bucket': '_foo_bucket-bearer-token',
'bucket': 'bucket-bearer-token',
'foo': 'foo-bearer-token',
'foo_bucket': 'foo_bucket-bearer-token',
'licensing': 'licensing-bearer-token',
'l... | Add buckets for collecting pingdom data | Add buckets for collecting pingdom data
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
653ae451e204905b8295e424ca86c20d60ee686c | settings/__init__.py | settings/__init__.py | import yaml
import utils
with open('settings.yml') as settings_file:
YML = yaml.safe_load(settings_file)
IMAGE = utils.Settings(YML['image'])
SNAP = utils.Settings(YML['snap'])
DROPBOX_TOKEN_FILE = "./dropbox.txt"
WORKING_DIRECTORY = "/home/pi/time-lapse"
IMAGES_DIRECTORY = WORKING_DIRECTORY + "/images"
... | import glob
import yaml
import utils
with open('settings.yml') as settings_file:
YML = yaml.safe_load(settings_file)
IMAGE = utils.Settings(YML['image'])
SNAP = utils.Settings(YML['snap'])
DROPBOX_TOKEN_FILE = "./dropbox.txt"
WORKING_DIRECTORY = "/home/pi/time-lapse"
IMAGES_DIRECTORY = WORKING_DIRECTORY ... | Make a class to manage job settings | Make a class to manage job settings
| Python | mit | projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse |
7d4b2af132001927ea42b69650b6b45301ee335f | astrobin/management/commands/notify_new_blog_entry.py | astrobin/management/commands/notify_new_blog_entry.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from zinnia.models import Entry
from astrobin.notifications import push_notification
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import persistent_messages
from zinnia.models import Entry
class Command(BaseCommand):
help = "Notifies all users about most recent blog entry."
def handle(self, *args, **options):
entry = Entry.objects.a... | Fix management command to send notification about new blog post. | Fix management command to send notification about new blog post.
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin |
0a04752396bdd57a8c197e2c76e5bda92d0bad1a | reddit_meatspace/utils.py | reddit_meatspace/utils.py | import hashlib
from pylons import g
def make_secret_code(meetup, user):
hash = hashlib.md5(g.SECRET)
hash.update(str(meetup._id))
hash.update(str(user._id))
return int(hash.hexdigest()[-8:], 16) % 100
| import hashlib
from pylons import g
def make_secret_code(meetup, user):
hash = hashlib.md5(g.secrets["SECRET"])
hash.update(str(meetup._id))
hash.update(str(user._id))
return int(hash.hexdigest()[-8:], 16) % 100
| Use the zk secret safe for g.SECRET. | Use the zk secret safe for g.SECRET.
| Python | bsd-3-clause | reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace,reddit/reddit-plugin-meatspace |
22ce36b227c40ace101db5d9c4e30575adca5f36 | tests/settings.py | tests/settings.py | import os
from settings import *
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
... | from __future__ import absolute_import
import os
from settings import *
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif d... | Use absolute imports to avoid module naming issues | Use absolute imports to avoid module naming issues
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/infrastructure,Inboxen/Inboxen,Inboxen/Inboxen |
8df3076b6315a74e57ee27fe3478d36737be0ff9 | roche/scripts/xml-load.py | roche/scripts/xml-load.py | # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.c... | # coding=utf-8
#
# Must be called in roche root dir
#
import sys
import os
sys.path.append('.')
import roche.settings
from os import walk
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.c... | Load other resources into exist-db | Load other resources into exist-db
| Python | mit | beijingren/roche-website,beijingren/roche-website,beijingren/roche-website,beijingren/roche-website |
63a539ff4a3a832286136c40a74b1a8b3db1a5c0 | falcom/api/uri/api_querier.py | falcom/api/uri/api_querier.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from time import sleep
class APIQuerier:
def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0):
self.uri = uri
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from time import sleep
class APIQuerier:
def __init__ (self, uri, url_opener, sleep_time=300, max_tries=0):
self.uri = uri
... | Rewrite get() to be less repetitive but still stupid | Rewrite get() to be less repetitive but still stupid
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
edc88421bec2798d82faeece2df5229888d97db9 | contrib/performance/graph.py | contrib/performance/graph.py |
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
stats, samples = select(
pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time')
da... |
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
fname, bench, param, stat = fname.split(',')
stats, samples = select(
pickle.load(fil... | Make the bench/param/stat a commandline parameter | Make the bench/param/stat a commandline parameter
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver |
a4913289ce0672cfe60bb443db469356f970c353 | wakatime/projects/projectmap.py | wakatime/projects/projectmap.py | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | # -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~
Information from ~/.waka-projectmap mapping folders (relative to home folder)
to project names
:author: 3onyc
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from ..packages import s... | Make ProjectMap use config section | Make ProjectMap use config section
| Python | bsd-3-clause | wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,Djabbz/wakatime,wakatime/wakatime,Djabbz/wakatime,queenp/wakatime,gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,Djabbz/wakatime,gandarez/wakatime,wakatime/wakatime,Djabbz/wakatime,prashant... |
f1436f7f5140ea51fd5fc1f231e28f57c69f0cb1 | tutorials/urls.py | tutorials/urls.py | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
] | from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url... | Add markdownx url, Add add-tutrorial url | Add markdownx url, Add add-tutrorial url
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
6bdc335ebb8ed009cbc926e681ee6be8f475f323 | reviewboard/reviews/features.py | reviewboard/reviews/features.py | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created d... | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created d... | Mark status updates as stable. | Mark status updates as stable.
This allows people to actually use the feature without turning it on in their
`settings_local.py`.
Reviewed at https://reviews.reviewboard.org/r/8569/
| Python | mit | sgallagher/reviewboard,brennie/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,davidt/reviewboard,reviewboard/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,sgallagher/reviewboard,davidt/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie... |
f413f5bc2015843a4e74dd969d56bc54f9dbba4e | deconstrst/__init__.py | deconstrst/__init__.py | # -*- coding: utf-8 -*-
import sys
from sphinxwrapper import build
__author__ = 'Ash Wilson'
__email__ = 'ash.wilson@rackspace.com'
__version__ = '0.1.0'
def main():
sys.exit(build(sys.argv))
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import sys
from deconstrst import build
__author__ = 'Ash Wilson'
__email__ = 'ash.wilson@rackspace.com'
__version__ = '0.1.0'
def main():
sys.exit(build(sys.argv))
if __name__ == '__main__':
main()
| Fix an import that missed the renaming sweep. | Fix an import that missed the renaming sweep.
| Python | apache-2.0 | deconst/preparer-sphinx,ktbartholomew/preparer-sphinx,smashwilson/deconst-preparer-sphinx,deconst/preparer-sphinx,ktbartholomew/preparer-sphinx |
44e64c4f0c0296015fb124cddf87bea2188559fe | stagpy/__main__.py | stagpy/__main__.py | # PYTHON_ARGCOMPLETE_OK
"""The stagpy module is callable"""
from . import config
def main():
"""StagPy entry point"""
args = config.parse_args()
args.func(args)
if __name__ == '__main__':
main()
| # PYTHON_ARGCOMPLETE_OK
"""The stagpy module is callable"""
import signal
import sys
from . import config
def sigint_handler(*_):
"""SIGINT handler"""
print('\nSo long, and thanks for all the fish.')
sys.exit()
def main():
"""StagPy entry point"""
signal.signal(signal.SIGINT, sigint_handler)
... | Handle SIGINT in a clean way | Handle SIGINT in a clean way
| Python | apache-2.0 | StagPython/StagPy |
e2574515d9879a5aa023df949031370969dc896c | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import six
if six.PY2:
import unittest2 as unittest
else:
import unittest
def main():
# Configure python path
parent = os.path.dirname(os.path.abspath(__file__))
if not parent in sys.path:
sys.path.insert(0, parent)
# Discover tests
os.e... | #!/usr/bin/env python
import os
import sys
import six
if six.PY2:
import unittest2 as unittest
else:
import unittest
def main():
# Configure python path
parent = os.path.dirname(os.path.abspath(__file__))
if not parent in sys.path:
sys.path.insert(0, parent)
# Discover tests
os.e... | Remove extra setup() from rebase. | Remove extra setup() from rebase.
| Python | bsd-3-clause | andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms |
fdf132c0b7cba6bd00f855b54ab354462c924b5c | nn/embedding/bidirectional_embeddings_to_embedding.py | nn/embedding/bidirectional_embeddings_to_embedding.py | import functools
import tensorflow as tf
from ..util import static_shape, funcname_scope
from .embeddings_to_embedding import embeddings_to_embedding
@funcname_scope
def bidirectional_embeddings_to_embedding(child_embeddings,
**kwargs):
child_embeddings_to_embedding = fun... | import functools
import tensorflow as tf
from ..util import static_shape, static_rank, funcname_scope
from .embeddings_to_embedding import embeddings_to_embedding
@funcname_scope
def bidirectional_embeddings_to_embedding(child_embeddings,
**kwargs):
child_embeddings_to_em... | Use tf.reverse function to reverse embedding sequences | Use tf.reverse function to reverse embedding sequences
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten |
a576432d045d14308012a4eaa6eaeb12fe004a37 | scarplet.py | scarplet.py | """ Functions for determinig best-fit template parameters by convolution with a
grid """
| """ Functions for determinig best-fit template parameters by convolution with a
grid """
import dem
import WindowedTemplate as wt
import numpy as np
from scipy import signal
def calculate_best_fit_parameters(dem, template_function, **kwargs):
template_args = parse_args(**kwargs)
num_angles = 180/ang_ste... | Add generic grid search function | Add generic grid search function
| Python | mit | rmsare/scarplet,stgl/scarplet |
90d6c6ed4f2846ef009ee95217a69cc061623135 | meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py | meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py | from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
modules = list(project.module_se... | from functools import cmp_to_key
from django import template
from adhocracy4.modules.models import Module
from adhocracy4.phases.models import Phase
from meinberlin.apps.offlineevents.models import OfflineEvent
register = template.Library()
@register.assignment_tag
def offlineevents_and_modules_sorted(project):
... | Sort modules without start dates to the future | Sort modules without start dates to the future
Modules without a start date (phases dates are not set) will be sorted
after every other module or offlineevent.
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
b2f6d9c5fec4316dbceb25bd91cb5831065c1957 | string/compress.py | string/compress.py | # Compress string using counts of repeated characters
def compress_str(str):
output = ""
curr_char = ""
char_count = ""
for i in str:
if curr_char != str[i]:
output = output + curr_char + char_count # add new unique character and its count to our output
curr_char = str[i] # move on to the next character ... | # Compress string using counts of repeated characters
def compress_str(string):
output = ""
char_count = 1
# add first character
output += string[0]
for i in range(len(string)-1): # doesn't do character count for last group of a unique character
if string[i] == string[i+1]:
char_count += 1
else:
outpu... | Rewrite method and add test cases | Rewrite method and add test cases
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
a61148a71a022b6877af0445f799f3dfa3eb6136 | BinPy/examples/source/algorithms/make_boolean_function_example.py | BinPy/examples/source/algorithms/make_boolean_function_example.py |
# coding: utf-8
### An example to demostrate the usage of make boolean function.
# In[1]:
from __future__ import print_function
from BinPy.algorithms.makebooleanfunction import *
# In[2]:
# Usage of make_boolean() function
logical_expression, gate_form = make_boolean(['A', 'B', 'C'], [1, 4, 7], minterms=True)
... | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# An example to demostrate the usage of make boolean function.
# <codecell>
from __future__ import print_function
from BinPy.algorithms.makebooleanfunction import *
# <codecell>
# Usage of make_boolean() function
logical_expression, gate_f... | Update python sources for algorithms | Update python sources for algorithms
| Python | bsd-3-clause | daj0ker/BinPy,rajathkumarmp/BinPy,yashu-seth/BinPy,BinPy/BinPy,rajathkumarmp/BinPy,BinPy/BinPy,daj0ker/BinPy,yashu-seth/BinPy |
519d1f23682b6815c41c2ac34df775ea2e333eab | jasmin_notifications/views.py | jasmin_notifications/views.py | """
Module defining views for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.views.decorators.http import require_safe
from django import http
from django.shortcuts import redirect
from django.utils import timezone
... | """
Module defining views for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.views.decorators.http import require_safe
from django import http
from django.shortcuts import redirect
from django.utils import timezone
... | Mark all similar notifications as followed when following one | Mark all similar notifications as followed when following one
| Python | mit | cedadev/jasmin-notifications,cedadev/jasmin-notifications |
ccdb5001a450859ae9eb85f1c2c90a9a80fa0ce1 | eforge/wiki/urls.py | eforge/wiki/urls.py | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | # -*- coding: utf-8 -*-
# EForge project management system, Copyright © 2010, Element43
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWA... | Update wiki to be a little more flexible with naming | Update wiki to be a little more flexible with naming
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge |
98393be0011f4e4227e6f5e86db68533af8b78e0 | webserver/profiles/models.py | webserver/profiles/models.py | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
import markdown
import bleach
class UserProfile(models.Model):
user = models.OneToOneField(User)
about_me = ... | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
from django.core.validators import MaxLengthValidator
import markdown
import bleach
class UserProfile(models.Model):
... | Add maximum length validator to about_me | Add maximum length validator to about_me
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver |
0d37ada90d4648f1e45cc3aa95dace014a26c599 | components/includes/utilities.py | components/includes/utilities.py | import random
import json
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['retu... | import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if ... | Clean up, comments, liveness checking, robust data transfer | Clean up, comments, liveness checking, robust data transfer
| Python | bsd-2-clause | mavroudisv/Crux |
f4415c9ba2df6f0cd511986d78e454194017db2e | en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py | en-2018-04-22-on-incomplete-http-reads-and-the-requests-library-in-python/clients/python/client-with-check.py | #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (not needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.format(respon... | #!/usr/bin/env python3
#
# An HTTP client that checks that the content of the response has at least
# Content-Length bytes.
#
# For requests 2.x (should not be needed for requests 3.x).
#
import requests
import sys
response = requests.get('http://localhost:8080/')
if not response.ok:
sys.exit('error: HTTP {}'.for... | Make a statement concerning requests 3.x more precise. | en-2018-04-22: Make a statement concerning requests 3.x more precise.
requests 3 has not yet been released, so it may theoretically happen that the
fix will be also needed for requests 3.x.
| Python | bsd-3-clause | s3rvac/blog,s3rvac/blog,s3rvac/blog,s3rvac/blog |
c129e600b91ac0c35e26847ef5b1df75a1dec695 | fmn/filters/generic.py | fmn/filters/generic.py | # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if f... | # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedms... | Update the documentation title for the user_filter | Update the documentation title for the user_filter | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn |
fe7e841c166ebc227e00baca4c8a72fb04ce0693 | src/mcedit2/util/directories.py | src/mcedit2/util/directories.py | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(script)
else:
... | import os
import sys
def getUserFilesDirectory():
exe = sys.executable
if hasattr(sys, 'frozen'):
folder = os.path.dirname(exe)
else:
script = sys.argv[0]
if exe.endswith("python") or exe.endswith("python.exe"):
folder = os.path.dirname(os.path.dirname(os.path.dirname(sc... | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this) | Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)
| Python | bsd-3-clause | Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2 |
2a00e0b25ebbcac58b7e65efbfcd88bd0539c3e7 | metakernel/magics/cd_magic.py | metakernel/magics/cd_magic.py | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic
import os
class CDMagic(Magic):
def line_cd(self, path):
"""
%cd PATH - change current directory of session
This line magic is used to change the director... | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic
import os
class CDMagic(Magic):
def line_cd(self, path):
"""
%cd PATH - change current directory of session
This line magic is used to change the director... | Fix cd magic for ~ paths and add test | Fix cd magic for ~ paths and add test
| Python | bsd-3-clause | Calysto/metakernel |
21c7232081483c05752e6db3d60692a04d482d24 | dakota/tests/test_dakota_base.py | dakota/tests/test_dakota_base.py | #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
import os
import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Fixtures -------------------------------------------------------------
def setup_mo... | #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Helpers --------------------------------------------------------------
class Concrete(DakotaBase):
"""A s... | Add tests for dakota.dakota_base module | Add tests for dakota.dakota_base module
Make a subclass of DakotaBase to use for testing. Add tests for the
"block" sections used to define an input file.
| Python | mit | csdms/dakota,csdms/dakota |
170293123c89696bbdcfca0cbc72233ea03f90c8 | real_estate_agency/real_estate_agency/views.py | real_estate_agency/real_estate_agency/views.py | from django.shortcuts import render,render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor
def corporation_benefit_plan(request):
... | from django.shortcuts import render,render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor... | Add form content to the index page. | Add form content to the index page.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency |
a149c8664ed8f44ab9118a85440d95239362edf2 | src/ansible/tests/test_views.py | src/ansible/tests/test_views.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from ansible.models import Playbook
class PlaybookListViewTest(TestCase):
fixtures = ['initial_data.json']
def test_view_url_exists_at_desired_location(self):
resp = self.client.get('/playbooks/')
self.assertEqual(... | from django.core.urlresolvers import reverse
from django.test import TestCase
from ansible.models import Playbook
class PlaybookListViewTest(TestCase):
fixtures = ['initial_data.json']
def test_view_url_exists_at_desired_location(self):
resp = self.client.get('/playbooks/')
self.assertEqual(... | Test to make sure link to create playbook exists | Test to make sure link to create playbook exists
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
76981dc76d17b51c73682f84ba94ae4d6329d66d | scripts/wait_for_postgres.py | scripts/wait_for_postgres.py | """Wait up to 30 seconds for postgres to be available.
This is useful when running in docker, as the first time we create a
postgres volume it takes a few seconds to become ready.
"""
import time
from os import environ
import psycopg2
if __name__ == '__main__':
elapsed = 0
while elapsed < 30:
try:
... | """Wait up to 30 seconds for postgres to be available.
This is useful when running in docker, as the first time we create a
postgres volume it takes a few seconds to become ready.
"""
import time
import os
import psycopg2
import dotenv
if __name__ == '__main__':
env_path = os.path.join(
os.path.dirname(... | Fix bug in script that blocks Travis on postgres ready state | Fix bug in script that blocks Travis on postgres ready state
| Python | mit | ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing |
5a4ff0b4da37a97e6ef86074dde63b47ba553ad8 | test/typing.py | test/typing.py | #!/usr/bin/env python
from stella import stella
from random import randint
from test import *
def return_bool(): return True
def return_arg(x): return x
def equality(a,b): return a==b
def test1():
make_eq_test(return_bool, ())
@mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5]))
def test2(arg... | #!/usr/bin/env python
from stella import stella
from random import randint
from test import *
def return_bool(): return True
def return_arg(x): return x
def equality(a,b): return a==b
def test1():
make_eq_test(return_bool, ())
@mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5]))
def test2(arg... | Add a test that automatic type promotions are not allowed. | Add a test that automatic type promotions are not allowed.
| Python | apache-2.0 | squisher/stella,squisher/stella,squisher/stella,squisher/stella |
70098ce0c9db57cb82b97bc9fee8a799fb355e98 | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
def run_once(sel... | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
binary_to_run = ... | Make the sync integration tests self-contained on autotest | Make the sync integration tests self-contained on autotest
In the past, the sync integration tests used to require a password file
stored on every test device in order to do a gaia sign in using
production gaia servers. This caused the tests to be brittle.
As of today, the sync integration tests no longer rely on a p... | Python | bsd-3-clause | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-u... |
9fcff13a4438268aa76cf2817bca1086258a083b | src/mr_landmark_mapper.py | src/mr_landmark_mapper.py | #!/usr/bin/env python
import sys
import json
import codecs
import zipimport
importer = zipimport.zipimporter('landmark.mod')
extraction = importer.load_module('extraction')
postprocessing = importer.load_module('postprocessing')
from extraction.Landmark import RuleSet
current_id = None
with codecs.open("lib/rules.... | #!/usr/bin/env python
import sys
import json
import codecs
import zipimport
importer = zipimport.zipimporter('landmark.mod')
extraction = importer.load_module('extraction')
postprocessing = importer.load_module('postprocessing')
from extraction.Landmark import RuleSet
current_id = None
with codecs.open("rules.txt"... | Change mapper to use SequenceFileAsJSONInputBatchFormat | Change mapper to use SequenceFileAsJSONInputBatchFormat
| Python | apache-2.0 | usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction,usc-isi-i2/landmark-extraction |
4c00345ec0a66363d3b9d7e423e2fcd19aa2a307 | ditto/core/context_processors.py | ditto/core/context_processors.py | from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled(),
'DITTO_FLICKR_USE_LOCAL_MEDIA':
app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA,
}
| from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled()
}
| Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor | Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor
| Python | mit | philgyford/django-ditto,philgyford/django-ditto,philgyford/django-ditto |
760a952851664232b11ad95acb8884dda59308a4 | sysrev/widgets.py | sysrev/widgets.py | from django.forms import widgets
from django.utils.safestring import *
# See static/js/querywidget.js
class QueryWidget(widgets.Textarea):
def __init__(self, attrs=None):
default_attrs = {'class': "queryWidget"}
if attrs:
default_attrs.update(attrs)
super(QueryWidget, self).__in... | from django.forms import widgets
from django.utils.safestring import *
# See static/js/querywidget.js
class QueryWidget(widgets.Textarea):
def __init__(self, attrs=None):
default_attrs = {'class': "queryWidget"}
if attrs:
default_attrs.update(attrs)
super(QueryWidget, self).__in... | Add <noscript> message to indicate that only the advanced query editor is available. | Add <noscript> message to indicate that only the advanced query editor is available.
| Python | mit | iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview |
7f41a424143334a8c8e1ccbd768c911f8e6ffb31 | transform_quandl_xjpx_archive.py | transform_quandl_xjpx_archive.py | # -*- coding: utf-8 -*-
"""
```
# 1.
$ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \
/tmp/quandl-xjpx/
# 2.
$ python transform_quandl_xjpx_archive.py
```
"""
import tarfile
with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f:
f.add('/tmp/quandl-xjpx')
| # -*- coding: utf-8 -*-
"""
```
# 1.
$ cp -r ~/.zipline/data/quandl-xjpx/2016-12-28T08\;14\;58.046694 \
/tmp/quandl-xjpx/
# 2.
$ python transform_quandl_xjpx_archive.py
```
"""
import tarfile
import os
with tarfile.open('/tmp/quandl-xjpx.tar', 'w') as f:
os.chdir('/tmp/quandl-xjpx')
for fn in os.list... | Fix bug on transform quandl archive | Fix bug on transform quandl archive
| Python | apache-2.0 | magne-max/zipline-ja,magne-max/zipline-ja |
812f1fec796e4c7d86731d5e3e91293fb1b0296b | scripts/europeana-meta.py | scripts/europeana-meta.py | from __future__ import print_function
import sys, os
from re import sub
import zipfile, json
# from pyspark import SparkContext
# from pyspark.sql import SQLContext
# from pyspark.sql import Row
# from pyspark.sql.types import StringType
def getSeries(fname):
with zipfile.ZipFile(fname, 'r') as zf:
names... | from __future__ import print_function
import sys, os
from re import sub
import zipfile, json
# from pyspark import SparkContext
# from pyspark.sql import SQLContext
# from pyspark.sql import Row
# from pyspark.sql.types import StringType
def getSeries(fname):
with zipfile.ZipFile(fname, 'r') as zf:
names... | Use file path as Europeana series name. | Use file path as Europeana series name.
| Python | apache-2.0 | ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim |
0ec5aeca33676172f458ec6761282157dcb19635 | tests/test_set_pref.py | tests/test_set_pref.py | # tests.test_set_pref
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)... | # tests.test_set_pref
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)... | Add test for setting preferred search engine | Add test for setting preferred search engine
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest |
9d65dbb84126a26e8e6dfe31179087f75134f564 | tests/integration/auth_tests.py | tests/integration/auth_tests.py | from django.test import TestCase
from django.contrib.auth import authenticate, get_user_model
from django.core import mail
User = get_user_model()
class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase):
def test_authenticates_when_passwords_are_different(self):
# Create two users with the same email ... | from django.test import TestCase
from django.contrib.auth import authenticate
from django.core import mail
from oscar.core.compat import get_user_model
User = get_user_model()
class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase):
def test_authenticates_when_passwords_are_different(self):
# Create ... | Load User model from compatibility layer | Load User model from compatibility layer
| Python | bsd-3-clause | jinnykoo/wuyisj.com,josesanch/django-oscar,itbabu/django-oscar,kapt/django-oscar,Jannes123/django-oscar,nickpack/django-oscar,bnprk/django-oscar,marcoantoniooliveira/labweb,lijoantony/django-oscar,ahmetdaglarbas/e-commerce,marcoantoniooliveira/labweb,itbabu/django-oscar,manevant/django-oscar,bschuon/django-oscar,faratr... |
7ab7eae4254f8ee62b3a8620982c72b07c2299e4 | tests/__init__.py | tests/__init__.py | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args, **kwargs):
sleep = kwargs.pop('sleep', DEFAULT_SLEEP)
expected_return = kwargs.pop('expected_return', None)
call = kwargs.pop('call', True)
def func():
time.sleep(sleep)
... | import threading
import time
DEFAULT_SLEEP = 0.01
class CustomError(Exception):
pass
def defer(callback, *args,
sleep=DEFAULT_SLEEP, expected_return=None, call=True,
**kwargs):
def func():
time.sleep(sleep)
if call:
assert expected_return == callback(*args, ... | Use named kwargs after *args | Use named kwargs after *args
Another Python 3 thing.
| Python | mit | FichteFoll/resumeback |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.