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 |
|---|---|---|---|---|---|---|---|---|---|
eec8ddc6beb08a02577831b6f64b0455e5c1ef05 | local.py | local.py | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
... | import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.registe... | Disable icon temporarily and adjust the debug print statements | Disable icon temporarily and adjust the debug print statements | Python | mit | kfdm/gntp |
0d3507d5eb9801b38c66fb03804e15b089fb2233 | tests/cdek_test.py | tests/cdek_test.py | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unr... | # coding: utf-8
from __future__ import unicode_literals, print_function
import datetime
import unittest
import mock
from cdek import api, exceptions
@mock.patch('cdek.api.urlopen')
class CdekApiTest(unittest.TestCase):
def setUp(self):
self.reg_user = api.CdekCalc('123456', '123456')
self.unr... | Fix date for generate secure_key | Fix date for generate secure_key
| Python | mit | xtelaur/python-cdek,xtelaur/python-cdek |
00fd8b13e36c5e7020b7769f6dcd1afecfb79fb3 | examples/source.py | examples/source.py | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | Fix logic around lost connection. | Fix logic around lost connection.
| Python | apache-2.0 | Martiusweb/asyncio,manipopopo/asyncio,jashandeep-sohi/asyncio,manipopopo/asyncio,ajdavis/asyncio,1st1/asyncio,gvanrossum/asyncio,manipopopo/asyncio,1st1/asyncio,fallen/asyncio,vxgmichel/asyncio,haypo/trollius,gvanrossum/asyncio,vxgmichel/asyncio,fallen/asyncio,ajdavis/asyncio,gsb-eng/asyncio,jashandeep-sohi/asyncio,Mar... |
991a376736e50ddd6622947d713f61cebb565c8d | server/server/urls.py | server/server/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_inventory.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^django/inventory/$', 'inventory.views.index'),
u... | Add some CRUD URLs to Django. | Add some CRUD URLs to Django.
| Python | agpl-3.0 | TomDataworks/angular-inventory,TomDataworks/angular-inventory |
4823b42b23580e0a294c1e4ddb3b5b62abf9c7bc | sf/mmck/parameters.py | sf/mmck/parameters.py | from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label
class Integer(Parameter):
def... | from collections import OrderedDict
from sf.lib.orderedattrdict import OrderedAttrDict
class Parameters(OrderedAttrDict):
pass
class ParameterValues(OrderedAttrDict):
pass
class Parameter(object):
def __init__(self, default=None, label=None):
self.default = default
self.label = label... | Add a key/value pairs parameter type | Add a key/value pairs parameter type
| Python | mit | metrasynth/solar-flares |
ab83da7b6152dfdc50cf40fa328f3c3d24c13861 | emailmgr/urls.py | emailmgr/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
... | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
email_send_activation, email_activate, email_make_primary
#add an email to a User account
urlpatterns = patterns('',
url(
r'^emai... | Fix import for django 1.6 | Fix import for django 1.6 | Python | bsd-3-clause | un33k/django-emailmgr,un33k/django-emailmgr |
aa15e9195c6e16ec000338e71051f64a692642e0 | nightreads/user_manager/forms.py | nightreads/user_manager/forms.py | from django.contrib.auth.models import User
from django import forms
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags'].split(',')
return [t.strip().lower() for t in tags]
class UnsubscribeForm(form... | from django.contrib.auth.models import User
from django.core.signing import BadSignature, SignatureExpired
from django import forms
from . import user_service
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags... | Update `ConfirmEmailForm` to use `user_service.validate_key` | Update `ConfirmEmailForm` to use `user_service.validate_key`
| Python | mit | avinassh/nightreads,avinassh/nightreads |
8f226fffd17b9d89d916ad4a1c42d43afc1f0634 | minitrue/utils.py | minitrue/utils.py | """
Generically useful utilities.
"""
import urlparse
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self.kw = {}
def kwarg(self, kwargName=None):
"""
... | """
Generically useful utilities.
"""
import urlparse
from twisted.internet import defer
from twisted.python import log
try: # pragma: no cover
from cStringIO import StringIO; StringIO
except ImportError:
from StringIO import StringIO; StringIO
class Constructor(object):
def __init__(self):
self... | Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution. | Support for deferred-returning manglers for Combined. Added OrderedCombined that guarantees order of execution.
| Python | isc | lvh/minitrue |
aace7956091f10af19dfe9eaaf12aef8b0f9f579 | new_validity.py | new_validity.py | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
os.system('ltahdr -i'+ argv[1]+ '> lta_fi... | import pandas as pd
import numpy as np
import operator
from sys import argv
import os
def extract( file_name ):
with open(file_name) as f:
for i,line in enumerate(f,1):
if "SCN" in line:
return i
def main(lta_name):
os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
di... | Insert main body of code into function | Insert main body of code into function
| Python | mit | NCRA-TIFR/gadpu,NCRA-TIFR/gadpu |
7cd69c1a4b8cc221bbbb40d5b2a1a53a835b11e9 | nhs/raw/urls.py | nhs/raw/urls.py | """
URLs for the Raw data dumps.
"""
from django.conf.urls.defaults import patterns, url
from nhs.raw.views import Ratio, Drug
urlpatterns = patterns(
'',
url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$',
Ratio.as_view(), name='rawcompare'),
url(r'/drug/percapitamap/ccg/(?P... | """
URLs for the Raw data dumps.
"""
from django.conf.urls.defaults import patterns, url
from nhs.raw.views import Ratio, Drug
urlpatterns = patterns(
'',
url(r'/ratio/(?P<bucket1>[0-9A-Z]+)/(?P<bucket2>[0-9A-Z]+)/ratio.zip$',
Ratio.as_view(), name='rawcompare'),
url(r'/drug/(?P<bnf_code>[0-9A-Z... | Update URls for raw download. | Update URls for raw download.
| Python | agpl-3.0 | openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing |
3f1f666606a0b092c796fab27a67b2dde5a33cb9 | nipype/setup.py | nipype/setup.py | def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('nipype', parent_package, top_path)
# List all packages to be loaded here
config.add_subpackage('interfaces')
config.add_subpackage('pipeline')
config.add_subpackage('u... | def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('nipype', parent_package, top_path)
# List all packages to be loaded here
config.add_subpackage('algorithms')
config.add_subpackage('interfaces')
config.add_subpackage(... | Add missing packages for install: algorithms, testing. | Add missing packages for install: algorithms, testing.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@527 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| Python | bsd-3-clause | christianbrodbeck/nipype,arokem/nipype,carlohamalainen/nipype,pearsonlab/nipype,sgiavasis/nipype,gerddie/nipype,blakedewey/nipype,FredLoney/nipype,fprados/nipype,grlee77/nipype,sgiavasis/nipype,JohnGriffiths/nipype,iglpdc/nipype,gerddie/nipype,iglpdc/nipype,dmordom/nipype,arokem/nipype,FCP-INDI/nipype,mick-d/nipype_sou... |
d54854c11094e0ca8598e59de0bc0795dc8143c9 | lib/recordclass/__init__.py | lib/recordclass/__init__.py | # The MIT License (MIT)
#
# Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | # The MIT License (MIT)
#
# Copyright (c) <2011-2014> <Shibzukhov Zaur, szport at gmail dot com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | Add import of RecordClass to init | Add import of RecordClass to init
--HG--
branch : typing
| Python | mit | vovanbo/trafaretrecord,vovanbo/trafaretrecord |
7c9dac667c47d41c2da52ff993967f27016f6ba9 | profile_benchmark.py | profile_benchmark.py | # Profile the basic test execution
from pyresttest import resttest
from pyresttest.benchmarks import Benchmark
import cProfile
test = Benchmark()
test.warmup_runs = 0
test.benchmark_runs = 1000
test.raw_metrics = set()
test.metrics = {'total_time'}
test.aggregated_metrics = {'total_time': ['total','mean']}
test.url =... | # Profile the basic test execution
from pyresttest import resttest
from pyresttest.benchmarks import Benchmark
from pyresttest.binding import Context
from pyresttest.contenthandling import ContentHandler
from pyresttest.generators import factory_generate_ids
import cProfile
test = Benchmark()
test.warmup_runs = 0
te... | Add profiler benchmark for generator functionality | Add profiler benchmark for generator functionality
| Python | apache-2.0 | MorrisJobke/pyresttest,alazaro/pyresttest,suvarnaraju/pyresttest,sunyanhui/pyresttest,wirewit/pyresttest,holdenweb/pyresttest,suvarnaraju/pyresttest,janusnic/pyresttest,MorrisJobke/pyresttest,alazaro/pyresttest,wirewit/pyresttest,sunyanhui/pyresttest,svanoort/pyresttest,netjunki/pyresttest,janusnic/pyresttest,TimYi/pyr... |
bc65fb47a777c0ef501bb492d8003d01ce22b233 | libpam/utc-time/utc-time.py | libpam/utc-time/utc-time.py | #!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
| #!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
| Disable caching of stale time stamp information. | Disable caching of stale time stamp information.
| Python | apache-2.0 | fargly/google-authenticator,google/google-authenticator,fargly/google-authenticator,fargly/google-authenticator,google/google-authenticator |
5a808dfa9ae8661382fbc00641562f2024931b57 | test/test_packages.py | test/test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("handbrake"),
("handbrake-cli"),
("haveged"),
("htop... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-ce"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("handbrake"),
("handbrake-cli"),
("haveged"),
("htop... | Update for vim plugin changes | Update for vim plugin changes
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build |
51413c8cb63bfdc4fba3f0a144459b0082ce2bf2 | tests/basics/list1.py | tests/basics/list1.py | # basic list functionality
x = [1, 2, 3 * 4]
print(x)
x[0] = 4
print(x)
x[1] += -4
print(x)
x.append(5)
print(x)
f = x.append
f(4)
print(x)
x.extend([100, 200])
print(x)
x += [2, 1]
print(x)
print(x[1:])
print(x[:-1])
print(x[2:3])
| # basic list functionality
x = [1, 2, 3 * 4]
print(x)
x[0] = 4
print(x)
x[1] += -4
print(x)
x.append(5)
print(x)
f = x.append
f(4)
print(x)
x.extend([100, 200])
print(x)
x += [2, 1]
print(x)
print(x[1:])
print(x[:-1])
print(x[2:3])
try:
print(x[1.0])
except TypeError:
print("TypeError")
| Add test for implicit float to int conversion (not allowed!) | tests: Add test for implicit float to int conversion (not allowed!)
| Python | mit | pramasoul/micropython,dmazzella/micropython,HenrikSolver/micropython,turbinenreiter/micropython,stonegithubs/micropython,bvernoux/micropython,ernesto-g/micropython,ernesto-g/micropython,blazewicz/micropython,cloudformdesign/micropython,puuu/micropython,slzatz/micropython,omtinez/micropython,SHA2017-badge/micropython-es... |
ec7bbe8ac8715ea22142680f0d880a7d0b71c687 | paws/request.py | paws/request.py | from urlparse import parse_qs
from utils import cached_property, MultiDict
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@property
def query(self):
... | from Cookie import SimpleCookie
from urlparse import parse_qs
from utils import MultiDict, cached_property
class Request(object):
def __init__(self, event, context):
self.event = event
self.context = context
@property
def method(self):
return self.event['httpMethod']
@proper... | Add cookies property to Request | Add cookies property to Request
| Python | bsd-3-clause | funkybob/paws |
423d40b8162ff2763346ddf0a115760c6efb4222 | tests/test_classes.py | tests/test_classes.py | from thinglang import run
def test_class_integration():
assert run("""
thing Person
has text name
has number age
created with name
self.name = name
self.age = 0
does grow_up
self.age = self.age + 1
does say_hello with excitement_level
Output.write("Hello from... | from unittest.mock import patch
import io
from thinglang import run
def test_class_integration():
with patch('sys.stdin', io.StringIO('yotam\n19\n5')):
assert run("""
thing Person
has text name
has number age
setup with name
self.name = name
does say_hello with repeat_count
... | Update class integration test to use new syntax and output assertion | Update class integration test to use new syntax and output assertion
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
d825a94007c9ef2d464528572ea99aa2636ea4fa | tests/test_convert.py | tests/test_convert.py | import pytest # type: ignore
from ppb_vector import Vector2
from utils import vector_likes
@pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore
def test_convert_subclass(vector_like):
class V(Vector2): pass
# test_binop_vectorlike already checks the output v... | import pytest # type: ignore
from ppb_vector import Vector2
from utils import vector_likes
@pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore
def test_convert_subclass(vector_like):
class V(Vector2): pass
vector = V.convert(vector_like)
assert isinstan... | Test converted vector equals original vector-like | tests/convert: Test converted vector equals original vector-like
The comment mentioned that property was tested by `test_binop_vectorlike`, but
Vector2.convert isn't a binary operator, so it isn't exercised by that test.
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
f4bc89564828011d2306e16cdc84e053beb7c1d6 | tests/test_logging.py | tests/test_logging.py | from .fixtures import elasticsearch
import pytest
image_flavor = pytest.config.getoption('--image-flavor')
def test_elasticsearch_logs_are_in_docker_logs(elasticsearch):
elasticsearch.assert_in_docker_log('o.e.n.Node')
# eg. elasticsearch1 | [2017-07-04T00:54:22,604][INFO ][o.e.n.Node ] [docker-test-node-1]... | from .fixtures import elasticsearch
import pytest
image_flavor = pytest.config.getoption('--image-flavor')
def test_elasticsearch_logs_are_in_docker_logs(elasticsearch):
elasticsearch.assert_in_docker_log('o.e.n.Node')
# eg. elasticsearch1 | [2017-07-04T00:54:22,604][INFO ][o.e.n.Node ] [docker-test-node-1]... | Remove test that sporadically gives false negatives | Remove test that sporadically gives false negatives
Nothing worse than an unreliable test; remove this test as there can be
errors in the logs that do not necessarily correspond to a broken
image.
Relates #119 | Python | apache-2.0 | jarpy/elasticsearch-docker,jarpy/elasticsearch-docker |
f0157d9523f09d6a1392685f7b13cfac9f6bf6c0 | dad/worker/__init__.py | dad/worker/__init__.py | import click
from flask import Flask, current_app
app = Flask(__name__)
app.config.from_object('dad.worker.settings')
import dad.worker.server # noqa
@click.command()
@click.option('--port', '-p', default=6010)
def run(port):
with app.app_context():
dad.worker.server.register(current_app)
app.run(p... | import os
import yaml
import click
from flask import Flask, current_app
app = Flask(__name__)
app.config.from_object('dad.worker.settings')
if os.environ.get('APP_SETTINGS_YAML'):
config = yaml.safe_load(open(os.environ['APP_SETTINGS_YAML']))
app.config.update(config)
import dad.worker.server # noqa
@cl... | Allow overriding the config with app settings yaml in the worker process. | Allow overriding the config with app settings yaml in the worker process.
| Python | bsd-3-clause | ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd |
26b1b92d23eddd3496aa77a97d93bc7745047f24 | dashboard/run_tests.py | dashboard/run_tests.py | #!/usr/bin/python
"""Runs the unit test suite for perf dashboard."""
import argparse
import dev_appserver
import os
import sys
import unittest
_DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__))
_DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard')
def _GetTests(args):
loader = unittest.TestLoader()
... | #!/usr/bin/python
"""Runs the unit test suite for perf dashboard."""
import argparse
import dev_appserver
import logging
import os
import sys
import unittest
_DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__))
_DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard')
def _GetTests(args):
loader = unittes... | Stop printing logs while running dashboard tests in catapult. | Stop printing logs while running dashboard tests in catapult.
Some of the dashboard tests invoke functions which log errors,
but these are not interesting or indicative of actual errors when
running the test.
By setting the logging level in run_tests.py, this makes it so
no log messages are printed when run_tests.py ... | Python | bsd-3-clause | catapult-project/catapult,zeptonaut/catapult,catapult-project/catapult-csm,modulexcite/catapult,catapult-project/catapult-csm,danbeam/catapult,sahiljain/catapult,dstockwell/catapult,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,sahiljain/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult,catapult-pro... |
da85cfae848df4cee5ccf2cbbbc370848ea172a7 | src/txkube/_memory.py | src/txkube/_memory.py | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
An in-memory implementation of the Kubernetes client interface.
"""
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . impo... | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
An in-memory implementation of the Kubernetes client interface.
"""
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . impo... | Use a non-routeable address for this URL. | Use a non-routeable address for this URL.
We do not anticipate ever sending any traffic to this since this is the
in-memory-only implementation.
| Python | mit | LeastAuthority/txkube |
d0bd57cbdf8ba451e12f7e6b2574cd77132f0f3b | kboard/board/forms.py | kboard/board/forms.py | from django import forms
from django_summernote.widgets import SummernoteWidget
from django.core.exceptions import NON_FIELD_ERRORS
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'content', 'file')
widgets = {
'title': for... | from django import forms
from django.forms.utils import ErrorList
from django_summernote.widgets import SummernoteWidget
from .models import Post
EMPTY_TITLE_ERROR = "제목을 입력하세요"
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(self):
if not self:
... | Customize the error list format in modelform | Customize the error list format in modelform
| Python | mit | cjh5414/kboard,darjeeling/k-board,cjh5414/kboard,hyesun03/k-board,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board,kboard/kboard,hyesun03/k-board |
2f29db7bd30b3db40f6577a4718623f6cd97a5cf | search/sorting.py | search/sorting.py |
def sort_by_property(prop):
def _sort_by_property(items):
return sorted(items,
key=lambda item: getattr(item, prop),
reverse=True)
return _sort_by_property
sort_by_popularity = sort_by_property('popularity')
|
def sort_by_property(prop, reverse=False):
def _sort_by_property(items):
return sorted(items,
key=lambda item: getattr(item, prop),
reverse=reverse)
return _sort_by_property
sort_by_popularity = sort_by_property('popularity', reverse=True)
| Make it possible to control reverse | Make it possible to control reverse | Python | mit | vanng822/geosearch,vanng822/geosearch,vanng822/geosearch |
9797c47fea8f5f690ed3989142b0f7e508e13fa0 | pskb_website/cache.py | pskb_website/cache.py | """
Caching utilities
"""
import urlparse
from . import app
url = None
redis_obj = None
try:
import redis
except ImportError:
app.logger.warning('No caching available, missing redis module')
else:
try:
url = urlparse.urlparse(app.config['REDISCLOUD_URL'])
except KeyError:
app.logger.... | """
Caching utilities
"""
import functools
import urlparse
from . import app
url = None
redis_obj = None
try:
import redis
except ImportError:
app.logger.warning('No caching available, missing redis module')
else:
try:
url = urlparse.urlparse(app.config['REDISCLOUD_URL'])
except KeyError:
... | Add small decorator to check for valid redis instance | Add small decorator to check for valid redis instance
| Python | agpl-3.0 | paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms |
fc8c7a62b737e4f291250c4d45bf34ae944ef6da | sweettooth/upload/urls.py | sweettooth/upload/urls.py |
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_e... |
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'new-version/(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'vi... | Adjust URL for new version upload, was competing with 'edit-data'. | Adjust URL for new version upload, was competing with 'edit-data'.
| Python | agpl-3.0 | magcius/sweettooth,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,GNOME/extensions-web |
ada3e5dca1e777187a0933bd7b83fcb38c4faf66 | nightreads/user_manager/forms.py | nightreads/user_manager/forms.py | from django import forms
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean(self):
tags = self.cleaned_data['tags'].split(',')
self.cleaned_data['tags'] = [t.strip().lower() for t in tags]
return self.cleaned_data
class UnsubscribeForm... | from django import forms
class SubscribeForm(forms.Form):
email = forms.EmailField()
tags = forms.CharField()
def clean_tags(self):
tags = self.cleaned_data['tags'].split(',')
return [t.strip().lower() for t in tags]
class UnsubscribeForm(forms.Form):
email = forms.EmailField()
| Use `clean_tags` instead of `clean` | Use `clean_tags` instead of `clean`
| Python | mit | avinassh/nightreads,avinassh/nightreads |
d4de2b2ff0cb7ba6ad4eed7fe2c0b70801e3c057 | juriscraper/opinions/united_states/state/massappct128.py | juriscraper/opinions/united_states/state/massappct128.py | """
Scraper for Massachusetts Appeals Court
CourtID: massapp
Court Short Name: MS
Author: William Palin
Court Contact: SJCReporter@sjc.state.ma.us (617) 557-1030
Reviewer:
Date: 2020-01-17
"""
from juriscraper.opinions.united_states.state import mass
class Site(mass.Site):
def __init__(self, *args, **kwargs):
... | """
Scraper for Massachusetts Appeals Court
CourtID: massapp
Court Short Name: MS
Author: William Palin
Court Contact: SJCReporter@sjc.state.ma.us (617) 557-1030
Reviewer:
Date: 2020-01-17
"""
from juriscraper.opinions.united_states.state import mass
class Site(mass.Site):
def __init__(self, *args, **kwargs):
... | Change url to 128archive.com website. | fix(mass128): Change url to 128archive.com website.
| Python | bsd-2-clause | freelawproject/juriscraper,freelawproject/juriscraper |
00c5f9b382fd1b060a973a3a3a1db33c280f2dd7 | respite/middleware.py | respite/middleware.py | import re
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if request.META.has_key('HTTP_X_HTTP_METHOD_OVER... | import re
from django.http import QueryDict
class HttpMethodOverrideMiddleware:
"""
Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
header or a '_method' HTTP POST parameter.
"""
def process_request(self, request):
if 'HTTP_X_HTTP_METHOD_OVERRIDE' in request.META... | Refactor to use 'in' instead of 'has_key' | Refactor to use 'in' instead of 'has_key'
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite |
b5db068a5545880d5d66d0be3ce88ccc393adcb0 | h5py/_hl/__init__.py | h5py/_hl/__init__.py | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
from __future__ import absolute_import
| # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
This subpackage implements the high-level in... | Fix lint issues in _hl subpackage | Fix lint issues in _hl subpackage
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py |
3f2f8e1cf57c44b589b053902e2945cd2486414d | src/dashboard/src/components/accounts/backends.py | src/dashboard/src/components/accounts/backends.py | import re
from django.conf import settings
from django.dispatch import receiver
from django_auth_ldap.backend import LDAPBackend, populate_user
from shibboleth.backends import ShibbolethRemoteUserBackend
from components.helpers import generate_api_key
class CustomShibbolethRemoteUserBackend(ShibbolethRemoteUserBac... | import re
from django.conf import settings
from django.dispatch import receiver
from django_auth_ldap.backend import LDAPBackend, populate_user
from shibboleth.backends import ShibbolethRemoteUserBackend
from components.helpers import generate_api_key
class CustomShibbolethRemoteUserBackend(ShibbolethRemoteUserBac... | Fix API key generation with LDAP | Fix API key generation with LDAP
* Only generate on first login, not every login
* Handle case where user has not yet been saved
| Python | agpl-3.0 | artefactual/archivematica,artefactual/archivematica,artefactual/archivematica,artefactual/archivematica |
57a5042b8a01c16937206678924f6fe9c5273cc9 | example/__init__.py | example/__init__.py | from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import *
nav = Nav()
class UserGreeting(Text):
def __init__(self):
pass
@property
def text(self):
return 'Hello, {}'.format('bob')
# registers the "top" menubar
nav.register_element('top', Navbar... | from flask import Flask, render_template
from flask_nav import Nav
from flask_nav.elements import *
nav = Nav()
# registers the "top" menubar
nav.register_element('top', Navbar(
View('Widgits, Inc.', 'index'),
View('Our Mission', 'about'),
Subgroup(
'Products',
View('Wg240-Series', 'produ... | Remove accidentally added UserGreeting from example app. | Remove accidentally added UserGreeting from example app.
| Python | mit | mbr/flask-nav,mbr/flask-nav |
644252445b6c9b2729e73f97ba20e96dcfadb73b | tests/test_parser.py | tests/test_parser.py | from gogoutils.parser import Parser
def test_parser_url():
"""Test parsing of url"""
urls = [
'http://github.com/gogoair/test',
'https://github.com/gogoair/test',
'http://github.com/gogoair/test.git',
'https://github.com/gogoair/test.git',
'https://username@testgithub.... | from gogoutils.parser import Parser
def test_parser_url():
"""Test parsing of url"""
urls = [
'http://github.com/gogoair/test',
'https://github.com/gogoair/test',
'http://github.com/gogoair/test.git',
'https://github.com/gogoair/test.git',
'https://username@testgithub.... | Add additional git url formats | Add additional git url formats
| Python | apache-2.0 | gogoair/gogo-utils |
96dc9e590b81926fddb83a85a1352039c10c1509 | links/mlp.py | links/mlp.py | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chain... | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chain... | Support configuration with no hidden-layer | Support configuration with no hidden-layer
| Python | mit | toslunar/chainerrl,toslunar/chainerrl |
5a88126b53bbd47a4c8899b50bdbf0d913183bd5 | norm/test/test_porcelain.py | norm/test/test_porcelain.py | from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
... | from twisted.trial.unittest import TestCase
from twisted.internet import defer
import os
from norm.porcelain import makePool
postgres_url = os.environ.get('NORM_POSTGRESQL_URI', None)
skip_postgres = ('You must define NORM_POSTGRESQL_URI in order to run this '
'postgres test')
if postgres_url:
... | Fix postgres porcelain test and add sqlite one | Fix postgres porcelain test and add sqlite one
| Python | mit | iffy/norm,iffy/norm |
7d7043560f26c31346472b6452e8b191729c54a3 | offsite_storage/settings.py | offsite_storage/settings.py | from django.conf import settings
AWS_ACCESS_KEY_ID = getattr(settings, 'AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = getattr(settings, 'AWS_SECRET_ACCESS_KEY')
AWS_STATIC_BUCKET_NAME = getattr(settings, 'AWS_STATIC_BUCKET_NAME')
AWS_MEDIA_ACCESS_KEY_ID = getattr(
settings, 'AWS_MEDIA_ACCESS_KEY_ID', AWS_ACCESS_KE... | from django.conf import settings
AWS_ACCESS_KEY_ID = getattr(settings, 'AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = getattr(settings, 'AWS_SECRET_ACCESS_KEY')
AWS_STATIC_BUCKET_NAME = getattr(settings, 'AWS_STATIC_BUCKET_NAME')
AWS_MEDIA_ACCESS_KEY_ID = getattr(
settings, 'AWS_MEDIA_ACCESS_KEY_ID', AWS_ACCESS_KE... | Use custom endpoint url in AWS_HOST_URL variable | Use custom endpoint url in AWS_HOST_URL variable
| Python | bsd-3-clause | mirumee/django-offsite-storage |
1daf5825580d31e3f2825b5b5edfaa2aed8146fe | mopidy/internal/gi.py | mopidy/internal/gi.py | from __future__ import absolute_import, unicode_literals
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python p... | from __future__ import absolute_import, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObje... | Check GStreamer version on start | gst1: Check GStreamer version on start
If GStreamer is too old, it fails like this:
$ mopidy
ERROR: Mopidy requires GStreamer >= 1.2, but found GStreamer 1.0.0.
| Python | apache-2.0 | kingosticks/mopidy,jodal/mopidy,mokieyue/mopidy,tkem/mopidy,kingosticks/mopidy,tkem/mopidy,mokieyue/mopidy,adamcik/mopidy,adamcik/mopidy,jodal/mopidy,mopidy/mopidy,vrs01/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,tkem/mopidy,jodal/mopidy,jcass77/mopidy,mopidy/mopidy,adamcik/mopidy,tkem/mopidy,mokieyue/mopidy,jcass77/mopidy... |
b65c95ca400f91648a53553f51979f5ceb7a0d94 | test/test-unrealcv.py | test/test-unrealcv.py | # TODO: Test robustness, test speed
import unittest, time, sys, argparse, threading
sys.path.append('./test/ipc')
from common_conf import *
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--trav... | '''
Run python test.py to test unrealcv
'''
import unittest, time, sys, argparse, threading
from common_conf import *
def run_full_test():
pass
def run_travis_test():
sys.path.append('./test/ipc')
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
load = unittest.Tes... | Clean up the portal of test script. | Clean up the portal of test script.
| Python | mit | unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv |
26250bf43e659c03576a4d7e4d986b622a18bb48 | swifpy/dictionary.py | swifpy/dictionary.py | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getite... | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getite... | Implement `keys` and `values` of `Dictionary` | Implement `keys` and `values` of `Dictionary`
| Python | mit | koher/swifpy |
5b18bcfa03876dbfda75b14bf8239f01c1f70ec2 | fftresize/fftresize.py | fftresize/fftresize.py | #!/usr/bin/env python2
'''Resize images using the FFT
FFTresize resizes images using zero-padding in the frequency domain.
'''
from fftinterp import interp2
import imutils
from numpy import zeros as _zeros
__author__ = 'Mansour Moufid'
__copyright__ = 'Copyright 2013, Mansour Moufid'
__license__ = 'ISC'
__version... | #!/usr/bin/env python2
'''Resize images using the FFT
FFTresize resizes images using zero-padding in the frequency domain.
'''
from numpy import zeros as _zeros
from . import fftinterp
from . import imutils
__author__ = 'Mansour Moufid'
__copyright__ = 'Copyright 2013, Mansour Moufid'
__license__ = 'ISC'
__versi... | Use relative imports in the package. | Use relative imports in the package.
| Python | isc | eliteraspberries/fftresize |
8d0325e28a1836a8afdfc33916d36a3e259ad131 | fil_finder/__init__.py | fil_finder/__init__.py | # Licensed under an MIT open source license - see LICENSE
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
from .width_profiles import filament_profile
| # Licensed under an MIT open source license - see LICENSE
__version__ = "1.2.2"
from .analysis import Analysis
from .filfind_class import fil_finder_2D
| Revert importing from the top | Revert importing from the top
| Python | mit | e-koch/FilFinder |
77c245240fcccf1c7c6f3251168801de45182b8d | klaxer/__init__.py | klaxer/__init__.py | """Entry point for all things Klaxer"""
__author__ = 'Aru Sahni, Kevin Dwyer, Justin Shelton, Dylan Bernard, Will Schneider, et al'
__version__ = '0.0.1'
__license__ = 'MIT'
APP_NAME = 'Klaxer'
| """Entry point for all things Klaxer"""
__author__ = 'Aru Sahni, Kevin Dwyer, Justin Shelton, Dylan Bernard, et al'
__version__ = '0.0.1'
__license__ = 'MIT'
APP_NAME = 'Klaxer'
| Adjust author list to only include contributors. | Adjust author list to only include contributors.
| Python | mit | klaxer/klaxer |
feddcfd9153da81777c25571f35ee3c97e655c64 | generate_migrations.py | generate_migrations.py | #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests t... | #!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)
# Load Django-related settings; necessary for tests t... | Refactor migrations after generating to ensure custom user model compatibility. | Refactor migrations after generating to ensure custom user model compatibility.
| Python | mit | vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,vden/djoauth2-ng,seler/djoauth2,Locu/djoauth2 |
93c6e5d39b1779f0eca9b28f5111d7c402ebc1ba | geotagging/views.py | geotagging/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from geotagging.models import Point
def add_edit_point(request, content_type_id, object_id,
template=Non... | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from geotagging.models import Point
def add_edit_point(request, cont... | Fix a bug when you try to add a geo tag to an object that does not have already one | Fix a bug when you try to add a geo tag to an object that does not have already one | Python | bsd-3-clause | lincolnloop/django-geotagging,lincolnloop/django-geotagging |
c485ac39ede0bfbcc6b68fd10ed35ff692124c6d | server/api/auth.py | server/api/auth.py | """All routes regarding authentication."""
from datetime import datetime
from sqlalchemy import or_
from webargs.flaskparser import use_args
from server import user_bp
from server.extensions import db
from server.models import User
from server.responses import bad_request, ok
from server.validation.user import login_... | """All routes regarding authentication."""
from datetime import datetime
from sqlalchemy import or_
from webargs.flaskparser import use_args
from server import user_bp
from server.extensions import db
from server.models import User
from server.responses import bad_request, ok
from server.validation.user import login_... | Send user id and token | Send user id and token
| Python | mit | Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival |
84816dda37d071e521f65449ee59c992b5e302bc | megaprojects/blog/models.py | megaprojects/blog/models.py | from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from core.models import AuthorModel, ImageModel
from .managers import PostManager, ImageManager
import util
STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')]
class Post(AuthorModel)... | from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from core.models import AuthorModel, ImageModel
from .managers import PostManager, ImageManager
import util
STATUS_CHOICES = [('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn')]
class Post(AuthorModel)... | Add property for Post thumbnail | Add property for Post thumbnail
| Python | apache-2.0 | megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke |
3350460fdb4f0360b9251f30340ed9d1b6f97839 | shibboleth/urls.py | shibboleth/urls.py | from distutils.version import StrictVersion
import django
if StrictVersion(django.get_version()) >= StrictVersion('1.6'):
from django.conf.urls import patterns, url, include
else:
from django.conf.urls.defaults import *
from views import ShibbolethView, ShibbolethLogoutView, ShibbolethLoginView
urlpatt... | from distutils.version import StrictVersion
import django
if StrictVersion(django.get_version()) < StrictVersion('1.4'):
from django.conf.urls.defaults import *
else:
from django.conf.urls import patterns, url
from views import ShibbolethView, ShibbolethLogoutView, ShibbolethLoginView
urlpatterns = p... | Change version check. Remove include import. | Change version check. Remove include import.
| Python | mit | trevoriancox/django-shibboleth-remoteuser,CloudComputingCourse/django-shibboleth-remoteuser,KonstantinSchubert/django-shibboleth-adapter,ties/django-shibboleth-remoteuser,denisvlr/django-shibboleth-remoteuser,ties/django-shibboleth-remoteuser,uchicago-library/django-shibboleth-remoteuser,trevoriancox/django-shibboleth-... |
baf3ef0ddcb7b59973750443f4c0a3732dd0f12a | spacy/cli/__init__.py | spacy/cli/__init__.py | from .download import download
from .info import info
from .link import link
from .package import package
from .train import train, train_config
from .model import model
from .convert import convert
| from .download import download
from .info import info
from .link import link
from .package import package
from .train import train
from .model import model
from .convert import convert
| Remove import of removed train_config script | Remove import of removed train_config script
| Python | mit | spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/... |
cf77d5b49416c33b05955a66450adda289a342d0 | main.py | main.py | from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(description="... | from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(description="... | Implement dynamic username and collection type | Implement dynamic username and collection type
| Python | apache-2.0 | AmosGarner/PyInventory |
6eaa58149bae1c5462fc79255656321145a4b45f | hashbrown/models.py | hashbrown/models.py | from django.db import models
from .compat import User
class Switch(models.Model):
label = models.CharField(max_length=200)
description = models.TextField(
help_text='Short description of what this switch is doing', blank=True)
globally_active = models.BooleanField(default=False)
users = mod... | from django.db import models
from .compat import User
class Switch(models.Model):
label = models.CharField(max_length=200)
description = models.TextField(
help_text='Short description of what this switch is doing', blank=True)
globally_active = models.BooleanField(default=False)
users = mod... | Allow no selected users when editing a switch. | Allow no selected users when editing a switch.
| Python | bsd-2-clause | potatolondon/django-hashbrown |
f4eac1d029b79c5dc5a6a07e696f9ea4c341342f | gittip/models/user.py | gittip/models/user.py | import uuid
from gittip.orm import db
from gittip.models.participant import Participant
class User(Participant):
"""Represent a website user.
Every current website user is also a participant, though if the user is
anonymous then the methods from Participant will fail with NoParticipantId.
"""
@... | import uuid
from gittip.orm import db
from gittip.models.participant import Participant
class User(Participant):
"""Represent a website user.
Every current website user is also a participant, though if the user is
anonymous then the methods from gittip.Participant will fail with
NoParticipantId. Th... | Clarify comment re: Participant class | Clarify comment re: Participant class
This refers to the old participant class, which is going away.
| Python | cc0-1.0 | bountysource/www.gittip.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,bountysource/www.gittip.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,bountysource/www.gittip.com,mccolgst/www.gittip.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/grat... |
ae9b50b72d69a06c47cff0bc78d58346399b65d3 | hdbscan/__init__.py | hdbscan/__init__.py | from .hdbscan_ import HDBSCAN, hdbscan
from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
| from .hdbscan_ import HDBSCAN, hdbscan
from .robust_single_linkage_ import RobustSingleLinkage, robust_single_linkage
from .prediction import approximate_predict, membership_vector, all_points_membership_vectors
| Add prediction functions to imports in init | Add prediction functions to imports in init
| Python | bsd-3-clause | scikit-learn-contrib/hdbscan,lmcinnes/hdbscan,lmcinnes/hdbscan,scikit-learn-contrib/hdbscan |
f93888778e1710136d3ba5cc5365711a1c658ff6 | data/pipeline/run/30_exoplanets/exoread.py | data/pipeline/run/30_exoplanets/exoread.py | #!/usr/bin/env python
import json
import sys
import csv
from pymongo import MongoClient
if len(sys.argv) < 2:
print 'usage: python read.py filepath'
sys.exit(1)
reader = csv.DictReader(open(sys.argv[1]), delimiter=',', quotechar='"')
conn = MongoClient()
db = conn.asterank
coll = db.exo
coll.drop()
coll.ensure_i... | #!/usr/bin/env python
import json
import sys
import csv
from pymongo import MongoClient
if len(sys.argv) < 2:
print 'usage: python read.py filepath'
sys.exit(1)
reader = csv.DictReader(open(sys.argv[1]), delimiter=',', quotechar='"')
conn = MongoClient()
db = conn.asterank
coll = db.exo
coll.drop()
coll.ensure_i... | Clean things up a little | Clean things up a little | Python | mit | typpo/asterank,typpo/asterank,typpo/asterank,typpo/asterank |
c600d1e1ad3cef69f6028afd64e14a04c747e1c6 | tests/test_install.py | tests/test_install.py | import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
... | import sys
import os
from subprocess import check_call
from pew._utils import invoke_pew as invoke
from utils import skip_windows, connection_required
import pytest
def skip_marker(f):
return skip_windows(reason='Pythonz unavailable in Windows')(
pytest.mark.skipif(
sys.platform == 'cygwin',
... | Replace version of Python to install in test_{un,}install test | Replace version of Python to install in test_{un,}install test
PyPy 2.6.1's download link is not working anymore.
| Python | mit | berdario/pew,berdario/pew |
5038c49c1597ef6182c429dd63b34045a69de945 | tests/test_version.py | tests/test_version.py | # coding=utf-8
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import re
version_regex = re.compile(r'^\d+\.\d+')
import lasio.las_version
def test_verify_default_vcs_tool():
result = lasio.las_version._get_vcs_version()
if 'GITHUB_WORKFLOW' in os.environ:
assert resul... | # coding=utf-8
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import re
version_regex = re.compile(r'^\d+\.\d+')
import lasio.las_version
def test_non_existent_vcs_tool():
version_cmd = ["gt", "describe", "--tags", "--match", "v*"]
result = lasio.las_version._get_vcs_version(v... | Add check for pushed tag version to version tests | Add check for pushed tag version to version tests
When getting Lasio's version in GITHUB_WORK flow environment, test for
both a '--no-tag' empty string version and a pushed release tag string
version.
| Python | mit | kinverarity1/lasio,kwinkunks/lasio,kinverarity1/las-reader |
e5351bba6cdf7b76da895afda80c18309c7f90eb | tests/test_config.py | tests/test_config.py | from yacron import config
def test_mergedicts():
assert dict(config.mergedicts({"a": 1}, {"b": 2})) == {"a": 1, "b": 2}
def test_mergedicts_nested():
assert dict(config.mergedicts(
{"a": {'x': 1, 'y': 2, 'z': 3}},
{'a': {'y': 10}, "b": 2})) == \
{"a": {'x': 1, 'y': 10, 'z': 3}, "b": 2}
def test_merg... | from yacron import config
def test_mergedicts():
assert dict(config.mergedicts({"a": 1}, {"b": 2})) == {"a": 1, "b": 2}
def test_mergedicts_nested():
assert (dict(config.mergedicts(
{"a": {'x': 1, 'y': 2, 'z': 3}},
{'a': {'y': 10}, "b": 2}
)) == {"a": {'x': 1, 'y': 10, 'z': 3}, "b": 2})
... | Replace tabs with spaces, use parens to get rid of backslashes | Replace tabs with spaces, use parens to get rid of backslashes
| Python | mit | gjcarneiro/yacron |
eca2199c90fa169acef8672458df0df3e6d65fad | tests/test_device.py | tests/test_device.py | def test_test():
assert True
| import pytest
from xbee_helper import device, exceptions, ZigBee
def test_raise_if_error_no_status():
"""
Should return None without raising if there's no "status" key in frame.
"""
assert device.raise_if_error({}) is None
def test_raise_if_error_zero():
"""
Should return None without raisi... | Add tests for raise_if_error function | Add tests for raise_if_error function
| Python | mit | flyte/xbee-helper |
fd909f383ab8a930c8a858144e0566075821f019 | tests/test_search.py | tests/test_search.py | from sharepa.search import ShareSearch
from sharepa.search import basic_search
import elasticsearch_dsl
import types
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
my_search = my_se... | from sharepa.search import ShareSearch
from sharepa.search import basic_search
import vcr
import types
import elasticsearch_dsl
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
my_sea... | Add vcr to scan test | Add vcr to scan test
| Python | mit | fabianvf/sharepa,erinspace/sharepa,samanehsan/sharepa,CenterForOpenScience/sharepa |
1efb717cec51ce5d2aa67d668528cb0fcdde94e8 | scuevals_api/auth/decorators.py | scuevals_api/auth/decorators.py | from functools import wraps
from flask_jwt_extended import get_jwt_identity, jwt_required, current_user
from werkzeug.exceptions import Unauthorized
from scuevals_api.models import User
def optional_arg_decorator(fn):
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
retu... | from functools import wraps
from flask_jwt_extended import get_jwt_identity, jwt_required, current_user
from werkzeug.exceptions import Unauthorized
from scuevals_api.models import User
def optional_arg_decorator(fn):
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
retu... | Allow multiple permissions for an endpoint | Allow multiple permissions for an endpoint
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api |
4fa9cff24867d3288d4f46c669151e823e934df0 | nmea.py | nmea.py | import re
def gpgga_get_position(gpgga_sentence):
gps = re.search("\$GPGGA,,([0-9]+\.[0-9]+),([NS]),([0-9]+\.[0-9]+),([WE]),,,,([0-9]+),M,+\*(\w+)", gpgga_sentence)
position = {}
position['lat'] = gps.group(1)
position['lat_coord'] = gps.group(2)
position['long'] = gps.group(3)
position['long_coord'] = gps.group... | import re
def gpgga_get_position(gpgga_sentence):
sentence = gpgga_sentence.split(",")
position = {}
position['lat'] = sentence[2]
position['lat_coord'] = sentence[3]
position['lon'] = sentence[4]
position['lon_coord'] = sentence[5]
position['height'] = str(int(float(sentence[11]) * 3.28084)).zfill(6)
return ... | Simplify how we get lat and long from GPGGA sentence. | Simplify how we get lat and long from GPGGA sentence.
| Python | mit | elielsardanons/dstar_sniffer,elielsardanons/dstar_sniffer |
c0312176d9a53eeb6ffdc7e44e3a5c240072b33c | trac/upgrades/db20.py | trac/upgrades/db20.py | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicit... | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicitly store... | Make db upgrade step 20 more robust. | Make db upgrade step 20 more robust.
git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@5815 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac |
72302898ba5a6fc74dcedfc6f2049f4a0c1299ac | src/conftest.py | src/conftest.py | import pytest
def pytest_addoption(parser):
parser.addoption("--filter-project-name",
action="store",
default=None,
help="pass a project name to filter a test file to run only tests related to it")
@pytest.fixture
def filter_project_name(request):
... | import logging
import pytest
import buildercore.config
LOG = logging.getLogger("conftest")
def pytest_addoption(parser):
parser.addoption("--filter-project-name",
action="store",
default=None,
help="pass a project name to filter a test file to run onl... | Add logs for test start and end | Add logs for test start and end
| Python | mit | elifesciences/builder,elifesciences/builder |
74f0cfae2e56157c4bd3e5dde6d68cd8e40cf412 | feincms/module/page/extensions/symlinks.py | feincms/module/page/extensions/symlinks.py | """
This introduces a new page type, which has no content of its own but inherits
all content from the linked page.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms._internal import monkeypatch_property
def register(cls, admin_cls):
cls.add_to_class('symlinke... | """
This introduces a new page type, which has no content of its own but inherits
all content from the linked page.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms._internal import monkeypatch_property
def register(cls, admin_cls):
cls.add_to_class('symlinke... | Move symlinked page field to "Other options" | Move symlinked page field to "Other options"
| Python | bsd-3-clause | feincms/feincms,nickburlett/feincms,michaelkuty/feincms,feincms/feincms,nickburlett/feincms,matthiask/feincms2-content,matthiask/feincms2-content,joshuajonah/feincms,matthiask/django-content-editor,pjdelport/feincms,joshuajonah/feincms,matthiask/feincms2-content,michaelkuty/feincms,michaelkuty/feincms,nickburlett/feinc... |
697ffec14e11e3558c8ebd33637aeebd7119a772 | mltsp/__init__.py | mltsp/__init__.py | """Machine Learning Time-Series Platform (MLTSP)
See http://mltsp.io for more information.
"""
__version__ = '0.3dev'
def install():
"""Install MLTSP config file in ~/.config/mltsp/mltsp.yaml.
"""
import os
import shutil
cfg = os.path.expanduser('~/.config/mltsp/mltsp.yaml')
cfg_dir = os.p... | """Machine Learning Time-Series Platform (MLTSP)
See http://mltsp.io for more information.
"""
__version__ = '0.3dev'
def install():
"""Install MLTSP config file in ~/.config/mltsp/mltsp.yaml.
"""
import os
import shutil
from distutils.dir_util import copy_tree
data_src = os.path.join(os.p... | Copy data directory to ~/.local/mltsp during install; fix path to mltsp.yaml.example | Copy data directory to ~/.local/mltsp during install; fix path to mltsp.yaml.example
| Python | bsd-3-clause | mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,bnaul/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp,mltsp/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp |
8a0fc8a9241a7d090f801101cd5324d15e7ae990 | heutagogy/views.py | heutagogy/views.py | from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
r = re... | from heutagogy import app
import heutagogy.persistence
from flask import request, jsonify, Response
import json
import datetime
import sqlite3
heutagogy.persistence.initialize()
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/api/v1/bookmarks', methods=['POST'])
def bookmarks_post():
r = re... | Fix reading json from client (ignore mimetype). | Fix reading json from client (ignore mimetype).
• http://stackoverflow.com/a/14112400/2517622
| Python | agpl-3.0 | heutagogy/heutagogy-backend,heutagogy/heutagogy-backend |
2f2f18abbcde94e61c38a519b3b8d959be2e0301 | modules/roles.py | modules/roles.py | import discord
rolesTriggerString = '!role'
async def parse_roles_command(message, client):
msg = 'Role!'
await client.send_message(message.channel, msg)
| import discord
import shlex
rolesTriggerString = '!role'
async def parse_roles_command(message, client):
msg = shlex.split(message.content)
if len(msg) != 1
await client.send_message(message.channel, msg[1])
else:
break
| Modify to use shlex for getting command arguments | Modify to use shlex for getting command arguments
| Python | mit | suclearnub/scubot |
21cb063ec63792ddeb45a62570a8565c69f2091b | tests/functional/test_product.py | tests/functional/test_product.py | from .base import FunctionalTest
from store.tests.factories import *
class ProductTest(FunctionalTest):
def test_product_navigation(self):
# Create a product
product = ProductFactory.create()
# Get the product detail page
self.browser.get(self.live_server_url + product.get_absol... | from .base import FunctionalTest
from store.tests.factories import *
class ProductTest(FunctionalTest):
def setUp(self):
super(ProductTest, self).setUp()
# Create a product
self.product = ProductFactory.create()
def test_product_navigation(self):
# Get the product detail pag... | Create product in setUp() method for DRY | Create product in setUp() method for DRY
Create the product to be reused in the test methods in the setUp method
that is run before each test method
| Python | bsd-3-clause | kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop |
f3687b849dd01e9af32e6786ed6a813448cf8a38 | kaitaistructures.py | kaitaistructures.py | from struct import unpack
class KaitaiStruct:
def read_u1(self):
return unpack('B', self._io.read(1))[0]
| from struct import unpack
class KaitaiStruct:
def close(self):
self._io.close()
def read_u1(self):
return unpack('B', self._io.read(1))[0]
| Fix formatting as per PEP8 | Fix formatting as per PEP8
| Python | mit | kaitai-io/kaitai_struct_python_runtime |
e2fb7715d10a9a02216fa5668f482952bbb60310 | readthedocs/donate/forms.py | readthedocs/donate/forms.py | import logging
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
import stripe
from .models import Supporter
log = logging.getLogger(__name__)
class SupporterForm(forms.ModelForm):
class Meta:
model = Supporter
fields = (
... | import logging
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
import stripe
from .models import Supporter
log = logging.getLogger(__name__)
class SupporterForm(forms.ModelForm):
class Meta:
model = Supporter
fields = (
... | Add receipt_email to payment processing on donations | Add receipt_email to payment processing on donations
| Python | mit | SteveViss/readthedocs.org,rtfd/readthedocs.org,KamranMackey/readthedocs.org,safwanrahman/readthedocs.org,wijerasa/readthedocs.org,laplaceliu/readthedocs.org,jerel/readthedocs.org,pombredanne/readthedocs.org,fujita-shintaro/readthedocs.org,VishvajitP/readthedocs.org,CedarLogic/readthedocs.org,atsuyim/readthedocs.org,rav... |
b9bd647cfd8def947838cb35c266b3b9ac855201 | test_apriori.py | test_apriori.py | import unittest
from itertools import chain
from apriori import subsets
class AprioriTest(unittest.TestCase):
def test_subsets_should_return_empty_subsets_if_input_empty_set(self):
result = tuple(subsets(set([])))
self.assertEqual(result, ())
def test_subsets_should_return_non_empty_subsets... | from collections import defaultdict
from itertools import chain
import unittest
from apriori import (
subsets,
returnItemsWithMinSupport,
)
class AprioriTest(unittest.TestCase):
def test_subsets_should_return_empty_subsets_if_input_empty_set(self):
result = tuple(subsets(frozenset([])))
... | Test returning items with minimum support | Test returning items with minimum support
| Python | mit | asaini/Apriori,gst-group/apriori_demo |
c14bdaf3043cb38571073db7162a0899a35778ed | app/utils.py | app/utils.py | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | Fix index_for_role function to use index field in Role class. | Fix index_for_role function to use index field in Role class.
| Python | mit | hack4impact/reading-terminal-market,hack4impact/reading-terminal-market,hack4impact/reading-terminal-market |
9cb21f98e1b6670d733940ea74d75a7a01a1b38e | misp_modules/modules/expansion/__init__.py | misp_modules/modules/expansion/__init__.py | from . import _vmray # noqa
__all__ = ['vmray_submit', 'bgpranking', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'btc_steroids', 'domaintools', 'eupi',
'farsight_passivedns', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal',
'whois', 'shodan', 'reversedns'... | from . import _vmray # noqa
__all__ = ['vmray_submit', 'bgpranking', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'btc_steroids', 'domaintools', 'eupi',
'farsight_passivedns', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal',
'whois', 'shodan', 'reversedns'... | Add the new module sin the list of modules availables. | fix: Add the new module sin the list of modules availables.
| Python | agpl-3.0 | VirusTotal/misp-modules,MISP/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,amuehlem/misp-modules,amuehlem/misp-modules |
ba4a8815305e402b4e0d587601565d44524a114e | oslo/__init__.py | oslo/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Remove extraneous vim editor configuration comments | Remove extraneous vim editor configuration comments
Change-Id: Id8fb52db12695bff4488ea9e74b492a9dabbbccf
Partial-Bug: #1229324
| Python | apache-2.0 | varunarya10/oslo.db,openstack/oslo.db,akash1808/oslo.db,magic0704/oslo.db,JioCloud/oslo.db,openstack/oslo.db |
80bbff34e7bb8d9d3779d46b1bf9e64b62592055 | spotify/__init__.py | spotify/__init__.py | from __future__ import unicode_literals
import os
from cffi import FFI
__version__ = '2.0.0a1'
header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
header = open(header_file).read()
header += '#define SPOTIFY_API_VERSION ...\n'
ffi = FFI()
ffi.cdef(header)
lib = ffi.verify('#include "libspoti... | from __future__ import unicode_literals
import os
import cffi
__version__ = '2.0.0a1'
_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspoti... | Make header file variables private | Make header file variables private
| Python | apache-2.0 | kotamat/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,felix1m/pyspotify,mopidy/pyspotify,mopidy/pyspotify,jodal/pyspotify,jodal/pyspotify,kotamat/pyspotify,felix1m/pyspotify |
b84fe94128c308be3e95be800693eb92ec8c7d25 | keyring/py33compat.py | keyring/py33compat.py | """
Compatibility support for Python 3.3. Remove when Python 3.3 support is
no longer required.
"""
from .py27compat import builtins
def max(*args, **kwargs):
"""
Add support for 'default' kwarg.
>>> max([], default='res')
'res'
>>> max(default='res')
Traceback (most recent call last):
... | """
Compatibility support for Python 3.3. Remove when Python 3.3 support is
no longer required.
"""
from .py27compat import builtins
def max(*args, **kwargs):
"""
Add support for 'default' kwarg.
>>> max([], default='res')
'res'
>>> max(default='res')
Traceback (most recent call last):
... | Remove superfluous check for default | Remove superfluous check for default
| Python | mit | jaraco/keyring |
3874ca578c52879d9861213e321f6ece9e67f10b | sopel/modules/ping.py | sopel/modules/ping.py | # coding=utf8
"""
ping.py - Sopel Ping Module
Author: Sean B. Palmer, inamidst.com
About: http://sopel.chat
"""
from __future__ import unicode_literals
import random
from sopel.module import rule, priority, thread
@rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$')
def hello(bot, trigger):
if trigger.owner:
... | # coding=utf8
"""
ping.py - Sopel Ping Module
Author: Sean B. Palmer, inamidst.com
About: http://sopel.chat
"""
from __future__ import unicode_literals
import random
from sopel.module import rule, priority, thread
@rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$')
def hello(bot, trigger):
greeting = random.choice((... | Stop Sopel from relying rudely to the bot's owner. | Stop Sopel from relying rudely to the bot's owner.
| Python | mit | Uname-a/knife_scraper,Uname-a/knife_scraper,Uname-a/knife_scraper |
cf663c4961a84260e34ec422a4983d312df9e8c3 | calc.py | calc.py | """calc.py: A simple python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif co... | """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif com... | Add support to min command | Add support to min command
| Python | bsd-3-clause | anchavesb/pyCalc |
8e00a63f539413b39aaaad77a230f5fac5a37261 | conary/build/capsulerecipe.py | conary/build/capsulerecipe.py | #
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | #
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | Enable building hybrid capsule/non-capsule packages (CNY-3271) | Enable building hybrid capsule/non-capsule packages (CNY-3271)
| Python | apache-2.0 | sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary |
c0512873d1f558768c174c64faf419e03b63e24b | pijobs/flashjob.py | pijobs/flashjob.py | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
... | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class FlashJob(ScrollphatJob):
def run(self):
scrollphat.clear()
for i in range(int(self.options['loop'])):
scrollphat.set_pixels(lambda x, y: True, True)
self.sleep_interval()
scrollphat.clear()
... | Add default options for FlashJob. | Add default options for FlashJob.
| Python | mit | ollej/piapi,ollej/piapi |
70efd2427caf52a5ba45e05eb33dc47fce2147c6 | redwind/tasks.py | redwind/tasks.py | from contextlib import contextmanager
from flask import current_app
from redis import StrictRedis
import rq
_queue = None
def get_queue():
global _queue
if _queue is None:
_queue = create_queue()
return _queue
def create_queue():
"""Connect to Redis and create the RQ. Since this is not imp... | from contextlib import contextmanager
from redis import StrictRedis
import rq
_queue = None
def get_queue():
global _queue
if _queue is None:
_queue = create_queue()
return _queue
def create_queue():
"""Connect to Redis and create the RQ. Since this is not imported
directly, it is a co... | Revert "Added configuration options for Redis" | Revert "Added configuration options for Redis"
This reverts commit 80129aac1fb4471e7a519b8f86df2db0b978903a.
| Python | bsd-2-clause | Lancey6/redwind,Lancey6/redwind,Lancey6/redwind |
f68808dc85b2bb0ea8fb0d7de4669099740cdb61 | mesoblog/models.py | mesoblog/models.py | from django.db import models
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
# Article model represents one article in the blog.
class Article(models.Model):
titl... | from django.db import models
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
# Article model represents one article in the blog.
class Article(models.Model):
titl... | Add a primary category which will decide which category is shown as current in the chrome for this article. | Add a primary category which will decide which category is shown as current in the chrome for this article.
TODO: Enforce including the primary category as one of the categories for the article, both in UI and server side.
| Python | mit | grundleborg/mesosphere |
cfb0bda6096378de428a1460823626f3dc4c9059 | spyder_terminal/__init__.py | spyder_terminal/__init__.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Spyder Te... | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Spyder Te... | Set package version info to 0.3.0.dev0 | Set package version info to 0.3.0.dev0
| Python | mit | spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal |
7a362c4a516a1bf6fa91b9d8c670a5d5613e5aeb | miniraf/combine.py | miniraf/combine.py | import argparse
import astropy.io.fits as fits
import numpy as np
import sys
METHOD_MAP = {"median": lambda x: np.median(x, axis=0),
"average": lambda x: np.average(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def stack_fits_data(filenames):
fits_files = []
for f in filenames:
... | import argparse
import astropy.io.fits as fits
import numpy as np
import sys
METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True),
"average": lambda x: np.average(x, axis=0),
"sum": lambda x: np.sum(x, axis=0)}
def stack_fits_data(filenames):
fits_files = []
... | Allow the median method to overwrite in-memory intermediate | Allow the median method to overwrite in-memory intermediate
Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu>
| Python | mit | vulpicastor/miniraf |
f7ade90b6f68a4a8e71a3720ef529c228f2a035a | slackelot/slackelot.py | slackelot/slackelot.py | import time
import requests
class SlackNotificationError(Exception):
pass
def send_slack_message(message, webhook_url, pretext=None, title=None):
""" Send slack message using webhooks
Args:
message (string)
webhook_url (string), 'https://hooks.slack.com/services/{team id}/{bot or channe... | import time
import requests
class SlackNotificationError(Exception):
pass
def send_slack_message(message, webhook_url, pretext='', title='', author_name='', color=None):
"""Send slack message using webhooks
Args:
message (string)
webhook_url (string), 'https://hooks.slack.com/services/{... | Add author_name, color, and fallback to payload | Add author_name, color, and fallback to payload
| Python | mit | Chris-Graffagnino/slackelot |
a71f79d3966c7b3f491c2dacce721cd974af52c4 | sale_properties_dynamic_fields/__openerp__.py | sale_properties_dynamic_fields/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | Remove active key since is deprecated | Remove active key since is deprecated
| Python | agpl-3.0 | xpansa/sale-workflow,Antiun/sale-workflow,akretion/sale-workflow,acsone/sale-workflow,brain-tec/sale-workflow,brain-tec/sale-workflow,Eficent/sale-workflow,thomaspaulb/sale-workflow,acsone/sale-workflow,open-synergy/sale-workflow,jabibi/sale-workflow,Endika/sale-workflow,fevxie/sale-workflow,factorlibre/sale-workflow,B... |
15fd86ff33d4f585578ef4e67614e249b1e94d45 | jjvm.py | jjvm.py | #!/usr/bin/python
import argparse
import os
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTIN... | #!/usr/bin/python
import argparse
import os
import struct
import sys
CP_STRUCT_SIZES = { 0xa:3 }
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
####... | Use constants dictionary in lenCpStruct() | Use constants dictionary in lenCpStruct()
| Python | apache-2.0 | justinccdev/jjvm |
7cf58ed386028a616c2083364d3f5c92e0c0ade3 | examples/hello_world/hello_world.py | examples/hello_world/hello_world.py | #!/usr/bin/env python
# encoding: utf-8
"""
A Simple Example Flask Application
==================================
"""
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/foo')
def foo():
d = document.Document(data={
... | #!/usr/bin/env python
# encoding: utf-8
"""
A Simple Example Flask Application
==================================
"""
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/hello')
def foo():
return document.Document(data={
... | Update to hello world example | Update to hello world example
| Python | unlicense | thisissoon/Flask-HAL,thisissoon/Flask-HAL |
774ece47574466f6661de469ef0f43ecf97d66f0 | molly/utils/misc.py | molly/utils/misc.py | import urllib2, sys, os.path, imp
class AnyMethodRequest(urllib2.Request):
def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=None, method=None):
self.method = method and method.upper() or None
urllib2.Request.__init__(self, url, data, headers, origin_req_host, unveri... | import urllib2, sys, os.path, imp
class AnyMethodRequest(urllib2.Request):
def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=None, method=None):
self.method = method and method.upper() or None
urllib2.Request.__init__(self, url, data, headers, origin_req_host, unveri... | Make create_crontab fall back to default settings search before explicitly searching for DJANGO_SETTINGS_MODULE | Make create_crontab fall back to default settings search before explicitly searching for DJANGO_SETTINGS_MODULE
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
c1510244999e1e88dd66f62857d855e466cec570 | deprecated/__init__.py | deprecated/__init__.py | # -*- coding: utf-8 -*-
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated(reason):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
if isinst... | # -*- coding: utf-8 -*-
import functools
import warnings
def deprecated(func):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used.
"""
@functools.wraps(func)
def new_func(*args, **kwargs):
... | Replace invalid string format '{}' by '{0}' for Python 2.6 compatibility. | Replace invalid string format '{}' by '{0}' for Python 2.6 compatibility.
| Python | mit | vrcmarcos/python-deprecated |
d4d04b72727b5e3886255a866f984b75fe610406 | organizations/admin.py | organizations/admin.py | from django.contrib import admin
from organizations.models import (Organization, OrganizationUser,
OrganizationOwner)
class OwnerInline(admin.StackedInline):
model = OrganizationOwner
class OrganizationAdmin(admin.ModelAdmin):
inlines = [OwnerInline]
list_display = ['name', 'is_active']
pre... | from django.contrib import admin
from organizations.models import (Organization, OrganizationUser,
OrganizationOwner)
class OwnerInline(admin.StackedInline):
model = OrganizationOwner
raw_id_fields = ('organization_user',)
class OrganizationAdmin(admin.ModelAdmin):
inlines = [OwnerInline]
l... | Use raw ID fields for users, organizations | Use raw ID fields for users, organizations
Avoids slowing down admin sites
| Python | bsd-2-clause | bennylope/django-organizations,st8st8/django-organizations,DESHRAJ/django-organizations,GauthamGoli/django-organizations,bennylope/django-organizations,GauthamGoli/django-organizations,aptivate/django-organizations,DESHRAJ/django-organizations,aptivate/django-organizations,st8st8/django-organizations,arteria/django-ar-... |
ff476b33c26a9067e6ac64b2c161d29b0febea33 | py/capnptools/examples/tests/test_books.py | py/capnptools/examples/tests/test_books.py | import unittest
from examples import books
class BooksTest(unittest.TestCase):
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = 'Moby-Dick; or, The Whale'
book.authors = ['Herman Melville']
self.assertEqual(
{
... | import unittest
import os
import tempfile
from examples import books
class BooksTest(unittest.TestCase):
BOOK = {
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
}
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
bo... | Add unit tests for write_to and write_packed_to | Add unit tests for write_to and write_packed_to
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage |
a5b40d9781caf74179f8c7e1f6fe4de5299b1e59 | src/osmviz/__init__.py | src/osmviz/__init__.py | # osmviz module #
# Copyright (c) 2010 Colin Bick, Robert Damphousse
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, co... | # osmviz module #
# Copyright (c) 2010 Colin Bick, Robert Damphousse
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, co... | Remove Python 2 ImportError, let python_requires handle it | Remove Python 2 ImportError, let python_requires handle it
| Python | mit | hugovk/osmviz,hugovk/osmviz |
787494af73a0b0e316547c3ec8536aa9ac21575e | clients.py | clients.py | #!/usr/bin/env python
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = raw_input('> ')
if not data:
break
tcpCliSock.send('%s\r\n' % data)
data = tcpCliSock.recv... | #!/usr/bin/env python
import argparse
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
parser = argparse.ArgumentParser(description='Allow the user to specify a hostname and a port.')
parser.add_argument('--hostname', default=HOST, help='Add hostname')
parser.add_argument('--port', default=PORT, he... | Allow the user to specify a hostname and port | Allow the user to specify a hostname and port
| Python | mit | ccandillo/chapter2 |
540c0130ccca7d7d7cf51ddbe251652a5c46364e | registrations/admin.py | registrations/admin.py | from django.contrib import admin
from .models import Source, Registration
class RegistrationAdmin(admin.ModelAdmin):
list_display = [
"id", "stage", "validated", "mother_id", "source",
"created_at", "updated_at", "created_by", "updated_by"]
list_filter = ["source", "validated", "created_at"]
... | from django.contrib import admin
from .models import Source, Registration, SubscriptionRequest
class RegistrationAdmin(admin.ModelAdmin):
list_display = [
"id", "stage", "validated", "mother_id", "source",
"created_at", "updated_at", "created_by", "updated_by"]
list_filter = ["source", "valida... | Add SubscriptionRequestAdmin - reviewed over shoulder by @gsvr | Add SubscriptionRequestAdmin - reviewed over shoulder by @gsvr
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration |
20a8d57f5e3d00898c7362d650b37f7962fdfe7a | tests/test_distributions.py | tests/test_distributions.py | from __future__ import division
import sympy
from symfit import Variable, Parameter
from symfit.distributions import Gaussian, Exp
def test_gaussian():
"""
Make sure that symfit.distributions.Gaussians produces the expected
sympy expression.
"""
x0 = Parameter()
sig = Parameter(positive=True... | from __future__ import division
import sympy
from symfit import Variable, Parameter
from symfit.distributions import Gaussian, Exp
def test_gaussian():
"""
Make sure that symfit.distributions.Gaussians produces the expected
sympy expression.
"""
x0 = Parameter('x0')
sig = Parameter('sig', po... | Add names to Parameters/Variables to surpress DepricationWarnings | Add names to Parameters/Variables to surpress DepricationWarnings
| Python | mit | tBuLi/symfit |
22dc2bd827143c4c73b7b122d94a64611960e9a1 | wiki/models.py | wiki/models.py | from couchdb.schema import *
from couchdb.schema import View
from wiki.auth.models import User
class Page(Document):
created_date = DateTimeField()
last_edited_date = DateTimeField()
title = TextField()
contents = TextField()
auth_user_editable = BooleanField()
us... | from couchdb.schema import *
from couchdb.schema import View
class Page(Document):
created_date = DateTimeField()
last_edited_date = DateTimeField()
title = TextField()
contents = TextField()
auth_user_editable = BooleanField()
user = DictField()
... | Fix an unreferenced module bug | Fix an unreferenced module bug
| Python | mit | theju/django-couch-wiki |
ff6ef6752b4aa0f561f2776d400e3c313963815c | polling/models.py | polling/models.py | from __future__ import unicode_literals
from django.db import models
# Create your models here.
| from __future__ import unicode_literals
from django.db import models
# Create your models here.
PARTY_DEMOCRATIC = 'democratic'
PARTY_GREEN = 'green'
PARTY_LIBERTARIAN = 'libertarian'
PARTY_REPUBLICAN = 'republican'
PARTIES = (
(PARTY_DEMOCRATIC, PARTY_DEMOCRATIC.title()),
(PARTY_GREEN, PARTY_GREEN.title()... | Add a State model and some enums | Add a State model and some enums
| Python | mit | sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap |
2293cc41ef1fada91c1d71c2f75ebf3e5609bd9e | admin/metrics/views.py | admin/metrics/views.py | from django.views.generic import TemplateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from admin.base.settings import KEEN_CREDENTIALS
class MetricsView(PermissionRequiredMixin, TemplateView):
template_name = 'metrics/osf_metrics.html'
permission_required = 'common_auth.view_metrics'
... | from django.views.generic import TemplateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from admin.base.settings import KEEN_CREDENTIALS
class MetricsView(PermissionRequiredMixin, TemplateView):
template_name = 'metrics/osf_metrics.html'
permission_required = 'osf.view_metrics'
raise... | Update permission required to match new permission name | Update permission required to match new permission name
| Python | apache-2.0 | HalcyonChimera/osf.io,caseyrollins/osf.io,chennan47/osf.io,hmoco/osf.io,crcresearch/osf.io,felliott/osf.io,saradbowman/osf.io,chennan47/osf.io,caseyrollins/osf.io,cslzchen/osf.io,icereval/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,adlius/osf.io,sloria/osf.io,ba... |
e9a8d67115295e852e376d17bd159f5b9789bb4d | videos/module/chapters/models.py | videos/module/chapters/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Chapter(models.Model):
"""
Video section.
"""
video = models.ForeignKey('videos.Video')
title = models.CharField(max_length=255)
timecode = models.TimeField(help_text='hh:mm:ss')
preview = models.Imag... | import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Chapter(models.Model):
"""Video section"""
video = models.ForeignKey('videos.Video')
title = models.CharFie... | Refactor for python 3 and shinyness | Refactor for python 3 and shinyness
| Python | bsd-2-clause | incuna/incuna-videos,incuna/incuna-videos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.