Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Bump version: 0.0.20 -> 0.0.21 | # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.20",
description="""Parse shebangs and return their comp... | # /setup.py
#
# Installation and setup script for parse-shebang
#
# See /LICENCE.md for Copyright information
"""Installation and setup script for parse-shebang."""
from setuptools import find_packages, setup
setup(name="parse-shebang",
version="0.0.21",
description="""Parse shebangs and return their comp... |
Increase to version 0.3.11 due to TG-dev requiring it for ming support | from setuptools import setup, find_packages
import os
version = '0.3.10'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin... | from setuptools import setup, find_packages
import os
version = '0.3.11'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin... |
Remove this requirement as travis-ci doesnt understand it. | from setuptools import setup
setup(
name='qual',
version='0.1',
description='Calendar stuff',
url='http://github.com/jwg4/qual',
author='Jack Grahl',
author_email='jack.grahl@yahoo.co.uk',
license='Apache License 2.0',
packages=['qual'],
test_suite='nose.collector',
tests_requir... | from setuptools import setup
setup(
name='qual',
version='0.1',
description='Calendar stuff',
url='http://github.com/jwg4/qual',
author='Jack Grahl',
author_email='jack.grahl@yahoo.co.uk',
license='Apache License 2.0',
packages=['qual'],
test_suite='nose.collector',
tests_requir... |
Use only on task to have control and it is finished | from celery.task import task
from celery.task.sets import subtask
from rest_api.models import Url
from rest_api.backend import Request
#TODO: read long_url from memcache
#TODO: ensure with retry that if we made a resquest we have to save the result
#TODO: should we ensure that user are logged and have permission her... | from celery.task import task
from celery.task.sets import subtask
from rest_api.models import Url
from rest_api.backend import Request
#TODO: read long_url from memcache
#TODO: ensure with retry that if we made a resquest we have to save the result
#TODO: should we ensure that user are logged and have permission her... |
Increment version since the change from M2Crypto to cryptography is fairly significant | # Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | # Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
Apply a couple refinements to object name strategy. | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedOb... | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Hypothesis strategies useful for testing ``pykube``.
"""
from string import ascii_lowercase, digits
from pyrsistent import pmap
from hypothesis.strategies import builds, fixed_dictionaries, text, lists, sampled_from
from .. import NamespacedOb... |
Downgrade standard version of ImageMagick to a non-changing URL. | from spack import *
class Imagemagick(Package):
"""ImageMagick is a image processing library"""
homepage = "http://www.imagemagic.org"
url = "http://www.imagemagick.org/download/ImageMagick-6.8.9-10.tar.gz"
version('6.9.0-0', '2cf094cb86ec518fa5bc669ce2d21613')
version('6.8.9-10', 'aa050bf97... | from spack import *
class Imagemagick(Package):
"""ImageMagick is a image processing library"""
homepage = "http://www.imagemagic.org"
#-------------------------------------------------------------------------
# ImageMagick does not keep around anything but *-10 versions, so
# this URL may change.... |
Use open-ended dependency on six | from setuptools import setup
setup(
name='django-extra-views',
version='0.6.5',
url='https://github.com/AndrewIngram/django-extra-views',
install_requires=[
'Django >=1.3',
'six==1.5.2',
],
description="Extra class-based views for Django",
long_description=open('README.rst',... | from setuptools import setup
setup(
name='django-extra-views',
version='0.6.5',
url='https://github.com/AndrewIngram/django-extra-views',
install_requires=[
'Django >=1.3',
'six>=1.5.2',
],
description="Extra class-based views for Django",
long_description=open('README.rst',... |
Update the PyPI version to 7.0.14. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.13',
packages=['todoist', 'todoist.managers'],
author='Doist Team... | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.14',
packages=['todoist', 'todoist.managers'],
author='Doist Team... |
Update the project URL to point to github. | #!/usr/bin/env python
try:
from setuptools import setup
extra = dict(test_suite="tests.test.suite", include_package_data=True)
except ImportError:
from distutils.core import setup
extra = {}
long_description = \
'''
A python library for console-based raw input-based questions with answers and
extensiv... | #!/usr/bin/env python
try:
from setuptools import setup
extra = dict(test_suite="tests.test.suite", include_package_data=True)
except ImportError:
from distutils.core import setup
extra = {}
long_description = \
'''
A python library for console-based raw input-based questions with answers and
extensiv... |
Correct author to oemof developER group | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... |
Add some classifiers for pypi | from setuptools import setup
def getVersion():
f = open("sphinxarg/__init__.py")
_ = f.read()
ver = _.split("'")[1]
f.close()
return ver
setup(
name='sphinx-argparse',
version=getVersion(),
packages=[
'sphinxarg',
],
url='https://github.com/ribozz/sphinx-argparse',
... | from setuptools import setup
def getVersion():
f = open("sphinxarg/__init__.py")
_ = f.read()
ver = _.split("'")[1]
f.close()
return ver
setup(
name='sphinx-argparse',
version=getVersion(),
packages=[
'sphinxarg',
],
url='https://github.com/ribozz/sphinx-argparse',
... |
Set license and long description | from setuptools import setup
setup(
name='redis-url-py',
version='0.0.3',
url='https://github.com/Xopherus/redis-url-py',
license='BSD',
author='Chris Raborg',
author_email='craborg1@umbc.edu',
description='Use Redis URLs in your Python applications',
py_modules=['redis_url'],
zip_s... | #!/usr/bin/env python
import os
from setuptools import setup
LICENSE = open(
os.path.join(os.path.dirname(__file__), 'LICENSE')).read().strip()
DESCRIPTION = open(
os.path.join(os.path.dirname(__file__), 'README.md')).read().strip()
setup(
name='redis-url-py',
version='0.0.3',
url='https://github.... |
Tweak the way that on_production_server is determined | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... |
Add help message to cli tool | # -*- coding: utf-8 -*-
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '-... | # -*- coding: utf-8 -*-
65;5403;1c
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argumen... |
Use the array API types for the array API type annotations | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', '... |
Remove stray whitespace in test file | """Test FEI SEM image plugin functionality.
FEI TIFFs contain metadata as ASCII plaintext at the end of the file.
"""
from __future__ import unicode_literals
import os
import numpy as np
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import image... | """Test FEI SEM image plugin functionality.
FEI TIFFs contain metadata as ASCII plaintext at the end of the file.
"""
from __future__ import unicode_literals
import os
import numpy as np
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import image... |
Add so tags to ProductGroup entity | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = ('id', 'tag', 'description', 'url', 'image')
_api_key = No... | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = (
'id', 'tag', 'description', 'url', 'image', 'so_tags'... |
Make part task creation explicit | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transit... | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transit... |
Return file with correct mimetype | from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from pos... | from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from pos... |
Update the port to be an integer. | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
... | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
... |
Make this resembling more of production settings. | SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
SECRET_KEY = 'dummy - change me'
| DEBUG=False
SQLALCHEMY_DATABASE_URI = 'sqlite:///prod.db'
SECRET_KEY = 'dummy - change me'
|
Fix 'class DataverseFile' to handle old and new response format Tests were failing after swith to new server/version | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... | from __future__ import absolute_import
from dataverse.utils import sanitize
class DataverseFile(object):
def __init__(self, dataset, name, file_id=None):
self.dataset = dataset
self.name = sanitize(name)
self.id = file_id
self.download_url = '{0}/access/datafile/{1}'.format(
... |
Update code as commented, update readme. | # -*- coding:utf-8 -*-
##############################################################################
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | # -*- coding:utf-8 -*-
##############################################################################
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... |
Update script to use boto3 instead of boto2 | #!/usr/bin/env python
import boto
print 'Security group information:\n'
ec2 = boto.connect_ec2()
sgs = ec2.get_all_security_groups()
for sg in sgs:
instances = sg.instances()
print 'id: %s, name: %s, count: %s' % (sg.id, sg.name, len(instances))
for inst in instances:
tag_name = 'UNKNOWN'
... | #!/usr/bin/env python
import boto3
print 'Security group information:\n'
ec2 = boto3.resource('ec2')
sgs = ec2.security_groups.all()
for sg in sgs:
tag_name = sg.group_name
if sg.tags is not None:
for tag in sg.tags:
if tag['Key'] == 'Name' and tag['Value'] != '':
tag_name... |
Add DI to App object | #!/usr/bin/env python3
import argparse
from server import *
from commandRunner import *
class App:
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
def run(self):
runner = CommandRunner()
command = self.server.get()
while command is not None:
response = runner... | #!/usr/bin/env python3
import argparse
from server import *
from commandRunner import *
class App:
server = None
runner = None
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
self.runner = CommandRunner()
def run(self):
command = self.server.get()
while co... |
Tag builds in the correct order | """The services that can be shown on a Flash dashboard."""
from collections import OrderedDict
import logging
from uuid import uuid4
from flask import Blueprint
from .codeship import Codeship
from .github import GitHub
from .tracker import Tracker
from .travis import TravisOS
__author__ = 'Jonathan Sharpe'
__versio... | """The services that can be shown on a Flash dashboard."""
from collections import OrderedDict
import logging
from uuid import uuid4
from flask import Blueprint
from .codeship import Codeship
from .github import GitHub
from .tracker import Tracker
from .travis import TravisOS
__author__ = 'Jonathan Sharpe'
__versio... |
Add description on root route | import config
from flask import Flask, request
import json
import os
import requests
import modules
ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN)
VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', config.VERIFY_TOKEN)
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
... | import config
from flask import Flask, request
import json
import os
import requests
import modules
ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', config.ACCESS_TOKEN)
VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', config.VERIFY_TOKEN)
app = Flask(__name__)
@app.route('/')
def about():
return 'Just A Rather Very I... |
Move string above the import so it becomes a docstring | from __future__ import print_function, absolute_import, unicode_literals, division
""" Compatability module for different Python versions. """
try:
import unittest2 as unittest
except ImportError: # pragma: no cover
import unittest
try:
from ordereddict import OrderedDict
except ImportError: # pragma: n... | """ Compatability module for different Python versions. """
from __future__ import print_function, absolute_import, unicode_literals, division
try:
import unittest2 as unittest
except ImportError: # pragma: no cover
import unittest
try:
from ordereddict import OrderedDict
except ImportError: # pragma: n... |
Prepare first 2.0 alpha release | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU... | import sys
from setuptools import find_packages, setup
VERSION = '2.0a1'
install_requires = [
'django-local-settings>=1.0a13',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OI... |
Fix for dependencies using pip | #!/usr/bin/env python
from setuptools import setup
setup(name='igtdetect',
version='1.1.0',
description='Line-level classifier for IGT instances, part of RiPLEs pipeline.',
author='Ryan Georgi',
author_email='rgeorgi@uw.edu',
url='https://github.com/xigt/igtdetect',
scripts=['detect... | #!/usr/bin/env python
from setuptools import setup
setup(name='igtdetect',
version='1.1.1',
description='Line-level classifier for IGT instances, part of RiPLEs pipeline.',
author='Ryan Georgi',
author_email='rgeorgi@uw.edu',
url='https://github.com/xigt/igtdetect',
scripts=['detect... |
Throw more data into the autocomplete view. | from django.views.generic import View
from django.views.generic.base import TemplateView
from braces.views import AjaxResponseMixin, JSONResponseMixin
from haystack.query import SearchQuerySet
class SiteView(TemplateView):
template_name = 'landings/home_site.html'
class AutocompleteView(JSONResponseMixin, View... | from django.views.generic import View
from django.views.generic.base import TemplateView
from braces.views import AjaxResponseMixin, JSONResponseMixin
from haystack.query import SearchQuerySet
from haystack.inputs import AutoQuery, Exact, Clean
class SiteView(TemplateView):
template_name = 'landings/home_site.ht... |
Add imaginary fence list comprehension | # File: rail_fence_cipher.py
# Purpose: Implement encoding and decoding for the rail fence cipher.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Friday 30 September 2016, 08:35 PM
| # File: rail_fence_cipher.py
# Purpose: Implement encoding and decoding for the rail fence cipher.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Friday 30 September 2016, 08:35 PM
class Rail():
"""Implementation of Rail Fence Cipher."""
def __init__(self, text, rail_count):
... |
Use BulkText instead of Text in input keyword | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""Writes text to a textbox.
... | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""Writes text to a textbox.
... |
Add cppcheck issue id as code field | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}: {severity}: {message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\... | from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
cmd = (
'cppcheck',
'--template={file}:{line}:{column}:{severity}:{id}:{message}',
'--inline-suppr',
'--quiet',
'${args}',
'${file}'
)
regex = (
r'^(?P<file>(:\\|[^:])+):(?P<line>\d+... |
Fix QDataStream <</>> QPixmap test | # -*- coding: utf-8 -*-
import unittest
import sys
from PySide import QtGui, QtCore
class QAppPresence(unittest.TestCase):
def testQPixmap(self):
ds = QtCore.QDataStream()
p = QtGui.QPixmap()
ds << p
ds >> p
if __name__ == '__main__':
app = QtGui.QApplication([])
unitte... | # -*- coding: utf-8 -*-
import unittest
import sys
from PySide.QtCore import QDataStream, QByteArray, QIODevice, Qt
from PySide.QtGui import QPixmap, QColor
from helper import UsesQApplication
class QPixmapQDatastream(UsesQApplication):
'''QDataStream <<>> QPixmap'''
def setUp(self):
super(QPixmapQ... |
Support for Django > 1.4 for test proj | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'do... | try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),... |
Add Apache 2.0 license to source file | #!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False')
| #!/usr/bin/env python
# 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, so... |
Fix java.nio.file import in AutoCloseable example | import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._... | import jpype
class Thread:
""" Thread support for Python
JPype adds methods to ``java.lang.Thread`` to interact with
Python threads. These methods are all classmethods that
act on the current Python thread.
"""
isAttached = jpype._jthread._JThread.isAttached
attach = jpype._jthread._... |
Remove a test that is no longer relevant | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_request(self, mock_req):
client.request('123', 'lorem ipsum', 'GET')
mock_req.assert_cal... | import json
from django.conf import settings
from django.test import TestCase
from go.api.go_api import client
from mock import patch
class ClientTestCase(TestCase):
@patch('requests.request')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc')
mock_re... |
Add scikit-image to test header information | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... |
Index action ready with "Hello, World!" message | from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
| from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return 'Hello World!'
if __name__ == '__main__':
app.run()
|
Refactor Heroku tests to have shared setup | """Tests for the Wallace API."""
import subprocess
import re
import requests
class TestHeroku(object):
"""The Heroku test class."""
def test_sandbox(self):
"""Launch the experiment on Heroku."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox... | """Tests for the Wallace API."""
import subprocess
import re
import os
import requests
class TestHeroku(object):
"""The Heroku test class."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
os.environ['app_id'] = re.search(
'... |
Add timestamp to link too | import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id']
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOME... | import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
# Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
# 20 seconds for how long the actual event is...
linkts = timestamp - 45
... |
Create and redirect to Tag in tag_create(). | from django.shortcuts import (
get_object_or_404, render)
from .forms import TagForm
from .models import Startup, Tag
def startup_detail(request, slug):
startup = get_object_or_404(
Startup, slug__iexact=slug)
return render(
request,
'organizer/startup_detail.html',
{'star... | from django.shortcuts import (
get_object_or_404, redirect, render)
from .forms import TagForm
from .models import Startup, Tag
def startup_detail(request, slug):
startup = get_object_or_404(
Startup, slug__iexact=slug)
return render(
request,
'organizer/startup_detail.html',
... |
Change custom theme settings and url pattern | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Leonardo Zhou'
SITENAME = u'\u4e91\u7ffc\u56fe\u5357'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = Non... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Leonardo Zhou'
SITENAME = u'\u4e91\u7ffc\u56fe\u5357'
SITEURL = ''
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = u'zh'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = Non... |
Make the API not use trailing slashes. This is what Ember expects. | """lcp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... | """lcp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
Add loop, allowing several tests. | import json
#from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp
import jsonrpclib
class StanfordNLP:
def __init__(self, port_number=8080):
self.server = jsonrpclib.Server("http://localhost:%d" % port_number)
def parse(self, text):
return json.loads(self.server.parse(text))
nlp = Stanf... | import json
#from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp
import jsonrpclib
import fileinput
class StanfordNLP:
def __init__(self, port_number=8080):
self.server = jsonrpclib.Server("http://localhost:%d" % port_number)
def parse(self, text):
return json.loads(self.server.parse(te... |
Add author info to package config | #!/usr/bin/env python
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
url='http://compmusic.upf.edu',
install_requires=[... | #!/usr/bin/env python
from setuptools import setup, find_packages
import versioneer
setup(name='pycompmusic',
version=versioneer.get_version(),
description='Tools for playing with the compmusic collection',
author='CompMusic / MTG UPF',
author_email='compmusic@upf.edu',
url='http://comp... |
Update do version 0.1.1 which should hopefully trigger automatic pypi deployment | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-game-info',
version='0.1',
... | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-game-info',
version='0.1.1'... |
Add service functions to create a party setting and to obtain one's value | """
byceps.services.party.settings_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ...typing import PartyID
from .models.setting import Setting as DbSetting
from .transfer.models import Pa... | """
byceps.services.party.settings_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ...database import db
from ...typing import PartyID
from .models.setting import Setting as DbSetting
from... |
Fix exception syntax for Python3. | """
Filter submodule for libhxl.
David Megginson
Started February 2015
License: Public Domain
Documentation: https://github.com/HXLStandard/libhxl-python/wiki
"""
import sys
from hxl import HXLException
from hxl.model import HXLDataProvider, HXLColumn
class HXLFilterException(HXLException):
pass
def run_script(... | """
Filter submodule for libhxl.
David Megginson
Started February 2015
License: Public Domain
Documentation: https://github.com/HXLStandard/libhxl-python/wiki
"""
import sys
from hxl import HXLException
from hxl.model import HXLDataProvider, HXLColumn
class HXLFilterException(HXLException):
pass
def run_script(... |
Handle None for org or file with default org name | import logging
import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
... | import logging
import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
... |
Add a check if the target output directories exist | #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
cmd = [cyclus, ... | #! /usr/bin/env python
import os
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
# ma... |
Add HTML fragment to test sample | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки."
def setUp(self):
from paka.cmark import to_html
self.func = to_html
def check(self, source, expe... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
class ToHTMLTest(unittest.TestCase):
SAMPLE = (
"Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n"
"<p>Test of <em>HTML</em>.</p>")
def setUp(self):
from paka.cmark import to_html
... |
Add ALLOWED_HOSTS on staging server settings | DEBUG = False
ENVIRONMENT = "staging"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
| DEBUG = False
ENVIRONMENT = "staging"
ALLOWED_HOSTS = ('dev.lutris.net',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'lutris_staging',
'USER': 'lutris_staging',
'PASSWORD': 'admin'
}
}
|
Format messages in stream handler | from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--tabl... | from argparse import ArgumentParser
import logging
from . import run_server
from .handlers import SQLiteHandler
parser = ArgumentParser(
description="Run a standalone log server using a SQLite database.")
parser.add_argument("-p", "--port", default=9123, help="Port to listen on")
parser.add_argument("-t", "--tabl... |
Sort ignored packages when adding native PHP package | import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.g... | import sublime
def plugin_loaded():
# Native package causes some conflicts.
# Thanks https://github.com/SublimeText-Markdown/MarkdownEditing
disable_native_php_package()
def disable_native_php_package():
settings = sublime.load_settings('Preferences.sublime-settings')
ignored_packages = settings.g... |
Fix setup.py for installs without Django | from __future__ import absolute_import
from .utils import *
VERSION = (0, 5,)
| from __future__ import absolute_import
# this is required for setup.py to work
try:
from .utils import *
except ImportError:
pass
VERSION = (0, 5, 1,)
|
Set the overworld as the default level again. | from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Cliff]
#return [Overworld, Cliff]
| from thecure.levels.base import *
from thecure.levels.cliff import Cliff
from thecure.levels.overworld import Overworld
def get_levels():
return [Overworld, Cliff]
|
Add a start and end method to MockRequest | #!/usr/bin/python2.5
#
# Copyright 2008 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... | #!/usr/bin/python2.5
#
# Copyright 2008 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... |
Make it harder to accidentally empty the database | """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all")
def clear_all():
mongo = current_app.mongo
mongo.db.userSessions.remove()
mongo.db.interactionSessions.remove()
return redirect(ur... | """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for, request
debug_pages = Blueprint('debug', __name__)
@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
if request.method == 'GET':
return '<form method="POST"><input type="submit" value=... |
Add the ModelComponentSets to the number of subcomponents. | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printC... | import os
import unittest
import opensim as osim
test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
'tests')
# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)
class TestComponentInterface(unittest.TestCase):
def test_printC... |
Add delay after listener start (for testing) | from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(setting... | from common.bounty import *
from common.peers import *
from common import settings
from time import sleep
from common.safeprint import safeprint
def main():
settings.setup()
try:
import miniupnpc
except:
settings.config['outbound'] = True
safeprint("settings are:")
safeprint(setting... |
Fix rout for diary/event, argument has to be item_id | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', ... | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'devlol.views.index'),
# Static Stuff
url(r'^location/$', 'devlol.views.location'),
url(r'^mail/$', 'devlol.views.mail'),
# Diary Stuff
url(r'^diary/$', ... |
Fix date for generate secure_key | # 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 logic around lost connection. | """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 ... |
Insert main body of code into function | 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... |
Add data files for KuModel to package data | #! /usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='permamodel',
version='0.1.0',
author='Elchin Jafarov and Scott Stewart',
author_email='james.stewart@colorado.edu',
description='Permamodel',
long_descripti... | #! /usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name='permamodel',
version='0.1.0',
author='Elchin Jafarov and Scott Stewart',
author_email='james.stewart@colorado.edu',
description='Permamodel',
long_descripti... |
Move to rc1. Figuring this out. |
from setuptools import setup
setup(
name='exp_sdk',
packages= ['exp_sdk'],
version='1.0.0a2',
description='EXP Python SDK',
author='Scala',
author_email='james.dalessio@scala.com',
url='https://github.com/scalainc/exp-python2-sdk',
download_url='https://github.com/scalainc/exp-python2-sdk/tarball/1.0.... |
from setuptools import setup
setup(
name='exp_sdk',
packages= ['exp_sdk'],
version='1.0.0rc1',
description='EXP Python SDK',
author='Scala',
author_email='james.dalessio@scala.com',
url='https://github.com/scalainc/exp-python2-sdk',
download_url='https://github.com/scalainc/exp-python2-sdk/tarball/1.0... |
Update for vim plugin changes | 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... |
Refactor script to clean up code a bit. | #!/usr/bin/env python3
"""Get a markdown-formatted list of PRs merged since a certain tag."""
import github_tools
Repo = github_tools.get_repo()
# TODO: implement getting date from repo tag./
tagname = '0.8.1'
tags = Repo.get_tags()
for t in tags:
if t.name == tagname:
startdate = t.commit.commit.commit... | #!/usr/bin/env python3
"""Get a markdown-formatted list of PRs merged since a certain tag."""
import github_tools
Repo = github_tools.get_repo()
# TODO: implement getting date from repo tag.
tagname = '0.8.1'
tags = Repo.get_tags()
for t in tags:
if t.name == tagname:
startdate = t.commit.commit.committ... |
Send user id and token | """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_... |
Enable building hybrid capsule/non-capsule packages (CNY-3271) | #
# 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/... |
Revert "Added configuration options for Redis" | 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... |
Make create_crontab fall back to default settings search before explicitly searching for DJANGO_SETTINGS_MODULE | 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... |
Use raw ID fields for users, organizations | 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... |
Fix an unreferenced module bug | 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()
... |
Allow alpha versions in the versioning string | __version_info__ = (0, 1, 1)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (0, 1, 1, 'a1')
__version__ = '.'.join(map(str, __version_info__[:3]))
if len(__version_info__) == 4:
__version__ += __version_info__[-1]
|
Fix the manifest.load call in the test runner. | import imp
import json
import os
import sys
here = os.path.dirname(__file__)
localpaths = imp.load_source("localpaths", os.path.abspath(os.path.join(here, os.pardir, "localpaths.py")))
root = localpaths.repo_root
import manifest
def main(request, response):
path = os.path.join(root, "MANIFEST.json")
manifes... | import imp
import json
import os
import sys
here = os.path.dirname(__file__)
localpaths = imp.load_source("localpaths", os.path.abspath(os.path.join(here, os.pardir, "localpaths.py")))
root = localpaths.repo_root
import manifest
def main(request, response):
path = os.path.join(root, "MANIFEST.json")
manifes... |
Add BzTar and EGG format to Fabric script | from fabric.api import local, cd
def docs():
local("./bin/docs")
local("./bin/python setup.py upload_sphinx --upload-dir=docs/html")
def release():
# update version id in setup.py, changelog and docs/source/conf.py
local("python setup.py sdist --formats=gztar,zip upload")
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fabric.api import local, cd
def docs():
local("./bin/docs")
local("./bin/python setup.py upload_sphinx --upload-dir=docs/html")
def release():
"""Update version id in setup.py, changelog and docs/source/conf.py."""
local(("python setup.py bdist_e... |
Fix router details's name empty and change inheritance project table | # Copyright 2012 NEC Corporation
#
# 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 ag... | # Copyright 2012 NEC Corporation
#
# 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 ag... |
Add command to mock some db data | import os
import unittest
from flask.ext.script import Manager
from server import app
from server.models import db
manager = Manager(app)
@manager.command
def init_db():
""" Initialize database: drop and create all columns """
db.drop_all()
db.create_all()
@manager.command
def test():
tests_path ... | import os
import unittest
from flask.ext.script import Manager
from server import app
from server.models import db
from server.models import Lecturer, Course, Lecture, Comment
manager = Manager(app)
@manager.command
def init_db():
""" Initialize database: drop and create all columns """
db.drop_all()
... |
Define proxy function for course specific tracking logs | """
In this module we define the interface between the cli input provided
by the user and the analytics required by the user
"""
from edx_data_research import parsing
from edx_data_research import reporting
def cmd_report_basic(args):
"""
Run basic analytics
"""
edx_obj = reporting.Basic(args)
geta... | """
In this module we define the interface between the cli input provided
by the user and the analytics required by the user
"""
from edx_data_research import parsing
from edx_data_research import reporting
def cmd_report_basic(args):
"""
Run basic analytics
"""
edx_obj = reporting.Basic(args)
geta... |
Add instruction for returning a value | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]),
pyte.tokens.RETURN_VALUE... | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
bc = [pyte.ops.CALL_FUNCTION(names[0], consts[1]),
pyte.ops.END_FUNCTION(con... |
Change call signature of hav to 2 pairs | from math import sin, cos, asin, sqrt
def hav(lona, lonb, lata, latb):
# ported from latlontools
# assume latitude and longitudes are in radians
diff_lat = lata - latb
diff_lon = lona - lonb
a = sin(diff_lat/2)**2 + cos(lona) * cos(latb) * sin(diff_lon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # radius of earth in... | from math import sin, cos, asin, sqrt
def hav(lonlata, lonlatb):
# ported from latlontools
# assume latitude and longitudes are in radians
lona = lonlata[0]
lata = lonlata[1]
lonb = lonlatb[0]
latb = lonlatb[1]
diff_lat = lata - latb
diff_lon = lona - lonb
a = sin(diff_lat/2)**2 + cos(lona) * cos(latb) * ... |
Disable live tests by default | """
Tests run against live mail providers.
These aren't generally run as part of the test suite.
"""
import os
import pytest
from aiosmtplib import SMTP, SMTPAuthenticationError, SMTPStatus
pytestmark = [
pytest.mark.skipif(
os.environ.get("CI") == "true",
reason="No tests against real servers ... | """
Tests run against live mail providers.
These aren't generally run as part of the test suite.
"""
import os
import pytest
from aiosmtplib import SMTP, SMTPAuthenticationError, SMTPStatus
pytestmark = [
pytest.mark.skipif(
os.environ.get("AIOSMTPLIB_LIVE_TESTS") != "true",
reason="No tests ag... |
Remove useless conversion in remove row code | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRo... | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRo... |
Add dependencies to contenttypes to the migration | # encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | # encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth', '__first__'),
('contenttypes', '_... |
Change how console_scripts is invoked | from setuptools import setup
import sys
try:
from PyQt4.QtCore import QT_VERSION_STR
except ImportError:
sys.exit("PyQt4 is required to install this package (see README.md for installation instructions)")
setup(
name = "wethepeopletoolkit",
version = "1.3",
author = "Alex Peattie",
author_email = "me@alex... | from setuptools import setup
import sys
try:
from PyQt4.QtCore import QT_VERSION_STR
except ImportError:
sys.exit("PyQt4 is required to install this package (see README.md for installation instructions)")
setup(
name = "wethepeopletoolkit",
version = "1.4",
author = "Alex Peattie",
author_email = "me@alex... |
Remove 3rd package required version | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='ptwit',
version='0.0.9',
description='A simple twitter command line client',
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='ptwit',
version='0.0.9',
description='A simple twitter command line client',
... |
Remove textile requirement from install_requires | from setuptools import setup, find_packages
setup(
name='django-timepiece',
version=__import__('timepiece').__version__,
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=find_packages(exclude=['example_project']),
include_package_data=True,
url='https://g... | from setuptools import setup, find_packages
setup(
name='django-timepiece',
version=__import__('timepiece').__version__,
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=find_packages(exclude=['example_project']),
include_package_data=True,
url='https://g... |
Add ability to download a random file with a given size from any domain. | #!/usr/bin/python2.4
#
# Copyright 2014 Google Inc. All Rights Reserved.
"""WebRTC Test
This module serves the WebRTC Test Page.
"""
import cgi
import logging
import os
import jinja2
import webapp2
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class MainPage... | #!/usr/bin/python2.4
#
# Copyright 2014 Google Inc. All Rights Reserved.
"""WebRTC Test
This module serves the WebRTC Test Page.
"""
import cgi
import logging
import random
import os
import jinja2
import webapp2
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
... |
Add Error statement to add_occupant method for when max capacity is reached | class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if len(self.persons) < self.max_persons:
self.pe... | class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if len(self.persons) < self.max_persons:
self.per... |
Use __invert__ instead of __not__ | import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __not__(self):
return Not(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInter... | import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __invert__(self):
return Invert(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(Boolea... |
Increase viewport margin (10% was not enough for small screens) | """
Geotrek startup script.
This is executed only once at startup.
"""
from south.signals import post_migrate
from django.conf import settings
from mapentity.helpers import api_bbox
from geotrek.common.utils.postgresql import load_sql_files
"""
http://djangosnippets.org/snippets/2311/
Ensure Sout... | """
Geotrek startup script.
This is executed only once at startup.
"""
from south.signals import post_migrate
from django.conf import settings
from mapentity.helpers import api_bbox
from geotrek.common.utils.postgresql import load_sql_files
"""
http://djangosnippets.org/snippets/2311/
Ensure Sout... |
Add option to send message as json payload in HTTPNotifier | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If given, auth... | import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If ... |
Use ICEkit settings by default again. | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.glamkit import * # glamkit, icekit
# Override the def... | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.icekit import * # glamkit, icekit
# Override the defa... |
Update url pattern syntax for django 1.10 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf import settings
import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name... | from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib import admin
from django.conf import settings
import views
admin.autodiscover()
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='{{project_name}}/ba... |
Add myself as a maintainer & update the url | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name="django-anonymizer",
version='0.5.0.13-bw',
packages=find_packages(exclude=['*.tests']),
include_package_data=True,
... | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name="django-anonymizer",
version='0.5.0.13-bw',
packages=find_packages(exclude=['*.tests']),
include_package_data=True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.