Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Change assertGet body check from StringType to str | import types
import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self... | import unittest
import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
hosts = []
def assertGet(self, endpoint="", status_code=200, body=""):
"""
Asserts GET requests on a given endpoint
"""
for host in self.hosts:
... |
Add lint/autolint tasks for running flake8 on everything | from fabric.api import execute, local, settings, task
@task
def docs():
local('make -C docs/ html')
@task
def autodocs():
auto(docs)
@task
def test(path=None):
path = path or 'tests/'
local('nosetests ' + path)
@task
def autotest(path=None):
auto(test, path=path)
@task
def coverage(path=No... | from fabric.api import execute, local, settings, task
@task
def docs():
local('make -C docs/ html')
@task
def autodocs():
auto(docs)
@task
def test(path=None):
path = path or 'tests/'
local('nosetests ' + path)
@task
def autotest(path=None):
auto(test, path=path)
@task
def coverage(path=No... |
Replace usage of url with re_path. | from django.urls import path
from invite import views
app_name = 'invite'
urlpatterns = [
path('$', views.index, name='index'),
path('invite/$', views.invite, name='invite'),
path('resend/(?P<code>.*)/$', views.resend, name='resend'),
path('revoke/(?P<code>.*)/$', views.revoke, name='revoke'),
pat... | from django.urls import re_path
from invite import views
app_name = 'invite'
urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r'^invite/$', views.invite, name='invite'),
re_path(r'^resend/(?P<code>.*)/$', views.resend, name='resend'),
re_path(r'^revoke/(?P<code>.*)/$', views.revoke, ... |
Remove leftover relic from supporting CPython 2.6. | # cf. https://github.com/pypa/manylinux/issues/53
GOOD_SSL = "https://google.com"
BAD_SSL = "https://self-signed.badssl.com"
import sys
print("Testing SSL certificate checking for Python:", sys.version)
if (sys.version_info[:2] < (2, 7)
or sys.version_info[:2] < (3, 4)):
print("This version never checks SSL... | # cf. https://github.com/pypa/manylinux/issues/53
GOOD_SSL = "https://google.com"
BAD_SSL = "https://self-signed.badssl.com"
import sys
print("Testing SSL certificate checking for Python:", sys.version)
if (sys.version_info[:2] < (3, 4)):
print("This version never checks SSL certs; skipping tests")
sys.exit... |
Include some tests for _asarray | # -*- coding: utf-8 -*-
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import dask
import dask.array as da
import dask.array.utils as dau
import dask_distance._compat
@pytest.mark.parametrize("x", [
list(range(5)),
np.random.randint(10, size=(15, 16)),
da.random.randint(10, size=(15, 16), chu... |
Allow to specify role name on commandline | #!/usr/bin/env python
import sys, os, json, logging
sys.path.append(os.path.abspath("."))
import gevent
import msgflo
class Repeat(msgflo.Participant):
def __init__(self, role):
d = {
'component': 'PythonRepeat',
'label': 'Repeat input data without change',
}
msgflo.Participant.__init__(sel... | #!/usr/bin/env python
import sys, os, json, logging
sys.path.append(os.path.abspath("."))
import gevent
import msgflo
class Repeat(msgflo.Participant):
def __init__(self, role):
d = {
'component': 'PythonRepeat',
'label': 'Repeat input data without change',
}
msgflo.Participant.__init__(sel... |
Split user settings test into two tests | import django_webtest
import django.contrib.auth.models as auth_models
import pylab.accounts.models as accounts_models
class SettingsTests(django_webtest.WebTest):
def setUp(self):
super().setUp()
auth_models.User.objects.create_user('u1')
def test_settings(self):
resp = self.app.ge... | import django_webtest
import django.contrib.auth.models as auth_models
import pylab.accounts.models as accounts_models
class SettingsTests(django_webtest.WebTest):
def setUp(self):
super().setUp()
auth_models.User.objects.create_user('u1')
def test_user_settings(self):
resp = self.a... |
Change time_amount type,now handle float values | import os.path
from srtmod.srtmod import SrtMod
import argparse
def main():
parser = argparse.ArgumentParser(prog='SrtModPy',
description='Just adjusts the timing of subtitle files')
parser.add_argument('file_name', help='the subtitle to be modified')
parser.add_argument('time_amount', metavar... | import os.path
from srtmod.srtmod import SrtMod
import argparse
def main():
parser = argparse.ArgumentParser(prog='SrtModPy',
description='Just adjusts the timing of subtitle files')
parser.add_argument('file_name', help='the subtitle to be modified')
parser.add_argument('time_amount', metavar... |
Remove string annotation (likely incomprehensible to mypy) and minor doc-string formatting. | ##
# .protocol.version
##
'PQ version class'
from struct import Struct
version_struct = Struct('!HH')
class Version(tuple):
"""Version((major, minor)) -> Version
Version serializer and parser.
"""
major = property(fget = lambda s: s[0])
minor = property(fget = lambda s: s[1])
def __new__(subtype, major_minor :... | ##
# .protocol.version
##
"""
PQ version class used by startup messages.
"""
from struct import Struct
version_struct = Struct('!HH')
class Version(tuple):
"""
Version((major, minor)) -> Version
Version serializer and parser.
"""
major = property(fget = lambda s: s[0])
minor = property(fget = lambda s: s[1])
... |
Switch order (again) of legend for example | """
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import d... | """
QuadTree: Hanging Nodes
=======================
You can give the refine method a function, which is evaluated on every
cell of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
import d... |
Add OpenCV viewer for debug. | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Show the images from a USB camera
#
#
# External dependencies
#
import sys
from PySide import QtGui
import VisionToolkit as vtk
#
# Main application
#
if __name__ == '__main__' :
application = QtGui.QApplication( sys.argv )
widget = vtk.UsbCameraWidget()
... | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Show the images from a USB camera
#
#
# External dependencies
#
#import sys
import cv2
#from PySide import QtGui
import VisionToolkit as vt
#
# Image callback function
#
def Callback( image ) :
# Display the stereo image
cv2.imshow( 'Camera', image )
cv2.waitKe... |
Raise invalid page on paging error | from django.core.paginator import Paginator
class ElasticsearchPaginator(Paginator):
"""
Paginator that prevents two queries to ES (for count and objects)
as ES gives count with objects
"""
MAX_ES_OFFSET = 10000
def page(self, number):
"""
Returns a Page object for the given 1... | from django.core.paginator import Paginator, InvalidPage
class ElasticsearchPaginator(Paginator):
"""
Paginator that prevents two queries to ES (for count and objects)
as ES gives count with objects
"""
MAX_ES_OFFSET = 10000
def page(self, number):
"""
Returns a Page object fo... |
Revise elif to if due to continue | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def valid_parentheses(s):
"""Balance parentheses in a string."""
open_close_d = {
'(': ')',
'[': ']',
'{': '}'
}
# Use stack to collect open parentheses.
stack = []... |
Fix hardwired weights for res10ssd | import cv2
# TODO: make this downloadable
PATH_PROTO = "/mnt/kodi/blackbird/Scry/models/3rd_party/res10_ssd/deploy.prototxt.txt"
PATH_WEIGHTS = "/mnt/kodi/blackbird/Scry/models/3rd_party/res10_ssd/res10_300x300_ssd_iter_140000.caffemodel"
def get_kernel(params, unparsed_args=None):
assert params["mode"] == "inf... | from pathlib import Path
import cv2
def get_kernel(params, unparsed_args=None):
proto = "deploy.prototxt.txt"
weights = "res10_300x300_ssd_iter_140000.caffemodel"
BASE = Path("~/.cache/benchmarker/models").expanduser()
PATH_PROTO = BASE.joinpath(proto)
PATH_WEIGHTS = BASE.joinpath(weights)
... |
Make module graph call return a file. | """Device call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
... | """Device call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall, FileCall
from ubersmith.utils import prepend_base
__all__ = [
'G... |
Make script for adding sample feeds more usable | from smoke_signal import app, init_db
from smoke_signal.database.helpers import add_feed
from utils.generate_feed import SampleFeed
from os import walk
feeds_dir = app.root_path + "/test_resources/feeds/"
app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db'
def create_sample_feed_files(nu... | from smoke_signal import app, init_db
from smoke_signal.database.helpers import add_feed
from utils.generate_feed import SampleFeed
import feedparser
from os import walk, makedirs
FEEDS_DIR = app.root_path + "/test_resources/feeds/"
app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db'
def... |
Put Question Admin fields in a fieldset and added a collapse class to the date field | from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin) | from django.contrib import admin
# Register your models here.
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'question_text']
fieldsets = [
(None, {'fields' : ['question_text']}),
('Date Information', { 'fields' : ['pub_date'], 'classes': ['collap... |
Change DATE_FORMAT to be equivalent to datetime.isoformat() | """Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
# Flask
DEBUG = False
TEST... | """Default settings for all environments.
These settings will be extended by additional config files in ROOT/config.
Run `python manage.py create_config` to create such a config file.
"""
from os.path import abspath, dirname, join
# Custom
ROOT_DIR = abspath(join(dirname(__file__), ".."))
# Flask
DEBUG = False
TEST... |
Switch Django version from 1.0 to 1.1 | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats... | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats... |
Fix broken test (not the intermittent one, this was just a dumb thing) | from django.test import TestCase
from django.conf import settings
from django.template import Context, Template
from bongo.apps.bongo.tests import factories
def render_template(string, context=None):
context = Context(context) if context else None
return Template(string).render(context)
class TemplateTagsTe... | from django.test import TestCase
from django.conf import settings
from django.utils.html import escape
from django.template import Context, Template
from bongo.apps.bongo.tests import factories
def render_template(string, context=None):
context = Context(context) if context else None
return Template(string).r... |
Add 5s timeout to checkproxy (in an effort to prevent bot hanging | import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy):
"""Checks the provided proxy."""
p = proxy
... | import discord
import requests
from discord.ext import commands
class checkproxy:
"""Cog for proxy checking"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def checkproxy(self, ctx, proxy):
"""Checks the provided proxy."""
p = proxy
... |
Update ID to match others | from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'CINCH0001'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include J... | from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,
class NoFormattingInWhenRule(AnsibleLintRule):
id = 'ANSIBLE0019'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include... |
Fix formfield to return an empty string if an empty value is given. This allows empty input for not null model fields with blank=True. | #-*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonenumber import to_python
class PhoneNumberF... | #-*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonenumber import to_python
class PhoneNumberF... |
Support endpoint name in route. | import logging
__license__ = "MIT"
__project__ = "Flask-Restler"
__version__ = "1.6.2"
logger = logging.getLogger('flask-restler')
logger.addHandler(logging.NullHandler())
class APIError(Exception):
"""Store API exception's information."""
status_code = 400
def __init__(self, message, status_code=N... | import logging
__license__ = "MIT"
__project__ = "Flask-Restler"
__version__ = "1.6.2"
logger = logging.getLogger('flask-restler')
logger.addHandler(logging.NullHandler())
class APIError(Exception):
"""Store API exception's information."""
status_code = 400
def __init__(self, message, status_code=N... |
Return a list of dicts for data. | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
__all__ = []
import requests
DATASET_URL = 'http://lincs.hms.harvard.edu/db/datasets/20000/results'
def _get_lincs_drug_target_data():
resp = requests.get(DATASET_URL, params={'output_type': '.csv'})
ass... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
__all__ = []
import csv
import requests
from indra.sources.lincs.processor import LincsProcessor
DATASET_URL = 'http://lincs.hms.harvard.edu/db/datasets/20000/results'
def process_from_web():
lincs_data = _... |
Move initialization of logger and cfg parser to separate function. | #!/usr/bin/python
import xmlrpclib, logging
from ConfigParser import SafeConfigParser
# Configure logging.
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m/%d %H:%M:%S',
filename='/tmp/kts46_rpc... | #!/usr/bin/python
import xmlrpclib, logging
from ConfigParser import SafeConfigParser
def init():
# Configure logging.
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m/%d %H:%M:%S',
... |
Fix URL error with Geotrek light | from django.conf import settings
from django.conf.urls import patterns, url
from mapentity import registry
from geotrek.altimetry.urls import AltimetryEntityOptions
from geotrek.core.models import Path, Trail
from geotrek.core.views import get_graph_json
if settings.TREKKING_TOPOLOGY_ENABLED:
urlpatterns = patt... | from django.conf import settings
from django.conf.urls import patterns, url
from mapentity import registry
from geotrek.altimetry.urls import AltimetryEntityOptions
from geotrek.core.models import Path, Trail
from geotrek.core.views import get_graph_json
urlpatterns = patterns('',
url(r'^api/graph.json$', get_g... |
Add band members as unassigned to new bands | from rest_framework import serializers
from members.models import Band
from members.models import BandMember
class BandMemberSerializer(serializers.ModelSerializer):
class Meta:
model = BandMember
fields = ('id',
'account',
'section',
'instrument_number',
... | from rest_framework import serializers
from members.models import Band
from members.models import BandMember
class BandMemberSerializer(serializers.ModelSerializer):
class Meta:
model = BandMember
fields = ('id',
'account',
'section',
'instrument_number',
... |
Add a long description based on README.rst | from setuptools import setup, find_packages
setup(
name='fakeredis',
version='0.1',
description="Fake implementation of redis API for testing purposes.",
license='BSD',
url="https://github.com/jamesls/fakeredis",
author='James Saryerwinnie',
author_email='jlsnpi@gmail.com',
py_modules=[... | from setuptools import setup, find_packages
setup(
name='fakeredis',
version='0.1',
description="Fake implementation of redis API for testing purposes.",
long_description=open(os.path.join(os.path.dirname(__file__),
'README.rst')).read(),
license='BSD',
ur... |
Use install_requires instead of requires. | from setuptools import setup
setup(
name='eclipsegen',
version='0.1',
description='Generate Eclipse instances in Python',
url='http://github.com/Gohla/eclipsegen',
author='Gabriel Konat',
author_email='gabrielkonat@gmail.com',
license='Apache 2.0',
packages=['eclipsegen'],
requires=['requests'],
te... | from setuptools import setup
setup(
name='eclipsegen',
version='0.1',
description='Generate Eclipse instances in Python',
url='http://github.com/Gohla/eclipsegen',
author='Gabriel Konat',
author_email='gabrielkonat@gmail.com',
license='Apache 2.0',
packages=['eclipsegen'],
install_requires=['requests... |
Add new paths for audit/ | #!/usr/bin/env python
#
# ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from distutils.core import setup
from hydra_agent import __version__
setup(
name = 'hydra-agent',
version = __version__,
author = "Whamcloud, Inc.",
author_email = "info@whamcloud... | #!/usr/bin/env python
#
# ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from distutils.core import setup
from hydra_agent import __version__
setup(
name = 'hydra-agent',
version = __version__,
author = "Whamcloud, Inc.",
author_email = "info@whamcloud... |
Drop support for EOL Python 2.6 and 3.3 | #!/usr/bin/env python
import os
from setuptools import setup
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
requirements = [
'six >= 1.4.0',
]
version = None
exec(open('dockerpycreds/version.py').read())
with open('./test-requirements.txt') as test_reqs_txt:
test_requirements = [... | #!/usr/bin/env python
import os
from setuptools import setup
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
requirements = [
'six >= 1.4.0',
]
version = None
exec(open('dockerpycreds/version.py').read())
with open('./test-requirements.txt') as test_reqs_txt:
test_requirements = [... |
Update install_requires to support future django versions | #!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['dja... | #!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['dja... |
Add iteration tests for reversed type | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ReversedTests(TranspileTestCase):
pass
class BuiltinReversedFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["reversed"]
not_implemented = [
'test_range',
]
| from .. utils import SAMPLE_DATA, TranspileTestCase, BuiltinFunctionTestCase
def _iterate_test(datatype):
def test_func(self):
code = '\n'.join([
'\nfor x in {value}:\n print(x)\n'.format(value=value)
for value in SAMPLE_DATA[datatype]
])
self.assertCodeExecutio... |
Bump version to prepare release v0.2.0 | # -*- coding: utf-8 -*-
__version__ = '0.1.3'
__version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')])
| # -*- coding: utf-8 -*-
__version__ = '0.2.0'
__version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')])
|
Remove kronos from installed apps | from .base import *
INSTALLED_APPS += (
'django_hstore',
'provider',
'provider.oauth2',
'south',
'easy_thumbnails',
'kronos',
)
| from .base import *
INSTALLED_APPS += (
'django_hstore',
'provider',
'provider.oauth2',
'south',
'easy_thumbnails',
)
|
Add peek() and revise main() | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
class Stack(object):
"""Stack class."""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[-1]
def ... |
Add basic AddEvent form with datetime conversion. | from flask_wtf import Form
from wtforms import TextField
from wtforms.validators import InputRequired, Length, Regexp
class SignupForm(Form):
username = TextField(validators=[InputRequired(), Length(min=1, max=30), Regexp("^[a-zA-Z0-9]+$")])
publicKey = TextField(validators=[InputRequired()]) # Add Length and ... | from flask_wtf import Form
from wtforms import TextField, DateTimeField
from wtforms.validators import InputRequired, Length, Regexp
class SignupForm(Form):
username = TextField(validators=[InputRequired(), Length(min=1, max=30), Regexp("^[a-zA-Z0-9]+$")])
publicKey = TextField(validators=[InputRequired()]) # ... |
Allow render to take a template different from the default one. | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... |
Fix default of grouping option for AAT | #! /usr/bin/env python
from pbhla.typing.sequences import type_sequences
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
add = parser.add_argument
add('amplicon_analysis', metavar='INPUT',
help="Fasta/Fastq/Folder of Amplicon Analysis output")
add('-g', '--gr... | #! /usr/bin/env python
from pbhla.typing.sequences import type_sequences
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
add = parser.add_argument
add('amplicon_analysis', metavar='INPUT',
help="Fasta/Fastq/Folder of Amplicon Analysis output")
add('-g', '--gr... |
Reduce some pubnub log noise | #!/usr/bin/env python3
import logging
from lrrbot.main import bot, log
from common.config import config
logging.basicConfig(level=config['loglevel'], format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
if config['logfile'] is not None:
fileHandler = logging.FileHandler(config['logfile'], 'a', 'utf-8')
file... | #!/usr/bin/env python3
import logging
from lrrbot.main import bot, log
from common.config import config
logging.basicConfig(level=config['loglevel'], format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
if config['logfile'] is not None:
fileHandler = logging.FileHandler(config['logfile'], 'a', 'utf-8')
file... |
FIX working with HTTPS correctly | try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbos... | try:
import xmlrpclib
from xmlrpclib import *
except ImportError:
# Python 3.0 portability fix...
import xmlrpc.client as xmlrpclib
from xmlrpc.client import *
import httplib
import socket
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbos... |
Set log level to 'WARN' | # Configuration file for jupyterhub.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# JupyterHub... | # Configuration file for jupyterhub.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# JupyterHub... |
Stop pylint complaining about bare-except | """
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (i... | """
plumbium.environment
====================
Module containing the get_environment function.
"""
import os
try:
import pip
except ImportError:
pass
import socket
def get_environment():
"""Obtain information about the executing environment.
Captures:
* installed Python packages using pip (i... |
Delete using deprecated fnc in test | # -*- coding: utf-8 -*-
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.css('.post_show')
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkd... | # -*- coding: utf-8 -*-
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(pat... |
Set parallel to 1000 because supervisor + ulimit = fail | # Source Server Stats
# File: sourcestats/settings.py
# Desc: settings for the Flask server
DEBUG = True
# Number of servers to collect from in parallel
PARALLEL = 4000
# Loop intervals (+time to execute!)
COLLECT_INTERVAL = 30
FIND_INTERVAL = 300
# Timeout for reading addresses via UDP from Valve
MASTER_TIMEOUT = ... | # Source Server Stats
# File: sourcestats/settings.py
# Desc: settings for the Flask server
DEBUG = True
# Number of servers to collect from in parallel
PARALLEL = 1000
# Loop intervals (+time to execute!)
COLLECT_INTERVAL = 30
FIND_INTERVAL = 300
# Timeout for reading addresses via UDP from Valve
MASTER_TIMEOUT = ... |
Add OCA as author of OCA addons | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2011 Elico Corp. All Rights Reserved.
# Author: Ian Li <ian.li@elico-corp.com>
#
# This program is free software: you can redistribute it a... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2011 Elico Corp. All Rights Reserved.
# Author: Ian Li <ian.li@elico-corp.com>
#
# This program is free software: you can redistribute it a... |
Add logger for junebug backend | from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID_FIELDNAME',
'registrant_id',
)
PODS[0]['field_mapping'] = [ # noqa: F405
{"field": "faccode",... | from __future__ import unicode_literals
import os
# import our default settings
from settings_production import * # noqa
LOGGING['loggers']['casepro.backend.junebug'] = {
'handlers': ['console'],
'level': 'INFO',
}
PODS[0]['contact_id_fieldname'] = os.environ.get( # noqa: F405
'REGISTRATION_CONTACT_ID... |
Fix jinja loader on Py3 | """Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based... | """Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based... |
Use correct m2m join table name in LatestCommentsFeed | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... | from django.conf import settings
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.contrib import comments
class LatestCommentFeed(Feed):
"""Feed of latest comments on the current site."""
def title(self):
if not hasattr(self, '_site'):
... |
Update test for changed filename | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir, create_update_dir
import os
@needinternet
def test_check_get_new(fixture_update_dir, create_update_dir):
"""Test that gets n... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir, create_update_dir
import os
@needinternet
def test_check_get_new(fixture_update_dir, create_update_dir):
"""Test that gets n... |
Add subparser for run analytics commands | import argparse
parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='List commands')
list_p... | import argparse
parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='List commands')
list_p... |
Use patch.object for python 2 compat | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
... | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
... |
Update installer autocreate for games with no icon | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = ... | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = ... |
Update DAX per 2021-06-24 changes | # Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import boolean
class SSESpecification(AWSProperty):
props = {
"SSEEnabled": (boolean, False),
}
class Cluster(AWSObject):
reso... | # Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import boolean
class SSESpecification(AWSProperty):
props = {
"SSEEnabled": (boolean, False),
}
class Cluster(AWSObject):
reso... |
Return name instead of unicode in autocomplete API | import json
from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
from tx_highered.models import Institution
class ApiView(View):
def get(self, request, *args, **kwargs):
data = self.get_content_data()
content = json.... | import json
from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
from tx_highered.models import Institution
class ApiView(View):
def get(self, request, *args, **kwargs):
data = self.get_content_data()
content = json.... |
Add import links for MultiHeadedAttention and prepare_self_attention | # coding: utf8
from __future__ import unicode_literals
from .neural._classes.convolution import ExtractWindow # noqa: F401
from .neural._classes.attention import ParametricAttention # noqa: F401
from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401
| # coding: utf8
from __future__ import unicode_literals
from .neural._classes.convolution import ExtractWindow # noqa: F401
from .neural._classes.attention import ParametricAttention # noqa: F401
from .neural._classes.rnn import LSTM, BiLSTM # noqa: F401
from .neural._classes.multiheaded_attention import MultiHeaded... |
Add search fields to stock models | from django.contrib import admin
from .models import *
class StockReportAdmin(admin.ModelAdmin):
model = StockReport
list_display = ['date', 'type', 'form_id']
list_filter = ['date', 'type']
class StockTransactionAdmin(admin.ModelAdmin):
model = StockTransaction
list_display = ['report_date', 'sec... | from django.contrib import admin
from .models import *
class StockReportAdmin(admin.ModelAdmin):
model = StockReport
list_display = ['date', 'type', 'form_id']
list_filter = ['date', 'type']
search_fields = ['form_id']
class StockTransactionAdmin(admin.ModelAdmin):
model = StockTransaction
l... |
Add test for no title search | from sharepa.search import basic_search
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
| from sharepa.search import ShareSearch
from sharepa.search import basic_search
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
my_search = my_search.query(
'query_string',
... |
Change platform and python fields to lists | import sys
import json
release_tag = sys.argv[1]
python_version = sys.argv[2]
ci_os = sys.argv[3]
platform_mapping = {
"ubuntu-latest": "linux-64",
"macOS-latest": "osx-64",
}
data = {
"name": "openforcefield",
"channel": "omnia",
"python": python_version,
"platform": platform_mapping[ci_os]... | import sys
import json
release_tag = sys.argv[1]
python_version = sys.argv[2]
ci_os = sys.argv[3]
platform_mapping = {
"ubuntu-latest": "linux-64",
"macOS-latest": "osx-64",
}
data = {
"name": "openforcefield",
"channel": "omnia",
"python": [python_version],
"platform": [platform_mapping[ci_... |
Allow reading word list from stdin. | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... | import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
... |
Fix type causing import error. | from __future__ import unicode_literals
from .impl import verify_spec_name
from .impl import get_spec_plugin_list
from .impl import Spec
from .rules import SpecParsingError
__all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name',
'Spec']
| from __future__ import unicode_literals
from .impl import verify_spec_name
from .impl import get_spec_plugin_list
from .impl import Spec
from .plugins.rules import SpecParsingError
__all__ = ['get_spec_plugin_list', 'SpecParsingError', 'verify_spec_name',
'Spec']
|
Fix splashscreen size on HiDPI (windows) screens | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QColor, QFont
from PyQt5.QtWidgets import QSplashScreen
from UM.Resources import Resources
from UM.Application import Application
class CuraSplashScreen(QSpl... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from PyQt5.QtCore import Qt, QCoreApplication
from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics
from PyQt5.QtWidgets import QSplashScreen
from UM.Resources import Resources
from UM.Application import Applicat... |
Remove all references to actually swapping | import os
import logging
import threading
log = logging.getLogger(__name__)
class Hotswap(threading.Thread):
def __init__(self, out, mod, *args, **kwargs):
self.out = out
self.mod = mod
self.gen = mod.generate(*args, **kwargs)
self.loaded = self.current_modtime
self.args =... | import os
import logging
import threading
log = logging.getLogger(__name__)
class Hotswap(threading.Thread):
def __init__(self, out, mod, *args, **kwargs):
self.out = out
self.gen = mod.generate(*args, **kwargs)
threading.Thread.__init__(self)
self.daemon = True
def run(self... |
Implement functions to obtain position and orientation given a pose | #!/usr/bin/env python
import rospy
def compute_control_actions(msg):
pass
if __name__ == '__main__':
rospy.init_node('controller')
subscriber = rospy.Subscriber('odometry_10_hz', Odometry, compute_control_actions)
rospy.spin()
| #!/usr/bin/env python
import rospy
import tf
from nav_msgs.msg import Odometry
i = 0
def get_position(pose):
return pose.pose.position
def get_orientation(pose):
quaternion = (
pose.pose.orientation.x,
pose.pose.orientation.y,
pose.pose.orientation.z,
pose.pose.orientation.w
... |
Fix doc formatting; wasn't expecting <pre> | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... |
Add test for RFC 6070 vectors. | import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
| import binascii
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
@pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
(b"password", b"salt",
1, 20, b"0c60c80f961f... |
Add crosshair and hover tools to bokeh html output | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import itertools
from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
def save_plot_to_file(traces, num... | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import itertools
from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
from bokeh.models import tools
de... |
Change pin LED is connected to. | from apiclient import errors
import threading
import time
import RPi.GPIO as GPIO
import GmailAuthorization
PIN = 22
CHECK_INTERVAL = 30
service = None
unread_count = 0
def refresh():
global unread_count
try:
messages = service.users().messages().list(userId='me', q='is:inbox + is:unread').execute()... | from apiclient import errors
import threading
import time
import RPi.GPIO as GPIO
import GmailAuthorization
PIN = 35
CHECK_INTERVAL = 30
service = None
unread_count = 0
def refresh():
global unread_count
try:
messages = service.users().messages().list(userId='me', q='is:inbox + is:unread').execute()... |
Add method to create resource | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... |
Fix read of wrong dictionnary | # Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class ProcurementRule(models.Model):
_inherit = 'procurement.rule'
def _get_stock_move_values(self, product_id, product_qty, product_uom,
... | # Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class ProcurementRule(models.Model):
_inherit = 'procurement.rule'
def _get_stock_move_values(self, product_id, product_qty, product_uom,
... |
Fix regex to optionally match substitution type and better whitespace support | #!/usr/bin/python
# Read doc comments and work out what fields to anonymize
import inspect
import re
from nova.db.sqlalchemy import models
ANON_CONFIG_RE = re.compile('^ *:anon ([^ ]+): ([^ ]+)$')
def load_configuration():
configs = {}
for name, obj in inspect.getmembers(models):
if not inspect... | #!/usr/bin/python
# Read doc comments and work out what fields to anonymize
import inspect
import re
from nova.db.sqlalchemy import models
ANON_CONFIG_RE = re.compile('^\s*:anon\s+(\S+):\s+(\S+)\s+(\S+)?\s*$')
def load_configuration():
configs = {}
for name, obj in inspect.getmembers(models):
i... |
Revert "tidy up ajax page loads so they count towards experiments" | from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# We detect widgets by relying on the fact that they are flagged as being embedable, and don't include these in visit tracking
if getattr(response, 'xframe_options... | from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# Don't track, failed pages, ajax requests, logged out users or widget impressions.
# We detect widgets by relying on the fact that they are flagged as being embeda... |
Check for WARN macro with space separating it from its paren | #!/usr/bin/env python3
# A linter to warn for ASSERT macros which are separated from their argument
# list by a space, which Clang's CPP barfs on
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'ASSERT\s+\(',
message='CPP macros should not have a space between the macro na... | #!/usr/bin/env python3
# A linter to warn for ASSERT macros which are separated from their argument
# list by a space, which Clang's CPP barfs on
from linter import run_linters, RegexpLinter
linters = [
RegexpLinter(r'WARN\s+\(',
message='CPP macros should not have a space between the macro name... |
Fix bug in Element to allow subclassing |
class Button(object):
"""Button object, used for creating button messages"""
def __init__(self, type=None, title="", payload=""):
# Type: request param key
valid_types = {
'web_url': 'url',
'postback': 'payload'
}
assert type in valid_types, "Type %s i... |
class Button(object):
"""Button object, used for creating button messages"""
def __init__(self, type=None, title="", payload=""):
# Type: request param key
valid_types = {
'web_url': 'url',
'postback': 'payload'
}
assert type in valid_types, "Type %s i... |
Handle no config.yaml in migrations | """
Migrate config to docker hosts list
"""
import os
import yaml
filename = os.path.join('data', 'configs.yaml')
with open(filename) as handle:
data = yaml.load(handle)
host = data.pop('docker_host')
data['docker_hosts'] = [host]
with open(filename, 'w') as handle:
yaml.dump(data, handle, default_flow_styl... | """
Migrate config to docker hosts list
"""
import os
import sys
import yaml
filename = os.path.join('data', 'configs.yaml')
try:
with open(filename) as handle:
data = yaml.load(handle)
except FileNotFoundError:
# This is fine; will fail for new installs
sys.exit(0)
host = data.pop('docker_host')... |
Create documentation of DataSource Settings | ######
# 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 test examples to assert against exceptions | from unittest import TestCase
from mock import NonCallableMock, patch
from modules.web_caller import get_google, GOOGLE_URL
class TestWebCaller(TestCase):
"""
Tests for the `web_caller` module.
"""
@patch('modules.web_caller.requests.get')
def test_get_google(self, get):
"""
Call... | from unittest import TestCase
from requests.exceptions import ConnectionError
from mock import NonCallableMock, patch
from modules.web_caller import get_google, GOOGLE_URL
MOCK_GOOGLE_URL = 'http://not-going-to-work!!!'
class TestWebCaller(TestCase):
"""
Tests for the `web_caller` module.
"""
@patc... |
Add ProtectedFile, ProtectedImage, AdminFile and AdminImage. | from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from .models import (Location, Permanence, Equipment, Lending, Position,
MembershipType, Membership, PublicFile, PublicImage,
ProtectedFile, ProtectedImage, AdminFile, AdminImage)
... | from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from .models import (Location, Permanence, Equipment, Lending, Position,
MembershipType, Membership, PublicFile, PublicImage,
ProtectedFile, ProtectedImage, AdminFile, AdminImage)
... |
Test unit test constructor and destructor | #/usr/bin/env python
import unittest
from my_calc import my_add
class test_func(unittest.TestCase):
def test_my_add(self):
res = my_add(1, 2)
self.assertEqual(res, 3)
if __name__ == "__main__":
unittest.main()
| #/usr/bin/env python
import unittest
from my_calc import my_add
class test_func(unittest.TestCase):
def test_my_add(self):
print("Test begin")
res = my_add(1, 2)
self.assertEqual(res, 3)
def setUp(self):
print("Setup")
def tearDown(self):
print("Tear down")
if __na... |
Update the equality test for database files | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------... | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------... |
Set vv cron script to use Agg backend | #!/usr/bin/env python
import mica.vv
mica.vv.update()
| #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import mica.vv
mica.vv.update()
|
Move utility function to migration | # Generated by Django 3.0.6 on 2020-06-05 14:35
from django.db import migrations
from ..utils import get_countries_without_shipping_zone
def assign_countries_in_default_shipping_zone(apps, schema_editor):
ShippingZone = apps.get_model("shipping", "ShippingZone")
qs = ShippingZone.objects.filter(default=True... | # Generated by Django 3.0.6 on 2020-06-05 14:35
from django.db import migrations
from django_countries import countries
def get_countries_without_shipping_zone(ShippingZone):
"""Return countries that are not assigned to any shipping zone."""
covered_countries = set()
for zone in ShippingZone.objects.all(... |
Test for sets, not dicts. | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from binascii import unhexlify
class TestHPACKDecoderInte... | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hyper.http20.hpack import Decoder
from binascii import unhexlify
class TestHPACKDecoderInte... |
Add message to user ban migration | """empty message
Revision ID: 1d91199c02c5
Revises:
Create Date: 2017-05-01 23:02:26.034481
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1d91199c02c5'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gener... | """Add user banned column
Revision ID: 1d91199c02c5
Revises:
Create Date: 2017-05-01 23:02:26.034481
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1d91199c02c5'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands a... |
Add quotes around date and time for python 2 | from django.db.backends.mysql.schema import DatabaseSchemaEditor \
as BaseDatabaseSchemaEditor
import sys
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
def execute(self, sql, params=()):
sql = str(sql)
if self.collect_sql:
ending = "" if sql.endswith(";") else ";"
... | from django.db.backends.mysql.schema import DatabaseSchemaEditor \
as BaseDatabaseSchemaEditor
import datetime
import sys
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
def execute(self, sql, params=()):
sql = str(sql)
if self.collect_sql:
ending = "" if sql.endswith(";") el... |
Update get_model_list to use app config rather than deprecated django.db.models.loading functions | import os
from django.conf import settings
from django.db.models.loading import get_models, get_app
default_app_config = 'calaccess_raw.apps.CalAccessRawConfig'
def get_download_directory():
"""
Returns the download directory where we will store downloaded data.
"""
if hasattr(settings, 'CALACCESS_DOW... | import os
from django.conf import settings
from django.apps import apps as django_apps
default_app_config = 'calaccess_raw.apps.CalAccessRawConfig'
def get_download_directory():
"""
Returns the download directory where we will store downloaded data.
"""
if hasattr(settings, 'CALACCESS_DOWNLOAD_DIR'):
... |
Refactor test to use cool py.test's fixture | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
Update to support python 3. | from os.path import join
import re
from setuptools_scm.utils import data_from_mime, trace
from setuptools_scm.version import meta, tags_to_versions
tag_re = re.compile(r'(?<=\btag: )([^,]+)\b')
def archival_to_version(data):
trace('data', data)
versions = tags_to_versions(tag_re.findall(data.get('ref-names... | from os.path import join
import re
from setuptools_scm.utils import data_from_mime, trace
from setuptools_scm.version import meta, tags_to_versions
tag_re = re.compile(r'(?<=\btag: )([^,]+)\b')
def archival_to_version(data):
trace('data', data)
versions = tags_to_versions(tag_re.findall(data.get('ref-names... |
Make DQN backward compatible with pytorch 0.1.2. | from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Ta... | from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Ta... |
Update imports and added PyQt4 support | import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class ComboBox(QWidget):
def __init__(self, parent=None, items=[]):
super(ComboBox, self).__init__(parent)
layout = QHBoxLayout()
self.cb = QComboBox()
self.items = items
self.cb.... | try:
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QComboBox
except ImportError:
# needed for py3+qt4
# Ref:
# http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
# http://stackoverflow.com/questions/21217399/pyqt4-qtcore-qvariant-object-instead-of-a-string
if sys.version_info.majo... |
Allow passing User directly to get_change_metadata | import sys
from datetime import datetime
from random import randint
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[-1].strip()
else:
ip = request.META.get("REMOTE_ADDR")
return ip
def create_v... | import sys
from datetime import datetime
from random import randint
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[-1].strip()
else:
ip = request.META.get("REMOTE_ADDR")
return ip
def create_v... |
Sort constant names alphabetically in docstring | """
Contains astronomical and physical constants for use in Astropy or other
places.
The package contains a `~astropy.constants.cgs` and `~astropy.constants.si`
module that define constants in CGS and SI units, respectively. A typical use
case might be::
from astropy.constants.cgs import c
... define the ma... | """
Contains astronomical and physical constants for use in Astropy or other
places.
The package contains a `~astropy.constants.cgs` and `~astropy.constants.si`
module that define constants in CGS and SI units, respectively. A typical use
case might be::
from astropy.constants.cgs import c
... define the ma... |
Test project: update settings names | DJMERCADOPAGO_CLIENT_ID = 'your-mp-client-id'
DJMERCADOPAGO_CLIENTE_SECRET = 'your-mp-secret'
DJMERCADOPAGO_SANDBOX_MODE = True
DJMERCADOPAGO_CHECKOUT_PREFERENCE_BUILDER = \
'full.path.to.checkout.builder.implementation.function'
| DJMERCADOPAGO_CLIENT_ID = 'your-mp-client-id'
DJMERCADOPAGO_CLIENTE_SECRET = 'your-mp-secret'
DJMERCADOPAGO_SANDBOX_MODE = True
DJMERCADOPAGO_CHECKOUT_PREFERENCE_UPDATER_FUNCTION = \
'full.path.to.checkout.builder.implementation.function'
|
Switch polling URL to git-on-borg. | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master.chromium_git_poller_bb8 import ChromiumGitPoller
def Update(config, active_master, c):
poller = ChromiumGitPoller(
repourl='http://g... | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master.chromium_git_poller_bb8 import ChromiumGitPoller
def Update(config, active_master, c):
poller = ChromiumGitPoller(
repourl='https://... |
Change host test to check for 'irrigatorpro' instead of my laptop's name, since the latter changes depending on the (wireless) network. | """
WSGI config for irrigator_pro project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os, os.path, site, sys, socket
# Add django root dir to python path
PROJECT_ROOT ... | """
WSGI config for irrigator_pro project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os, os.path, site, sys, socket
# Add django root dir to python path
PROJECT_ROOT ... |
Index on the cache collection. More work could be done here | """
Setup for the API
"""
import api
log = api.logger.use(__name__)
def index_mongo():
"""
Ensure the mongo collections are indexed.
"""
db = api.common.get_conn()
log.debug("Ensuring mongo is indexed.")
db.users.ensure_index("uid", unique=True, name="unique uid")
db.groups.ensure_inde... | """
Setup for the API
"""
import api
log = api.logger.use(__name__)
def index_mongo():
"""
Ensure the mongo collections are indexed.
"""
db = api.common.get_conn()
log.debug("Ensuring mongo is indexed.")
db.users.ensure_index("uid", unique=True, name="unique uid")
db.groups.ensure_inde... |
Fix background color on OS X for histogram widget of ray. | """
TrackingHistogramWidget
:Authors:
Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
class TrackingHistogramWidget(HistogramWidget):
"""
TrackingHistogramWidget
"""
updatePosition = Signal... | """
TrackingHistogramWidget
:Authors:
Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
from ui.widgets import Style
class TrackingHistogramWidget(HistogramWidget):
"""
TrackingHistogramWidget
... |
Add endpoint handling to Token/Endpoint auth | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
Apply OrderedDict changes to Bundle. | """STIX 2 Bundle object"""
from .base import _STIXBase
from .properties import IDProperty, Property, TypeProperty
class Bundle(_STIXBase):
_type = 'bundle'
_properties = {
'type': TypeProperty(_type),
'id': IDProperty(_type),
'spec_version': Property(fixed="2.0"),
'objects': ... | """STIX 2 Bundle object"""
from collections import OrderedDict
from .base import _STIXBase
from .properties import IDProperty, Property, TypeProperty
class Bundle(_STIXBase):
_type = 'bundle'
_properties = OrderedDict()
_properties = _properties.update([
('type', TypeProperty(_type)),
(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.