Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add workflow specific error classes | class NotSupportedError(Exception):
'''
Error class that is raised when a feature is not supported by the program.
'''
class MetadataError(Exception):
'''
Error class that is raised when a metadata element cannot be retrieved.
'''
class SubmissionError(Exception):
'''
Error class tha... | class NotSupportedError(Exception):
'''
Error class that is raised when a feature is not supported by the program.
'''
class MetadataError(Exception):
'''
Error class that is raised when a metadata element cannot be retrieved.
'''
class SubmissionError(Exception):
'''
Error class tha... |
Use new v2 api endpoint | from trakt.core.configuration import ConfigurationManager
from trakt.core.http import HttpClient
from trakt.interfaces import construct_map
from trakt.interfaces.base import InterfaceProxy
import logging
__version__ = '2.1.0'
log = logging.getLogger(__name__)
class TraktClient(object):
base_url = 'https://api.... | from trakt.core.configuration import ConfigurationManager
from trakt.core.http import HttpClient
from trakt.interfaces import construct_map
from trakt.interfaces.base import InterfaceProxy
import logging
__version__ = '2.1.0'
log = logging.getLogger(__name__)
class TraktClient(object):
base_url = 'https://api-... |
Check for pcre when building | #!/usr/bin/env python
from distutils.core import setup, Extension
packages=['qutepart', 'qutepart/syntax']
package_data={'qutepart/syntax' : ['data/*.xml',
'data/syntax_db.json']
}
extension = Extension('qutepart.syntax.cParser',
sources = ['qute... | #!/usr/bin/env python
import sys
from distutils.core import setup, Extension
import distutils.ccompiler
packages=['qutepart', 'qutepart/syntax']
package_data={'qutepart/syntax' : ['data/*.xml',
'data/syntax_db.json']
}
extension = Extension('qutepart.syntax.cParser',... |
Fix packaging to resolve the PEP420 namespace | """Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.0',
url='https://github.com/asyncdef/interfaces',
description='... | """Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.3',
url='https://github.com/asyncdef/interfaces',
description='... |
Add prefill_cache to make test_categorie_fiscale pass | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it ... | # -*- coding: utf-8 -*-
# OpenFisca -- A versatile microsimulation software
# By: OpenFisca Team <contact@openfisca.fr>
#
# Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team
# https://github.com/openfisca
#
# This file is part of OpenFisca.
#
# OpenFisca is free software; you can redistribute it and/or modify
# it ... |
Switch to new API domain | import requests
from allauth.socialaccount.providers.discord.provider import DiscordProvider
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class DiscordOAuth2Adapter(OAuth2Adapter):
provider_id = DiscordProvider.id
access_token_ur... | import requests
from allauth.socialaccount.providers.discord.provider import DiscordProvider
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class DiscordOAuth2Adapter(OAuth2Adapter):
provider_id = DiscordProvider.id
access_token_ur... |
Set default logging level to INFO | from __future__ import absolute_import, division, print_function
import logging
logging.basicConfig(level=logging.ERROR,
format='%(relativeCreated)6d %(threadName)s %(message)s')
from .satyr import get
from .delayed import mesos
| from __future__ import absolute_import, division, print_function
import logging
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
from .satyr import get
from .delayed import mesos
|
Set default server host address to 127.0.0.1 | import os
app_config = {
'DEBUG': bool(os.getenv('DEBUG', True)),
'REDIS_DB': int(os.getenv('REDIS_DB', 1)),
'REDIS_HOST': os.getenv('REDIS_HOST', '127.0.0.1'),
'REDIS_PORT': int(os.getenv('REDIS_PORT', 6379)),
'REDIS_PW': os.getenv('REDIS_PW', None),
'SERVER_HOST': os.getenv('SERVER_HOST', '0.... | import os
app_config = {
'DEBUG': bool(os.getenv('DEBUG', True)),
'REDIS_DB': int(os.getenv('REDIS_DB', 1)),
'REDIS_HOST': os.getenv('REDIS_HOST', '127.0.0.1'),
'REDIS_PORT': int(os.getenv('REDIS_PORT', 6379)),
'REDIS_PW': os.getenv('REDIS_PW', None),
'SERVER_HOST': os.getenv('SERVER_HOST', '12... |
Add pm2.5 avg view api | # coding=utf-8
from rest_framework import viewsets
from .models import AirCondition, AirAverage
from .serializers import AirAverageSerializer, AirConditionSerializer
class AirConditionViewSets(viewsets.ReadOnlyModelViewSet):
queryset = AirCondition.objects.all().order_by('-time')[:24] # 24 hours
serialize... | # coding=utf-8
from rest_framework import viewsets
from .models import AirCondition, AirAverage
from .serializers import AirAverageSerializer, AirConditionSerializer
class AirConditionViewSets(viewsets.ReadOnlyModelViewSet):
queryset = AirCondition.objects.all().order_by('-time')[:24] # 24 hours
serialize... |
Use plat_specific site-packages dir in CI script | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... | import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackages... |
Fix argparse of caffe model download script | #!/usr/bin/env python
from __future__ import print_function
import argparse
import six
parser = argparse.ArgumentParser(
descriptor='Download a Caffe reference model')
parser.add_argument('model_type',
help='Model type (alexnet, caffenet, googlenet)')
args = parser.parse_args()
if args.model... | #!/usr/bin/env python
from __future__ import print_function
import argparse
import six
parser = argparse.ArgumentParser(
description='Download a Caffe reference model')
parser.add_argument('model_type', choices=('alexnet', 'caffenet', 'googlenet'),
help='Model type (alexnet, caffenet, googlen... |
Fix undefined reference error in command line KeepKey plugin. | from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keys... | from electrum.plugins import hook
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class... |
Add new-style TEMPLATES setting for tests | import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATE_DIR... | import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATES=[
... |
Remove dependency check done by Mopidy | from __future__ import unicode_literals
import os
from mopidy import config, exceptions, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.di... | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file... |
Remove useless test about model representation | # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project %s>" % self.project.name)
def test_query(self... | # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_query(self):
pass
def test_get(self):
pass
def test_get_by(self):
pass
def test_get_all_by(self):
pass
def test_create(self):
pass
def tes... |
Load at a distance content in updatadata command | """Module for the custom Django updatedata command."""
from django.core import management
class Command(management.base.BaseCommand):
"""Required command class for the custom Django updatedata command."""
help = "Update all data from content folders for all applications"
def add_arguments(self, parser)... | """Module for the custom Django updatedata command."""
from django.core import management
class Command(management.base.BaseCommand):
"""Required command class for the custom Django updatedata command."""
help = "Update all data from content folders for all applications"
def add_arguments(self, parser)... |
Add stdout flushing statements to example. | #!/usr/bin/env python
# encoding: utf-8
from IPython.kernel import client
import time
tc = client.TaskClient()
mec = client.MultiEngineClient()
mec.execute('import time')
for i in range(24):
tc.run(client.StringTask('time.sleep(1)'))
for i in range(6):
time.sleep(1.0)
print "Queue status (vebose=False)... | #!/usr/bin/env python
# encoding: utf-8
from IPython.kernel import client
import time
import sys
flush = sys.stdout.flush
tc = client.TaskClient()
mec = client.MultiEngineClient()
mec.execute('import time')
for i in range(24):
tc.run(client.StringTask('time.sleep(1)'))
for i in range(6):
time.sleep(1.0)
... |
Clear cache when user changes info. | from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import Problem, Contest, Submission, Organization
from .caching import update_submission
@receiver(post_save, sender=Probl... | from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.cache import cache
from .models import Problem, Contest, Submission, Organization, Profile
from .caching import update_submission
@receiver(post_save, sen... |
Remove "is is" from lexical illusions | """WGD200: Lexical illusions.
---
layout: post
error_code: WGD200
source: write-good
source_url: https://github.com/btford/write-good
title: Lexical illusion present
date: 2014-06-10 12:31:19
categories: writing
---
A lexical illusion happens when a word word is unintentiall repeated twice, and
and... | """WGD200: Lexical illusions.
---
layout: post
error_code: WGD200
source: write-good
source_url: https://github.com/btford/write-good
title: Lexical illusion present
date: 2014-06-10 12:31:19
categories: writing
---
A lexical illusion happens when a word word is unintentiall repeated twice, and
and... |
Use 1212 as the default port | import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
help = "run a (local, debug) server"
def add_arguments(self, parser):
parser.add_argument(
'-p',
'--port',
... | import werkzeug.debug
import werkzeug.serving
from jacquard.commands import BaseCommand
from jacquard.service import get_wsgi_app
class RunServer(BaseCommand):
help = "run a (local, debug) server"
def add_arguments(self, parser):
parser.add_argument(
'-p',
'--port',
... |
Use mdptoolbox.example.small in the tests | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 14:44:07 2013
@author: steve
"""
import numpy as np
import scipy as sp
import mdptoolbox.example
STATES = 10
ACTIONS = 3
SMALLNUM = 10e-12
# np.arrays
P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]])
R_small = np.array([[5, 10], [-1, 2]])
P_sparse... | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 14:44:07 2013
@author: steve
"""
import numpy as np
import scipy as sp
import mdptoolbox.example
STATES = 10
ACTIONS = 3
SMALLNUM = 10e-12
# np.arrays
P_small, R_small = mdptoolbox.example.small()
P_sparse = np.empty(2, dtype=object)
P_sparse[0] = sp.sparse.csr_ma... |
Add ending slash to regex for article-detail view | from django.conf import settings
from django.conf.urls import patterns, include, url, static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'ctlibre.views.home', name='home'),
url(r'^article/(?P<slug>[^/]+)', 'news.views.article_detail',
name='article-det... | from django.conf import settings
from django.conf.urls import patterns, include, url, static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'ctlibre.views.home', name='home'),
url(r'^article/(?P<slug>[^/]+)/$', 'news.views.article_detail',
name='article-d... |
Revert "updated required sentrylogs version" | import os
from setuptools import setup, find_packages
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name='dj... | import os
from setuptools import setup, find_packages
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name='dj... |
Use real mail address to make PyPi happy | from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451 at laposte.net',
maintainer='montag451',
maintainer_email='montag451 at laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Pytho... | from setuptools import setup, Extension
setup(name='python-pytun',
author='montag451',
author_email='montag451@laposte.net',
maintainer='montag451',
maintainer_email='montag451@laposte.net',
url='https://github.com/montag451/pytun',
description='Linux TUN/TAP wrapper for Python',
... |
Increment to minor version 1.1.0 | import os
import setuptools
def readme():
if os.path.isfile('README.md'):
try:
import requests
r = requests.post(
url='http://c.docverter.com/convert',
data={'from': 'markdown', 'to': 'rst'},
files={'input_files[]': open('README.md', ... | import os
import setuptools
def readme():
if os.path.isfile('README.md'):
try:
import requests
r = requests.post(
url='http://c.docverter.com/convert',
data={'from': 'markdown', 'to': 'rst'},
files={'input_files[]': open('README.md', ... |
Change validate HTTP method to PUT | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400)... | import flask
from flask import request, json
def Response(data, status = 200):
body = json.dumps(data)
return flask.Response(body, status = status, mimetype = 'application/json')
def SuccessResponse(dataset_id = None):
return Response({ 'success': True, 'id': dataset_id })
def ErrorResponse(status = 400)... |
Use Juju 2 compatible deploy. | #!/usr/bin/env python
"""TODO: add rough description of what is assessed in this module."""
from __future__ import print_function
import argparse
import logging
import sys
from deploy_stack import (
BootstrapManager,
)
from utility import (
add_basic_testing_arguments,
configure_logging,
)
__me... | #!/usr/bin/env python
"""TODO: add rough description of what is assessed in this module."""
from __future__ import print_function
import argparse
import logging
import sys
from deploy_stack import (
BootstrapManager,
)
from jujucharm import local_charm_path
from utility import (
add_basic_testing_argumen... |
Add command to stop gkeepd | # Copyright 2018 Nathan Sommer and Ben Coleman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is dis... | # Copyright 2018 Nathan Sommer and Ben Coleman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is dis... |
Make the two Stack implementations consistent | class Stack(object):
def __init__(self):
self._items = []
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def size(self):
... | class Stack:
def __init__(self):
self._items = []
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def size(self):
r... |
Revert "Don't try to save SubjectSet.links.project on exiting objects" | from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.subject import Subject
class SubjectSet(PanoptesObject):
_api_slug = 'subject_sets'
_link_slug = 'subject_sets'
_edit_attributes = (
'display_name',
{
'links': (
'project',
... | from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.subject import Subject
class SubjectSet(PanoptesObject):
_api_slug = 'subject_sets'
_link_slug = 'subject_sets'
_edit_attributes = (
'display_name',
{
'links': (
'project',
... |
Add license to top of file. | # Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2019, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it unde... | |
Set logging level to be noisier, from CRITICAL to INFO. | import logging
session_mgr._logger.setLevel(logging.CRITICAL)
from ophyd.userapi import *
| import logging
session_mgr._logger.setLevel(logging.INFO)
from ophyd.userapi import *
|
Add type annotations for globus | from parsl.utils import RepresentationMixin
class GlobusScheme(RepresentationMixin):
"""Specification for accessing data on a remote executor via Globus.
Parameters
----------
endpoint_uuid : str
Universally unique identifier of the Globus endpoint at which the data can be accessed.
T... | import typeguard
from typing import Optional
from parsl.utils import RepresentationMixin
class GlobusScheme(RepresentationMixin):
"""Specification for accessing data on a remote executor via Globus.
Parameters
----------
endpoint_uuid : str
Universally unique identifier of the Globus endpoin... |
Tweak travis-ci settings for haystack setup and test | # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.
DEBUG = False
# include database settings to use Mari... | # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.
DEBUG = False
# include database settings to use Mari... |
Add test for empty responses | import unittest
from testbase import MQWebTest
'''
Test for AuthenticationInformationController
'''
class TestAuthInfoActions(MQWebTest):
'''
Test Inquire with HTTP GET
'''
def testInquire(self):
json = self.getJSON('/api/authinfo/inquire/' + self.qmgr)
'''
Test Inquire with HTTP POST
'''
def testInquire... | import unittest
from testbase import MQWebTest
'''
Test for AuthenticationInformationController
'''
class TestAuthInfoActions(MQWebTest):
'''
Test Inquire with HTTP GET
'''
def testInquire(self):
json = self.getJSON('/api/authinfo/inquire/' + self.qmgr)
'''
Test Empty Result with HTTP GET
'''
def testEmpt... |
Move hasher creation to constructor | from hashids import Hashids
class Shortener(object):
def __init__(self, secret, min_length, short_url_domain):
self.secret = secret
self.min_length = min_length
self.short_url_domain = short_url_domain
self._hasher = None
def get_short_id(self, number):
if self._hashe... | from hashids import Hashids
class Shortener(object):
def __init__(self, secret, min_length, short_url_domain):
self.secret = secret
self.min_length = min_length
self.short_url_domain = short_url_domain
self._hasher = Hashids(self.secret, self.min_length)
def get_short_id(self... |
Add User back into admin | from django.contrib.admin.sites import AdminSite
from django.conf.urls.defaults import patterns, url
from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet
class ShellsAdmin(AdminSite):
def get_urls(self):
urls = super(ShellsAdmin, self).get_urls()
my_urls = patterns('',
... | from django.contrib.admin.sites import AdminSite
from django.conf.urls.defaults import patterns, url
from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet
class ShellsAdmin(AdminSite):
def get_urls(self):
urls = super(ShellsAdmin, self).get_urls()
my_urls = patterns('',
... |
Add user registration URLs. Use what django-registration provides for the moment. | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import epiweb.apps.survey.urls
urlpatterns = patterns('',
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import epiweb.apps.survey.urls
urlpatterns = patterns('',
# Example:
# (r'^epiweb/', include('epiweb.foo.urls')),
# Uncomment the admin/doc line below and add... |
Add test to Path compare. | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... | from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize(... |
Allow access to state.output via API. | """
Non-init module for doing convenient * imports from.
Necessary because if we did this in __init__, one would be unable to import
anything else inside the package -- like, say, the version number used in
setup.py -- without triggering loads of most of the code. Which doesn't work so
well when you're using setup.py ... | """
Non-init module for doing convenient * imports from.
Necessary because if we did this in __init__, one would be unable to import
anything else inside the package -- like, say, the version number used in
setup.py -- without triggering loads of most of the code. Which doesn't work so
well when you're using setup.py ... |
Fix no module 'new', replaced new.instancemethod with types.MethodType | """
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import new
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return new.ins... | """
Some extra picklers needed to gracefully dump and load a canvas.
"""
from future import standard_library
standard_library.install_aliases()
import copyreg
# Allow instancemethod to be pickled:
import types
def construct_instancemethod(funcname, self, clazz):
func = getattr(clazz, funcname)
return types... |
Disable min_priority filter for now | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
CAPTURE_SCORE_BASE = 120 ** 3
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.curre... | #!/usr/bin/python
import board
import pente_exceptions
from ab_state import *
class ABGame():
""" This class acts as a bridge between the AlphaBeta code and my code """
def __init__(self, base_game):
s = self.current_state = ABState()
s.set_state(base_game.current_state)
self.base_gam... |
Remove the old coast import. | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import ev... | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '2.1.3'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave', 'Michael Bedington', 'Ricardo Torres']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
import sys
from warnings import warn
# Import ev... |
Fix paths for local execution different from cloud server. | #!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
inputpath = '/data/amnh/darwin/images'
segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])... | #!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
... |
Set user.email_address.verified as true when user changed his password | from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.signals import email_confirmation_sent, user_signed_up
from board.models import Board, Notification
from board.utils import treedict
@receiver(email_confirmation_sen... | from django.contrib.sessions.models import Session
from django.dispatch import receiver
from django.utils.translation import ugettext as _
from account.models import EmailAddress
from account.signals import email_confirmation_sent, password_changed, user_signed_up
from board.models import Board, Notification
from boar... |
Change the order of the subcommands. | from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands import repl, install, screenshot, logs, account, timeline
from .commands.sdk import build, emulator, create, convert
from .exceptions im... | from __future__ import absolute_import, print_function
__author__ = 'katharine'
import argparse
import logging
import sys
from .commands.base import register_children
from .commands.sdk import build, create
from .commands import install, logs, screenshot, timeline, account, repl
from .commands.sdk import convert, emu... |
Remove all of the SeriesNode inline stuff (doesn't work yet) | from django.contrib import admin
from django.contrib.contenttypes import generic
from . import models
class SeriesNodeInline(generic.GenericTabularInline):
model = models.SeriesNode
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
inlines = [
SeriesNodeInline,
]
prepopulated... | from django.contrib import admin
from . import models
class SeriesAdmin(admin.ModelAdmin):
model = models.Series
prepopulated_fields = {
'slug': ('title', ),
}
admin.site.register(models.Series, SeriesAdmin)
|
Add get_absolute_url method to serializer | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = Relations... | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class IdentifierSerializer(JSONAPISerializer):
category = ser.CharField(read_only=True)
identifier = LinksField({
'self': 'get_identifiers'
})
referent = Relations... |
Allow signal handlers to be disabled to run in subthread | import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HT... | import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_han... |
Change update value to produce less thrash on embedded side | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... | import blinkycolor
import serial
class BlinkyTape(object):
def __init__(self, port, baud_rate = 115200, pixel_count = 60):
self._serial = serial.Serial(port, baud_rate)
self._pixel_count = pixel_count
self._pixels = [blinkycolor.BLACK] * self._pixel_count
@property
def pixel_count(... |
Store current working directory before import | #
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
sys.path.append(os.getcwd() + "/classes")
... | #
# This program provides a simple command line to query population statistics.
# Author: Tay Joc Cing
# Date: 20 Mar 2015
#
import sys
import os
sys.path.append(os.getcwd() + "/classes")
from country import Country
from datamanager import DataManager
from dispatcher import CommandDispatcher
from constants import *
... |
Fix passing the search_term parameter to Searcher |
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display... |
"""
grep_redone, version 0.9
Search files for a pattern or string, optionally do this recursively.
usage: grep_redone [-rnfe] [SEARCH_TERM]
Arguments:
SEARCH_TERM The string to search for.
Options:
-h --help Display this page.
-r Do a recursive search.
-f Display... |
Add the newsitems to GAE NDB | from webapp2 import RequestHandler, WSGIApplication
from src.news_feed import get_news_feed
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Editorials!')
news = get_news_feed()
for n in news:
self.response.write("\n\n{}\n{}\n{}\n{}".form... | from time import mktime
from datetime import datetime
from webapp2 import RequestHandler, WSGIApplication
from google.appengine.ext import ndb
from src.news_feed import get_news_feed
import hashlib
class Feeds(RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
news_list = get_new... |
Set response encoding based on apparent_encoding. | import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
return r.text, r.status_code
| import requests
def user_guide():
r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html")
r.encoding = r.apparent_encoding
return r.text, r.status_code
|
Add interlinks urls for doc and tiliado | # -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from common_conf import *
SITEURL = ".."
TEMPLATE = "doc/theme/templates/jsdoc.html"
TITLE = "NuvolaKit 3.0 JavaScript API Reference"
| # -*- coding: utf-8 -*- #
from __future__ import unicode_literals
from common_conf import *
SITEURL = ".."
TEMPLATE = "doc/theme/templates/jsdoc.html"
TITLE = "NuvolaKit 3.0 JavaScript API Reference"
INTERLINKS = {
"doc": "../",
"tiliado": TILIADOWEB,
}
|
Delete the exercise bases, not the translations | # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exer... | # Generated by Django 3.2.15 on 2022-08-25 17:25
from django.db import migrations
from django.conf import settings
def delete_pending_exercises(apps, schema_editor):
"""
Delete all pending exercises
Note that we can't access STATUS_PENDING here because we are not using
a real model.
"""
Exer... |
Update common context processors tests. | from nose.tools import eq_
from django.test import TestCase
from us_ignite.common.tests import utils
from us_ignite.common import context_processors
class TestSettingsAvailableContextProcessor(TestCase):
def test_settings_are_available(self):
request = utils.get_request('get', '/')
context = co... | from nose.tools import eq_
from django.test import TestCase
from us_ignite.common.tests import utils
from us_ignite.common import context_processors
class TestSettingsAvailableContextProcessor(TestCase):
def test_settings_are_available(self):
request = utils.get_request('get', '/')
context = co... |
Change for EAS invalid pw case, to allow user to re-enter pw once before raising error. | # TODO perhaps move this to normal auth module...
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
class AuthError(Exception):
pass
def password_auth(email_address):
pw = getpass.getpass('Password for %s (hidden): ' % email_address)
if len(pw) <= 0:
raise ... | # TODO perhaps move this to normal auth module...
import getpass
AUTH_TYPES = {'Gmail': 'OAuth', 'Yahoo': 'Password', 'EAS': 'Password'}
message = 'Password for {0}(hidden): '
class AuthError(Exception):
pass
def password_auth(email_address, message=message):
pw = getpass.getpass(message.format(email_addre... |
Use 'isinstance' in preference to 'type' method | from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to... | from ._abstract import AbstractScraper
class AllRecipes(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to... |
Test - fix output dir name | # Copyright 2015 0xc0170
#
# 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, soft... | # Copyright 2015 0xc0170
#
# 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, soft... |
Add optional timeout argument to probe | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exi... | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns ... |
Add google analytics tracking id | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://blog.uname.gr'
RELATIVE_URLS = False
... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# This file is only used if you use `make publish` or
# explicitly specify it as your config file.
import os
import sys
sys.path.append(os.curdir)
from pelicanconf import *
SITEURL = 'http://blog.uname.gr'
RELATIVE_URLS = False
... |
Remove download link from GH | from setuptools import setup
setup(
name='sfdc-bulk',
packages=['sfdc_bulk'],
version='0.1',
description='Python client library for SFDC bulk API',
url='https://github.com/donaldrauscher/sfdc-bulk',
download_url='https://github.com/donaldrauscher/sfdc-bulk/archive/0.1.tar.gz',
author='Donal... | from setuptools import setup
setup(
name='sfdc-bulk',
packages=['sfdc_bulk'],
version='0.2',
description='Python client library for SFDC bulk API',
url='https://github.com/donaldrauscher/sfdc-bulk',
author='Donald Rauscher',
author_email='donald.rauscher@gmail.com',
license='MIT',
i... |
Add support for monitor starterlog | #!/bin/env python
#
# cat_StarterLog.py
#
# Print out the StarterLog for a glidein output file
#
# Usage: cat_StarterLog.py logname
#
import os.path
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StarterLog.py <logname>"
def main():
try:... | #!/bin/env python
#
# cat_StarterLog.py
#
# Print out the StarterLog for a glidein output file
#
# Usage: cat_StarterLog.py logname
#
import os.path
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StarterLog.py [-monitor] <logname>"
def main(... |
Check the existence of the images_path | import os
import base64
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.image import Image
class SyncImages(OpenStackSyncStep):
provides=[Image]
requested_interval=0
observes=Image
def fetch_pending(self, deleted... | import os
import base64
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.image import Image
class SyncImages(OpenStackSyncStep):
provides=[Image]
requested_interval=0
observes=Image
def fetch_pending(self, deleted... |
Add open directory utility function | import pkg_resources
def open_directory(engine, kwargs):
entry_point = None
for candidate_entry_point in pkg_resources.iter_entry_points(
'jacquard.directory_engines',
name=engine,
):
entry_point = candidate_entry_point
if entry_point is None:
raise RuntimeError("Cann... | |
Add dynamic mapping creation with nested type | # -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError
from storm import Bolt, log
class ESIndexBolt(Bolt):
def initialize(self, conf, context):
log('bolt initializing')
# TODO: Make connection params configurable.
self.es = Elas... | # -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.exceptions import NotFoundError
from elasticsearch.exceptions import TransportError
from storm import Bolt, log
class ESIndexBolt(Bolt):
def initialize(self, conf, context):
l... |
Update resource group unit test | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... | from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase
class AzureResourceGroupTestCase(ProviderTestBase):
def test_resource_group_create(self):
resource_group_params = {'location': self.provider.region_name}
rg = self.provider.azure_client. \
create_resource_group... |
Add avatarUrl to team member serializers | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMember
@register(OrganizationMember)
class OrganizationMemberSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'id': str(obj.id),
... | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import OrganizationMember
from sentry.utils.avatar import get_gravatar_url
@register(OrganizationMember)
class OrganizationMemberSerializer(Serializer):
def serialize(self, obj, attrs, user):
... |
Convert institutions detail to pytest | from nose.tools import * # flake8: noqa
from tests.base import ApiTestCase
from osf_tests.factories import InstitutionFactory
from api.base.settings.defaults import API_BASE
class TestInstitutionDetail(ApiTestCase):
def setUp(self):
super(TestInstitutionDetail, self).setUp()
self.institution = I... | import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import InstitutionFactory
@pytest.mark.django_db
class TestInstitutionDetail:
@pytest.fixture()
def institution(self):
return InstitutionFactory()
@pytest.fixture()
def url_institution(self):
def u... |
Remove logging from fact init | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
logger = logging.getLogger('awx.fact')
| # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
|
Make sure correct project name is used throughout | # -*- coding: utf-8 -*-
"""
parsescrapegenerate
---------------
Main package for ParseScapeFeed
"""
__title__ = 'ParseScrapeGenerate'
__version__ = '0.1.0'
| # -*- coding: utf-8 -*-
"""
parsescrapegenerate
---------------
Main package for ParseScrapeGenerate
"""
__title__ = 'ParseScrapeGenerate'
__version__ = '0.1.0'
|
Add url for 'list all bookings' view. | from django.conf.urls import include, url
from . import views
app_name = "students"
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^booking/$', views.booking, name='booking'),
url(r'^booking/list/$', views.booking_list, name='list_booking'),
url(r'^booking/(?P<booking_id>[\d]+)/delete... | from django.conf.urls import include, url
from . import views
app_name = "students"
urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^booking/$', views.booking, name='booking'),
url(r'^booking/list/$', views.booking_list, name='list_booking'),
url(r'^booking/listall/(?P<booking_date>\d{... |
Add fuzz call to SBStringList.AppendString(None). LLDB should not crash. | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.AppendString("another string")
obj.AppendList(None, 0)
obj.AppendList(lldb.SBStringList())
obj.GetSize()
obj.GetStringAtIndex(0xffffffff)
obj.Clear()
... | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.AppendString("another string")
obj.AppendString(None)
obj.AppendList(None, 0)
obj.AppendList(lldb.SBStringList())
obj.GetSize()
obj.GetStringAtIndex(0x... |
Make sure we're testing the right function! | import pytest
import pytz
from astral import LocationInfo
class TestLocationInfo:
def test_Default(self):
loc = LocationInfo()
assert loc.name == "Greenwich"
assert loc.region == "England"
assert loc.timezone == "Europe/London"
assert loc.latitude == pytest.approx(51.4733, ... | import pytest
import pytz
from astral import LocationInfo
class TestLocationInfo:
def test_Default(self):
loc = LocationInfo()
assert loc.name == "Greenwich"
assert loc.region == "England"
assert loc.timezone == "Europe/London"
assert loc.latitude == pytest.approx(51.4733, ... |
Remove job when done and match servicelayer api | import logging
from followthemoney import model
from servicelayer.worker import Worker
from servicelayer.jobs import JobStage as Stage
from ingestors.manager import Manager
log = logging.getLogger(__name__)
class IngestWorker(Worker):
"""A long running task runner that uses Redis as a task queue"""
def dis... | import logging
from followthemoney import model
from servicelayer.worker import Worker
from servicelayer.jobs import JobStage as Stage
from ingestors.manager import Manager
log = logging.getLogger(__name__)
class IngestWorker(Worker):
"""A long running task runner that uses Redis as a task queue"""
def dis... |
Handle sensors / types that aren't in config file | #!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open("config.yml", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = "sensor_mqtt_"+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqt... | #!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open("config.yml", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = "sensor_mqtt_"+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqt... |
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org... |
Increase iterations. Add assertion of max board cards. | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... |
Enable port list optimization by default for new install+provision | import string
template = string.Template("""
[DEFAULTS]
ifmap_server_ip=$__contrail_ifmap_server_ip__
ifmap_server_port=$__contrail_ifmap_server_port__
ifmap_username=$__contrail_ifmap_username__
ifmap_password=$__contrail_ifmap_password__
cassandra_server_list=$__contrail_cassandra_server_list__
listen_ip_addr=$__con... | import string
template = string.Template("""
[DEFAULTS]
ifmap_server_ip=$__contrail_ifmap_server_ip__
ifmap_server_port=$__contrail_ifmap_server_port__
ifmap_username=$__contrail_ifmap_username__
ifmap_password=$__contrail_ifmap_password__
cassandra_server_list=$__contrail_cassandra_server_list__
listen_ip_addr=$__con... |
Remove print statements for syncdb receivers | from django.db.models.signals import post_syncdb
from django.conf import settings
from accounts import models
def ensure_core_accounts_exists(sender, **kwargs):
create_source_account()
create_sales_account()
create_expired_account()
def create_sales_account():
name = getattr(settings, 'ACCOUNTS_SAL... | from django.db.models.signals import post_syncdb
from django.conf import settings
from accounts import models
def ensure_core_accounts_exists(sender, **kwargs):
create_source_account()
create_sales_account()
create_expired_account()
def create_sales_account():
name = getattr(settings, 'ACCOUNTS_SAL... |
Add altitude cross event detector | from astropy import units as u
from numpy.linalg import norm
class LithobrakeEvent:
"""Terminal event that detects impact with the attractor surface.
Parameters
----------
R : float
Radius of the attractor.
"""
def __init__(self, R):
self._R = R
self._last_t = None
... | from astropy import units as u
from numpy.linalg import norm
class LithobrakeEvent:
"""Terminal event that detects impact with the attractor surface.
Parameters
----------
R : float
Radius of the attractor.
"""
def __init__(self, R):
self._R = R
self._last_t = None
... |
Add compute_formula method to MrpPropertyFormula to use in modules which depending on it | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... |
Fix migration script 12.0.1.0.0 of partner_firstname | def store_ir_config_param(cr):
"""Prior to version 12.0 the default order of partner
names was last_first. In order to retain this behaviour we
store the config parameter if it is not present.
"""
cr.execute("SELECT 1 FROM ir_config_parameter "
"WHERE name = 'partner_names_order'")
... | def store_ir_config_param(cr):
"""Prior to version 12.0 the default order of partner
names was last_first. In order to retain this behaviour we
store the config parameter if it is not present.
"""
cr.execute("SELECT 1 FROM ir_config_parameter "
"WHERE key = 'partner_names_order'")
... |
Allow slugs in url patterns | from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w+)/$', 'views.withTag'),
... | from django.conf.urls.defaults import *
from .feed import blogFeed
urlpatterns = patterns('copywriting',
(r'^feed\.rss$', blogFeed()),
(r'^feed/$', blogFeed()),
(r'^tag/(?P<in_tag>\w[\w-]+)/$', 'views.withTag'),
# (r'^(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', 'views.listBlogEntriesByYearMonthDay'),... |
Fix a rather stupid bug. | #! /usr/bin/env python
#
# Copyright (c) 2011 SEOmoz
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, mer... | #! /usr/bin/env python
#
# Copyright (c) 2011 SEOmoz
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, mer... |
Add volume disk usage to snapshot tags | """Place of record for the package version"""
__version__ = "1.1.15"
__rpm_version__ = "WILL_BE_SET_BY_RPM_BUILD"
__git_hash__ = "WILL_BE_SET_BY_EGG_BUILD"
| """Place of record for the package version"""
__version__ = "1.1.16"
__rpm_version__ = "WILL_BE_SET_BY_RPM_BUILD"
__git_hash__ = "WILL_BE_SET_BY_EGG_BUILD"
|
Use appspotmail.com instead of appspot.com for email sender | # Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.
# The app name will be used in several places.
APP_NAME = 'Yelp Love'
APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'
LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspot.com>'
# Flask's secret key, used to encry... | # Copy this file to config.py and change the settings. Don't forget to specify your own SECRET_KEY.
# The app name will be used in several places.
APP_NAME = 'Yelp Love'
APP_BASE_URL = 'https://PROJECT_ID.appspot.com/'
LOVE_SENDER_EMAIL = 'Yelp Love <love@PROJECT_ID.appspotmail.com>'
# Flask's secret key, used to e... |
Make it easier to kill the daemon | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
import api
from threading import Thread
import sys
def callback(event):
if event:
print(str(event))
def listen(daemon):
while True:
house, unit, act = input().split()
unit = int(unit)
i... | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
import api
from threading import Thread
import sys
def callback(event):
if event:
print(str(event))
def listen(daemon):
while True:
house, unit, act = input().split()
unit = int(unit)
i... |
Change how logging works again :) | import logging
from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib
VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')
logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ:
if environ.get(VEXT_DEBUG_LOG, "0") == "1":
... | import logging
import sys
from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib
VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')
logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ and environ.get(VEXT_DEBUG_LOG, "0") == "1"... |
Add version handling in SummaryView for the patches BP | # Copyright (C) 2015 The Debsources developers <info@sources.debian.net>.
# See the AUTHORS file at the top-level directory of this distribution and at
# https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD
#
# This file is part of Debsources. Debsources is free software: you can
# redistrib... | # Copyright (C) 2015 The Debsources developers <info@sources.debian.net>.
# See the AUTHORS file at the top-level directory of this distribution and at
# https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD
#
# This file is part of Debsources. Debsources is free software: you can
# redistrib... |
Extend Sender.send() to return boolean status. | import datetime
import logging
import json
import urllib.parse
import requests
class Sender():
SERVER_SERVICES = {
'collections': '/collections'}
REQUEST_HEADERS = {
'Content-Type': 'application/json'}
def __init__(self, server_uri, logger=None):
self.server_uri = se... | import datetime
import logging
import json
import urllib.parse
import requests
class Sender():
SERVER_SERVICES = {
'collections': '/collections'}
REQUEST_HEADERS = {
'Content-Type': 'application/json'}
def __init__(self, server_uri, logger=None):
self.server_uri = se... |
Fix a copy paste fail | from nose.tools import *
from exercises import ex25
def test_make_ing_form_ie():
'''
Test for ie match
'''
present_verb = ex25.make_ing_form('tie')
assert_equal(third_person_form, 'tying')
def test_make_ing_form_e():
'''
Test for e match
'''
present_verb = ex25.make_ing_form('g... | from nose.tools import *
from exercises import ex25
def test_make_ing_form_ie():
'''
Test for ie match
'''
present_verb = ex25.make_ing_form('tie')
assert_equal(present_verb, 'tying')
def test_make_ing_form_e():
'''
Test for e match
'''
present_verb = ex25.make_ing_form('grate'... |
Fix an issue in python 2 for the scratch extension. | import os
import re
from jinja2 import Template
DEFAULT_TEMPLATE = os.path.join(os.path.dirname(__file__), 'extension.tpl.js')
supported_modules = [
'button',
'dynamixel',
'l0_dc_motor',
'l0_gpio',
'l0_servo',
'led',
'potard',
]
def find_modules(state, type):
return [
m['ali... | import os
import re
from jinja2 import Template
DEFAULT_TEMPLATE = os.path.join(os.path.dirname(__file__), 'extension.tpl.js')
supported_modules = [
'button',
'dynamixel',
'l0_dc_motor',
'l0_gpio',
'l0_servo',
'led',
'potard',
]
def find_modules(state, type):
return [
str(m[... |
Remove package import to prevent missing dependencies error | #!/usr/bin/env python
from setuptools import setup
from PyFileMaker import __version__
setup(
name='PyFileMaker',
version=__version__,
description='Python Object Wrapper for FileMaker Server XML Interface',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
... | #!/usr/bin/env python
from setuptools import setup
setup(
name='PyFileMaker',
version="3.3",
description='Python Object Wrapper for FileMaker Server XML Interface',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
... |
Add url pattern for debug toolbar | from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
| from django.conf.urls import include, url
from django.contrib import admin
from core import settings
admin.site.site_header = 'Coworking space administration'
urlpatterns = [
url(r'^billjobs/', include('billjobs.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
import debug_toolbar
... |
Add missing dev config values | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map =... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "certbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
bui... |
Adjust logging and fix module documentation | """Create the profile.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogge... | """Remove the profiles.
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import shutil
import dodocs.logger as dlog
import dodocs.utils as dutils
def remove(args):
"""Remove profile(s)
Parameters
----------
args : namespace
parsed command line arguments
"""
log = dlog.getLogg... |
Fix getting major.minor django version | def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join(version.split('.')[:2])
| def get_major_dot_minor_version(version):
"""
Convert full VERSION Django tuple to
a dotted string containing MAJOR.MINOR.
For example, (1, 9, 3, 'final', 0) will result in '1.9'
"""
return '.'.join([str(v) for v in version[:2]])
|
Add click support on layout widget | import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background"... | import base
from .. import manager, bar, hook
class CurrentLayout(base._TextBox):
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("padding", None, "Padding left and right. Calculated if None."),
("background"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.