Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix Invoke doc intersphinx path (and tweak formatting) | # Obtain shared config values
import os, sys
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(__file__), '..')))
sys.path.append(abspath(join(dirname(__file__), '..', '..')))
from shared_conf import *
# Enable autodoc, intersphinx
extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.inte... | # Obtain shared config values
import os, sys
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(__file__), '..')))
sys.path.append(abspath(join(dirname(__file__), '..', '..')))
from shared_conf import *
# Enable autodoc, intersphinx
extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.inte... |
Fix download link , again | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... |
Add first attempt of ActualDepartureQueryApi | # -*- coding: utf-8 -*-
| # -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from bvggrabber.api import QueryApi, Departure
ACTUAL_QUERY_API_ENDPOINT = 'http://mobil.bvg.de/IstAbfahrtzeiten/index/mobil'
class ActualDepartureQueryApi(QueryApi):
def __init__(self, station):
super(ActualDepartureQueryApi, se... |
Change UI loading for frozen | from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
| from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(... |
Order currencies by name by default | from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_('symbol'), max_length=4, blank=True)
factor = models.DecimalF... | from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_('symbol'), max_length=4, blank=True)
factor = models.DecimalF... |
Make the actual change to testfile mentioned in last commit(..) | #!/usr/bin/env python
from gaidaros.gaidaros import *
server = Gaidaros()
#TODO: run a client to do a request against a one-time handle action
#server.handle()
| #!/usr/bin/env python
from gaidaros import *
server = Gaidaros()
#TODO: run a client to do a request against a one-time handle action
#server.handle()
|
Add retry and failure detection to callback.execute | #! /usr/bin/python
import json
import requests
class Callback(object):
def __init__(self, url, method='GET', req_kwargs={}, **kwargs):
assert isinstance(url, (str, unicode))
assert isinstance(method, (str, unicode))
assert isinstance(req_kwargs, dict)
se... | #! /usr/bin/python
import json
import requests
from ufyr.decorators import retry
class Callback(object):
def __init__(self, url, method='GET', req_kwargs={}, **kwargs):
assert isinstance(url, (str, unicode))
assert isinstance(method, (str, unicode))
assert isinstance(req_kwargs,... |
Add KeyValue.__str__ for python 3 | from django.contrib.auth.models import Group
from django.db import models
from jsonfield import JSONField
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=True)
value = JSONField()
def __unicode__(self):
r... | from django.contrib.auth.models import Group
from django.db import models
from jsonfield import JSONField
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=True)
value = JSONField()
def __unicode__(self):
r... |
Add db creation and drop | from __future__ import print_function
import tornado
from tornado import autoreload
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.log import enable_pretty_logging
from app import app
enable_pretty_logging()
PORT = 8000
if __name__ == ... | from __future__ import print_function
import tornado
from tornado import autoreload
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.log import enable_pretty_logging
from app import app, db
from app.models import User
enable_pretty_logging... |
Bump up the version after fix | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.d... | import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.d... |
Update openfisca-core requirement from <28.0,>=27.0 to >=27.0,<32.0 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.8.0",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.8.0",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... |
Correct github URL for chessmoves module |
import chessmoves # Source: https://github.com/kervinck/floyd.git
import floyd as engine
import sys
def parseEpd(rawLine):
# 4-field FEN
line = rawLine.strip().split(' ', 4)
pos = ' '.join(line[0:4])
# EPD fields
operations = {'bm': '', 'am': ''}
fields = [op for op i... |
import chessmoves # Source: https://github.com/kervinck/chessmoves.git
import floyd as engine
import sys
def parseEpd(rawLine):
# 4-field FEN
line = rawLine.strip().split(' ', 4)
pos = ' '.join(line[0:4])
# EPD fields
operations = {'bm': '', 'am': ''}
fields = [op for... |
Remove empty lines in comments. | import unittest
import numpy
import chainer.functions as F
from chainer import testing
#
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.unary_math_function_test(F.Sqrt(), make_data=m... | import unittest
import numpy
import chainer.functions as F
from chainer import testing
# sqrt
def make_data(shape, dtype):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
@testing.unary_math_function_test(F.Sqrt(), make_data=mak... |
Add method for getting the default transformations. | """
AppResources
:Authors:
Berend Klein Haneveld
"""
import os
from AppVars import AppVars
class AppResources(object):
"""
AppResources is a static class that can be used to find common resources
easily. Just provide a name to the imageNamed() method and it will return
the correct path.
"""
@staticmethod
d... | """
AppResources
:Authors:
Berend Klein Haneveld
"""
import os
from AppVars import AppVars
from core.elastix.Transformation import Transformation
class AppResources(object):
"""
AppResources is a static class that can be used to find common resources
easily. Just provide a name to the imageNamed() method and it... |
Update dendro tests and specify no periodic boundaries to be consistent w/ previous unit testing | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_dista... | # Licensed under an MIT open source license - see LICENSE
'''
Tests for Dendrogram statistics
'''
import numpy as np
import numpy.testing as npt
from ..statistics import Dendrogram_Stats, DendroDistance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
min_deltas = np.logspace... |
Fix GitLab profile_url (html_url -> web_url) | # -*- coding: utf-8 -*-
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class GitLabAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('html_url')
def get_avatar_url(self)... | # -*- coding: utf-8 -*-
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class GitLabAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('web_url')
def get_avatar_url(self):... |
Update an example test that uses deferred asserts | """
This test demonstrates the use of deferred asserts.
Deferred asserts won't raise exceptions from failures until either
process_deferred_asserts() is called, or the test reaches the tearDown() step.
"""
import pytest
from seleniumbase import BaseCase
class DeferredAssertTests(BaseCase):
@pytest.mark.expected_f... | """
This test demonstrates the use of deferred asserts.
Deferred asserts won't raise exceptions from failures until either
process_deferred_asserts() is called, or the test reaches the tearDown() step.
Requires version 2.1.6 or newer for the deferred_assert_exact_text() method.
"""
import pytest
from seleniumbase impor... |
Fix the timeline_file_source test suite | import gst
from common import TestCase
import ges
class TimelineFileSource(TestCase):
def testTimelineFileSource(self):
src = ges.TimelineFileSource("blahblahblah")
src.set_mute(True)
src.set_max_duration(long(100))
src.set_supported_formats("video")
assert (src.get_suppo... | import gst
from common import TestCase
import ges
class TimelineFileSource(TestCase):
def testTimelineFileSource(self):
src = ges.TimelineFileSource("file://blahblahblah")
src.set_mute(True)
src.set_max_duration(long(100))
src.set_supported_formats("video")
assert (src.ge... |
Move api config outside of manager commands | from flask_script import Manager
from flask_restful import Api
from config import app
from api import api
manager = Manager(app)
def setup_api(app):
"""
Config resources with flask app
"""
service = Api(app)
service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list')
service.... | from flask_script import Manager
from flask_restful import Api
from config import app
from api import api
manager = Manager(app)
def setup_api(app):
"""
Config resources with flask app
"""
service = Api(app)
service.add_resource(api.MailChimpList,'/api/list/<list_id>',endpoint='list')
service.... |
Prepend '-S rubocop' to version args | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# License: MIT
#
"""This module exports the Rubocop plugin class."""
from SublimeLinter.lint import RubyLinter
class Rubocop(RubyLinter):
"""Provides... |
Drop the UUID; just use urandom | # Sample untracked-keys file
# If you get errors trying to 'import apikeys', do the following:
# 1) Copy this file to apikeys.py (keeping it in the package directory)
# 2) Replace all of the example values with real ones
# 3) Generate your own cookie key, possibly using urandom as per below
# You should then be able to... | # Sample untracked-keys file
# If you get errors trying to 'import apikeys', do the following:
# 1) Copy this file to apikeys.py (keeping it in the package directory)
# 2) Replace all of the example values with real ones
# 3) Generate your own cookie key, possibly using urandom as per below
# You should then be able to... |
Update Heart actors helper class to handle args | #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
... | #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
... |
Put validateSettings() after girder decorator | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS
})
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry App'
def validateSettings(self, e... | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features
from girder.plugin import GirderPlugin
@setting_utilities.validator({
Features.NOTEBOOKS
})
def validateSettings(event):
pass
class AppPlugin(GirderPlugin):
DISPLAY_NAME = 'OpenChemistry ... |
Work with custom user models in django >= 1.5 | from django.contrib import admin
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
User = settings.AUTH_USER_MODEL
except:
from django.contrib.auth.models import User
try... | from django.contrib import admin
from django.conf import settings
from django.db.models import get_model
from django.contrib.auth.models import Group
from django.contrib.auth.admin import GroupAdmin
from django.contrib.auth.forms import UserChangeForm
try:
app_label, model_name = settings.AUTH_USER_MODEL.spli... |
Add integration test for starting the API | from piper.cli import cmd_piperd
from piper.api import api
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piperd.entry(self.mock)
clibase.assert_called_once_with(
'piperd',
... | from piper.cli import cmd_piperd
from piper.api import api
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piperd.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piperd.entry(self.mock)
clibase.assert_called_once_with(
'piperd',
... |
Use program_name instead of script file name in macOS menu | '''
Main runner entry point for Gooey.
'''
import wx
# wx.html and wx.xml imports required here to make packaging with
# pyinstaller on OSX possible without manually specifying `hidden_imports`
# in the build.spec
import wx.html
import wx.xml
import wx.richtext # Need to be imported before the wx.App object... | '''
Main runner entry point for Gooey.
'''
import wx
# wx.html and wx.xml imports required here to make packaging with
# pyinstaller on OSX possible without manually specifying `hidden_imports`
# in the build.spec
import wx.html
import wx.xml
import wx.richtext # Need to be imported before the wx.App object... |
Change version from error to info | import logging
from django.utils.version import get_version
from subprocess import check_output, CalledProcessError
logger = logging.getLogger(__name__)
VERSION = (0, 0, 3, 'beta', 1)
__version__ = get_version(VERSION)
try:
__git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode()
... | import logging
from django.utils.version import get_version
from subprocess import check_output, CalledProcessError
logger = logging.getLogger(__name__)
VERSION = (0, 0, 3, 'beta', 1)
__version__ = get_version(VERSION)
try:
__git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode()
... |
Add option to pick single test file from the runner | import doctest
import glob
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
testfiles = glob.glob('*.txt')
for file in testfiles:
doctest.testfile(file)
| import doctest
import getopt
import glob
import sys
import pkg_resources
try:
pkg_resources.require('OWSLib')
except (ImportError, pkg_resources.DistributionNotFound):
pass
def run(pattern):
if pattern is None:
testfiles = glob.glob('*.txt')
else:
testfiles = glob.glob(pattern)
fo... |
Improve comment and logging text | from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import RedirectURL
from... | from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import RedirectURL
from... |
Update clean method to ensure that meal end_time is not same as or less than meal start_time | from __future__ import unicode_literals
from django.db import models
from common.mixins import ForceCapitalizeMixin
class Weekday(ForceCapitalizeMixin, models.Model):
"""Model representing the day of the week."""
name = models.CharField(max_length=60, unique=True)
capitalized_field_names = ('name',)
... | from __future__ import unicode_literals
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from common.mixins import ForceCapitalizeMixin
class Weekday(ForceCapitalizeMixin, models.Model):
"""Model representing the day of the w... |
Clean up existing gRPC bridge test (make it like t_tcpmapping.py) | import json
from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, EGRPC
class AcceptanceGrpcBridgeTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = EGRPC()
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v0
... | from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, EGRPC
class AcceptanceGrpcBridgeTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = EGRPC()
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v0
kind: Module... |
Move statement PDF URL off the root of the billing URL namespace. | from django.conf.urls import patterns, url
from go.billing import views
urlpatterns = patterns(
'',
url(
r'^(?P<statement_id>[\d]+)', views.statement_view,
name='pdf_statement')
)
| from django.conf.urls import patterns, url
from go.billing import views
urlpatterns = patterns(
'',
url(
r'^statement/(?P<statement_id>[\d]+)', views.statement_view,
name='pdf_statement')
)
|
Update extensions and GameController subclass | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... |
Revert "Bump up dev version to 4.4.4.dev0" | # Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '4.4.4.dev0'
__requires__ = [
'apptools',
'traits',
'trait... | # Author: Prabhu Ramachandran, Gael Varoquaux
# Copyright (c) 2004-2014, Enthought, Inc.
# License: BSD Style.
""" A tool for easy and interactive visualization of data.
Part of the Mayavi project of the Enthought Tool Suite.
"""
__version__ = '4.4.3'
__requires__ = [
'apptools',
'traits',
'traitsui',... |
Use dict iteration compatible with Python 2 and 3 | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
... | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
... |
Simplify the aws vpcs settings for testing | # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True
},
{
'CidrBlock': '16.0.0.0/16',
'Tags': ... | # -*- coding: utf-8 -*-
AWS_VPCS = [
{
'CidrBlock': '15.0.0.0/16',
'Tags': [
{
'Key': 'Name',
'Value': 'symaps-prod-proxies'
}
],
'create_internet_gateway': True,
'subnets': [
{
'CidrBlock': ... |
Fix RemovedInDjango40Warning from Signal arguments | """
Custom signals sent during the registration and activation processes.
"""
from django.dispatch import Signal
# A new user has registered.
user_registered = Signal(providing_args=["user", "request"])
# A user has activated his or her account.
user_activated = Signal(providing_args=["user", "request"])
| """
Custom signals sent during the registration and activation processes.
"""
from django.dispatch import Signal
# A new user has registered.
# Provided args: user, request
user_registered = Signal()
# A user has activated his or her account.
# Provided args: user, request
user_activated = Signal()
|
Handle the user id coming in via a header. | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the user) or they are logged in but somehow... | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
from django.contrib.auth import login
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the us... |
Update manager for Person requirement | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', **kwargs):
user = self.model(
email=email,
password='',
is_active=True,
**kwargs
)
user.save(using=... | # Django
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password='', person, **kwargs):
user = self.model(
email=email,
password='',
person=person,
is_active=True,
**kwargs... |
Print sum. Print description only if it exists. | #!/usr/bin/env python
# Print information columns of number values.
import sys
import numpy as np
from dwi import asciifile
for filename in sys.argv[1:]:
af = asciifile.AsciiFile(filename)
print filename
print af.d['description']
params = af.params()
for i, a in enumerate(af.a.T):
d = di... | #!/usr/bin/env python
# Print information columns of number values.
import sys
import numpy as np
from dwi import asciifile
for filename in sys.argv[1:]:
af = asciifile.AsciiFile(filename)
print filename
if af.d.has_key('description'):
print af.d['description']
params = af.params()
for i... |
Revert "Try fixing circular import" | from stable_baselines.a2c import A2C
from stable_baselines.acer import ACER
from stable_baselines.acktr import ACKTR
# from stable_baselines.ddpg import DDPG
from stable_baselines.deepq import DeepQ
from stable_baselines.gail import GAIL
from stable_baselines.ppo1 import PPO1
from stable_baselines.ppo2 import PPO2
from... | from stable_baselines.a2c import A2C
from stable_baselines.acer import ACER
from stable_baselines.acktr import ACKTR
from stable_baselines.ddpg import DDPG
from stable_baselines.deepq import DeepQ
from stable_baselines.gail import GAIL
from stable_baselines.ppo1 import PPO1
from stable_baselines.ppo2 import PPO2
from s... |
Upgrade versions of test tools | from setuptools import setup, find_packages
import simple_virtuoso_migrate
setup(
name = "simple-virtuoso-migrate",
version = simple_virtuoso_migrate.SIMPLE_VIRTUOSO_MIGRATE_VERSION,
packages = find_packages(),
author = "Percy Rivera",
author_email = "priverasalas@gmail.com",
description = "si... | from setuptools import setup, find_packages
import simple_virtuoso_migrate
setup(
name = "simple-virtuoso-migrate",
version = simple_virtuoso_migrate.SIMPLE_VIRTUOSO_MIGRATE_VERSION,
packages = find_packages(),
author = "Percy Rivera",
author_email = "priverasalas@gmail.com",
description = "si... |
Update the proxy server examples | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... |
Update feature version to 0.1.0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
setup(
name='django_excel_tools',
version='0.... |
Use flask redirects for random perspective and latest round | import flask
from handlers import app
import db.query as q
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/api/perspective/random')
def random_perspective():
return flask.jsonify(
q.random_perspective().to_dict()
)
| import flask
from handlers import app
import db.query as q
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/api/perspective/random')
def random_perspective():
random_id = q.random_perspective().id
return flask.redirect('/api/perspective/%s' % random_id)
@app.route('/api/roun... |
Add posibility to add extra information to occurence. | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class Event(Displayable, RichText):
"""
Main object for each event.
Derives from Displayable, which by default
- it is related to a certain Site ob... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class Event(Displayable, RichText):
"""
Main object for each event.
Derives from Displayable, which by default
- it is related to a certain Site ob... |
Fix running node from python. | #!/usr/bin/env python
import os
import subprocess
import sys
from lib.util import *
SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__))
def main():
input_file = sys.argv[1]
output_dir = os.path.dirname(sys.argv[2])
coffee = os.path.join(SOURCE_ROOT, 'node_modules', 'coffee-script', 'bin',
... | #!/usr/bin/env python
import os
import subprocess
import sys
from lib.util import *
SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__))
def main():
input_file = sys.argv[1]
output_dir = os.path.dirname(sys.argv[2])
coffee = os.path.join(SOURCE_ROOT, 'node_modules', 'coffee-script', 'bin',
... |
Split Energy and Environment, change Civil Liberties to Social Justice | from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics..... | from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics..... |
Update script to write results to the database. | #!/usr/bin/env python
#import hashlib
import os
def main():
for root, dirs, files in os.walk("/mcfs/data/materialscommons"):
for f in files:
print f
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import hashlib
import os
import rethinkdb as r
def main():
conn = r.connect('localhost', 28015, db='materialscommons')
for root, dirs, files in os.walk("/mcfs/data/materialscommons"):
for f in files:
path = os.path.join(root, f)
with open(path) as fd:
... |
Add a new dev (optional) parameter and use it | import json
import logging
import argparse
import emission.net.ext_service.push.notify_usage as pnu
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(prog="silent_ios_push")
parser.add_argument("interval",
help="specify the sync interval that the ... | import json
import logging
import argparse
import emission.net.ext_service.push.notify_usage as pnu
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(prog="silent_ios_push")
parser.add_argument("interval",
help="specify the sync interval that the ... |
Fix form retrieval in ModelForm | from achilles.forms import * # noqa
from nazs.models import SingletonModel
# Override forms template
Form.template_name = 'web/form.html'
class ModelForm(ModelForm):
def get_form(self, form_data=None, *args, **kwargs):
# manage SingletonModels
if issubclass(self.form_class.Meta.model, Singleto... | from achilles.forms import * # noqa
from nazs.models import SingletonModel
# Override forms template
Form.template_name = 'web/form.html'
class ModelForm(ModelForm):
def get_form(self, form_data=None, *args, **kwargs):
# manage SingletonModels
if issubclass(self.form_class.Meta.model, Singleto... |
Fix model import needed by create_all() | #!/usr/bin/env python3
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from service import app, db
# db.create_all() needs all models to be imported
from service.db_access import *
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if _... | #!/usr/bin/env python3
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from service import app, db
# db.create_all() needs all models to be imported explicitly (not *)
from service.db_access import User
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', ... |
Add cache in opps menu list via context processors | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects... | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(requ... |
Comment post endpoint return a ksopn, fix issue saving comments add post id and convert it to int | from flask import jsonify
from flask_classy import FlaskView
from flask_user import current_user, login_required
from ..models import CommentModel, PostModel
from ..forms import CommentForm
class Comment(FlaskView):
def get(self):
pass
def all(self, post_id):
comment = CommentModel()
... | from flask import jsonify
from flask_classy import FlaskView
from flask_user import current_user, login_required
from ..models import CommentModel, PostModel
from ..forms import CommentForm
class Comment(FlaskView):
def get(self):
pass
def all(self, post_id):
comment = CommentModel()
... |
Remove indentation level for easier review | """
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
if hasattr(code, "replace"):
return template.replace(**{"co_" + k : v for k, v in changes.items()})
else:
names = [
"argcount", "nlocals", "stacksize... | """
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
if hasattr(code, "replace"):
return template.replace(**{"co_" + k : v for k, v in changes.items()})
names = [
"argcount", "nlocals", "stacksize", "flags", "code"... |
Add DOI parsing to identifiers | '''
Harvester for the Smithsonian Digital Repository for the SHARE project
Example API call: http://repository.si.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class SiHarvester(OAIHarvester):
short_name = 'smithsonian'
... | '''
Harvester for the Smithsonian Digital Repository for the SHARE project
Example API call: http://repository.si.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
import re
from scrapi.base import helpers
from scrapi.base import OAIHarvester
class SiHarvester(OAIHa... |
Make url field check work over head requests | import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url)
h.follow_all_redirec... | import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url, method="HEAD")
h.fol... |
Improve the query execution order. | from application import app
from flask.ext.restful import Api, Resource
import os
from subprocess import Popen as run, PIPE
from distutils.sysconfig import get_python_lib
from autoupdate import lib_path, db_path
api = Api(app)
fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path)
def db(query):
cmd = ... | from application import app
from flask.ext.restful import Api, Resource
import os
from subprocess import Popen as run, PIPE
from distutils.sysconfig import get_python_lib
from autoupdate import lib_path, db_path
api = Api(app)
fetch = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path)
def db(query):
cmd = ... |
Split the sentence in case of infix coordinatiin | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
# Break the tree
def break_tree(self, tree):
self.has_infix_coordinati... | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.slice_point = -1
self.subtree_list = []
# Break the tree
... |
Fix word_count test import paths. | # coding: utf-8
from __future__ import unicode_literals
import unittest
from manoseimas.scrapy import textutils
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = textutils.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get... | # coding: utf-8
from __future__ import unicode_literals
import unittest
from manoseimas.common.utils import words
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = words.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_w... |
Add --extensions-in-dev-mode to the Binder dev mode | lab_command = ' '.join([
'jupyter',
'lab',
'--dev-mode',
'--debug',
'--no-browser',
'--port={port}',
'--ServerApp.ip=127.0.0.1',
'--ServerApp.token=""',
'--ServerApp.base_url={base_url}lab-dev',
# Disable dns rebinding protection here, since our 'Host' header
# is not going t... | lab_command = ' '.join([
'jupyter',
'lab',
'--dev-mode',
'--debug',
'--extensions-in-dev-mode',
'--no-browser',
'--port={port}',
'--ServerApp.ip=127.0.0.1',
'--ServerApp.token=""',
'--ServerApp.base_url={base_url}lab-dev',
# Disable dns rebinding protection here, since our 'H... |
Expand use for returning both exit code + content | # -*- coding: utf-8 -*-
import sys
from .processrunner import ProcessRunner
from .writeout import writeOut
def runCommand(command, outputPrefix="ProcessRunner> "):
"""Easy invocation of a command with default IO streams
Args:
command (list): List of strings to pass to subprocess.Popen
Kwargs:
... | # -*- coding: utf-8 -*-
import sys
from .processrunner import ProcessRunner
from .writeout import writeOut
def runCommand(command, outputPrefix="ProcessRunner> ", returnAllContent=False):
"""Easy invocation of a command with default IO streams
returnAllContent as False (default):
Args:
command ... |
Make sure I/O functions appear in API docs | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from . import kepler
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .kepler import *
|
Remove tensorflow as dependency for now | # -*- coding: utf-8 -*-
from setuptools import setup
import ogres
requirements = ["tensorflow>=0.10"]
version = ogres.__version__
setup(
name="ogres",
version=version,
url="https://github.com/butternutdog/ogres",
download_url="https://github.com/butternutdog/ogres/tarball/{0}".format(version),
licens... | # -*- coding: utf-8 -*-
from setuptools import setup
import ogres
requirements = [] # Requires tensorflow, but no easy install script exist
version = ogres.__version__
setup(
name="ogres",
version=version,
url="https://github.com/butternutdog/ogres",
download_url="https://github.com/butternutdog/ogres/t... |
Create script to save documentation to a file | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... |
Add more "GET /users/:id" tests | from tests.data import add_fixtures, users
def test_read_user(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/{id}'.format(id=john.id))
assert res.status_code == 200
assert res.json == {
u'id': john.id,
u'firstName': u'John',
... | from skylines.model import Follower
from tests.api import auth_for
from tests.data import add_fixtures, users
def test_read_user(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/{id}'.format(id=john.id))
assert res.status_code == 200
assert res.json... |
Update exercise of variables and names | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
p... | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
p... |
Select planet and display alt/az data | import ephem
m = getattr(ephem, (raw_input('Planet: ')))
print ephem.constellation(m(raw_input('yyyy/mm/dd: '))) | import ephem
def const(planet_name, date_string): # function name and parameters
planet_class = getattr(ephem, planet_name) # sets ephem object class
planet = planet_class() # sets planet variable
south_bend = ephem.Observer() # Creates the Observer object
... |
Return false if no alias. | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Comma... | import GlobalVars
class ModuleInterface(object):
triggers = []
acceptedTypes = ['PRIVMSG']
help = '<no help defined (yet)>'
def __init__(self):
self.onStart()
def onStart(self):
pass
def hasAlias(self, message):
if message.Type in self.acceptedTypes and message.Comma... |
Add twill to install requires. | from setuptools import setup, find_packages
setup(
name = "django-test-utils",
version = "0.3",
packages = find_packages(),
author = "Eric Holscher",
author_email = "eric@ericholscher.com",
description = "A package to help testing in Django",
url = "http://github.com/ericholscher/django-tes... | from setuptools import setup, find_packages
setup(
name = "django-test-utils",
version = "0.3",
packages = find_packages(),
author = "Eric Holscher",
author_email = "eric@ericholscher.com",
description = "A package to help testing in Django",
url = "http://github.com/ericholscher/django-tes... |
Exclude tests and devtools when packaging | from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(name='subvenv',
version='1.0.0',
description=('A tool for creating virtualenv-friendly '
'Sublime Text project files'),
long_description=readme(),
classi... | #!/usr/bin/env python
from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(name='subvenv',
version='1.0.0',
description=('A tool for creating virtualenv-friendly '
'Sublime Text project files'),
long_description... |
Add .stream to packages list. | #!/usr/bin/env python
from setuptools import setup, find_packages
from sys import version_info
version = "1.3"
deps = ["pbs", "requests>=0.12.1"]
# require argparse on Python <2.7 and <3.2
if (version_info[0] == 2 and version_info[1] < 7) or \
(version_info[0] == 3 and version_info[1] < 2):
deps.append("argpa... | #!/usr/bin/env python
from setuptools import setup, find_packages
from sys import version_info
version = "1.3"
deps = ["pbs", "requests>=0.12.1"]
# require argparse on Python <2.7 and <3.2
if (version_info[0] == 2 and version_info[1] < 7) or \
(version_info[0] == 3 and version_info[1] < 2):
deps.append("argpa... |
Add dependency on the dataclasses library | from setuptools import setup
def readme():
with open('README.md') as file:
return file.read()
setup(
name='ppb-vector',
version='0.4.0rc1',
packages=['ppb_vector'],
url='http://github.com/pathunstrom/ppb-vector',
license='',
author='Piper Thunstrom',
author_email='pathunstrom... | from setuptools import setup
def readme():
with open('README.md') as file:
return file.read()
setup(
name='ppb-vector',
version='0.4.0rc1',
packages=['ppb_vector'],
url='http://github.com/pathunstrom/ppb-vector',
license='',
author='Piper Thunstrom',
author_email='pathunstrom... |
Add header and url to package_data to fix pip installs from VCS | # coding=utf-8
from setuptools import setup
setup(
name='imboclient',
version='0.0.1',
author='Andreas Søvik',
author_email='arsovik@gmail.com',
packages=['imboclient'],
scripts=[],
url='http://www.imbo-project.org',
license='LICENSE.txt',
descrip... | # coding=utf-8
from setuptools import setup
setup(
name='imboclient',
version='0.0.1',
author='Andreas Søvik',
author_email='arsovik@gmail.com',
packages=['imboclient'],
scripts=[],
url='http://www.imbo-project.org',
license='LICENSE.txt',
descrip... |
Add user registration via api | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer... | from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
... |
Add a UiautoApk resource type. | # Copyright 2014-2015 ARM Limited
#
# 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 w... | # Copyright 2014-2015 ARM Limited
#
# 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 w... |
Make IsPostOrSuperuserOnly a non-object-level permission. | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_pe... | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_pe... |
Update import for classproperty in django 3.1 and above | # coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.decorators import classproperty
from taggit.managers import TaggableManager
from translator.util import get_key
class TranslationBase(models.Model):
key = models.CharField(max_length... | # coding=utf-8
from django.conf import settings
from django.core.cache import cache
from django.db import models
from taggit.managers import TaggableManager
from translator.util import get_key
try:
# Django 3.1 and above
from django.utils.functional import classproperty
except ImportError:
from django.uti... |
Fix bug with multiprocessing and Nose. | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
from setuptools.command.test import test
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools.command.test import test
setup(
name='modeldi... | #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
try:
import multiprocessing # Seems to fix http://bugs.python.org/issue15881
except ImportError:
pass
setup_requires = []
if 'nosetests' in sys.argv[1:]:
setup_requires.append('nose')
setup(
name='modeldict',
version... |
Use 'ruby -S' to find ruby-lint executable | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Joshua Hagins
# Copyright (c) 2015 Joshua Hagins
#
# License: MIT
#
"""This module exports the RubyLint plugin class."""
from SublimeLinter.lint import RubyLinter
class RubyLint(RubyLinter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Joshua Hagins
# Copyright (c) 2015 Joshua Hagins
#
# License: MIT
#
"""This module exports the RubyLint plugin class."""
from SublimeLinter.lint import RubyLinter
class RubyLint(RubyLinter):
"""Provides an in... |
Use README.rst for long description | from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.md'),
url='http://githu... | from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.rst'),
url='http://gith... |
Fix mistake returning the wrong authenticated user |
from tastypie.authentication import Authentication
from tastypie.resources import ModelResource
from provider.oauth2.models import AccessToken
from selvbetjening.core.members.models import SUser
class OAuth2Authentication(Authentication):
def is_authenticated(self, request, **kwargs):
access_key = re... |
from tastypie.authentication import Authentication
from tastypie.resources import ModelResource
from provider.oauth2.models import AccessToken
from selvbetjening.core.members.models import SUser
class OAuth2Authentication(Authentication):
def is_authenticated(self, request, **kwargs):
access_key = re... |
Use PEP8 style for conditionals | import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.... | import re
# A regular expression is a string like what you see below between the quote
# marks, and the ``re`` module interprets it as a pattern. Each regular
# expression describes a small program that takes another string as input and
# returns information about that string. See
# http://docs.python.org/library/re.... |
Use the python in virtualenv instead of global one | #!/usr/bin/python3
import sys
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
| #!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
|
Add Git link instead of name | from setuptools import find_packages, setup
setup(
name='blocks.contrib',
namespace_packages=['blocks'],
install_requires=['blocks'],
packages=find_packages(exclude=['examples']),
zip_safe=False)
| from setuptools import find_packages, setup
setup(
name='blocks.contrib',
namespace_packages=['blocks'],
install_requires=['git+git://github.com/bartvm/blocks.git#egg=blocks'],
packages=find_packages(exclude=['examples']),
zip_safe=False)
|
Disable Python 3 conversion until it's been tested. | import sys
from setuptools import setup
meta = dict(
name="stacklogger",
version="0.1.0",
description="A stack-aware logging extension",
author="Will Maier",
author_email="willmaier@ml1.net",
py_modules=["stacklogger"],
test_suite="tests.py",
install_requires=["setuptools"],
keywor... | import sys
from setuptools import setup
meta = dict(
name="stacklogger",
version="0.1.0",
description="A stack-aware logging extension",
author="Will Maier",
author_email="willmaier@ml1.net",
py_modules=["stacklogger"],
test_suite="tests.py",
install_requires=["setuptools"],
keywor... |
Mark version as beta Remove pytest plugin entrypoint (not ready) | from setuptools import setup
setup(
name='pytest-ui',
description='Text User Interface for running python tests',
version='0.1',
license='MIT',
platforms=['linux', 'osx', 'win32'],
packages=['pytui'],
url='https://github.com/martinsmid/pytest-ui',
author_email='martin.smid@gmail.com',
... | from setuptools import setup
setup(
name='pytest-ui',
description='Text User Interface for running python tests',
version='0.1b',
license='MIT',
platforms=['linux', 'osx', 'win32'],
packages=['pytui'],
url='https://github.com/martinsmid/pytest-ui',
author_email='martin.smid@gmail.com',
... |
Revert use of bintrees; it's not a great fit. | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://w... | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://w... |
Add type check helper; make typ or None optional for lists | # Tools for type checking
def assertListOf(lst, typ):
assert isinstance(lst, list), lst
for idx, value in enumerate(lst):
#assert isinstance(value, typ), (idx, value)
assert value is None or isinstance(value, typ), (idx, value)
return True
| # Tools for type checking
def assertListOf(lst, typ, orNone=True):
assert isinstance(lst, list), lst
if orNone:
for idx, value in enumerate(lst):
assert value is None or isinstance(value, typ), (idx, value)
else:
for idx, value in enumerate(lst):
assert isinstance(va... |
Fix splunk module name (splunk => splunklib) | #!/usr/bin/env python
#
# Copyright 2011-2012 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/env python
#
# Copyright 2011-2012 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
Add mock as a test dependency | #!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from moulinette import env
LOCALES_DIR = env["LOCALES_DIR"]
# Extend installation
locale_files = []
if "install" in sys.argv:
# Evaluate locale files
for f in os.listdir("locales"):
if f.endswith(".json"):
... | #!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from moulinette import env
LOCALES_DIR = env["LOCALES_DIR"]
# Extend installation
locale_files = []
if "install" in sys.argv:
# Evaluate locale files
for f in os.listdir("locales"):
if f.endswith(".json"):
... |
Fix script to output new line at end of file | #!/usr/bin/python
import sys
import depio
sentnum = int(sys.argv[2])
fnames = [sys.argv[1]]
for fname in fnames:
sents = list(depio.depread(fname))
i=0
out = open("%d.%s" % (sentnum,fname),'w')
for outl in sents[sentnum]:
out.write('\t'.join(outl) + '\n')
break
out.close()
| #!/usr/bin/python
import sys
import depio
sentnum = int(sys.argv[2])
fnames = [sys.argv[1]]
for fname in fnames:
sents = list(depio.depread(fname))
i=0
out = open("%d.%s" % (sentnum,fname),'w')
for outl in sents[sentnum]:
out.write('\t'.join(outl) + '\n')
out.write('\n')
out.close()
|
Move eventlent monkeypatch out of cmd/ | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | |
Implement input API as spec'd in oonib.md | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config
class InputDescHandler(OONIBHandler):
def get(self, inputID):
#XXX return the input descriptor
# see oonib.md in ooni-spec
bn = os.path.basename(inputID) + ".desc"
try:
... | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config, log
class InputDescHandler(OONIBHandler):
def get(self, inputID):
bn = os.path.basename(inputID) + ".desc"
try:
f = open(os.path.join(config.main.input_dir, bn))
... |
Use xml.sax.saxutils.escape instead of deprecated cgi.escape | from __future__ import unicode_literals
from .abc import Writer
import cgi
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
attribute_string = _gen... | from __future__ import unicode_literals
from xml.sax.saxutils import escape
from .abc import Writer
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
... |
Expand Mock Request to include path and built in URL parsing. | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from odin.codecs import json_codec
from odinweb.constants import Method
class MockRequest(object):
"""
Mocked Request object
"""
def __init__(self, query=None, post=None, headers=None, method=Method.GET, body=''... | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from typing import Dict, Any
from odin.codecs import json_codec
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
from urlparse import urlparse, parse_qs
from odinweb.constants import Method
class Mo... |
Send welcome message at very first of communication channel | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... |
Update the UA used in CloudSQLReplicator | # Copyright 2018 The Pontem Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | # Copyright 2018 The Pontem Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
Allow to search items by description. | # -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slu... | # -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slu... |
Make quota usage read only (nc-263) | from rest_framework import serializers
from nodeconductor.quotas import models, utils
from nodeconductor.core.serializers import GenericRelatedField
class QuotaSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True)
class... | from rest_framework import serializers
from nodeconductor.quotas import models, utils
from nodeconductor.core.serializers import GenericRelatedField
class QuotaSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True)
class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.