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 |
|---|---|---|---|---|---|---|---|---|---|
fb07eabac3847a1d454bbe6d663deef6ec47fc9b | seo/escaped_fragment/app.py | seo/escaped_fragment/app.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... | Fix broken content rendered by PhJS | Fix broken content rendered by PhJS
| Python | apache-2.0 | platformio/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web,orgkhnargh/platformio-web |
632a655f8f1f5867069f1c4d381417fa567b79a6 | controlled_vocabularies/urls.py | controlled_vocabularies/urls.py | from django.urls import re_path
from controlled_vocabularies.views import (
vocabulary_list, verbose_vocabularies, about,
all_vocabularies, term_list, vocabulary_file
)
urlpatterns = [
# Search View
re_path(r'^$', vocabulary_list, name="vocabulary_list"),
re_path(r'^all-verbose/?$', verbose_vocabul... | from django.urls import path, re_path
from controlled_vocabularies.views import (
vocabulary_list, verbose_vocabularies, about,
all_vocabularies, term_list, vocabulary_file
)
urlpatterns = [
# Search View
path('', vocabulary_list, name="vocabulary_list"),
path('all-verbose/', verbose_vocabularies, ... | Replace re_path with path wherever possible | Replace re_path with path wherever possible
| Python | bsd-3-clause | unt-libraries/django-controlled-vocabularies,unt-libraries/django-controlled-vocabularies |
ebf9628a55a82daa489f2bd5e2d83f2218369f01 | controllers/accounts_manager.py | controllers/accounts_manager.py | from flask_restful import Resource
class AccountsManager(Resource):
"""docstring for AccountsManager."""
def get(self):
return {"route": "login"}
def post(self):
return {"route": "register"}
| from flask import jsonify, make_response
from flask_restful import Resource, reqparse
from app.models import User
from app.db_instance import save
from validator import validate
class AccountsManager(Resource):
"""docstring for AccountsManager."""
def __init__(self):
self.parser = reqparse.RequestPars... | Add Register resource to handle user registration and save user data to the database | Add Register resource to handle user registration and save user data to the database
| Python | mit | brayoh/bucket-list-api |
45e180a6769584cad372399f9383dbb965e8ece8 | live_studio/build/views.py | live_studio/build/views.py | from django.http import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
@require_POST
def enqueue(request, config_id):
config = get_object_or_404(request.user.configs, pk=config_id)
config.builds.crea... | from django.http import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST
@require_POST
def enqueue(request, config_id):
config = get_object_or_404(request.user.configs, pk=config_id)
config.builds.crea... | Make it clearer that you get an email when the build completes | Make it clearer that you get an email when the build completes
| Python | agpl-3.0 | debian-live/live-studio,debian-live/live-studio,debian-live/live-studio |
bff55b65cd08259c64171e0ad5fd836875ce3008 | example/search/views.py | example/search/views.py | from __future__ import absolute_import, unicode_literals
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
import wagtail
if wagtail.VERSION >= (2, 0):
from wagtail.core.models import Page
from wagtail.search.models import Query
else:
from wagtail... | from __future__ import absolute_import, unicode_literals
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('query', None)
... | Drop wagtail 1.13 support from example | Drop wagtail 1.13 support from example
| Python | mit | Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget |
9080e9c967fa5e2af43c42a48de8b8ec3231a866 | src/tests/behave/agent/features/steps/common.py | src/tests/behave/agent/features/steps/common.py | from collections import defaultdict
from behave import given, then, when, step, use_step_matcher
use_step_matcher("parse")
@given('something with the agent')
def step_something_with_the_agent(context):
"""
:type context: behave.runner.Context
"""
pass
| from collections import defaultdict
from behave import given, then, when, step, use_step_matcher
use_step_matcher("parse")
@given('an agent is running on {ip}')
def step_an_agent_is_running_on_ip(context, ip):
"""
:type context: behave.runner.Context
:type ip: str
"""
pass
| Add ip argument to agent running step | Add ip argument to agent running step
| Python | apache-2.0 | jr0d/mercury,jr0d/mercury |
a23061a7efb241186ddf59911d6f1513cdec61a7 | geotrek/core/urls.py | geotrek/core/urls.py | from django.conf import settings
from django.conf.urls import patterns, url
from mapentity import registry
from geotrek.altimetry.urls import AltimetryEntityOptions
from geotrek.core.models import Path, Trail
from geotrek.core.views import get_graph_json
if settings.TREKKING_TOPOLOGY_ENABLED:
urlpatterns = patt... | from django.conf import settings
from django.conf.urls import patterns, url
from mapentity import registry
from geotrek.altimetry.urls import AltimetryEntityOptions
from geotrek.core.models import Path, Trail
from geotrek.core.views import get_graph_json
urlpatterns = patterns('',
url(r'^api/graph.json$', get_g... | Fix URL error with Geotrek light | Fix URL error with Geotrek light
| Python | bsd-2-clause | johan--/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,johan--/Geotrek,mabhub/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,makinaco... |
355b70412f8b725dcf6771967387cf4ba999c98b | fetch_configs/syzygy.py | fetch_configs/syzygy.py | # Copyright 2016 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.
import sys
import config_util # pylint: disable=import-error
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=no... | # Copyright 2016 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.
import sys
import config_util # pylint: disable=import-error
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=no... | Update fetch config with new Syzygy location. | Update fetch config with new Syzygy location.
Change-Id: Iacc2efd6974f1a161da6e33a0d25d6329fcaaf4f
Reviewed-on: https://chromium-review.googlesource.com/692697
Commit-Queue: Sébastien Marchand <b98658856fe44d267ccfa37efbb15fc831b08ae9@chromium.org>
Reviewed-by: Aaron Gable <bbed39beedae4cdb499af742d2fcd6c63934d93b@chr... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools |
e0d8289c8ea3240f1c7cceb4e42470c814a81e61 | members/serializers.py | members/serializers.py | from rest_framework import serializers
from members.models import Band
from members.models import BandMember
class BandMemberSerializer(serializers.ModelSerializer):
class Meta:
model = BandMember
fields = ('id',
'account',
'section',
'instrument_number',
... | from rest_framework import serializers
from members.models import Band
from members.models import BandMember
class BandMemberSerializer(serializers.ModelSerializer):
class Meta:
model = BandMember
fields = ('id',
'account',
'section',
'instrument_number',
... | Add band members as unassigned to new bands | Add band members as unassigned to new bands
| Python | mit | KonichiwaKen/band-dashboard,KonichiwaKen/band-dashboard,KonichiwaKen/band-dashboard |
1cf14753174b6fdbd5999ac857ce0e55852194b6 | dmoj/executors/ruby_executor.py | dmoj/executors/ruby_executor.py | import os
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_cmdline(self):
return [self.get_command(), '--disable-gems', self._code]
@classmethod
def get_version_flags(... | import os
import re
from .base_executor import ScriptExecutor
class RubyExecutor(ScriptExecutor):
ext = '.rb'
name = 'RUBY'
address_grace = 65536
test_program = 'puts gets'
def get_fs(self):
fs = super(RubyExecutor, self).get_fs()
home = self.runtime_dict.get('%s_home' % self.get... | Make Ruby work on Travis | Make Ruby work on Travis
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge |
a735ad28d1d8996ece647dd95f68d19e629a4d53 | frigg/worker/fetcher.py | frigg/worker/fetcher.py | # -*- coding: utf8 -*-
import json
import threading
import time
import logging
from frigg.worker import config
from frigg.worker.jobs import Build
logger = logging.getLogger(__name__)
def fetcher():
redis = config.redis_client()
while redis:
task = redis.rpop('frigg:queue')
if task:
... | # -*- coding: utf8 -*-
import sys
import json
import threading
import time
import logging
from frigg.worker import config
from frigg.worker.jobs import Build
logger = logging.getLogger(__name__)
def fetcher():
redis = config.redis_client()
while redis:
task = redis.rpop('frigg:queue')
if tas... | Make worker exit after a build | Make worker exit after a build
| Python | mit | frigg/frigg-worker |
f9b4f5857d3266a2c5661920144f33aad9ef8a3f | amy/autoemails/tests/base.py | amy/autoemails/tests/base.py | import django_rq
from fakeredis import FakeStrictRedis
from redis import Redis
from rq import Queue
class FakeRedisTestCaseMixin:
"""TestCase mixin that provides easy setup of FakeRedis connection to both
Django-RQ and RQ-Scheduler, as well as test-teardown with scheduled jobs
purging."""
def setUp(s... | import django_rq
from fakeredis import FakeStrictRedis
from redis import Redis
from rq import Queue
connection = FakeStrictRedis()
class FakeRedisTestCaseMixin:
"""TestCase mixin that provides easy setup of FakeRedis connection to both
Django-RQ and RQ-Scheduler, as well as test-teardown with scheduled jobs... | Switch tests to fake redis implementation | Switch tests to fake redis implementation
| Python | mit | swcarpentry/amy,swcarpentry/amy,swcarpentry/amy,pbanaszkiewicz/amy,pbanaszkiewicz/amy,pbanaszkiewicz/amy |
ed5f7ac5b6583c1e88e51f87bb73d6d50717b2f6 | test/test_parameters.py | test/test_parameters.py | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
import pytest
def test_check_urlslash():
launch = Launcher('not here',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch2 = Launcher('why do I need to do this',
... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
import os
import pytest
def test_check_urlslash():
launch = Launcher('not here',
r'http://rlee287.github.io/pyautoupdate/testing/')
launch2 = Launcher('why do I need to do this',
... | Write test for error checks | Write test for error checks
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
0251d3d3956a75fbeb66a0d4466cbcefa2e49f93 | examples/web_app.py | examples/web_app.py | """
Example for running Application using the `aiohttp.web` CLI.
Run this app using::
$ python -m aiohttp.web web_app.init
"""
from aiohttp.web import Application, Response
def hello_world(req):
return Response(text="Hello World")
def init(args):
app = Application()
app.router.add_route('GET', '/... | """
Example of serving an Application using the `aiohttp.web` CLI.
Serve this app using::
$ python -m aiohttp.web -H localhost -P 8080 --repeat 10 web_app.init \
> "Hello World"
Here ``--repeat`` & ``"Hello World"`` are application specific command-line
arguments. `aiohttp.web` only parses & consumes the com... | Update CLI example to use nested argparse | Update CLI example to use nested argparse
| Python | apache-2.0 | panda73111/aiohttp,elastic-coders/aiohttp,hellysmile/aiohttp,moden-py/aiohttp,mind1master/aiohttp,hellysmile/aiohttp,jashandeep-sohi/aiohttp,moden-py/aiohttp,AraHaanOrg/aiohttp,jettify/aiohttp,esaezgil/aiohttp,KeepSafe/aiohttp,jashandeep-sohi/aiohttp,decentfox/aiohttp,z2v/aiohttp,mind1master/aiohttp,KeepSafe/aiohttp,je... |
0a4d3f5b837cfa0d41a927c193a831a1c00b51f5 | setup.py | setup.py | #!/usr/bin/env python
#
# ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from distutils.core import setup
from hydra_agent import __version__
setup(
name = 'hydra-agent',
version = __version__,
author = "Whamcloud, Inc.",
author_email = "info@whamcloud... | #!/usr/bin/env python
#
# ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from distutils.core import setup
from hydra_agent import __version__
setup(
name = 'hydra-agent',
version = __version__,
author = "Whamcloud, Inc.",
author_email = "info@whamcloud... | Add new paths for audit/ | Add new paths for audit/
| Python | mit | intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre |
3e4707a3f25f3a2f84f811394d738cebc1ca9f19 | mygpo/search/models.py | mygpo/search/models.py | """ Wrappers for the results of a search """
class PodcastResult(object):
""" Wrapper for a Podcast search result """
@classmethod
def from_doc(cls, doc):
""" Construct a PodcastResult from a search result """
obj = cls()
for key, val in doc['_source'].items():
seta... | """ Wrappers for the results of a search """
import uuid
class PodcastResult(object):
""" Wrapper for a Podcast search result """
@classmethod
def from_doc(cls, doc):
""" Construct a PodcastResult from a search result """
obj = cls()
for key, val in doc['_source'].items():
... | Fix parsing UUID in search results | Fix parsing UUID in search results
| Python | agpl-3.0 | gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo |
0d3b11648af33b57671f3a722b41e04625b7d984 | tests/test_fragments.py | tests/test_fragments.py | import sci_parameter_utils.fragment as frag
class TestInputInt:
def test_create(self):
name = 'test'
fmt = "{}"
elem = frag.TemplateElem.elem_by_type('int',
name,
{}
... | import sci_parameter_utils.fragment as frag
class TestInputInt:
tstr = 'int'
def test_create(self):
name = 'test'
fmt = "{}"
elem = frag.TemplateElem.elem_by_type(self.tstr,
name,
{}
... | Add tests for all input elements | Add tests for all input elements
| Python | mit | class4kayaker/Parameter_Utils |
ca953b2ef7662e4a70eba386e66ed6d66fad4eec | setup.py | setup.py | #!/usr/bin/env python
# encoding: utf-8
"""
setup.py
Setup the Keyring Lib for Python.
"""
import sys
from distutils.core import setup, Extension
from extensions import get_extensions
setup(name = 'keyring',
version = "0.1",
description = "Store and access your passwords safely.",
url = "http://ke... | #!/usr/bin/env python
# encoding: utf-8
"""
setup.py
Setup the Keyring Lib for Python.
"""
import sys
from distutils.core import setup, Extension
from extensions import get_extensions
setup(name = 'keyring',
version = "0.1",
description = "Store and access your passwords safely.",
url = "http://ho... | Fix the error in the home page URL. | Fix the error in the home page URL.
| Python | mit | jaraco/keyring |
ef2c1115fdebfacea76d19b3fac6bbde7f0cbbf2 | gitlab_tests/test_v91/test_tags.py | gitlab_tests/test_v91/test_tags.py | import responses
from gitlab.exceptions import HttpError
from gitlab_tests.base import BaseTest
from response_data.tags import *
class TestDeleteRepositoryTag(BaseTest):
@responses.activate
def test_delete_repository_tag(self):
responses.add(
responses.DELETE,
self.gitlab.api_... | import responses
from requests.exceptions import HTTPError
from gitlab_tests.base import BaseTest
from response_data.tags import *
class TestDeleteRepositoryTag(BaseTest):
@responses.activate
def test_delete_repository_tag(self):
responses.add(
responses.DELETE,
self.gitlab.ap... | Update Tags cases for new behaviour | tests: Update Tags cases for new behaviour
See also: #193
| Python | apache-2.0 | pyapi-gitlab/pyapi-gitlab,Itxaka/pyapi-gitlab,Itxaka/pyapi-gitlab,pyapi-gitlab/pyapi-gitlab |
c39260e64c8820bad9243c35f10b352419425810 | marble/tests/test_exposure.py | marble/tests/test_exposure.py | """ Tests for the exposure computation """
from nose.tools import *
import marble as mb
# Test maximum value of exposure
# Test maximum value of isolation
# Test minimum of exposure
# Test minimum of isolation
| """ Tests for the exposure computation """
from __future__ import division
from nose.tools import *
import itertools
import marble as mb
#
# Synthetic data for tests
#
def segregated_city():
""" perfect segregation """
city = {"A":{1:7, 2:0, 3:0},
"B":{1:0, 2:0, 3:14},
"C":{1:0, 2:42,... | Write tests for the exposure | Write tests for the exposure
| Python | bsd-3-clause | walkerke/marble,scities/marble |
4d7aea55408e96946a2a12fc75fb00fe62d9cfec | conftest.py | conftest.py | import tempfile
import pytest
import photomosaic as pm
@pytest.fixture(scope='module')
def pool():
pool_dir = tempfile.mkdtemp()
pm.generate_tile_pool(pool_dir)
pool = pm.make_pool(pool_dir)
| import tempfile
import shutil
import pytest
import photomosaic as pm
@pytest.fixture(scope='module')
def pool():
tempdirname = tempfile.mkdtemp()
pm.generate_tile_pool(tempdirname)
pool = pm.make_pool(tempdirname)
shutil.rmtree(tempdirname)
| Clean up temp pool dir after tests. | TST: Clean up temp pool dir after tests.
| Python | bsd-3-clause | danielballan/photomosaic |
d9b43099c114f2398e82bd2631555c2807610a06 | homebrew/printer.py | homebrew/printer.py | UNDERLINE_SYMBOL = "-"
def print_title(logline):
print(logline)
print(len(logline) * UNDERLINE_SYMBOL)
def print_blank_line():
print("")
def print_overview(
installed,
packages_not_needed_by_other,
packages_needed_by_other,
package_dependencies,
):
print_title("Installed packages:"... | UNDERLINE_SYMBOL = "-"
def print_title(logline):
print(logline)
print(len(logline) * UNDERLINE_SYMBOL)
def print_blank_line():
print("")
def print_overview(
installed,
packages_not_needed_by_other,
packages_needed_by_other,
package_dependencies):
print_title("Instal... | Use and extra level of indentation for funcion arguments | Use and extra level of indentation for funcion arguments
See: https://www.python.org/dev/peps/pep-0008/#indentation
| Python | isc | igroen/homebrew |
38a6b7b4e190905ef935eec29fae761130dbef35 | employees/admin.py | employees/admin.py | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "email",)
fieldsets = (
(None, {'fields': ('username', 'email', 'password')}),
('Personal info'... | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "first_name", "last_name", "email",)
fieldsets = (
(None, {'fields': ('username', 'email', 'password')}... | Add first name and last name to Admin employee list | Add first name and last name to Admin employee list
| Python | mit | neosergio/allstars |
d66b9ecd1a28042ab6511c99b4cba38480b1b96e | fpsd/test/test_sketchy_sites.py | fpsd/test/test_sketchy_sites.py | #!/usr/bin/env python3.5
# This test crawls some sets that have triggered http.client.RemoteDisconnected
# exceptions
import unittest
from crawler import Crawler
class CrawlBadSitesTest(unittest.TestCase):
bad_sites = ["http://jlve2diknf45qwjv.onion/",
"http://money2mxtcfcauot.onion",
... | #!/usr/bin/env python3.5
# This test crawls some sets that have triggered http.client.RemoteDisconnected
# exceptions
import unittest
from crawler import Crawler
class CrawlBadSitesTest(unittest.TestCase):
bad_sites = ["http://jlve2diknf45qwjv.onion/",
"http://money2mxtcfcauot.onion",
... | Add more sites that cause unusual errors | Add more sites that cause unusual errors
| Python | agpl-3.0 | freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/fingerprint-securedrop |
efb82776d08e8f8003d8038a4fcac52094bd8f86 | readthedocs/core/management/commands/symlink.py | readthedocs/core/management/commands/symlink.py | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from tastyapi import apiv2 as api
import redis
log = logging.getLogger(__name__)
def symlink(slug):
version_data = api.version().get(project=slug, slug='latest')['results'][0]
v = ... | import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from projects import tasks
from tastyapi import apiv2 as api
import redis
log = logging.getLogger(__name__)
def symlink(slug):
version_data = api.version().get(project=slug, slug='latest')['results'][0]
v = ... | Handle exceptions and use proper slug | Handle exceptions and use proper slug
| Python | mit | clarkperkins/readthedocs.org,rtfd/readthedocs.org,SteveViss/readthedocs.org,mrshoki/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org,sid-kap/readthedocs.org,hach-que/readthedocs.org,kenshinthebattosai/readthedocs.org,nikolas/readthedocs.org,GovReady/readthedocs.org,davidfischer/readthedocs.org,nyergle... |
446680c789ad970316209eeecc947d8e5afddeb7 | jenny/__init__.py | jenny/__init__.py | # coding=utf8
"""
Copyright 2015 jenny
"""
import pandoc
import subprocess
def compile(content, input_format, output_format, *args):
subprocess_arguments = ['pandoc',
'--from=%s' % input_format,
'--to=%s' % output_format]
subprocess_arguments.extend(a... | # coding=utf8
"""
Copyright 2015 jenny
"""
import six
import pandoc
import subprocess
def compile(content, input_format, output_format, *args):
if six.PY2 and isinstance(content, unicode):
content = content.encode("utf8")
subprocess_arguments = ['pandoc',
'--from=%s' % i... | Fix a bug on encoding. | Fix a bug on encoding.
| Python | mit | docloud/jenny |
24ca48098777d89835cf169ee2b4f06db50ec9f1 | koans/triangle.py | koans/triangle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | Simplify logic conditionals as tests still pass. | Simplify logic conditionals as tests still pass.
| Python | mit | javierjulio/python-koans-completed,javierjulio/python-koans-completed |
eb5294f0df32442dbd7431fd9200388ca4c63d62 | tests/builtins/test_reversed.py | tests/builtins/test_reversed.py | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ReversedTests(TranspileTestCase):
pass
class BuiltinReversedFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["reversed"]
not_implemented = [
'test_range',
]
| from .. utils import SAMPLE_DATA, TranspileTestCase, BuiltinFunctionTestCase
def _iterate_test(datatype):
def test_func(self):
code = '\n'.join([
'\nfor x in {value}:\n print(x)\n'.format(value=value)
for value in SAMPLE_DATA[datatype]
])
self.assertCodeExecutio... | Add iteration tests for reversed type | Add iteration tests for reversed type
| Python | bsd-3-clause | cflee/voc,cflee/voc,freakboy3742/voc,freakboy3742/voc |
41217b13d6a59b6919f72a0d8b24a86d16f2f22c | quotedb/serializers.py | quotedb/serializers.py | from rest_framework import serializers
from quotedb.models import Quote
class QuoteSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Quote
fields = ('body', 'owner', 'created', 'approved')
| from rest_framework import serializers
from quotedb.models import Quote
class QuoteSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Quote
fields = ('id', 'body', 'owner', 'created', 'approved')
read_only = ('id',)
| Add id to api results | Add id to api results
| Python | mit | kfdm/django-qdb,kfdm/django-qdb |
16c8baf99b90abe5f8f273647f02604b6e11f8b2 | humbug/test_settings.py | humbug/test_settings.py | from settings import *
DATABASES['default']["NAME"] = "zephyr/tests/zephyrdb.test"
| from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
| Fix running tests when the default database is MySQL. | Fix running tests when the default database is MySQL.
(imported from commit b692b64219fb67792cdfd3bd208df2c6103d23ad)
| Python | apache-2.0 | MayB/zulip,samatdav/zulip,willingc/zulip,easyfmxu/zulip,TigorC/zulip,natanovia/zulip,Cheppers/zulip,vaidap/zulip,MayB/zulip,Galexrt/zulip,ipernet/zulip,esander91/zulip,yuvipanda/zulip,eastlhu/zulip,joyhchen/zulip,noroot/zulip,jessedhillon/zulip,TigorC/zulip,timabbott/zulip,LeeRisk/zulip,zwily/zulip,udxxabp/zulip,pravee... |
a17b3f1b84d9c87ef3e469a140896dc4dabf9a2b | examples/vhosts.py | examples/vhosts.py | from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
... | from sanic import response
from sanic import Sanic
from sanic.blueprints import Blueprint
# Usage
# curl -H "Host: example.com" localhost:8000
# curl -H "Host: sub.example.com" localhost:8000
# curl -H "Host: bp.example.com" localhost:8000/question
# curl -H "Host: bp.example.com" localhost:8000/answer
app = Sanic()
... | Use of register_blueprint will be deprecated, why not upgrade? | Use of register_blueprint will be deprecated, why not upgrade?
| Python | mit | channelcat/sanic,channelcat/sanic,Tim-Erwin/sanic,ashleysommer/sanic,yunstanford/sanic,ashleysommer/sanic,lixxu/sanic,Tim-Erwin/sanic,lixxu/sanic,r0fls/sanic,lixxu/sanic,channelcat/sanic,ashleysommer/sanic,jrocketfingers/sanic,r0fls/sanic,jrocketfingers/sanic,yunstanford/sanic,lixxu/sanic,channelcat/sanic,yunstanford/s... |
d3837972d5aff2812ea534e053695373497192d5 | cheroot/__init__.py | cheroot/__init__.py | try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except ImportError:
__version__ = 'unknown'
| try:
import pkg_resources
__version__ = pkg_resources.get_distribution('cheroot').version
except (ImportError, pkg_resources.DistributionNotFound):
__version__ = 'unknown'
| Handle DistributionNotFound when getting version | Handle DistributionNotFound when getting version
When frozen with e.g. cx_Freeze, cheroot will be importable, but not discoverable by pkg_resources. | Python | bsd-3-clause | cherrypy/cheroot |
0e02b72c8c37fa5c51a0036ba67a57c99bc1da86 | housecanary/__init__.py | housecanary/__init__.py | from housecanary.apiclient import ApiClient
from housecanary.excel import export_analytics_data_to_excel
from housecanary.excel import export_analytics_data_to_csv
from housecanary.excel import concat_excel_reports
from housecanary.excel import utilities
__version__ = '0.6.5'
| __version__ = '0.6.5'
from housecanary.apiclient import ApiClient
from housecanary.excel import export_analytics_data_to_excel
from housecanary.excel import export_analytics_data_to_csv
from housecanary.excel import concat_excel_reports
from housecanary.excel import utilities
| Revert moving the __version__ declaration which broke things | Revert moving the __version__ declaration which broke things
| Python | mit | housecanary/hc-api-python |
31af6fefec9770e1ca6663fafe397465732fbf4d | lc0023_merge_k_sorted_lists.py | lc0023_merge_k_sorted_lists.py | """Leetcode 23. Merge k Sorted Lists
Hard
URL: https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
# Definition for singly-linked lis... | """Leetcode 23. Merge k Sorted Lists
Hard
URL: https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
# Definition for singly-linked lis... | Complete sort sol w/ time/space complexity | Complete sort sol w/ time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
98dc8375bcfeecc5106940a02395599ea1e60152 | core/settings/contrib.py | core/settings/contrib.py | from .base import *
INSTALLED_APPS += (
'django_hstore',
'provider',
'provider.oauth2',
'south',
'easy_thumbnails',
'kronos',
)
| from .base import *
INSTALLED_APPS += (
'django_hstore',
'provider',
'provider.oauth2',
'south',
'easy_thumbnails',
)
| Remove kronos from installed apps | Remove kronos from installed apps
| Python | apache-2.0 | nagyistoce/geokey,nagyistoce/geokey,nagyistoce/geokey |
a81186cdad8ac878c4968c8e2563d9aeae6f1c58 | tests/test_design_patterns.py | tests/test_design_patterns.py | __author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2014, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '1/24/14'
import unittest
from monty.design_patterns import singleton, cached_class
class SingletonTest(unittest.TestCase):
de... | __author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2014, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '1/24/14'
import unittest
import pickle
from monty.design_patterns import singleton, cached_class
class SingletonTest(unittest.Test... | Add pickle test for monty cached_class decorator. | Add pickle test for monty cached_class decorator.
| Python | mit | gmatteo/monty,yanikou19/monty,gmatteo/monty,materialsvirtuallab/monty,davidwaroquiers/monty,gpetretto/monty,materialsvirtuallab/monty,davidwaroquiers/monty |
c135e9ac8fead8e9e58d2f34e5aa66354bd1b996 | tests/test_route_requester.py | tests/test_route_requester.py | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test... | import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
import os
MAPS_API_KEY = os.environ['MAPS_API_KEY']
class TestOptionalParameters(unittest.TestCase):
def test_invalid_mode(self):
"""
Te... | Refactor tests to include API KEY | Refactor tests to include API KEY
| Python | apache-2.0 | apranav19/pydirections |
c3db5ba2860dc4ddf034aa036be573dd75093473 | tests/test_barebones.py | tests/test_barebones.py | # -*- coding: utf-8 -*-
"""
Tests for the barebones example project
"""
import os
import py.path
from tarbell.app import TarbellSite
PATH = os.path.realpath('examples/barebones')
def test_get_site():
site = TarbellSite(PATH)
assert os.path.realpath(site.path) == os.path.realpath(PATH)
assert site.project... | # -*- coding: utf-8 -*-
"""
Tests for the barebones example project
"""
import os
import py.path
from tarbell.app import EXCLUDES, TarbellSite
PATH = os.path.realpath('examples/barebones')
def test_get_site():
site = TarbellSite(PATH)
assert os.path.realpath(site.path) == os.path.realpath(PATH)
assert s... | Add a test for default excludes, which is failing | Add a test for default excludes, which is failing
| Python | bsd-3-clause | eyeseast/tarbell,eyeseast/tarbell,tarbell-project/tarbell,tarbell-project/tarbell |
c16006cd8983bbd73f52921c63a51aa6f29b9e88 | ituro/accounts/tests.py | ituro/accounts/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from django.utils import timezone
from accounts.models import CustomUser, CustomUserManager
class UserCreateTestCase(TestCase):
def test_create_user_correctly(self):
"Creating users correctly"
new_user = CustomUser.objects.create(
email="participant@gm... | Add test for creating accounts | Add test for creating accounts
| Python | mit | bilbeyt/ituro,ITURO/ituro,bilbeyt/ituro,bilbeyt/ituro,ITURO/ituro,ITURO/ituro |
0315f2b47261cfabe11b2668225ec1bc19e5493c | vispy_volume/tests/test_vispy_widget.py | vispy_volume/tests/test_vispy_widget.py | import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class Event(object):
def __init__(self, text):
self.text = text
def test_widget():
# Make sure QApplication is started
get_qapp()
# Create fake data
data = np.arange(1000).reshape((10,10,10))
... | import numpy as np
from ..vispy_widget import QtVispyWidget
from glue.qt import get_qapp
class KeyEvent(object):
def __init__(self, text):
self.text = text
class MouseEvent(object):
def __init__(self, delta, type):
self.type = type
self.delta = delta
def test_widget():
# Make su... | Fix the mouse_wheel test unit | Fix the mouse_wheel test unit
| Python | bsd-2-clause | astrofrog/glue-3d-viewer,PennyQ/astro-vispy,PennyQ/glue-3d-viewer,astrofrog/glue-vispy-viewers,glue-viz/glue-3d-viewer,glue-viz/glue-vispy-viewers |
1c216c833d42b648e4d38298eac1616d8748c76d | tests/test_pathutils.py | tests/test_pathutils.py | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
if version < '3000':
from libsass import pathutils
else:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
@classmethod
def setUpCla... | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
class TestPathutils(TestCase):
@classmethod
def setUpClass(cls):
super(TestPathutils, cls).setUpClass()
if version < '3000':
from libsass i... | Move importing of source to class setup | Move importing of source to class setup
| Python | mit | blitzrk/sublime_libsass,blitzrk/sublime_libsass |
d20e916a23974f92ae4ea82226eef98a7c00de9e | ds_stack.py | ds_stack.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[-1]
def ... | Add peek() and revise main() | Add peek() and revise main()
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
7d605d762b204cb608553a27ec51925d0e3bfcb6 | scripts/export-tutorial.py | scripts/export-tutorial.py | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in... | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in... | Add docs README; remove unused assets. | Add docs README; remove unused assets.
| Python | mit | ResidentMario/geoplot |
214b74d4cf3902456ed274f756f4827f18c0c988 | logster/server.py | logster/server.py | import os
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.httpserver import HTTPServer
from . import handlers
class LogsterApplication(Application):
handlers = [
(r'/', handlers.IndexHandler),
]
settings = {
'template_path': os.path.join(
o... | import os
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.httpserver import HTTPServer
from . import handlers
from .conf import config
class LogsterApplication(Application):
handlers = [
(r'/', handlers.IndexHandler),
]
settings = {
'template_path': os... | Use post value from config | Use post value from config
| Python | mit | irvind/logster,irvind/logster,irvind/logster |
cde4bc1112f2ceb45f42de21c45d46d96097d5bc | app/forms.py | app/forms.py | from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import InputRequired, Length, Regexp
class SignupForm(Form):
username = TextField(validators=[InputRequired(), Length(min=1, max=30), Regexp("^[a-zA-Z0-9]+$")])
publicKey = TextField(validators=[InputRequired()]) # Add Length and ... | from flask_wtf import Form
from wtforms import TextField, DateTimeField
from wtforms.validators import InputRequired, Length, Regexp
class SignupForm(Form):
username = TextField(validators=[InputRequired(), Length(min=1, max=30), Regexp("^[a-zA-Z0-9]+$")])
publicKey = TextField(validators=[InputRequired()]) # ... | Add basic AddEvent form with datetime conversion. | Add basic AddEvent form with datetime conversion.
| Python | agpl-3.0 | mitclap/backend |
9e0e8f37942b85d9ebd86b2da05bb8eb54c99e7d | src/minerva/storage/trend/engine.py | src/minerva/storage/trend/engine.py | from contextlib import closing
from minerva.directory import EntityType
from minerva.storage import Engine
from minerva.storage.trend import TableTrendStore
class TrendEngine(Engine):
@staticmethod
def store(package):
"""
Return a function to bind a data source to the store command.
... | from contextlib import closing
from minerva.util import k, identity
from minerva.directory import EntityType
from minerva.storage import Engine
from minerva.storage.trend import TableTrendStore
class TrendEngine(Engine):
@staticmethod
def store(package, filter_package=k(identity)):
"""
Return... | Add functionality to filter a data package before storing | Add functionality to filter a data package before storing
| Python | agpl-3.0 | hendrikx-itc/minerva,hendrikx-itc/minerva |
e955cebb8872f5d073739c43936aebd100636c49 | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | Allow render to take a template different from the default one. | Allow render to take a template different from the default one.
| Python | bsd-2-clause | vmuriart/grako,frnknglrt/grako |
013a3f11453787e18f7acd08c7e54fede59b1b01 | letsencrypt/__init__.py | letsencrypt/__init__.py | """Let's Encrypt client."""
# version number like 1.2.3a0, must have at least 2 parts, like 1.2
__version__ = '0.1.0.dev0'
| """Let's Encrypt client."""
# version number like 1.2.3a0, must have at least 2 parts, like 1.2
# '0.1.0.dev0'
__version__ = '0.1.0'
| Switch to "next production release" as the version in the tree | Switch to "next production release" as the version in the tree
| Python | apache-2.0 | mitnk/letsencrypt,brentdax/letsencrypt,brentdax/letsencrypt,goofwear/letsencrypt,jtl999/certbot,dietsche/letsencrypt,lmcro/letsencrypt,TheBoegl/letsencrypt,xgin/letsencrypt,letsencrypt/letsencrypt,wteiken/letsencrypt,wteiken/letsencrypt,thanatos/lets-encrypt-preview,VladimirTyrin/letsencrypt,jtl999/certbot,twstrike/le_... |
468e82418ceec8eb453054c1b3fbce433a27240f | keyring/__init__.py | keyring/__init__.py | from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
try:
import pkg_resources
__version__ = pkg_resources.get_distribution('keyring').version
except... | from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
__all__ = (
'set_keyring', 'get_keyring', 'set_password', 'get_password',
'delete_password', 'ge... | Remove usage of pkg_resources, which has huge import overhead. | Remove usage of pkg_resources, which has huge import overhead. | Python | mit | jaraco/keyring |
8fbd999bb6d4db865cd04e428533ea97ce139a23 | tests/test_exceptions.py | tests/test_exceptions.py | import unittest
import os
import battlenet
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_KEY')
class ExceptionTest(unittest.TestCase):
def setUp(self):
self.connection = battlenet.Connection(public_key=PUBLIC_KEY, private_key=PRIVATE_KEY)
def test_character... | import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest as unittest
import os
import battlenet
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_KEY')
class ExceptionTest(unittest.TestCase):
def setUp(self):
self.connectio... | Use unittest2 when python version is less than 2.7. | Use unittest2 when python version is less than 2.7.
In Google App Engine (GAE) you have to use unittest2 if the unit test code uses any of
the capabilities added in Python 2.7 to the unittest module.
| Python | mit | PuckCh/battlenet,vishnevskiy/battlenet |
25b0164b78298475513a45e7a6d5574d32c280f7 | tests/test_naivebayes.py | tests/test_naivebayes.py | import ML.naivebayes as naivebayes
import data
import numpy as np
def test_gaussian_naive_bayes():
X, y = data.categorical_2Dmatrix_data()
nb = naivebayes.GaussianNaiveBayes()
nb.fit(X, y)
for index, row in enumerate(X):
predicted_y = nb.predict(row)
assert predicted_y == y[index]
def... | import ML.naivebayes as naivebayes
import data
def test_gaussian_naive_bayes():
X, y = data.categorical_2Dmatrix_data()
nb = naivebayes.GaussianNaiveBayes()
nb.fit(X, y)
for index, row in enumerate(X):
predicted_y = nb.predict(row)
assert predicted_y == y[index]
def test_gaussian_nai... | Rename tests to avoid name re-use | Rename tests to avoid name re-use
| Python | mit | christopherjenness/ML-lib |
a6bca7eb3825e9c9722f3fc2dcff2a09dfd47f99 | runserver.py | runserver.py | #!/usr/bin/env python3
from argparse import ArgumentParser
from argparse import FileType
from os.path import dirname
from os.path import join
from connexion import App
from opwen_email_server.utils.imports import can_import
try:
# noinspection PyUnresolvedReferences
from dotenv import load_dotenv
load_d... | #!/usr/bin/env python3
from connexion import App
from opwen_email_server.utils.imports import can_import
_servers = list(filter(can_import, ('tornado', 'gevent', 'flask')))
_hosts = ['127.0.0.1', '0.0.0.0']
_server = _servers[0]
_host = _hosts[0]
_port = 8080
_ui = False
def build_app(apis, host=_host, port=_port... | Make script importable without side-effects | Make script importable without side-effects
This enables for example wrapping the runserver script in a wsgi server
like gunicorn that doesn't support passing args to the downstream app.
| Python | apache-2.0 | ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver |
921df8b8309b40e7a69c2fa0434a51c1cce82c28 | examples/rpc_pipeline.py | examples/rpc_pipeline.py | import asyncio
import aiozmq.rpc
class Handler(aiozmq.rpc.AttrHandler):
@aiozmq.rpc.method
def handle_some_event(self, a: int, b: int):
pass
@asyncio.coroutine
def go():
listener = yield from aiozmq.rpc.serve_pipeline(
Handler(), bind='tcp://*:*')
listener_addr = next(iter(listener.... | import asyncio
import aiozmq.rpc
from itertools import count
class Handler(aiozmq.rpc.AttrHandler):
def __init__(self):
self.connected = False
@aiozmq.rpc.method
def remote_func(self, step, a: int, b: int):
self.connected = True
print("HANDLER", step, a, b)
@asyncio.coroutine
d... | Make rpc pipeine example stable | Make rpc pipeine example stable
| Python | bsd-2-clause | claws/aiozmq,MetaMemoryT/aiozmq,asteven/aiozmq,aio-libs/aiozmq |
b17472c86ffca7811246080cf3b4b3f3b84e36b1 | common/src/tests/common/components/test_command.py | common/src/tests/common/components/test_command.py | #!/usr/bin/python3
import unittest
from gosa.common.components.command import *
class CommandTestCase(unittest.TestCase):
"""Docs"""
@Command(__help__="TEST")
def test_command(self):
pass
"""Docs"""
@Command()
def test_command2(self):
pass
# agent and client terms... | #!/usr/bin/python3
import unittest
from gosa.common.components.command import *
class CommandTestCase(unittest.TestCase):
@Command(__help__="TEST")
def test_command(self):
pass
@Command()
def test_command2(self):
"""Docs"""
pass
# agent and client terms still in u... | Fix in tests: Docstring at wrong location | Fix in tests: Docstring at wrong location
| Python | lgpl-2.1 | gonicus/gosa,gonicus/gosa,gonicus/gosa,gonicus/gosa |
502e01be7fdf427e3fbbf03887bbb323d8c74d43 | src/pi/pushrpc.py | src/pi/pushrpc.py | """Pusher intergration for messages from the cloud."""
import json
import logging
import Queue
import sys
from common import creds
from pusherclient import Pusher
class PushRPC(object):
"""Wrapper for pusher integration."""
def __init__(self):
self._queue = Queue.Queue()
self._pusher = Pusher(creds.pus... | """Pusher intergration for messages from the cloud."""
import json
import logging
import Queue
import sys
from common import creds
from pusherclient import Pusher
class PushRPC(object):
"""Wrapper for pusher integration."""
def __init__(self):
self._queue = Queue.Queue()
self._pusher = Pusher(creds.pus... | Make the script respond to ctrl-c | Make the script respond to ctrl-c
| Python | mit | tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation |
0f3cd463a2c6920cf4b727c01d0768fdb225acc4 | rl-rc-car/sensor_server.py | rl-rc-car/sensor_server.py | """
This runs continuously and serves our sensor readings when requested.
Base script from:
http://ilab.cs.byu.edu/python/socket/echoserver.html
"""
import socket
from sensors import Sensors
class SensorServer:
def __init__(self, host='', port=8888, size=1024, backlog=5):
self.host = host
self.p... | """
This runs continuously and serves our sensor readings when requested.
Base script from:
http://ilab.cs.byu.edu/python/socket/echoserver.html
"""
import socket
import json
class SensorServer:
def __init__(self, host='', port=8888, size=1024, backlog=5):
self.host = host
self.port = port
... | Update sensor server to grab from disk. | Update sensor server to grab from disk.
| Python | mit | harvitronix/rl-rc-car |
2007c7190f95a2656715e99af7ca632bbb98b313 | linkatos/firebase.py | linkatos/firebase.py | import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.... | import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.... | Change based on PR comments | refactor: Change based on PR comments
| Python | mit | iwi/linkatos,iwi/linkatos |
9876500ca8a897489e40c1b4e0c6379e18f9e985 | corehq/apps/userreports/transforms/custom/numeric.py | corehq/apps/userreports/transforms/custom/numeric.py | def get_short_decimal_display(num):
return round(num, 2)
| def get_short_decimal_display(num):
try:
return round(num, 2)
except:
return num
| Return num if rounding fails | Return num if rounding fails
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq |
75a598e2b9cf237448cd1b1934d3d58d093808ec | server/scraper/util.py | server/scraper/util.py | import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_f... | import os
import re
import sys
import json
def parse_money(moneystring):
# Sometimes 0 is O :(
moneystring = moneystring.replace("O", "0")
return re.sub("[^0-9,]", "", str(moneystring)).replace(',', '.')
def stderr_print(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def write_json_to_f... | Fix price in de brug | Fix price in de brug
| Python | mit | ZeusWPI/hydra,ZeusWPI/hydra,ZeusWPI/hydra |
157c08a6ccd738d5bccfe8145c2a1f1e9d21ba82 | madlib_web_client.py | madlib_web_client.py | import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to pe... | import os
from flask import Flask
import psycopg2
from urllib.parse import urlparse
url = urlparse(os.environ["DATABASE_URL"])
# Connect to a database
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
# Open a cursor to pe... | Add a drop table for testing. | Add a drop table for testing.
| Python | isc | appletonmakerspace/madlib,mikeputnam/madlib |
5e47f95bcc147a9735083f32a15df362bb6dcacd | pcs/packets/__init__.py | pcs/packets/__init__.py | __revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $"
all = ['ethernet',
'loopback',
'ipv4',
'ipv6',
'icmpv4',
'tcp',
'udp',
'data']
| __revision__ = "$Id: __init__.py,v 1.3 2006/06/27 14:45:43 gnn Exp $"
all = ['ethernet',
'loopback',
'ipv4',
'ipv6',
'icmpv4',
'igmpv2',
'igmpv3',
'tcp',
'udp',
'data']
| Connect IGMP to the build. | Connect IGMP to the build.
| Python | bsd-3-clause | gvnn3/PCS,gvnn3/PCS |
c848a5a1d94da7919b3272e9e0ee9748091ba04a | md/data/__init__.py | md/data/__init__.py | DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip" # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'
| DEFAULT_URL = 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip' # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'
| Fix URL to current MD dataset on S3 | Fix URL to current MD dataset on S3
| Python | mit | OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops |
66fdc9b0732b083f6f9bbb7142c8e07f1dd964ff | tests/__init__.py | tests/__init__.py | import threading
import time
from ..send_self import (
WeakGeneratorWrapper,
StrongGeneratorWrapper
)
default_sleep = 0.1
class CustomError(Exception):
pass
def defer(callback, *args, sleep=default_sleep, expected_return=None, call=True,
**kwargs):
def func():
time.sleep(sleep)... | import threading
import time
from ..send_self import WeakGeneratorWrapper
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... | Reduce test runtime by decreasing default sleep | Reduce test runtime by decreasing default sleep
Also remove WeakGeneratorWrapper check until gc tests are implemented.
| Python | mit | FichteFoll/resumeback |
bc0c460bf6d1cae2e7675e2f484bdac8e84f376e | tools/python/readLogFile.py | tools/python/readLogFile.py | #!/usr/bin/env python
import sys
import subprocess
import signal
def printMsg(msgDict):
print msgDict['name']
print '\t','type: ',msgDict['type']
print '\t','subtype: ',msgDict['subtype']
for key,value in msgDict.items():
if ((key != 'name') and (key != 'type') and (key != 'subtype')):
... | #!/usr/bin/env python
import sys
import subprocess
import signal
# example usage:
# ./readLogFile.py "INFO: headers" /projects/databridge/howard/DataBridge/log/ingest.log Insert.Metadata
# to find and display all of the Insert.Metadata.* messages.
#
# ./readLogFile.py "INFO: headers" /projects/databridge/howard/DataBr... | Add some documentation about how to use this file. | Add some documentation about how to use this file.
| Python | bsd-3-clause | HowardLander/DataBridge,HowardLander/DataBridge,HowardLander/DataBridge,HowardLander/DataBridge |
2a3f4ff6686f1630348a73dd62d7ad8e3215dff5 | tests/conftest.py | tests/conftest.py | import pytest
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
| import platform
import pytest
from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
if platform.python_implementation() == 'PyPy':
settings.default.suppress_health_check.append(HealthCheck.too_slow)
| Disable Hypothesis health check for PyPy. | Disable Hypothesis health check for PyPy.
| Python | mit | python-attrs/cattrs,Tinche/cattrs |
b40adb2a54d7022e3ca13edea332e6c5b26feed8 | start_bot.py | start_bot.py | #!/usr/bin/env python3
import logging
from lrrbot.main import bot, log
from common.config import config
logging.basicConfig(level=config['loglevel'], format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
if config['logfile'] is not None:
fileHandler = logging.FileHandler(config['logfile'], 'a', 'utf-8')
file... | #!/usr/bin/env python3
import logging
from lrrbot.main import bot, log
from common.config import config
logging.basicConfig(level=config['loglevel'], format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
if config['logfile'] is not None:
fileHandler = logging.FileHandler(config['logfile'], 'a', 'utf-8')
file... | Reduce some pubnub log noise | Reduce some pubnub log noise
| Python | apache-2.0 | mrphlip/lrrbot,andreasots/lrrbot,mrphlip/lrrbot,mrphlip/lrrbot,andreasots/lrrbot,andreasots/lrrbot |
3d48f181f90995bd66dc436acccde9d18c5cfa3c | tests/settings.py | tests/settings.py | import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.... | import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MID... | Remove django.contrib.comments and add MIDDLEWARE_CLASSES | Remove django.contrib.comments and add MIDDLEWARE_CLASSES
| Python | bsd-3-clause | imgmix/django-avatar,barbuza/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,jezdez/django-avatar,MachineandMagic/django-avatar,barbuza/django-avatar,ad-m/django-avatar,grantmcconnaughey/django-avatar,dannybrowne86/django-avatar,dannybrowne86/django-avatar,therocode/django-avatar,therocode/django-avata... |
2da853601e9746663aed35b51db3bfc7640dc9c3 | publisher/middleware.py | publisher/middleware.py | from threading import current_thread
class PublisherMiddleware(object):
_draft_status = {}
@staticmethod
def is_draft(request):
authenticated = request.user.is_authenticated() and request.user.is_staff
is_draft = 'edit' in request.GET and authenticated
return is_draft
def pro... | from threading import current_thread
class PublisherMiddleware(object):
_draft_status = {}
@staticmethod
def is_draft(request):
authenticated = request.user.is_authenticated() and request.user.is_staff
is_draft = 'edit' in request.GET and authenticated
return is_draft
def pro... | Remove unecessary try.. except.. block from PublisherMiddleware.process_response(). | Remove unecessary try.. except.. block from PublisherMiddleware.process_response().
The key should always be set by process_request(), which should always be called
before process_response().
| Python | bsd-3-clause | wearehoods/django-model-publisher-ai,wearehoods/django-model-publisher-ai,jp74/django-model-publisher,jp74/django-model-publisher,wearehoods/django-model-publisher-ai,jp74/django-model-publisher |
8774517714c8c8a7f7a2be9316a23497adfa9f59 | pi_gpio/urls.py | pi_gpio/urls.py | from pi_gpio import app, socketio
from flask.ext import restful
from flask import render_template
from handlers import PinList, PinDetail
api = restful.Api(app)
api.add_resource(PinList, '/api/v1/pin')
api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>')
import RPi.GPIO as GPIO
def event_callback(pin):
... | from pi_gpio import app, socketio
from flask.ext import restful
from flask import render_template
from handlers import PinList, PinDetail
from events import PinEventManager
api = restful.Api(app)
api.add_resource(PinList, '/api/v1/pin')
api.add_resource(PinDetail, '/api/v1/pin/<string:pin_num>')
@app.route('/', def... | Call event manager in index route | Call event manager in index route
| Python | mit | projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server |
5a36bfb8bb8eceab57203387072f3bf492b2a418 | src/onixcheck/exeptions.py | src/onixcheck/exeptions.py | # -*- coding: utf-8 -*-
class OnixError(Exception):
pass
| # -*- coding: utf-8 -*-
import logging
class OnixError(Exception):
pass
class NullHandler(logging.Handler):
"""Not in python 2.6 so we use our own"""
def emit(self, record):
pass
def get_logger(logger_name='onixcheck', add_null_handler=True):
logger = logging.getLogger(logger_name)
if... | Add NullHandler to silence errors when logging without configuration | Add NullHandler to silence errors when logging without configuration
| Python | bsd-2-clause | titusz/onixcheck |
8ab254490dac4f4ebfed1f43d615c321b5890e29 | xmlrpclib_to/__init__.py | xmlrpclib_to/__init__.py | try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbos... | try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbos... | FIX working with HTTPS correctly | FIX working with HTTPS correctly
| Python | mit | gisce/xmlrpclib-to |
4348927a9ed5bdcbf0284086103e927f45091e15 | saau/utils/header.py | saau/utils/header.py | import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag for thing in xml_line.getiterator(... | import numpy as np
from lxml.etree import fromstring, XMLSyntaxError
def parse_lines(lines):
for line in lines:
try:
xml_line = fromstring(line.encode('utf-8'))
except XMLSyntaxError:
attrs = []
else:
attrs = [thing.tag for thing in xml_line.getiterator(... | Clean up y index generation | Clean up y index generation
| Python | mit | Mause/statistical_atlas_of_au |
ebd6d12ca16003e771a7015505be1b42d96483a3 | roles/gvl.commandline-utilities/templates/jupyterhub_config.py | roles/gvl.commandline-utilities/templates/jupyterhub_config.py | # Configuration file for jupyterhub.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# JupyterHub... | # Configuration file for jupyterhub.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# JupyterHub... | Set log level to 'WARN' | Set log level to 'WARN' | Python | mit | gvlproject/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,gvlproject/gvl_commandline_utilities |
9676024c92348ed52c78620f2a8b0b4cd104430d | location.py | location.py | # -*- coding: utf-8 -*-
"""
location.py
"""
from trytond.pool import PoolMeta
from trytond.model import fields
from trytond.pyson import Eval
__all__ = ['Location']
__metaclass__ = PoolMeta
class Location:
__name__ = "stock.location"
return_address = fields.Many2One(
"party.address", "Return Ad... | # -*- coding: utf-8 -*-
"""
location.py
"""
from trytond.pool import PoolMeta
from trytond.model import fields
from trytond.pyson import Eval
__all__ = ['Location']
__metaclass__ = PoolMeta
class Location:
__name__ = "stock.location"
return_address = fields.Many2One(
"party.address", "Return Ad... | Rename help text of return address field | Rename help text of return address field
| Python | bsd-3-clause | joeirimpan/trytond-shipping,trytonus/trytond-shipping,fulfilio/trytond-shipping,prakashpp/trytond-shipping,tarunbhardwaj/trytond-shipping |
783948e6d5ce9f4a8cbdbecd4731615381ca89c0 | scripts/set_alpha.py | scripts/set_alpha.py | #!/usr/bin/env python
import sys
alpha_deg = sys.argv[1]
with open("system/fvOptions", "w") as f:
with open("system/fvOptions.template") as template:
txt = template.read()
f.write(txt.format(alpha_deg=alpha_deg))
| #!/usr/bin/env python
import sys
if len(sys.argv) > 1:
alpha_deg = sys.argv[1]
else:
alpha_deg = 4.0
with open("system/fvOptions", "w") as f:
with open("system/fvOptions.template") as template:
txt = template.read()
f.write(txt.format(alpha_deg=alpha_deg))
| Add a default angle of attack | Add a default angle of attack
| Python | mit | petebachant/actuatorLine-2D-turbinesFoam,petebachant/actuatorLine-2D-turbinesFoam,petebachant/actuatorLine-2D-turbinesFoam |
a7b92bdbb4c71a33896105022e70c69c3bc33861 | patterns/gradient.py | patterns/gradient.py | from blinkytape import color
class Gradient(object):
def __init__(self, pixel_count, start_color, end_color):
self._pixels = self._rgb_gradient(pixel_count, start_color, end_color)
@property
def pixels(self):
return list(self._pixels)
def _rgb_gradient(self, pixel_count, start_color, ... | from blinkytape import color
class Gradient(object):
# TBD: If this had a length it would also work as a streak; consider
def __init__(self, pixel_count, start_color, end_color):
self._pixels = self._rgb_gradient(pixel_count, start_color, end_color)
@property
def pixels(self):
return l... | Add another TBD for future reference | Add another TBD for future reference
| Python | mit | jonspeicher/blinkyfun |
9e9910346f7bacdc2a4fc2e92ecb8237bf38275e | plumbium/environment.py | plumbium/environment.py | """
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (i... | """
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (i... | Stop pylint complaining about bare-except | Stop pylint complaining about bare-except
| Python | mit | jstutters/Plumbium |
ed5dcd72b661878913be224d641c5595c73ef049 | tests/test_auditory.py | tests/test_auditory.py | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
... | Test of the erb calculation | Test of the erb calculation
| Python | bsd-3-clause | achabotl/pambox |
721f18da4d38ac76171165596bc11e2572c60204 | algebra.py | algebra.py | """
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (int(x),
int(math.cos(theta) * y - math.sin(theta) * z),
int(math.sin(theta) * y + math... | """
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (round(x, 1),
round(math.cos(theta) * y - math.sin(theta) * z, 1),
round(math.sin(theta... | Fix bug where vector calculations returned Ints only | Fix bug where vector calculations returned Ints only
| Python | mit | supermitch/clipycube |
9f82fe03a38d9eaf4ccd22f2ee6d13907bc3b42e | relay_api/api/server.py | relay_api/api/server.py | from flask import Flask, jsonify
server = Flask(__name__)
def get_relays(relays):
return jsonify({"relays": relays}), 200
def get_relay(relays, relay_name):
code = 200
try:
relay = relays[relay_name]
except KeyError:
code = 404
return "", code
return jsonify({"relay": r... | from flask import Flask, jsonify
# import json
server = Flask(__name__)
def __serialize_relay(relays):
if type(relays).__name__ == "relay":
return jsonify({"gpio": relays.gpio,
"NC": relays.nc,
"state": relays.state})
di = {}
for r in relays:
... | Change to get a dict with the relay instances | Change to get a dict with the relay instances
| Python | mit | pahumadad/raspi-relay-api |
967a82011c2a8e154c8386dfd0499dc5cea06da1 | sheldon/bot.py | sheldon/bot.py | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
class Sheldon:
"""
Main ... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | Add load config function to Sheldon class | Add load config function to Sheldon class
| Python | mit | lises/sheldon |
b07f4997b72702023721786de425533db38b5867 | vsub/urls.py | vsub/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
# See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
# See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
admin.auto... | Set the default URL to point to index.html. | Set the default URL to point to index.html.
| Python | mit | PrecisionMojo/pm-www,PrecisionMojo/pm-www |
b8796c355bc8a763dbd2a5b6c5ed88a61f91eab7 | tests/test_conditionals.py | tests/test_conditionals.py | import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unc... | import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unc... | Update conditional else branch tests | Update conditional else branch tests
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
d2444e557e097f375ee830ebf382d68b702b80da | src/ansible/forms.py | src/ansible/forms.py | from django import forms
from django.conf import settings
from django.forms import ModelForm
from ansible.models import Playbook
class AnsibleForm1(ModelForm):
class Meta:
model = Playbook
fields = ['repository', 'username']
class AnsibleForm2(ModelForm):
class Meta:
model = Playbook
... | from django import forms
from django.conf import settings
from django.forms import ModelForm
from ansible.models import Playbook
class AnsibleForm1(ModelForm):
class Meta:
model = Playbook
fields = ['repository', 'username']
class AnsibleForm2(ModelForm):
class Meta:
model = Playbook
... | Set Textarea width and height | Set Textarea width and height
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin |
a4f09620d8939aa8141b39972fb49d82f5380875 | src/build/console.py | src/build/console.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
import datetime
start_time = 0
def start_timer():
global start_time
start_time = int(round(time.ti... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import time
import datetime
start_time = 0
def start_timer():
global start_time
start_time = int(round(time.ti... | Add colored time in output | Add colored time in output
| Python | mpl-2.0 | seleznev/firefox-complete-theme-build-system |
9ceace60593f133b4f6dfdbd9b6f583362415294 | src/configuration.py | src/configuration.py | import ConfigParser
import os
def class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self)
"""Open the configuration files handler, choosing the right
path depending o... | import ConfigParser
import os
class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self):
"""Open the configuration files handler, choosing the right
path depend... | Fix a few syntax errors | Fix a few syntax errors
| Python | agpl-3.0 | MichelJuillard/dlstats,Widukind/dlstats,mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,MichelJuillard/dlstats |
4298e82a3dc4c6577b41b4acbb73ff7bb5795002 | src/django_registration/backends/one_step/views.py | src/django_registration/backends/one_step/views.py | """
A one-step (user signs up and is immediately active and logged in)
workflow.
"""
from django.contrib.auth import authenticate, get_user_model, login
from django.urls import reverse_lazy
from django_registration import signals
from django_registration.views import RegistrationView as BaseRegistrationView
User =... | """
A one-step (user signs up and is immediately active and logged in)
workflow.
"""
from django.contrib.auth import authenticate, get_user_model, login
from django.urls import reverse_lazy
from django_registration import signals
from django_registration.views import RegistrationView as BaseRegistrationView
User =... | Make the one-step backend a little more robust with custom users. | Make the one-step backend a little more robust with custom users.
| Python | bsd-3-clause | ubernostrum/django-registration |
76ed0bb6415209aa28350d4304e7b87715ba37f5 | qllr/templating.py | qllr/templating.py | import typing
from jinja2 import Undefined, contextfunction, escape
from starlette.templating import Jinja2Templates
def render_ql_nickname(nickname):
nickname = str(escape(nickname))
for i in range(8):
nickname = nickname.replace(
"^" + str(i), '</span><span class="qc' + str(i) + '">'
... | import typing
from urllib.parse import ParseResult, urlparse
from jinja2 import Undefined, contextfunction, escape
from starlette.templating import Jinja2Templates
def render_ql_nickname(nickname):
nickname = str(escape(nickname))
for i in range(8):
nickname = nickname.replace(
"^" + str(... | Make templates to return relative path | Make templates to return relative path
| Python | agpl-3.0 | em92/quakelive-local-ratings,em92/pickup-rating,em92/quakelive-local-ratings,em92/quakelive-local-ratings,em92/quakelive-local-ratings,em92/pickup-rating,em92/pickup-rating,em92/quakelive-local-ratings |
240d4d33dc6570c957ce568a952a1a282dc50736 | opps/article/views.py | opps/article/views.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwa... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from opps.article.models import Post
class OppsList(ListView):
context_object_name = "context"
@property
def template_name(self):
long_slug = self.kwa... | Fix template name on entry home page (/) on detail page | Fix template name on entry home page (/) on detail page
| Python | mit | williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps |
e68b0f10cd2dcbeade127ca3c2a30408595e9ecb | ownership/__init__.py | ownership/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
def health(self):
try:
with self.engine.connect() as c:
c.execute('select 1=1').fetchall()
return True... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
def health(self):
try:
with self.engine.con... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/ownership-alpha,LandRegistry/ownership-alpha,LandRegistry/ownership-alpha |
6947a38fd99447809870d82a425abd4db9d884fe | test/htmltoreadable.py | test/htmltoreadable.py | # -*- coding: utf-8 -*-
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.css('.post_show')
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkd... | # -*- coding: utf-8 -*-
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(pat... | Delete using deprecated fnc in test | Delete using deprecated fnc in test
| Python | mit | shigarus/NewsParser |
2dad35a7fb6f4daa80b7f760889013fd8eb54753 | examples/drawing/random_geometric_graph.py | examples/drawing/random_geometric_graph.py | import networkx as nx
import matplotlib.pyplot as plt
G=nx.random_geometric_graph(200,0.125)
pos=G.pos # position is stored as member data for random_geometric_graph
# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter=n
dmi... | import networkx as nx
import matplotlib.pyplot as plt
G=nx.random_geometric_graph(200,0.125)
# position is stored as node attribute data for random_geometric_graph
pos=nx.get_node_attributes(G,'pos')
# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
x,y=pos[n]
d=(x-0.5)**2+(y-0.5)**2
if d<d... | Update exmple for node position in new RGG interface. | Update exmple for node position in new RGG interface.
| Python | bsd-3-clause | blublud/networkx,nathania/networkx,jni/networkx,ghdk/networkx,RMKD/networkx,ionanrozenfeld/networkx,kai5263499/networkx,bzero/networkx,dmoliveira/networkx,kernc/networkx,SanketDG/networkx,RMKD/networkx,jni/networkx,debsankha/networkx,jakevdp/networkx,kai5263499/networkx,wasade/networkx,chrisnatali/networkx,yashu-seth/n... |
3f025b5400c0855472a772487de8930bac9b5eef | numpy/setupscons.py | numpy/setupscons.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numpy',parent_package,top_path, setup_name = 'setupscons.py')
config.add_subpackage('distutils')
config.add_subpackage('testing')
config.add_subpacka... | #!/usr/bin/env python
from os.path import join as pjoin
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.misc_util import scons_generate_config_py
pkgname = 'numpy'
config = Configuration(pkgname,parent_package,top_path, setup... | Handle inplace generation of __config__. | Handle inplace generation of __config__.
| Python | bsd-3-clause | rhythmsosad/numpy,numpy/numpy,grlee77/numpy,ViralLeadership/numpy,mattip/numpy,chiffa/numpy,numpy/numpy-refactor,numpy/numpy-refactor,bmorris3/numpy,joferkington/numpy,ekalosak/numpy,mindw/numpy,madphysicist/numpy,matthew-brett/numpy,BMJHayward/numpy,stefanv/numpy,WillieMaddox/numpy,solarjoe/numpy,rajathkumarmp/numpy,m... |
1c1d2b1dfba2fbf02a642da516119a1e280a4bc3 | account_invoice_merge/__openerp__.py | account_invoice_merge/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2011 Elico Corp. All Rights Reserved.
# Author: Ian Li <ian.li@elico-corp.com>
#
# This program is free software: you can redistribute it a... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2011 Elico Corp. All Rights Reserved.
# Author: Ian Li <ian.li@elico-corp.com>
#
# This program is free software: you can redistribute it a... | Add OCA as author of OCA addons | Add OCA as author of OCA addons
In order to get visibility on https://www.odoo.com/apps the OCA board has
decided to add the OCA as author of all the addons maintained as part of the
association.
| Python | agpl-3.0 | OCA/account-invoicing,OCA/account-invoicing |
66cc5b8ecae568c3a20948718ef2d4f162cfd786 | test/test_pycompile.py | test/test_pycompile.py | """
Test the high-level compile function
"""
import unittest
from six import StringIO
from lesscpy import compile
class TestCompileFunction(unittest.TestCase):
"""
Unit tests for compile
"""
def test_compile(self):
"""
It can compile input from a file-like object
"""
... | """
Test the high-level compile function
"""
import unittest
from six import StringIO
from lesscpy import compile
class TestCompileFunction(unittest.TestCase):
"""
Unit tests for compile
"""
def test_compile(self):
"""
It can compile input from a file-like object
"""
... | Add test if compile() raises an CompilationError | Add test if compile() raises an CompilationError
| Python | mit | lesscpy/lesscpy,fivethreeo/lesscpy,joequery/lesscpy |
3febcda544f372af01e9d2138c131f103ed45455 | app/soc/mapreduce/delete_gci_data.py | app/soc/mapreduce/delete_gci_data.py | # Copyright 2013 the Melange authors.
#
# 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 wr... | # Copyright 2013 the Melange authors.
#
# 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 wr... | Update the docstring for the mapper to reflect what it does correctly. | Update the docstring for the mapper to reflect what it does correctly.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son |
d98a2f8944c9b1ba6ef587b496987316c33488e5 | sample-settings.py | sample-settings.py | SECRET_KEY = 'Set the secret_key to something unique and secret.'
CLIENT_ID = 'xxxxxxx'
CLIENT_SECRET = 'yyyyyyyyyyyyyyyyyy'
| SECRET_KEY = 'Set the secret_key to something unique and secret.'
CLIENT_ID = 'xxxxxxx'
CLIENT_SECRET = 'yyyyyyyyyyyyyyyyyy'
LOG_FILENAME = 'dump'
| Add log filename to sample settings for tests. | Add log filename to sample settings for tests.
| Python | mit | punchagan/statiki,punchagan/statiki |
27035d6abba16fb06c8fa548385b33ab08bf787a | test/proper_noun_test.py | test/proper_noun_test.py |
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentance():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentance():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_... |
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentence():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentence():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_... | Add some more proper noun tests | Add some more proper noun tests
Fixes #35.
| Python | mit | ejh243/MunroeJargonProfiler,ejh243/MunroeJargonProfiler |
8e362baea40a6b11140a93c13fc60c4c0d1ba577 | scuole/core/utils.py | scuole/core/utils.py | # -*- coding: utf-8 -*-
import re
def string_replace(text, key_dict):
"""
A function to convert text in a string to another string if
it matches any of the keys in the provided pattern dictionary.
"""
rx = re.compile('|'.join(map(re.escape, key_dict)))
def one_xlat(match):
return key... | # -*- coding: utf-8 -*-
import re
def string_replace(text, key_dict):
"""
A function to convert text in a string to another string if
it matches any of the keys in the provided pattern dictionary.
Usage:
from core.utils import string_replace
KEY_DICT = {
'Isd': 'ISD',
}
s =... | Add usage section to docstring for string_replace | Add usage section to docstring for string_replace
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole |
72538db91eb722240bc23defd688f11356c54c25 | scripts/balance.py | scripts/balance.py | #!/usr/bin/env python
from __future__ import division, print_function
from multiprocessing import Pool
import numpy as np
import h5py
import cooler
import cooler.ice
N_CPUS = 5
if __name__ == '__main__':
# Compute a genome-wide balancing/bias/normalization vector
# *** assumes uniform binning ***
chunks... | #!/usr/bin/env python
from __future__ import division, print_function
from multiprocessing import Pool
import argparse
import numpy as np
import h5py
import cooler
import cooler.ice
N_CPUS = 5
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Compute a genome-wide balancing/bias/... | Add arg parser to balancing script | Add arg parser to balancing script
| Python | bsd-3-clause | mirnylab/cooler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.