"""
Main script to execute the gesture recognition software.
"""

# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time

# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')

sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")

# Import LeapSDK
import Leap

def run_step():

    face = face_detector_gui.FDetector()
    face.run()
    print('Is face detected? ', face.face_detected)
    if face.face_detected:
        print("Enabled Gesture Recognition")
        # Create a sample listener and controller
        listener = MyListener()
        controller = Leap.Controller()
        controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
        # Have the sample listener receive events from the controller
        controller.add_listener(listener)

        t_end = time.time() + 20
        while time.time() < t_end:
            pass
        print('Disabled Gesture Recognition')
    return

if __name__ == "__main__":
    while True:
        run_step()

Add some prints to improve verbosity

Add some prints to improve verbosity

Response:
<REPLACE_OLD> print face.face_detected
 <REPLACE_NEW> print('Is face detected? ', face.face_detected)
 <REPLACE_END> <INSERT>        print("Enabled Gesture Recognition")
 <INSERT_END> <INSERT>     print('Disabled Gesture Recognition')
    <INSERT_END> <|endoftext|> """
Main script to execute the gesture recognition software.
"""

# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time

# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')

sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")

# Import LeapSDK
import Leap

def run_step():

    face = face_detector_gui.FDetector()
    face.run()
    print('Is face detected? ', face.face_detected)
    if face.face_detected:
        print("Enabled Gesture Recognition")
        # Create a sample listener and controller
        listener = MyListener()
        controller = Leap.Controller()
        controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
        # Have the sample listener receive events from the controller
        controller.add_listener(listener)

        t_end = time.time() + 20
        while time.time() < t_end:
            pass
        print('Disabled Gesture Recognition')
    return

if __name__ == "__main__":
    while True:
        run_step()

Prompt:
Add some prints to improve verbosity

"""
Main script to execute the gesture recognition software.
"""

# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time

# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')

sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")

# Import LeapSDK
import Leap

def run_step():

    face = face_detector_gui.FDetector()
    face.run()
    print face.face_detected
    if face.face_detected:
        # Create a sample listener and controller
        listener = MyListener()
        controller = Leap.Controller()
        controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
        # Have the sample listener receive events from the controller
        controller.add_listener(listener)

        t_end = time.time() + 20
        while time.time() < t_end:
            pass
    return

if __name__ == "__main__":
    while True:
        run_step()


# Copyright 2017 FiberHome Telecommunication Technologies CO.,LTD
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from tempest.lib.services.volume.v2 import availability_zone_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base

class TestAvailabilityZoneClient(base.BaseServiceTest):

    FAKE_AZ_LIST = {
        "availabilityZoneInfo": [
            {
                "zoneState": {
                    "available": True
                },
                "zoneName": "nova"
            }
        ]
    }

    def setUp(self):
        super(TestAvailabilityZoneClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.client = availability_zone_client.AvailabilityZoneClient(
            fake_auth, 'volume', 'regionOne')

    def _test_list_availability_zones(self, bytes_body=False):
        self.check_service_client_function(
            self.client.list_availability_zones,
            'tempest.lib.common.rest_client.RestClient.get',
            self.FAKE_AZ_LIST,
            bytes_body)

    def test_list_availability_zones_with_str_body(self):
        self._test_list_availability_zones()

    def test_list_availability_zones_with_bytes_body(self):
        self._test_list_availability_zones(bytes_body=True)

Add unit test for volume availability zone client

This patch adds unit test for volume v2 availability zone client.

Partially Implements: blueprint tempest-lib-missing-test-coverage

Change-Id: I94f758307255de06fbaf8c6744912b46e15a6cb2

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Copyright 2017 FiberHome Telecommunication Technologies CO.,LTD
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from tempest.lib.services.volume.v2 import availability_zone_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base

class TestAvailabilityZoneClient(base.BaseServiceTest):

    FAKE_AZ_LIST = {
        "availabilityZoneInfo": [
            {
                "zoneState": {
                    "available": True
                },
                "zoneName": "nova"
            }
        ]
    }

    def setUp(self):
        super(TestAvailabilityZoneClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.client = availability_zone_client.AvailabilityZoneClient(
            fake_auth, 'volume', 'regionOne')

    def _test_list_availability_zones(self, bytes_body=False):
        self.check_service_client_function(
            self.client.list_availability_zones,
            'tempest.lib.common.rest_client.RestClient.get',
            self.FAKE_AZ_LIST,
            bytes_body)

    def test_list_availability_zones_with_str_body(self):
        self._test_list_availability_zones()

    def test_list_availability_zones_with_bytes_body(self):
        self._test_list_availability_zones(bytes_body=True)
 <REPLACE_END> <|endoftext|> # Copyright 2017 FiberHome Telecommunication Technologies CO.,LTD
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from tempest.lib.services.volume.v2 import availability_zone_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base

class TestAvailabilityZoneClient(base.BaseServiceTest):

    FAKE_AZ_LIST = {
        "availabilityZoneInfo": [
            {
                "zoneState": {
                    "available": True
                },
                "zoneName": "nova"
            }
        ]
    }

    def setUp(self):
        super(TestAvailabilityZoneClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.client = availability_zone_client.AvailabilityZoneClient(
            fake_auth, 'volume', 'regionOne')

    def _test_list_availability_zones(self, bytes_body=False):
        self.check_service_client_function(
            self.client.list_availability_zones,
            'tempest.lib.common.rest_client.RestClient.get',
            self.FAKE_AZ_LIST,
            bytes_body)

    def test_list_availability_zones_with_str_body(self):
        self._test_list_availability_zones()

    def test_list_availability_zones_with_bytes_body(self):
        self._test_list_availability_zones(bytes_body=True)

Prompt:
Add unit test for volume availability zone client

This patch adds unit test for volume v2 availability zone client.

Partially Implements: blueprint tempest-lib-missing-test-coverage

Change-Id: I94f758307255de06fbaf8c6744912b46e15a6cb2


"""
Logging
=======
"""
import logging

import colorlog

def init_logger(level, printout=True):
    """
    Initialize app logger to configure its level/handler/formatter/etc..

    Todo:
        * A mean to raise click.Abort or sys.exit when CRITICAL is used;

    Args:
        level (str): Level name (``debug``, ``info``, etc..).

    Keyword Arguments:
        printout (bool): If False, logs will never be outputed.

    Returns:
        logging.Logger: Application logger.
    """
    root_logger = logging.getLogger("boussole")
    root_logger.setLevel(level)

    # Redirect outputs to the void space, mostly for usage within unittests
    if not printout:
        from io import StringIO
        dummystream = StringIO()
        handler = logging.StreamHandler(dummystream)
    # Standard output with colored messages
    else:
        handler = logging.StreamHandler()
        handler.setFormatter(
            colorlog.ColoredFormatter(
                '%(asctime)s - %(log_color)s%(message)s',
                datefmt="%H:%M:%S"
            )
        )

    root_logger.addHandler(handler)

    return root_logger

Response:
<REPLACE_OLD> StringIO <REPLACE_NEW> io <REPLACE_END> <|endoftext|> """
Logging
=======
"""
import logging

import colorlog

def init_logger(level, printout=True):
    """
    Initialize app logger to configure its level/handler/formatter/etc..

    Todo:
        * A mean to raise click.Abort or sys.exit when CRITICAL is used;

    Args:
        level (str): Level name (``debug``, ``info``, etc..).

    Keyword Arguments:
        printout (bool): If False, logs will never be outputed.

    Returns:
        logging.Logger: Application logger.
    """
    root_logger = logging.getLogger("boussole")
    root_logger.setLevel(level)

    # Redirect outputs to the void space, mostly for usage within unittests
    if not printout:
        from io import StringIO
        dummystream = StringIO()
        handler = logging.StreamHandler(dummystream)
    # Standard output with colored messages
    else:
        handler = logging.StreamHandler()
        handler.setFormatter(
            colorlog.ColoredFormatter(
                '%(asctime)s - %(log_color)s%(message)s',
                datefmt="%H:%M:%S"
            )
        )

    root_logger.addHandler(handler)

    return root_logger

Prompt:
Use StringIO object from 'io' module instead of deprecated 'StringIO' module

"""
Logging
=======
"""
import logging

import colorlog

def init_logger(level, printout=True):
    """
    Initialize app logger to configure its level/handler/formatter/etc..

    Todo:
        * A mean to raise click.Abort or sys.exit when CRITICAL is used;

    Args:
        level (str): Level name (``debug``, ``info``, etc..).

    Keyword Arguments:
        printout (bool): If False, logs will never be outputed.

    Returns:
        logging.Logger: Application logger.
    """
    root_logger = logging.getLogger("boussole")
    root_logger.setLevel(level)

    # Redirect outputs to the void space, mostly for usage within unittests
    if not printout:
        from StringIO import StringIO
        dummystream = StringIO()
        handler = logging.StreamHandler(dummystream)
    # Standard output with colored messages
    else:
        handler = logging.StreamHandler()
        handler.setFormatter(
            colorlog.ColoredFormatter(
                '%(asctime)s - %(log_color)s%(message)s',
                datefmt="%H:%M:%S"
            )
        )

    root_logger.addHandler(handler)

    return root_logger


import zmq
import time
import json

from django.core.management.base import NoArgsCommand

addr = 'tcp://127.0.0.1:5555'

class Command(NoArgsCommand):
    help = "Run the 0MQ based job processor. Accepts jobs from the job server and processes them."
    def handle(self, **options):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(addr)

        while True:
            socket.send("GET")
            job = socket.recv()
            if job == "EMPTY":
                time.sleep(1)
                continue

            job = json.loads(job)
            command = command_map[job['command']]
            del job['command']
            command(**job)

# Create the actual commands here and keep the command_map below up to date
def bootstrap(project_id):
    '''Run the bootstrap process inside the given project's base directory.'''
    print("bootstrapping %s" % project_id)

command_map = {
    'BOOTSTRAP': bootstrap,
}

Move the basic job processor into a django management command as well.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import zmq
import time
import json

from django.core.management.base import NoArgsCommand

addr = 'tcp://127.0.0.1:5555'

class Command(NoArgsCommand):
    help = "Run the 0MQ based job processor. Accepts jobs from the job server and processes them."
    def handle(self, **options):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(addr)

        while True:
            socket.send("GET")
            job = socket.recv()
            if job == "EMPTY":
                time.sleep(1)
                continue

            job = json.loads(job)
            command = command_map[job['command']]
            del job['command']
            command(**job)

# Create the actual commands here and keep the command_map below up to date
def bootstrap(project_id):
    '''Run the bootstrap process inside the given project's base directory.'''
    print("bootstrapping %s" % project_id)

command_map = {
    'BOOTSTRAP': bootstrap,
}
 <REPLACE_END> <|endoftext|> import zmq
import time
import json

from django.core.management.base import NoArgsCommand

addr = 'tcp://127.0.0.1:5555'

class Command(NoArgsCommand):
    help = "Run the 0MQ based job processor. Accepts jobs from the job server and processes them."
    def handle(self, **options):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(addr)

        while True:
            socket.send("GET")
            job = socket.recv()
            if job == "EMPTY":
                time.sleep(1)
                continue

            job = json.loads(job)
            command = command_map[job['command']]
            del job['command']
            command(**job)

# Create the actual commands here and keep the command_map below up to date
def bootstrap(project_id):
    '''Run the bootstrap process inside the given project's base directory.'''
    print("bootstrapping %s" % project_id)

command_map = {
    'BOOTSTRAP': bootstrap,
}

Prompt: Move the basic job processor into a django management command as well.


# -*- encoding: utf-8 -*-
import logging

from celery import shared_task
from django.utils import timezone

from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary

logger = logging.getLogger(__name__)

@shared_task
def mail_time_summary():
    users = []
    for item in InvoiceUser.objects.all():
        if item.mail_time_summary and item.user.email:
            users.append(item.user)
    for user in users:
        logger.info('mail_time_summary: {}'.format(user.username))
        report = time_summary(user, days=1)
        message = ''
        for d, summary in report.items():
            message = message + '\n\n{}, total time {}'.format(
                d.strftime('%d/%m/%Y %A'),
                summary['format_total'],
            )
            for ticket in summary['tickets']:
                message = message + '\n{}: {}, {} ({})'.format(
                    ticket['pk'],
                    ticket['contact'],
                    ticket['description'],
                    ticket['format_minutes'],
                )
        queue_mail_message(
            user,
            [user.email],
            'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
            message,
        )
    if users:
        process_mail.delay()

Response:
<REPLACE_OLD> '<table border="0">'
 <REPLACE_NEW> ''
 <REPLACE_END> <REPLACE_OLD> '<tr colspan="3">'
            message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A'))
            message = message + '</tr>'
 <REPLACE_NEW> '\n\n{}, total time {}'.format(
                d.strftime('%d/%m/%Y %A'),
                summary['format_total'],
            )
 <REPLACE_END> <REPLACE_OLD> '<tr>'
                message = message + '<td>{}</td>'.format(ticket['pk'])
                message = message + '<td>{}, {}</td>'.format(
 <REPLACE_NEW> '\n{}: {}, {} ({})'.format(
                    ticket['pk'],
 <REPLACE_END> <INSERT>     ticket['format_minutes'],
                <INSERT_END> <DELETE>                message = message + '<td>{}</td>'.format(
                    ticket['format_minutes'],
                )
                message = message + '</tr>'
            message = message + '<tr>'
            message = message + '<td></td><td></td>'
            message = message + '<td><b>{}</b></td>'.format(
                summary['format_total']
            )
            message = message + '</tr>'
        message = message + '</table>'
 <DELETE_END> <|endoftext|> # -*- encoding: utf-8 -*-
import logging

from celery import shared_task
from django.utils import timezone

from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary

logger = logging.getLogger(__name__)

@shared_task
def mail_time_summary():
    users = []
    for item in InvoiceUser.objects.all():
        if item.mail_time_summary and item.user.email:
            users.append(item.user)
    for user in users:
        logger.info('mail_time_summary: {}'.format(user.username))
        report = time_summary(user, days=1)
        message = ''
        for d, summary in report.items():
            message = message + '\n\n{}, total time {}'.format(
                d.strftime('%d/%m/%Y %A'),
                summary['format_total'],
            )
            for ticket in summary['tickets']:
                message = message + '\n{}: {}, {} ({})'.format(
                    ticket['pk'],
                    ticket['contact'],
                    ticket['description'],
                    ticket['format_minutes'],
                )
        queue_mail_message(
            user,
            [user.email],
            'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
            message,
        )
    if users:
        process_mail.delay()

Prompt:
Remove HTML table (our mail cannot send HTML)

# -*- encoding: utf-8 -*-
import logging

from celery import shared_task
from django.utils import timezone

from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary

logger = logging.getLogger(__name__)

@shared_task
def mail_time_summary():
    users = []
    for item in InvoiceUser.objects.all():
        if item.mail_time_summary and item.user.email:
            users.append(item.user)
    for user in users:
        logger.info('mail_time_summary: {}'.format(user.username))
        report = time_summary(user, days=1)
        message = '
'
        for d, summary in report.items():
            message = message + '
'
            message = message + '{}	'.format(d.strftime('%d/%m/%Y %A'))
            message = message + '
'
            for ticket in summary['tickets']:
                message = message + '
'
                message = message + '{}	'.format(ticket['pk'])
                message = message + '{}, {}	'.format(
                    ticket['contact'],
                    ticket['description'],
                )
                message = message + '{}	'.format(
                    ticket['format_minutes'],
                )
                message = message + '
'
            message = message + '
'
            message = message + '		'
            message = message + '{}	'.format(
                summary['format_total']
            )
            message = message + '
'
        message = message + '
'
        queue_mail_message(
            user,
            [user.email],
            'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
            message,
        )
    if users:
        process_mail.delay()


# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat  # noqa: F401

Add missing vat alias for Costa Rica

Add missing vat alias for Costa Rica

Response:
<REPLACE_OLD> numbers."""
 <REPLACE_NEW> numbers."""
from stdnum.cr import cpj as vat  # noqa: F401
 <REPLACE_END> <|endoftext|> # __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat  # noqa: F401

Prompt:
Add missing vat alias for Costa Rica

# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Costa Rican numbers."""


import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main',
                   'dusty = dusty.client:main']},
    zip_safe=False
)

Add entrypoint for Dusty client

Add entrypoint for Dusty client

Response:
<REPLACE_OLD> dusty.daemon:main']},
 <REPLACE_NEW> dusty.daemon:main',
                   'dusty = dusty.client:main']},
 <REPLACE_END> <|endoftext|> import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main',
                   'dusty = dusty.client:main']},
    zip_safe=False
)

Prompt:
Add entrypoint for Dusty client

import os
import sys
import imp
from setuptools import find_packages

try:
    from restricted_pkg import setup
except:
    # allow falling back to setuptools only if
    # we are not trying to upload
    if 'upload' in sys.argv:
        raise ImportError('restricted_pkg is required to upload, first do pip install restricted_pkg')
    from setuptools import setup

requirements = imp.load_source('requirements', os.path.realpath('requirements.py'))

setup(
    name='dusty',
    version='0.0.1',
    description='Docker-based development environment manager',
    url='https://github.com/gamechanger/dusty',
    private_repository='gamechanger',
    author='GameChanger',
    author_email='travis@gamechanger.io',
    packages=find_packages(),
    install_requires=requirements.install_requires,
    tests_require=requirements.test_requires,
    test_suite="nose.collector",
    entry_points={'console_scripts':
                  ['dustyd = dusty.daemon:main']},
    zip_safe=False
)


Response:
<INSERT> from __future__ <INSERT_END> <INSERT> absolute_import

import <INSERT_END> <|endoftext|> from __future__ import absolute_import

import logging

from django.contrib.auth import authenticate
from rest_framework import exceptions
from rest_framework.authentication import (
    BaseAuthentication, get_authorization_header
)

logger = logging.getLogger(__name__)

class AdfsAccessTokenAuthentication(BaseAuthentication):
    """
    ADFS access Token authentication
    """
    www_authenticate_realm = 'api'

    def authenticate(self, request):
        """
        Returns a `User` if a correct access token has been supplied
        in the Authorization header.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid authorization header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = 'Invalid authorization header. Access token should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        # Authenticate the user
        # The AdfsBackend authentication backend will notice the "access_token" parameter
        # and skip the request for an access token using the authorization code
        user = authenticate(access_token=auth[1])

        if user is None:
            raise exceptions.AuthenticationFailed('Invalid access token.')

        if not user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted.')

        return user, auth[1]

    def authenticate_header(self, request):
        return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm

Prompt:
Make sure we don't have a import namespace clash with DRF

For python 2.7 you need to add from __future__ import absolute_import

import logging

from django.contrib.auth import authenticate
from rest_framework import exceptions
from rest_framework.authentication import (
    BaseAuthentication, get_authorization_header
)

logger = logging.getLogger(__name__)

class AdfsAccessTokenAuthentication(BaseAuthentication):
    """
    ADFS access Token authentication
    """
    www_authenticate_realm = 'api'

    def authenticate(self, request):
        """
        Returns a `User` if a correct access token has been supplied
        in the Authorization header.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid authorization header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = 'Invalid authorization header. Access token should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        # Authenticate the user
        # The AdfsBackend authentication backend will notice the "access_token" parameter
        # and skip the request for an access token using the authorization code
        user = authenticate(access_token=auth[1])

        if user is None:
            raise exceptions.AuthenticationFailed('Invalid access token.')

        if not user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted.')

        return user, auth[1]

    def authenticate_header(self, request):
        return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm


import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args = args

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=True)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>')
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)

Remove the -p command-line option.

Response:
<DELETE>   <DELETE_END> <REPLACE_OLD> args
        self.single = sys.stdin.isatty() or args.print

    def displayhook(self, value):

        self.args.print and print(value)
        return super().displayhook(value)

 <REPLACE_NEW> args

 <REPLACE_END> <REPLACE_OLD> single=self.single)
 <REPLACE_NEW> single=True)
 <REPLACE_END> <REPLACE_OLD> name='<module>', single=self.single)
 <REPLACE_NEW> name='<module>')
 <REPLACE_END> <REPLACE_OLD> argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', <REPLACE_NEW> argparse.ArgumentParser()
parser.add_argument('file', <REPLACE_END> <|endoftext|> import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args = args

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=True)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>')
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)

Prompt:
Remove the -p command-line option.

It's pretty useless anyway. Use  instead.

import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args   = args
        self.single = sys.stdin.isatty() or args.print

    def displayhook(self, value):

        self.args.print and print(value)
        return super().displayhook(value)

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=self.single)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>', single=self.single)
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)


# Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import pytest

from paasta_tools.monitoring.check_mesos_quorum import check_mesos_quorum

def test_check_mesos_quorum_ok(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=3,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert error.value.code == 0

def test_check_mesos_quorum_critical(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=1,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "CRITICAL" in out
        assert error.value.code == 2

Add last metastatus check test

Add last metastatus check test

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import pytest

from paasta_tools.monitoring.check_mesos_quorum import check_mesos_quorum

def test_check_mesos_quorum_ok(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=3,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert error.value.code == 0

def test_check_mesos_quorum_critical(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=1,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "CRITICAL" in out
        assert error.value.code == 2
 <REPLACE_END> <|endoftext|> # Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import mock
import pytest

from paasta_tools.monitoring.check_mesos_quorum import check_mesos_quorum

def test_check_mesos_quorum_ok(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=3,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert error.value.code == 0

def test_check_mesos_quorum_critical(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=1,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "CRITICAL" in out
        assert error.value.code == 2

Prompt: Add last metastatus check test


#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Armando Guereca'

class ScriptFields:
    _internal_name = "script_fields"
    """
    This object create the script_fields definition
    """
    def __init__(self, field_name, script, params = None):
        self.fields={}
        self.add_field(field_name, script, params or {})

    def add_field(self, field_name, script, params = None):
        """
        Add a field to script_fields
        """
        data = {}
        if script:
            data['script'] = script
        else:
            raise ScriptFieldsError("Script is required for script_fields definition")
        if params:
            if isinstance(params, dict):
                if len(params):
                    data['params'] = params
            else:
                raise ScriptFieldsError("Parameters should be a valid dictionary")

        self.fields[field_name] = data

    def add_parameter(self, field_name, param_name, param_value):
        """
        Add a parameter to a field into script_fields

        The ScriptFields object will be returned, so calls to this can be chained.
        """
        try:
            self.fields[field_name]['params'][param_name] = param_value
        except Exception as ex:
            raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name,param_value,ex))

        return self

    def serialize(self):
        return self.fields

Add ScriptFields object used as parameter script_fields of Search object

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Armando Guereca'

class ScriptFields:
    _internal_name = "script_fields"
    """
    This object create the script_fields definition
    """
    def __init__(self, field_name, script, params = None):
        self.fields={}
        self.add_field(field_name, script, params or {})

    def add_field(self, field_name, script, params = None):
        """
        Add a field to script_fields
        """
        data = {}
        if script:
            data['script'] = script
        else:
            raise ScriptFieldsError("Script is required for script_fields definition")
        if params:
            if isinstance(params, dict):
                if len(params):
                    data['params'] = params
            else:
                raise ScriptFieldsError("Parameters should be a valid dictionary")

        self.fields[field_name] = data

    def add_parameter(self, field_name, param_name, param_value):
        """
        Add a parameter to a field into script_fields

        The ScriptFields object will be returned, so calls to this can be chained.
        """
        try:
            self.fields[field_name]['params'][param_name] = param_value
        except Exception as ex:
            raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name,param_value,ex))

        return self

    def serialize(self):
        return self.fields
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Armando Guereca'

class ScriptFields:
    _internal_name = "script_fields"
    """
    This object create the script_fields definition
    """
    def __init__(self, field_name, script, params = None):
        self.fields={}
        self.add_field(field_name, script, params or {})

    def add_field(self, field_name, script, params = None):
        """
        Add a field to script_fields
        """
        data = {}
        if script:
            data['script'] = script
        else:
            raise ScriptFieldsError("Script is required for script_fields definition")
        if params:
            if isinstance(params, dict):
                if len(params):
                    data['params'] = params
            else:
                raise ScriptFieldsError("Parameters should be a valid dictionary")

        self.fields[field_name] = data

    def add_parameter(self, field_name, param_name, param_value):
        """
        Add a parameter to a field into script_fields

        The ScriptFields object will be returned, so calls to this can be chained.
        """
        try:
            self.fields[field_name]['params'][param_name] = param_value
        except Exception as ex:
            raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name,param_value,ex))

        return self

    def serialize(self):
        return self.fields

Prompt: Add ScriptFields object used as parameter script_fields of Search object


import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)

Fix the location path of OpenIPSL

Fix the location path of OpenIPSL

Response:
<REPLACE_OLD> ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")

if <REPLACE_NEW> ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")

if <REPLACE_END> <|endoftext|> import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)

Prompt:
Fix the location path of OpenIPSL

import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)


from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
    uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    for _ in range(20):
        print(generate_name())

Response:
<REPLACE_OLD> random

_select <REPLACE_NEW> random

_select_random <REPLACE_END> <REPLACE_OLD> {1});'
_uncommon_select <REPLACE_NEW> {1});'
_select_uncommon <REPLACE_END> <REPLACE_OLD> cursor.execute(_select.format('adjective', <REPLACE_NEW> cursor.execute(_select_random.format('adjective', <REPLACE_END> <REPLACE_OLD> cursor.execute(_select.format('animal', <REPLACE_NEW> cursor.execute(_select_random.format('animal', <REPLACE_END> <REPLACE_OLD> cursor.execute(_select.format('name', <REPLACE_NEW> cursor.execute(_select_random.format('name', <REPLACE_END> <REPLACE_OLD> cursor.execute(_uncommon_select, <REPLACE_NEW> cursor.execute(_select_uncommon, <REPLACE_END> <REPLACE_OLD> cursor.execute(_uncommon_select, <REPLACE_NEW> cursor.execute(_select_uncommon, <REPLACE_END> <INSERT> for _ in range(20):
        <INSERT_END> <|endoftext|> from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
    uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    for _ in range(20):
        print(generate_name())

Prompt:
Rename the SQL module vars for consistency.

from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_uncommon_select = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_uncommon_select, [adj]).fetchone()
    uncommon_adj = cursor.execute(_uncommon_select, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    print(generate_name())


#!/usr/bin/env python

"""Simple Genetic Algorithm for solving TSP.

Usage:
  main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
  main.py (-h | --help)
  main.py (-v | --version)

Options:
  -h --help     Show this screen.
  -v --version  Show version.

"""
from docopt import docopt

class Genotype(object):
    """The population of chromosomes."""

    def __init__(self, population, elite):
        self.population = population
        # TODO: new_pop?
        self.elite = elite

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1')
    print(arguments)
    # TODO
    # read file
    # initialize pop
    # run ga (break down)

# Default crossover is PMX. Can also use CX.

Build interface w/ docopt and add POD

Build interface w/ docopt and add POD

Response:
<REPLACE_OLD> python

if __name__ == "__main__":
 <REPLACE_NEW> python

"""Simple Genetic Algorithm for solving TSP.

Usage:
  main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
  main.py (-h | --help)
  main.py (-v | --version)

Options:
  -h --help <REPLACE_END> <REPLACE_OLD> run()
 <REPLACE_NEW>  Show this screen.
  -v --version  Show version.

"""
from docopt import docopt

class Genotype(object):
    """The population of chromosomes."""

    def __init__(self, population, elite):
        self.population = population
        # TODO: new_pop?
        self.elite = elite

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1')
    print(arguments)
    # TODO
    # read file
    # initialize pop
    # run ga (break down)

# Default crossover is PMX. Can also use CX.
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

"""Simple Genetic Algorithm for solving TSP.

Usage:
  main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
  main.py (-h | --help)
  main.py (-v | --version)

Options:
  -h --help     Show this screen.
  -v --version  Show version.

"""
from docopt import docopt

class Genotype(object):
    """The population of chromosomes."""

    def __init__(self, population, elite):
        self.population = population
        # TODO: new_pop?
        self.elite = elite

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1')
    print(arguments)
    # TODO
    # read file
    # initialize pop
    # run ga (break down)

# Default crossover is PMX. Can also use CX.

Prompt:
Build interface w/ docopt and add POD

#!/usr/bin/env python

if __name__ == "__main__":
    run()


# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm", "engine_name",
                   "environment_name", "databaseinfra_name")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")

Add more options on filters

Add more options on filters

Response:
<REPLACE_OLD> "volume_alarm")
 <REPLACE_NEW> "volume_alarm", "engine_name",
                   "environment_name", "databaseinfra_name")
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm", "engine_name",
                   "environment_name", "databaseinfra_name")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")

Prompt:
Add more options on filters

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")


"""Queries the CSDMS model repository for all models written in C,
C++, Fortran 77, or Fortran 90."""
from ask_api_examples import make_query

query = '[[Programming language::C||C++||Fortran77||Fortran90]]|limit=10000'

def main():
    r = make_query(query, __file__)
    return r

if __name__ == '__main__':
    print main()

Add example to list all models written in Fortran or C/C++

Response:
<INSERT> """Queries the CSDMS model repository for all models written in C,
C++, Fortran 77, or Fortran 90."""
from ask_api_examples import make_query

query = '[[Programming language::C||C++||Fortran77||Fortran90]]|limit=10000'

def main():
 <INSERT_END> <INSERT>   r = make_query(query, __file__)
    return r

if __name__ == '__main__':
    print main()
 <INSERT_END> <|endoftext|> """Queries the CSDMS model repository for all models written in C,
C++, Fortran 77, or Fortran 90."""
from ask_api_examples import make_query

query = '[[Programming language::C||C++||Fortran77||Fortran90]]|limit=10000'

def main():
    r = make_query(query, __file__)
    return r

if __name__ == '__main__':
    print main()

Prompt: Add example to list all models written in Fortran or C/C++


# List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        print model._meta.app_label
        print "BRISA1"
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        print model._meta.app_label
        print "BRISA"
        return None

Response:
<REPLACE_OLD> ['auth','login','sessions']

class <REPLACE_NEW> ['auth', 'login', 'sessions', 'contenttypes', 'sites']

class <REPLACE_END> <DELETE> print model._meta.app_label
        print "BRISA"
        <DELETE_END> <INSERT> print model._meta.app_label
        print "BRISA1"
        <INSERT_END> <INSERT> print model._meta.app_label
        print "BRISA"
        <INSERT_END> <|endoftext|> # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        print model._meta.app_label
        print "BRISA1"
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        print model._meta.app_label
        print "BRISA"
        return None

Prompt:
[login] Add apps on list that will be used on the test databases

Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.

Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com>

# List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        print model._meta.app_label
        print "BRISA"
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        return None


#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import json
import logging
import sys

from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.utils import run_tests_helper

def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  parser.add_argument('-d', '--device', action='append', dest='devices',
                      help='Device to run cmd on. Runs on all devices if not '
                           'specified. Set multiple times for multiple devices')
  parser.add_argument('-v', '--verbose', default=0, action='count',
                      help='Verbose level (multiple times for more)')
  parser.add_argument('--blacklist-file', help='Device blacklist file.')
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output',
                      help='File to dump json output to.')
  args = parser.parse_args()
  run_tests_helper.SetLogLevel(args.verbose)

  args.blacklist_file = device_blacklist.Blacklist(
      args.blacklist_file) if args.blacklist_file else None
  attached_devices = device_utils.DeviceUtils.HealthyDevices(
      blacklist=args.blacklist_file)

  if args.devices:
    selected_devices = []
    attached_devices = {str(d): d for d in attached_devices}
    for serial in args.devices:
      if serial in attached_devices:
        selected_devices.append(attached_devices[serial])
      else:
        logging.warning('Specified device %s not found.', serial)
  else:
    selected_devices = attached_devices

  if not selected_devices:
    raise device_errors.NoDevicesError

  p_out = (device_utils.DeviceUtils.parallel(selected_devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root, check_return=True)
      .pGet(None))

  data = {}
  for device, output in zip(selected_devices, p_out):
    for line in output:
      print '%s: %s' %(device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0

if __name__ == '__main__':
  sys.exit(main())

[Android] Add util for running adb shell commands on device.

BUG=543257

Review URL: https://codereview.chromium.org/1498113002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#365301}

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import json
import logging
import sys

from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.utils import run_tests_helper

def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  parser.add_argument('-d', '--device', action='append', dest='devices',
                      help='Device to run cmd on. Runs on all devices if not '
                           'specified. Set multiple times for multiple devices')
  parser.add_argument('-v', '--verbose', default=0, action='count',
                      help='Verbose level (multiple times for more)')
  parser.add_argument('--blacklist-file', help='Device blacklist file.')
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output',
                      help='File to dump json output to.')
  args = parser.parse_args()
  run_tests_helper.SetLogLevel(args.verbose)

  args.blacklist_file = device_blacklist.Blacklist(
      args.blacklist_file) if args.blacklist_file else None
  attached_devices = device_utils.DeviceUtils.HealthyDevices(
      blacklist=args.blacklist_file)

  if args.devices:
    selected_devices = []
    attached_devices = {str(d): d for d in attached_devices}
    for serial in args.devices:
      if serial in attached_devices:
        selected_devices.append(attached_devices[serial])
      else:
        logging.warning('Specified device %s not found.', serial)
  else:
    selected_devices = attached_devices

  if not selected_devices:
    raise device_errors.NoDevicesError

  p_out = (device_utils.DeviceUtils.parallel(selected_devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root, check_return=True)
      .pGet(None))

  data = {}
  for device, output in zip(selected_devices, p_out):
    for line in output:
      print '%s: %s' %(device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0

if __name__ == '__main__':
  sys.exit(main())
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import json
import logging
import sys

from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.utils import run_tests_helper

def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  parser.add_argument('-d', '--device', action='append', dest='devices',
                      help='Device to run cmd on. Runs on all devices if not '
                           'specified. Set multiple times for multiple devices')
  parser.add_argument('-v', '--verbose', default=0, action='count',
                      help='Verbose level (multiple times for more)')
  parser.add_argument('--blacklist-file', help='Device blacklist file.')
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output',
                      help='File to dump json output to.')
  args = parser.parse_args()
  run_tests_helper.SetLogLevel(args.verbose)

  args.blacklist_file = device_blacklist.Blacklist(
      args.blacklist_file) if args.blacklist_file else None
  attached_devices = device_utils.DeviceUtils.HealthyDevices(
      blacklist=args.blacklist_file)

  if args.devices:
    selected_devices = []
    attached_devices = {str(d): d for d in attached_devices}
    for serial in args.devices:
      if serial in attached_devices:
        selected_devices.append(attached_devices[serial])
      else:
        logging.warning('Specified device %s not found.', serial)
  else:
    selected_devices = attached_devices

  if not selected_devices:
    raise device_errors.NoDevicesError

  p_out = (device_utils.DeviceUtils.parallel(selected_devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root, check_return=True)
      .pGet(None))

  data = {}
  for device, output in zip(selected_devices, p_out):
    for line in output:
      print '%s: %s' %(device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0

if __name__ == '__main__':
  sys.exit(main())

Prompt:
[Android] Add util for running adb shell commands on device.

BUG=543257

Review URL: https://codereview.chromium.org/1498113002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#365301}


from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

with open('README', 'rt') as file_obj:
    detailed_description = file_obj.read()
with open('CHANGELOG', 'rt') as file_obj:
    detailed_description += file_obj.read()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)

Response:
<REPLACE_OLD> ]

readme_file = <REPLACE_NEW> ]

with <REPLACE_END> <REPLACE_OLD> 'rt')
try:
 <REPLACE_NEW> 'rt') as file_obj:
 <REPLACE_END> <REPLACE_OLD> readme_file.read()
finally:
 <REPLACE_NEW> file_obj.read()
with open('CHANGELOG', 'rt') as file_obj:
 <REPLACE_END> <REPLACE_OLD> readme_file.close()

setup(
 <REPLACE_NEW> detailed_description += file_obj.read()

setup(
 <REPLACE_END> <|endoftext|> from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

with open('README', 'rt') as file_obj:
    detailed_description = file_obj.read()
with open('CHANGELOG', 'rt') as file_obj:
    detailed_description += file_obj.read()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)

Prompt:
Use context managers to build detailed_description.

from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

readme_file = open('README', 'rt')
try:
    detailed_description = readme_file.read()
finally:
    readme_file.close()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)


from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls['detail']

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls['detail']

Use the item access variant instead

Use the item access variant instead

Response:
<REPLACE_OLD> self.urls.url('detail')

class <REPLACE_NEW> self.urls['detail']

class <REPLACE_END> <REPLACE_OLD> self.urls.url('detail')
 <REPLACE_NEW> self.urls['detail']
 <REPLACE_END> <|endoftext|> from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls['detail']

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls['detail']

Prompt:
Use the item access variant instead

from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls.url('detail')

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls.url('detail')


import os

import blivet
from blivet.size import Size
from blivet.util import set_up_logging, create_sparse_tempfile

set_up_logging()
b = blivet.Blivet()   # create an instance of Blivet (don't add system devices)

# create a disk image file on which to create new devices
disk1_file = create_sparse_tempfile("disk1", Size("100GiB"))
b.disk_images["disk1"] = disk1_file
disk2_file = create_sparse_tempfile("disk2", Size("100GiB"))
b.disk_images["disk2"] = disk2_file

b.reset()

try:
    disk1 = b.devicetree.get_device_by_name("disk1")
    disk2 = b.devicetree.get_device_by_name("disk2")

    b.initialize_disk(disk1)
    b.initialize_disk(disk2)

    pv = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk1])
    b.create_device(pv)
    pv2 = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk2])
    b.create_device(pv2)

    # allocate the partitions (decide where and on which disks they'll reside)
    blivet.partitioning.do_partitioning(b)

    vg = b.new_vg(parents=[pv, pv2])
    b.create_device(vg)

    # new lv with base size 5GiB and growth up to 15GiB and an ext4 filesystem
    lv = b.new_lv(fmt_type="ext4", size=Size("5GiB"), parents=[vg], name="cached")
    b.create_device(lv)

    # new cache pool
    cpool = b.new_lv(size=Size("1 GiB"), parents=[vg], pvs=[pv2], cache_pool=True, name="fastlv")
    b.create_device(cpool)

    # write the new partitions to disk and format them as specified
    b.do_it()
    print(b.devicetree)

    # attach the newly created cache pool to the "slow" LV
    lv.attach_cache(cpool)

    b.reset()
    print(b.devicetree)

    input("Check the state and hit ENTER to trigger cleanup")
finally:
    b.devicetree.teardown_disk_images()
    os.unlink(disk1_file)
    os.unlink(disk2_file)

Add LVM cache pool example

examples: Add LVM cache pool example

Response:
<REPLACE_OLD>  <REPLACE_NEW> import os

import blivet
from blivet.size import Size
from blivet.util import set_up_logging, create_sparse_tempfile

set_up_logging()
b = blivet.Blivet()   # create an instance of Blivet (don't add system devices)

# create a disk image file on which to create new devices
disk1_file = create_sparse_tempfile("disk1", Size("100GiB"))
b.disk_images["disk1"] = disk1_file
disk2_file = create_sparse_tempfile("disk2", Size("100GiB"))
b.disk_images["disk2"] = disk2_file

b.reset()

try:
    disk1 = b.devicetree.get_device_by_name("disk1")
    disk2 = b.devicetree.get_device_by_name("disk2")

    b.initialize_disk(disk1)
    b.initialize_disk(disk2)

    pv = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk1])
    b.create_device(pv)
    pv2 = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk2])
    b.create_device(pv2)

    # allocate the partitions (decide where and on which disks they'll reside)
    blivet.partitioning.do_partitioning(b)

    vg = b.new_vg(parents=[pv, pv2])
    b.create_device(vg)

    # new lv with base size 5GiB and growth up to 15GiB and an ext4 filesystem
    lv = b.new_lv(fmt_type="ext4", size=Size("5GiB"), parents=[vg], name="cached")
    b.create_device(lv)

    # new cache pool
    cpool = b.new_lv(size=Size("1 GiB"), parents=[vg], pvs=[pv2], cache_pool=True, name="fastlv")
    b.create_device(cpool)

    # write the new partitions to disk and format them as specified
    b.do_it()
    print(b.devicetree)

    # attach the newly created cache pool to the "slow" LV
    lv.attach_cache(cpool)

    b.reset()
    print(b.devicetree)

    input("Check the state and hit ENTER to trigger cleanup")
finally:
    b.devicetree.teardown_disk_images()
    os.unlink(disk1_file)
    os.unlink(disk2_file)
 <REPLACE_END> <|endoftext|> import os

import blivet
from blivet.size import Size
from blivet.util import set_up_logging, create_sparse_tempfile

set_up_logging()
b = blivet.Blivet()   # create an instance of Blivet (don't add system devices)

# create a disk image file on which to create new devices
disk1_file = create_sparse_tempfile("disk1", Size("100GiB"))
b.disk_images["disk1"] = disk1_file
disk2_file = create_sparse_tempfile("disk2", Size("100GiB"))
b.disk_images["disk2"] = disk2_file

b.reset()

try:
    disk1 = b.devicetree.get_device_by_name("disk1")
    disk2 = b.devicetree.get_device_by_name("disk2")

    b.initialize_disk(disk1)
    b.initialize_disk(disk2)

    pv = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk1])
    b.create_device(pv)
    pv2 = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk2])
    b.create_device(pv2)

    # allocate the partitions (decide where and on which disks they'll reside)
    blivet.partitioning.do_partitioning(b)

    vg = b.new_vg(parents=[pv, pv2])
    b.create_device(vg)

    # new lv with base size 5GiB and growth up to 15GiB and an ext4 filesystem
    lv = b.new_lv(fmt_type="ext4", size=Size("5GiB"), parents=[vg], name="cached")
    b.create_device(lv)

    # new cache pool
    cpool = b.new_lv(size=Size("1 GiB"), parents=[vg], pvs=[pv2], cache_pool=True, name="fastlv")
    b.create_device(cpool)

    # write the new partitions to disk and format them as specified
    b.do_it()
    print(b.devicetree)

    # attach the newly created cache pool to the "slow" LV
    lv.attach_cache(cpool)

    b.reset()
    print(b.devicetree)

    input("Check the state and hit ENTER to trigger cleanup")
finally:
    b.devicetree.teardown_disk_images()
    os.unlink(disk1_file)
    os.unlink(disk2_file)

Prompt: examples: Add LVM cache pool example


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from flask import Flask
from werkzeug.utils import import_string

from me_api.middleware.me import me
from me_api.cache import cache

middlewares = {
    'douban': 'me_api.middleware.douban:douban_api',
    'github': 'me_api.middleware.github:github_api',
    'instagram': 'me_api.middleware.instagram:instagram_api',
    'keybase': 'me_api.middleware.keybase:keybase_api',
    'medium': 'me_api.middleware.medium:medium_api',
    'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        blueprint = import_string(middlewares[module])
        app.register_blueprint(blueprint)

    return app

Improve the way that import middlewares

Improve the way that import middlewares

Response:
<REPLACE_OLD> Flask

from .middleware.me <REPLACE_NEW> Flask
from werkzeug.utils import import_string

from me_api.middleware.me <REPLACE_END> <REPLACE_OLD> .cache <REPLACE_NEW> me_api.cache <REPLACE_END> <REPLACE_OLD> cache

def _register_module(app, module):
 <REPLACE_NEW> cache

middlewares = {
 <REPLACE_END> <REPLACE_OLD> if module == 'douban':
 <REPLACE_NEW> 'douban': 'me_api.middleware.douban:douban_api',
 <REPLACE_END> <INSERT> 'github': 'me_api.middleware.github:github_api',
 <INSERT_END> <REPLACE_OLD>  from .middleware import douban
 <REPLACE_NEW> 'instagram': 'me_api.middleware.instagram:instagram_api',
 <REPLACE_END> <INSERT> 'keybase': 'me_api.middleware.keybase:keybase_api',
 <INSERT_END> <REPLACE_OLD>  app.register_blueprint(douban.douban_api)
 <REPLACE_NEW> 'medium': 'me_api.middleware.medium:medium_api',
 <REPLACE_END> <REPLACE_OLD> elif module == 'github':
        from .middleware import github
        app.register_blueprint(github.github_api)
    elif module == 'instagram':
        from .middleware import instagram
        app.register_blueprint(instagram.instagram_api)
    elif module == 'keybase':
        from .middleware import keybase
        app.register_blueprint(keybase.keybase_api)
    elif module == 'medium':
        from .middleware import medium
        app.register_blueprint(medium.medium_api)
    elif module == 'stackoverflow':
        from .middleware import stackoverflow
        app.register_blueprint(stackoverflow.stackoverflow_api)

def <REPLACE_NEW> 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}

def <REPLACE_END> <REPLACE_OLD> _register_module(app, module)

 <REPLACE_NEW> blueprint = import_string(middlewares[module])
        app.register_blueprint(blueprint)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from flask import Flask
from werkzeug.utils import import_string

from me_api.middleware.me import me
from me_api.cache import cache

middlewares = {
    'douban': 'me_api.middleware.douban:douban_api',
    'github': 'me_api.middleware.github:github_api',
    'instagram': 'me_api.middleware.instagram:instagram_api',
    'keybase': 'me_api.middleware.keybase:keybase_api',
    'medium': 'me_api.middleware.medium:medium_api',
    'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        blueprint = import_string(middlewares[module])
        app.register_blueprint(blueprint)

    return app

Prompt:
Improve the way that import middlewares

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from flask import Flask

from .middleware.me import me
from .cache import cache

def _register_module(app, module):
    if module == 'douban':
        from .middleware import douban
        app.register_blueprint(douban.douban_api)
    elif module == 'github':
        from .middleware import github
        app.register_blueprint(github.github_api)
    elif module == 'instagram':
        from .middleware import instagram
        app.register_blueprint(instagram.instagram_api)
    elif module == 'keybase':
        from .middleware import keybase
        app.register_blueprint(keybase.keybase_api)
    elif module == 'medium':
        from .middleware import medium
        app.register_blueprint(medium.medium_api)
    elif module == 'stackoverflow':
        from .middleware import stackoverflow
        app.register_blueprint(stackoverflow.stackoverflow_api)

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        _register_module(app, module)

    return app


import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    else:
        data.confidence = entry.data.zzaEh

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

Response:
<INSERT> if 'agb' in entry.data:
        <INSERT_END> <INSERT> else:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value

    if 'agc' in entry.data:
        <INSERT_END> <INSERT>    else:
        data.confidence = entry.data.zzaEh

 <INSERT_END> <|endoftext|> import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    else:
        data.confidence = entry.data.zzaEh

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

Prompt:
Handle the weird field names from the new version of the API

As part of the switch to cordova, we moved to a newer version of the google
play API. Unfortunately, this meant that the weird field names for the
confidence and type changed to a different set of weird field names. We should
really use a standard wrapper class for this on android as well to avoid such
silent breakages in the future.

https://github.com/e-mission/e-mission-data-collection/issues/80

import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    data.type = ecwa.MotionTypes(entry.data.agb).value
    data.confidence = entry.data.agc
    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry