Send timestamps as ISO8601 format

Send timestamps as ISO8601 format

--- girder/utility/__init__.py
+++ girder/utility/__init__.py
@@ -17,6 +17,7 @@
 #  limitations under the License.
 ###############################################################################

+import datetime
 import json
 import re

@@ -41,4 +42,6 @@
     def default(self, obj):
         if isinstance(obj, set):
             return tuple(obj)
+        elif isinstance(obj, datetime.datetime):
+            return obj.isoformat()
         return str(obj)

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

###############################################################################
#  Copyright Kitware 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 json
import re

def camelcase(value):
    """
    Convert a module name or string with underscores and periods to camel case.
    :param value: the string to convert
    :type value: str
    :returns: the value converted to camel case.
    """
    return ''.join(x.capitalize() if x else '_' for x in
                   re.split("[._]+", value))

class JsonEncoder(json.JSONEncoder):
    """
    This extends the standard json.JSONEncoder to allow for more types to be
    sensibly serialized. This is used in Girder's REST layer to serialize
    route return values when JSON is requested.
    """
    def default(self, obj):
        if isinstance(obj, set):
            return tuple(obj)
        return str(obj)

<|edits_diff|>
--- girder/utility/__init__.py
+++ girder/utility/__init__.py
@@ -17,6 +17,7 @@
 #  limitations under the License.
 ###############################################################################

+import datetime
 import json
 import re

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

###############################################################################
#  Copyright Kitware 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 datetime
import json
import re

def camelcase(value):
    """
    Convert a module name or string with underscores and periods to camel case.
    :param value: the string to convert
    :type value: str
    :returns: the value converted to camel case.
    """
    return ''.join(x.capitalize() if x else '_' for x in
                   re.split("[._]+", value))

class JsonEncoder(json.JSONEncoder):
    """
    This extends the standard json.JSONEncoder to allow for more types to be
    sensibly serialized. This is used in Girder's REST layer to serialize
    route return values when JSON is requested.
    """
    def default(self, obj):
        if isinstance(obj, set):
            return tuple(obj)
        return str(obj)

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

###############################################################################
#  Copyright Kitware 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 datetime
import json
import re

def camelcase(value):
    """
    Convert a module name or string with underscores and periods to camel case.
    :param value: the string to convert
    :type value: str
    :returns: the value converted to camel case.
    """
    return ''.join(x.capitalize() if x else '_' for x in
                   re.split("[._]+", value))

class JsonEncoder(json.JSONEncoder):
    """
    This extends the standard json.JSONEncoder to allow for more types to be
    sensibly serialized. This is used in Girder's REST layer to serialize
    route return values when JSON is requested.
    """
    def default(self, obj):
        if isinstance(obj, set):
            return tuple(obj)
        elif isinstance(obj, datetime.datetime):
            return obj.isoformat()
        return str(obj)


Add docstring to the methods structure in the abstract class

--- recipe_scrapers/_abstract.py
+++ recipe_scrapers/_abstract.py
@@ -13,22 +13,29 @@
             self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser")

     def host(self):
+        """ get the host of the url, so we can use the correct scraper (check __init__.py) """
         raise NotImplementedError("This should be implemented.")

     def publisher_site(self):
+        """ the original url of the publisher site """
         raise NotImplementedError("This should be implemented.")

     def title(self):
+        """ title of the recipe itself """
         raise NotImplementedError("This should be implemented.")

     def total_time(self):
+        """ total time it takes to preparate the recipe in minutes """
         raise NotImplementedError("This should be implemented.")

     def ingredients(self):
+        """ list of ingredients needed for the recipe """
         raise NotImplementedError("This should be implemented.")

     def directions(self):
+        """ directions provided on the recipe link """
         raise NotImplementedError("This should be implemented.")

     def social_rating(self):
+        """ social rating of the recipe in 0 - 100 scale """
         raise NotImplementedError("This should be implemented.")

<|original_code|>
from urllib import request

from bs4 import BeautifulSoup

class AbstractScraper():

    def __init__(self, url, test=False):
        if test:
            # when testing, we simply load a file
            self.soup = BeautifulSoup(url.read(), "html.parser")
        else:
            self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser")

    def host(self):
        raise NotImplementedError("This should be implemented.")

    def publisher_site(self):
        raise NotImplementedError("This should be implemented.")

    def title(self):
        raise NotImplementedError("This should be implemented.")

    def total_time(self):
        raise NotImplementedError("This should be implemented.")

    def ingredients(self):
        raise NotImplementedError("This should be implemented.")

    def directions(self):
        raise NotImplementedError("This should be implemented.")

    def social_rating(self):
        raise NotImplementedError("This should be implemented.")

<|edits_diff|>
--- recipe_scrapers/_abstract.py
+++ recipe_scrapers/_abstract.py
@@ -13,21 +13,27 @@
             self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser")

     def host(self):
+        """ get the host of the url, so we can use the correct scraper (check __init__.py) """
         raise NotImplementedError("This should be implemented.")

     def publisher_site(self):
+        """ the original url of the publisher site """
         raise NotImplementedError("This should be implemented.")

     def title(self):
+        """ title of the recipe itself """
         raise NotImplementedError("This should be implemented.")

     def total_time(self):
+        """ total time it takes to preparate the recipe in minutes """
         raise NotImplementedError("This should be implemented.")

     def ingredients(self):
+        """ list of ingredients needed for the recipe """
         raise NotImplementedError("This should be implemented.")

     def directions(self):
+        """ directions provided on the recipe link """
         raise NotImplementedError("This should be implemented.")

     def social_rating(self):
<|current_version|>
from urllib import request

from bs4 import BeautifulSoup

class AbstractScraper():

    def __init__(self, url, test=False):
        if test:
            # when testing, we simply load a file
            self.soup = BeautifulSoup(url.read(), "html.parser")
        else:
            self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser")

    def host(self):
        """ get the host of the url, so we can use the correct scraper (check __init__.py) """
        raise NotImplementedError("This should be implemented.")

    def publisher_site(self):
        """ the original url of the publisher site """
        raise NotImplementedError("This should be implemented.")

    def title(self):
        """ title of the recipe itself """
        raise NotImplementedError("This should be implemented.")

    def total_time(self):
        """ total time it takes to preparate the recipe in minutes """
        raise NotImplementedError("This should be implemented.")

    def ingredients(self):
        """ list of ingredients needed for the recipe """
        raise NotImplementedError("This should be implemented.")

    def directions(self):
        """ directions provided on the recipe link """
        raise NotImplementedError("This should be implemented.")

    def social_rating(self):
        raise NotImplementedError("This should be implemented.")

<|next_version|>
from urllib import request

from bs4 import BeautifulSoup

class AbstractScraper():

    def __init__(self, url, test=False):
        if test:
            # when testing, we simply load a file
            self.soup = BeautifulSoup(url.read(), "html.parser")
        else:
            self.soup = BeautifulSoup(request.urlopen(url).read(), "html.parser")

    def host(self):
        """ get the host of the url, so we can use the correct scraper (check __init__.py) """
        raise NotImplementedError("This should be implemented.")

    def publisher_site(self):
        """ the original url of the publisher site """
        raise NotImplementedError("This should be implemented.")

    def title(self):
        """ title of the recipe itself """
        raise NotImplementedError("This should be implemented.")

    def total_time(self):
        """ total time it takes to preparate the recipe in minutes """
        raise NotImplementedError("This should be implemented.")

    def ingredients(self):
        """ list of ingredients needed for the recipe """
        raise NotImplementedError("This should be implemented.")

    def directions(self):
        """ directions provided on the recipe link """
        raise NotImplementedError("This should be implemented.")

    def social_rating(self):
        """ social rating of the recipe in 0 - 100 scale """
        raise NotImplementedError("This should be implemented.")


Add func_scope to embedding functions

Add func_scope to embedding functions

--- nn/embedding/embeddings.py
+++ nn/embedding/embeddings.py
@@ -2,13 +2,16 @@

 from ..flags import FLAGS
 from ..variable import variable
+from ..util import func_scope

+@func_scope()
 def embeddings(*, id_space_size, embedding_size, name=None):
   return variable([id_space_size, embedding_size], name=name)

+@func_scope()
 def word_embeddings(name="word_embeddings"):
   if FLAGS.word_embeddings is None:
     return embeddings(id_space_size=FLAGS.word_space_size,

<|original_code|>
import tensorflow as tf

from ..flags import FLAGS
from ..variable import variable

def embeddings(*, id_space_size, embedding_size, name=None):
  return variable([id_space_size, embedding_size], name=name)

def word_embeddings(name="word_embeddings"):
  if FLAGS.word_embeddings is None:
    return embeddings(id_space_size=FLAGS.word_space_size,
                      embedding_size=FLAGS.word_embedding_size,
                      name=name)
  return tf.Variable(tf.cast(FLAGS.word_embeddings, FLAGS.float_type),
                     name=name)

<|edits_diff|>
--- nn/embedding/embeddings.py
+++ nn/embedding/embeddings.py
@@ -2,9 +2,11 @@

 from ..flags import FLAGS
 from ..variable import variable
+from ..util import func_scope

+@func_scope()
 def embeddings(*, id_space_size, embedding_size, name=None):
   return variable([id_space_size, embedding_size], name=name)

<|current_version|>
import tensorflow as tf

from ..flags import FLAGS
from ..variable import variable
from ..util import func_scope

@func_scope()
def embeddings(*, id_space_size, embedding_size, name=None):
  return variable([id_space_size, embedding_size], name=name)

def word_embeddings(name="word_embeddings"):
  if FLAGS.word_embeddings is None:
    return embeddings(id_space_size=FLAGS.word_space_size,
                      embedding_size=FLAGS.word_embedding_size,
                      name=name)
  return tf.Variable(tf.cast(FLAGS.word_embeddings, FLAGS.float_type),
                     name=name)

<|next_version|>
import tensorflow as tf

from ..flags import FLAGS
from ..variable import variable
from ..util import func_scope

@func_scope()
def embeddings(*, id_space_size, embedding_size, name=None):
  return variable([id_space_size, embedding_size], name=name)

@func_scope()
def word_embeddings(name="word_embeddings"):
  if FLAGS.word_embeddings is None:
    return embeddings(id_space_size=FLAGS.word_space_size,
                      embedding_size=FLAGS.word_embedding_size,
                      name=name)
  return tf.Variable(tf.cast(FLAGS.word_embeddings, FLAGS.float_type),
                     name=name)


Add NullHandler to the 'spotify' logger

Add NullHandler to the 'spotify' logger

--- spotify/__init__.py
+++ spotify/__init__.py
@@ -1,5 +1,6 @@
 from __future__ import unicode_literals

+import logging
 import os
 import weakref

@@ -7,6 +8,11 @@

 __version__ = '2.0.0a1'
+
+
+# Log to nowhere by default. For details, see:
+# http://docs.python.org/2/howto/logging.html#library-config
+logging.getLogger('spotify').addHandler(logging.NullHandler())

 _header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')

<|original_code|>
from __future__ import unicode_literals

import os
import weakref

import cffi

__version__ = '2.0.0a1'

_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')])

# Mapping between keys and objects that should be kept alive as long as the key
# is alive. May be used to keep objects alive when there isn't a more
# convenient place to keep a reference to it. The keys are weakrefs, so entries
# disappear from the dict when the key is garbage collected, potentially
# causing objects associated to the key to be garbage collected as well. For
# further details, refer to the CFFI docs.
global_weakrefs = weakref.WeakKeyDictionary()

from spotify.error import *  # noqa

<|edits_diff|>
--- spotify/__init__.py
+++ spotify/__init__.py
@@ -1,5 +1,6 @@
 from __future__ import unicode_literals

+import logging
 import os
 import weakref

<|current_version|>
from __future__ import unicode_literals

import logging
import os
import weakref

import cffi

__version__ = '2.0.0a1'

_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')])

# Mapping between keys and objects that should be kept alive as long as the key
# is alive. May be used to keep objects alive when there isn't a more
# convenient place to keep a reference to it. The keys are weakrefs, so entries
# disappear from the dict when the key is garbage collected, potentially
# causing objects associated to the key to be garbage collected as well. For
# further details, refer to the CFFI docs.
global_weakrefs = weakref.WeakKeyDictionary()

from spotify.error import *  # noqa

<|next_version|>
from __future__ import unicode_literals

import logging
import os
import weakref

import cffi

__version__ = '2.0.0a1'

# Log to nowhere by default. For details, see:
# http://docs.python.org/2/howto/logging.html#library-config
logging.getLogger('spotify').addHandler(logging.NullHandler())

_header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h')
_header = open(_header_file).read()
_header += '#define SPOTIFY_API_VERSION ...\n'
ffi = cffi.FFI()
ffi.cdef(_header)
lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')])

# Mapping between keys and objects that should be kept alive as long as the key
# is alive. May be used to keep objects alive when there isn't a more
# convenient place to keep a reference to it. The keys are weakrefs, so entries
# disappear from the dict when the key is garbage collected, potentially
# causing objects associated to the key to be garbage collected as well. For
# further details, refer to the CFFI docs.
global_weakrefs = weakref.WeakKeyDictionary()

from spotify.error import *  # noqa


Set MEDIA_ROOT and STATIC_ROOT settings

Set MEDIA_ROOT and STATIC_ROOT settings

--- overspill/settings/local.py
+++ overspill/settings/local.py
@@ -1,9 +1,12 @@
 from __future__ import absolute_import
+import os
 from djcelery import setup_loader
 from .base import *

 DEBUG = True
 ALLOWED_HOSTS = ['*']
+STATIC_ROOT = os.getenv('STATIC_ROOT')
+MEDIA_ROOT = os.getenv('STATIC_ROOT')
 STATIC_URL = '/static/'

 CELERY_REDIRECT_STDOUTS = False

<|original_code|>
from __future__ import absolute_import
from djcelery import setup_loader
from .base import *

DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'

CELERY_REDIRECT_STDOUTS = False
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True

setup_loader()

<|edits_diff|>
--- overspill/settings/local.py
+++ overspill/settings/local.py
@@ -1,4 +1,5 @@
 from __future__ import absolute_import
+import os
 from djcelery import setup_loader
 from .base import *

<|current_version|>
from __future__ import absolute_import
import os
from djcelery import setup_loader
from .base import *

DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'

CELERY_REDIRECT_STDOUTS = False
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True

setup_loader()

<|next_version|>
from __future__ import absolute_import
import os
from djcelery import setup_loader
from .base import *

DEBUG = True
ALLOWED_HOSTS = ['*']
STATIC_ROOT = os.getenv('STATIC_ROOT')
MEDIA_ROOT = os.getenv('STATIC_ROOT')
STATIC_URL = '/static/'

CELERY_REDIRECT_STDOUTS = False
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True

setup_loader()


Fix rtmpdump locking up when stderr buffer is filled.

--- src/livestreamer/stream.py
+++ src/livestreamer/stream.py
@@ -1,5 +1,6 @@
 from livestreamer.utils import urlopen

+import os
 import pbs

 class StreamError(Exception):
@@ -21,6 +22,7 @@

         self.params["flv"] = "-"
         self.params["_bg"] = True
+        self.params["_err"] = open(os.devnull, "w")

         stream = rtmpdump(**self.params)

<|original_code|>
from livestreamer.utils import urlopen

import pbs

class StreamError(Exception):
    pass

class Stream(object):
    def open(self):
       raise NotImplementedError

class RTMPStream(Stream):
    def __init__(self, params):
        self.params = params or {}

    def open(self):
        try:
            rtmpdump = pbs.rtmpdump
        except pbs.CommandNotFound:
            raise StreamError("Unable to find 'rtmpdump' command")

        self.params["flv"] = "-"
        self.params["_bg"] = True

        stream = rtmpdump(**self.params)

        return stream.process.stdout

class HTTPStream(Stream):
    def __init__(self, url):
        self.url = url

    def open(self):
        return urlopen(self.url)

<|edits_diff|>
--- src/livestreamer/stream.py
+++ src/livestreamer/stream.py
@@ -1,5 +1,6 @@
 from livestreamer.utils import urlopen

+import os
 import pbs

 class StreamError(Exception):
<|current_version|>
from livestreamer.utils import urlopen

import os
import pbs

class StreamError(Exception):
    pass

class Stream(object):
    def open(self):
       raise NotImplementedError

class RTMPStream(Stream):
    def __init__(self, params):
        self.params = params or {}

    def open(self):
        try:
            rtmpdump = pbs.rtmpdump
        except pbs.CommandNotFound:
            raise StreamError("Unable to find 'rtmpdump' command")

        self.params["flv"] = "-"
        self.params["_bg"] = True

        stream = rtmpdump(**self.params)

        return stream.process.stdout

class HTTPStream(Stream):
    def __init__(self, url):
        self.url = url

    def open(self):
        return urlopen(self.url)

<|next_version|>
from livestreamer.utils import urlopen

import os
import pbs

class StreamError(Exception):
    pass

class Stream(object):
    def open(self):
       raise NotImplementedError

class RTMPStream(Stream):
    def __init__(self, params):
        self.params = params or {}

    def open(self):
        try:
            rtmpdump = pbs.rtmpdump
        except pbs.CommandNotFound:
            raise StreamError("Unable to find 'rtmpdump' command")

        self.params["flv"] = "-"
        self.params["_bg"] = True
        self.params["_err"] = open(os.devnull, "w")

        stream = rtmpdump(**self.params)

        return stream.process.stdout

class HTTPStream(Stream):
    def __init__(self, url):
        self.url = url

    def open(self):
        return urlopen(self.url)


Add support for switching dpms

Add support for switching dpms

--- bumblebee/modules/caffeine.py
+++ bumblebee/modules/caffeine.py
@@ -39,9 +39,11 @@

     def _toggle(self, widget):
         if self._active():
+            bumblebee.util.execute("xset +dpms")
             bumblebee.util.execute("xset s default")
             bumblebee.util.execute("notify-send \"Out of coffee\"")
         else:
+            bumblebee.util.execute("xset -dpms")
             bumblebee.util.execute("xset s off")
             bumblebee.util.execute("notify-send \"Consuming caffeine\"")

<|original_code|>
# pylint: disable=C0111,R0903

"""Enable/disable automatic screen locking.

Requires the following executables:
    * xset
    * notify-send
"""

import bumblebee.input
import bumblebee.output
import bumblebee.engine

class Module(bumblebee.engine.Module):
    def __init__(self, engine, config):
        super(Module, self).__init__(engine, config,
            bumblebee.output.Widget(full_text=self.caffeine)
        )
        engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
            cmd=self._toggle
        )

    def caffeine(self, widget):
        return ""

    def state(self, widget):
        if self._active():
            return "activated"
        return "deactivated"

    def _active(self):
        for line in bumblebee.util.execute("xset q").split("\n"):
            if "timeout" in line:
                timeout = int(line.split(" ")[4])
                if timeout == 0:
                    return True
                return False
        return False

    def _toggle(self, widget):
        if self._active():
            bumblebee.util.execute("xset s default")
            bumblebee.util.execute("notify-send \"Out of coffee\"")
        else:
            bumblebee.util.execute("xset s off")
            bumblebee.util.execute("notify-send \"Consuming caffeine\"")

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

<|edits_diff|>
--- bumblebee/modules/caffeine.py
+++ bumblebee/modules/caffeine.py
@@ -39,6 +39,7 @@

     def _toggle(self, widget):
         if self._active():
+            bumblebee.util.execute("xset +dpms")
             bumblebee.util.execute("xset s default")
             bumblebee.util.execute("notify-send \"Out of coffee\"")
         else:
<|current_version|>
# pylint: disable=C0111,R0903

"""Enable/disable automatic screen locking.

Requires the following executables:
    * xset
    * notify-send
"""

import bumblebee.input
import bumblebee.output
import bumblebee.engine

class Module(bumblebee.engine.Module):
    def __init__(self, engine, config):
        super(Module, self).__init__(engine, config,
            bumblebee.output.Widget(full_text=self.caffeine)
        )
        engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
            cmd=self._toggle
        )

    def caffeine(self, widget):
        return ""

    def state(self, widget):
        if self._active():
            return "activated"
        return "deactivated"

    def _active(self):
        for line in bumblebee.util.execute("xset q").split("\n"):
            if "timeout" in line:
                timeout = int(line.split(" ")[4])
                if timeout == 0:
                    return True
                return False
        return False

    def _toggle(self, widget):
        if self._active():
            bumblebee.util.execute("xset +dpms")
            bumblebee.util.execute("xset s default")
            bumblebee.util.execute("notify-send \"Out of coffee\"")
        else:
            bumblebee.util.execute("xset s off")
            bumblebee.util.execute("notify-send \"Consuming caffeine\"")

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

<|next_version|>
# pylint: disable=C0111,R0903

"""Enable/disable automatic screen locking.

Requires the following executables:
    * xset
    * notify-send
"""

import bumblebee.input
import bumblebee.output
import bumblebee.engine

class Module(bumblebee.engine.Module):
    def __init__(self, engine, config):
        super(Module, self).__init__(engine, config,
            bumblebee.output.Widget(full_text=self.caffeine)
        )
        engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
            cmd=self._toggle
        )

    def caffeine(self, widget):
        return ""

    def state(self, widget):
        if self._active():
            return "activated"
        return "deactivated"

    def _active(self):
        for line in bumblebee.util.execute("xset q").split("\n"):
            if "timeout" in line:
                timeout = int(line.split(" ")[4])
                if timeout == 0:
                    return True
                return False
        return False

    def _toggle(self, widget):
        if self._active():
            bumblebee.util.execute("xset +dpms")
            bumblebee.util.execute("xset s default")
            bumblebee.util.execute("notify-send \"Out of coffee\"")
        else:
            bumblebee.util.execute("xset -dpms")
            bumblebee.util.execute("xset s off")
            bumblebee.util.execute("notify-send \"Consuming caffeine\"")

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


Add CORS headers to main studio Flask application, to allow initial API version request

Remove before_request from main application

--- qiime_studio/server.py
+++ qiime_studio/server.py
@@ -4,12 +4,15 @@
 from gevent.pywsgi import WSGIServer

 from qiime_studio.api.security import make_url
+from qiime_studio.api.cors import add_cors_headers
 from qiime_studio.api.v1 import v1
 from qiime_studio.static import static_files

 studio = Flask('qiime_studio')
 studio.register_blueprint(v1, url_prefix='/api/0.0.1')
 studio.debug = True
+
+studio.after_request(add_cors_headers)

 @studio.route("/api/", methods=['GET'])

<|original_code|>
import webbrowser

from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer

from qiime_studio.api.security import make_url
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files

studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = True

@studio.route("/api/", methods=['GET'])
def available_api():
    return jsonify(available=["/api/0.0.1/"])

@studio.route("/", methods=['GET'])
def hello():
    return "Hello World!"

def start_server(port, domain, in_dev, run_local, skip_open):
    host = "%s:%d/api/" % (domain, port)
    ihost = "qiime.studio/"
    if run_local:
        ihost = "%s:%d" % (domain, port)
        studio.register_blueprint(static_files)
    elif in_dev:
        ihost = "localhost:4242"

    url = make_url(host, ihost)

    print("Your QIIME Studio server is starting.")
    print("Please visit the following URL to access:\n")
    print(url)
    if not skip_open:
        webbrowser.open(url)
    WSGIServer((domain, port), studio).serve_forever()

<|edits_diff|>
--- qiime_studio/server.py
+++ qiime_studio/server.py
@@ -4,6 +4,7 @@
 from gevent.pywsgi import WSGIServer

 from qiime_studio.api.security import make_url
+from qiime_studio.api.cors import add_cors_headers
 from qiime_studio.api.v1 import v1
 from qiime_studio.static import static_files

<|current_version|>
import webbrowser

from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer

from qiime_studio.api.security import make_url
from qiime_studio.api.cors import add_cors_headers
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files

studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = True

@studio.route("/api/", methods=['GET'])
def available_api():
    return jsonify(available=["/api/0.0.1/"])

@studio.route("/", methods=['GET'])
def hello():
    return "Hello World!"

def start_server(port, domain, in_dev, run_local, skip_open):
    host = "%s:%d/api/" % (domain, port)
    ihost = "qiime.studio/"
    if run_local:
        ihost = "%s:%d" % (domain, port)
        studio.register_blueprint(static_files)
    elif in_dev:
        ihost = "localhost:4242"

    url = make_url(host, ihost)

    print("Your QIIME Studio server is starting.")
    print("Please visit the following URL to access:\n")
    print(url)
    if not skip_open:
        webbrowser.open(url)
    WSGIServer((domain, port), studio).serve_forever()

<|next_version|>
import webbrowser

from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer

from qiime_studio.api.security import make_url
from qiime_studio.api.cors import add_cors_headers
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files

studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = True

studio.after_request(add_cors_headers)

@studio.route("/api/", methods=['GET'])
def available_api():
    return jsonify(available=["/api/0.0.1/"])

@studio.route("/", methods=['GET'])
def hello():
    return "Hello World!"

def start_server(port, domain, in_dev, run_local, skip_open):
    host = "%s:%d/api/" % (domain, port)
    ihost = "qiime.studio/"
    if run_local:
        ihost = "%s:%d" % (domain, port)
        studio.register_blueprint(static_files)
    elif in_dev:
        ihost = "localhost:4242"

    url = make_url(host, ihost)

    print("Your QIIME Studio server is starting.")
    print("Please visit the following URL to access:\n")
    print(url)
    if not skip_open:
        webbrowser.open(url)
    WSGIServer((domain, port), studio).serve_forever()


Fix flaky mcrouter tko tests

Fix flaky mcrouter tko tests

Summary: As above

Reviewed By: edenzik

Differential Revision: D25722019

fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed

--- mcrouter/test/test_mcrouter_to_mcrouter_tko.py
+++ mcrouter/test/test_mcrouter_to_mcrouter_tko.py
@@ -5,6 +5,7 @@
 # LICENSE file in the root directory of this source tree.

 import re
+import time

 from mcrouter.test.McrouterTestCase import McrouterTestCase

@@ -24,6 +25,11 @@

         self.assertFalse(mcr.delete("key"))

+        retries = 10
+        while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0:
+            retries = retries - 1
+            time.sleep(1)
+
         stats = self.underlying_mcr.stats("suspect_servers")
         print(stats)
         self.assertEqual(1, len(stats))

<|original_code|>
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import re

from mcrouter.test.McrouterTestCase import McrouterTestCase

class TestMcrouterToMcrouterTko(McrouterTestCase):
    config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
    extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']

    def setUp(self):
        self.underlying_mcr = self.add_mcrouter(self.config,
                extra_args=self.extra_args, bg_mcrouter=True)

    def get_mcrouter(self):
        return self.add_mcrouter(self.config, extra_args=self.extra_args)

    def test_underlying_tko(self):
        mcr = self.get_mcrouter()

        self.assertFalse(mcr.delete("key"))

        stats = self.underlying_mcr.stats("suspect_servers")
        print(stats)
        self.assertEqual(1, len(stats))
        self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))

        stats = mcr.stats("suspect_servers")
        self.assertEqual(0, len(stats))

<|edits_diff|>
--- mcrouter/test/test_mcrouter_to_mcrouter_tko.py
+++ mcrouter/test/test_mcrouter_to_mcrouter_tko.py
@@ -5,6 +5,7 @@
 # LICENSE file in the root directory of this source tree.

 import re
+import time

 from mcrouter.test.McrouterTestCase import McrouterTestCase

<|current_version|>
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import re
import time

from mcrouter.test.McrouterTestCase import McrouterTestCase

class TestMcrouterToMcrouterTko(McrouterTestCase):
    config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
    extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']

    def setUp(self):
        self.underlying_mcr = self.add_mcrouter(self.config,
                extra_args=self.extra_args, bg_mcrouter=True)

    def get_mcrouter(self):
        return self.add_mcrouter(self.config, extra_args=self.extra_args)

    def test_underlying_tko(self):
        mcr = self.get_mcrouter()

        self.assertFalse(mcr.delete("key"))

        stats = self.underlying_mcr.stats("suspect_servers")
        print(stats)
        self.assertEqual(1, len(stats))
        self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))

        stats = mcr.stats("suspect_servers")
        self.assertEqual(0, len(stats))

<|next_version|>
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import re
import time

from mcrouter.test.McrouterTestCase import McrouterTestCase

class TestMcrouterToMcrouterTko(McrouterTestCase):
    config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json'
    extra_args = ['--timeouts-until-tko', '1', '--group-remote-errors']

    def setUp(self):
        self.underlying_mcr = self.add_mcrouter(self.config,
                extra_args=self.extra_args, bg_mcrouter=True)

    def get_mcrouter(self):
        return self.add_mcrouter(self.config, extra_args=self.extra_args)

    def test_underlying_tko(self):
        mcr = self.get_mcrouter()

        self.assertFalse(mcr.delete("key"))

        retries = 10
        while self.underlying_mcr.stats()['cmd_delete_count'] != 1 and retries > 0:
            retries = retries - 1
            time.sleep(1)

        stats = self.underlying_mcr.stats("suspect_servers")
        print(stats)
        self.assertEqual(1, len(stats))
        self.assertTrue(re.match("status:(tko|down)", list(stats.values())[0]))

        stats = mcr.stats("suspect_servers")
        self.assertEqual(0, len(stats))


Add phonelog to postgres models copied by copy_domain

--- corehq/apps/domainsync/management/commands/copy_utils.py
+++ corehq/apps/domainsync/management/commands/copy_utils.py
@@ -1,5 +1,6 @@
 from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
 from corehq.apps.products.models import SQLProduct
+from phonelog.models import DeviceReportEntry

 def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
@@ -19,6 +20,7 @@
         # StockState objects are "derived" and get created by StockTransaction post_save signal.
         # We may want to directly port these over in the future.
         # (StockState, 'case_id'),
+        (DeviceReportEntry, 'xform_id'),
     ]
     for model, doc_field in postgres_models:
         query_set = model.objects.using(remote_postgres_slug).filter(

<|original_code|>
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct

def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
    """
    Copies a set of data associated with a list of doc-ids from a remote postgres
    database to the locally configured one.
    """

    # can make this more configurable or less hard coded eventually
    # also note that ordering here is important for foreign key dependencies

    postgres_models = [
        (SQLProduct, 'product_id'),
        (StockReport, 'form_id'),
        (StockTransaction, 'case_id'),
        (DocDomainMapping, 'doc_id'),
        # StockState objects are "derived" and get created by StockTransaction post_save signal.
        # We may want to directly port these over in the future.
        # (StockState, 'case_id'),
    ]
    for model, doc_field in postgres_models:
        query_set = model.objects.using(remote_postgres_slug).filter(
            **{'{}__in'.format(doc_field): doc_ids}
        )
        count = query_set.count()
        print "Copying {} models ({})".format(model.__name__, count)
        if not simulate:
            for i, item in enumerate(query_set):
                # this can cause primary key conflicts to overwrite local data I think. Oh well?
                item.save(using='default')
                print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)

<|edits_diff|>
--- corehq/apps/domainsync/management/commands/copy_utils.py
+++ corehq/apps/domainsync/management/commands/copy_utils.py
@@ -1,5 +1,6 @@
 from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
 from corehq.apps.products.models import SQLProduct
+from phonelog.models import DeviceReportEntry

 def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
<|current_version|>
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry

def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
    """
    Copies a set of data associated with a list of doc-ids from a remote postgres
    database to the locally configured one.
    """

    # can make this more configurable or less hard coded eventually
    # also note that ordering here is important for foreign key dependencies

    postgres_models = [
        (SQLProduct, 'product_id'),
        (StockReport, 'form_id'),
        (StockTransaction, 'case_id'),
        (DocDomainMapping, 'doc_id'),
        # StockState objects are "derived" and get created by StockTransaction post_save signal.
        # We may want to directly port these over in the future.
        # (StockState, 'case_id'),
    ]
    for model, doc_field in postgres_models:
        query_set = model.objects.using(remote_postgres_slug).filter(
            **{'{}__in'.format(doc_field): doc_ids}
        )
        count = query_set.count()
        print "Copying {} models ({})".format(model.__name__, count)
        if not simulate:
            for i, item in enumerate(query_set):
                # this can cause primary key conflicts to overwrite local data I think. Oh well?
                item.save(using='default')
                print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)

<|next_version|>
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry

def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
    """
    Copies a set of data associated with a list of doc-ids from a remote postgres
    database to the locally configured one.
    """

    # can make this more configurable or less hard coded eventually
    # also note that ordering here is important for foreign key dependencies

    postgres_models = [
        (SQLProduct, 'product_id'),
        (StockReport, 'form_id'),
        (StockTransaction, 'case_id'),
        (DocDomainMapping, 'doc_id'),
        # StockState objects are "derived" and get created by StockTransaction post_save signal.
        # We may want to directly port these over in the future.
        # (StockState, 'case_id'),
        (DeviceReportEntry, 'xform_id'),
    ]
    for model, doc_field in postgres_models:
        query_set = model.objects.using(remote_postgres_slug).filter(
            **{'{}__in'.format(doc_field): doc_ids}
        )
        count = query_set.count()
        print "Copying {} models ({})".format(model.__name__, count)
        if not simulate:
            for i, item in enumerate(query_set):
                # this can cause primary key conflicts to overwrite local data I think. Oh well?
                item.save(using='default')
                print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)


Add CORS header to API responses

Add CORS header to API responses

--- prefixlist/api.py
+++ prefixlist/api.py
@@ -1,8 +1,10 @@
 from flask import Flask
 from flask_restful import abort, Api, Resource
+from flask_cors import CORS

 app = Flask("pre-fixlist")
 api = Api(app)
+CORS(app)

 class PrefixListList(Resource):

<|original_code|>
from flask import Flask
from flask_restful import abort, Api, Resource

app = Flask("pre-fixlist")
api = Api(app)

class PrefixListList(Resource):

    def get(self):
        # Return a list of all prefix lists we know about
        return None

class PrefixList(Resource):

    def get(self, listid):
        # Return a list of versions
        return None

    def post(self):
        # Create a new prefixlist
        return None

    def put(self, listid):
        # Update a prefixlist
        return None

    def delete(self, listid):
        return None

class PrefixListVersion(Resource):

    def get(self, listid, version):
        # Return a list of prefixes contained in the specific version of the prefixlist
        return None

api.add_resource(PrefixListList, "/prefixlist")
api.add_resource(PrefixList, "/prefixlist/<int:listid>")
api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>")

if __name__ == '__main__':
    app.run(debug=True)

<|edits_diff|>
--- prefixlist/api.py
+++ prefixlist/api.py
@@ -1,5 +1,6 @@
 from flask import Flask
 from flask_restful import abort, Api, Resource
+from flask_cors import CORS

 app = Flask("pre-fixlist")
 api = Api(app)
<|current_version|>
from flask import Flask
from flask_restful import abort, Api, Resource
from flask_cors import CORS

app = Flask("pre-fixlist")
api = Api(app)

class PrefixListList(Resource):

    def get(self):
        # Return a list of all prefix lists we know about
        return None

class PrefixList(Resource):

    def get(self, listid):
        # Return a list of versions
        return None

    def post(self):
        # Create a new prefixlist
        return None

    def put(self, listid):
        # Update a prefixlist
        return None

    def delete(self, listid):
        return None

class PrefixListVersion(Resource):

    def get(self, listid, version):
        # Return a list of prefixes contained in the specific version of the prefixlist
        return None

api.add_resource(PrefixListList, "/prefixlist")
api.add_resource(PrefixList, "/prefixlist/<int:listid>")
api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>")

if __name__ == '__main__':
    app.run(debug=True)

<|next_version|>
from flask import Flask
from flask_restful import abort, Api, Resource
from flask_cors import CORS

app = Flask("pre-fixlist")
api = Api(app)
CORS(app)

class PrefixListList(Resource):

    def get(self):
        # Return a list of all prefix lists we know about
        return None

class PrefixList(Resource):

    def get(self, listid):
        # Return a list of versions
        return None

    def post(self):
        # Create a new prefixlist
        return None

    def put(self, listid):
        # Update a prefixlist
        return None

    def delete(self, listid):
        return None

class PrefixListVersion(Resource):

    def get(self, listid, version):
        # Return a list of prefixes contained in the specific version of the prefixlist
        return None

api.add_resource(PrefixListList, "/prefixlist")
api.add_resource(PrefixList, "/prefixlist/<int:listid>")
api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>")

if __name__ == '__main__':
    app.run(debug=True)


Add mpv spawning to qutebrowser

Add mpv spawning to qutebrowser

Signed-off-by: Tomas <5fad2aa041dd6f0fec7c9125f282be028fd2d7b0@Tomass-MacBook-Pro.local>

--- qutebrowser/.qutebrowser/config.py
+++ qutebrowser/.qutebrowser/config.py
@@ -1,3 +1,4 @@
+# Adjust font
 c.fonts.completion.category = "bold 16pt monospace"
 c.fonts.completion.entry = "16pt monospace"
 c.fonts.debug_console = "16pt monospace"
@@ -11,3 +12,7 @@
 c.fonts.prompts = "16pt sans-serif"
 c.fonts.statusbar = "16pt monospace"
 c.fonts.tabs = "16pt monospace"
+
+# Play videos with mpv
+config.bind('e', 'spawn mpv {url}')
+config.bind('E', 'hint links spawn mpv {hint-url}')

<|original_code|>
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monospace"
c.fonts.messages.warning = "16pt monospace"
c.fonts.monospace = "\"xos4 Terminus\", Terminus, monospace"
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"

<|edits_diff|>
--- qutebrowser/.qutebrowser/config.py
+++ qutebrowser/.qutebrowser/config.py
@@ -1,3 +1,4 @@
+# Adjust font
 c.fonts.completion.category = "bold 16pt monospace"
 c.fonts.completion.entry = "16pt monospace"
 c.fonts.debug_console = "16pt monospace"
<|current_version|>
# Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monospace"
c.fonts.messages.warning = "16pt monospace"
c.fonts.monospace = "\"xos4 Terminus\", Terminus, monospace"
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"

<|next_version|>
# Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monospace"
c.fonts.messages.warning = "16pt monospace"
c.fonts.monospace = "\"xos4 Terminus\", Terminus, monospace"
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"

# Play videos with mpv
config.bind('e', 'spawn mpv {url}')
config.bind('E', 'hint links spawn mpv {hint-url}')


Add Filter option for order amd order group

--- digikey/admin.py
+++ digikey/admin.py
@@ -15,6 +15,7 @@

 @admin.register(Orders)
 class OrderAdmin(admin.ModelAdmin):
+    list_filter = ['sent', 'paid', 'sent_date']
     list_display = ('pk', 'group_id','paid', 'sent')

     fieldsets = [
@@ -28,6 +29,7 @@

 @admin.register(Groups)
 class GroupAdmin(admin.ModelAdmin):
+    list_filter = ['ordered', 'orderdate']
     fieldsets = [
                 (None,               {'fields': ['ordered', 'orderdate']}),
     ]

<|original_code|>
from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups

class ComponentInline(admin.TabularInline):
    model = Order_Details
    extra = 1

class OrderInline(admin.TabularInline):
    model = Orders
    extra = 1
    fieldsets = [
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

@admin.register(Orders)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('pk', 'group_id','paid', 'sent')

    fieldsets = [
                (None,               {'fields': ['Orderer', 'group_id']}),
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Uplink information', {'fields': ['sent', 'sent_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

    inlines = [ComponentInline]

@admin.register(Groups)
class GroupAdmin(admin.ModelAdmin):
    fieldsets = [
                (None,               {'fields': ['ordered', 'orderdate']}),
    ]

    inlines = [OrderInline]

@admin.register(Components)
class ComponentAdmin(admin.ModelAdmin):
    list_display = ('part_number','unit_price')

<|edits_diff|>
--- digikey/admin.py
+++ digikey/admin.py
@@ -15,6 +15,7 @@

 @admin.register(Orders)
 class OrderAdmin(admin.ModelAdmin):
+    list_filter = ['sent', 'paid', 'sent_date']
     list_display = ('pk', 'group_id','paid', 'sent')

     fieldsets = [
<|current_version|>
from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups

class ComponentInline(admin.TabularInline):
    model = Order_Details
    extra = 1

class OrderInline(admin.TabularInline):
    model = Orders
    extra = 1
    fieldsets = [
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

@admin.register(Orders)
class OrderAdmin(admin.ModelAdmin):
    list_filter = ['sent', 'paid', 'sent_date']
    list_display = ('pk', 'group_id','paid', 'sent')

    fieldsets = [
                (None,               {'fields': ['Orderer', 'group_id']}),
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Uplink information', {'fields': ['sent', 'sent_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

    inlines = [ComponentInline]

@admin.register(Groups)
class GroupAdmin(admin.ModelAdmin):
    fieldsets = [
                (None,               {'fields': ['ordered', 'orderdate']}),
    ]

    inlines = [OrderInline]

@admin.register(Components)
class ComponentAdmin(admin.ModelAdmin):
    list_display = ('part_number','unit_price')

<|next_version|>
from django.contrib import admin
from digikey.models import Components, Orders, Order_Details, Groups

class ComponentInline(admin.TabularInline):
    model = Order_Details
    extra = 1

class OrderInline(admin.TabularInline):
    model = Orders
    extra = 1
    fieldsets = [
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

@admin.register(Orders)
class OrderAdmin(admin.ModelAdmin):
    list_filter = ['sent', 'paid', 'sent_date']
    list_display = ('pk', 'group_id','paid', 'sent')

    fieldsets = [
                (None,               {'fields': ['Orderer', 'group_id']}),
                ('Payment information', {'fields': ['paid', 'paid_account', 'paid_date']}),
                ('Uplink information', {'fields': ['sent', 'sent_date']}),
                ('Additional Shipping information', {'fields': ['receiver', 'shipping_address', 'phone_number']}),
    ]

    inlines = [ComponentInline]

@admin.register(Groups)
class GroupAdmin(admin.ModelAdmin):
    list_filter = ['ordered', 'orderdate']
    fieldsets = [
                (None,               {'fields': ['ordered', 'orderdate']}),
    ]

    inlines = [OrderInline]

@admin.register(Components)
class ComponentAdmin(admin.ModelAdmin):
    list_display = ('part_number','unit_price')


Add EDITOR variable in urlaccesschecker

Add EDITOR variable in urlaccesschecker

This variable required by cmd2 library to work.
Without - it fails on bootstrap with traceback:

File "/usr/lib/python2.6/site-packages/cmd2.py", line 424, in Cmd
if subprocess.Popen(['which', editor])

Change-Id: I061f88b65d7bc7181752cd076da4067df2f84131
Related-Bug: 1439686

--- network_checker/url_access_checker/cli.py
+++ network_checker/url_access_checker/cli.py
@@ -12,7 +12,10 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.

+import os
 import sys
+# fixed in cmd2 >=0.6.6
+os.environ['EDITOR'] = '/usr/bin/nano'

 from cliff.commandmanager import CommandManager

<|original_code|>
#    Copyright 2015 Mirantis, 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 sys

from cliff.commandmanager import CommandManager

from fuel_network_checker import base_app

class UrlAccessCheckApp(base_app.BaseApp):
    LOG_FILENAME = '/var/log/url_access_checker.log'

    def __init__(self):
        super(UrlAccessCheckApp, self).__init__(
            description='Url access check application',
            version='0.1',
            command_manager=CommandManager('urlaccesscheck'),
        )

def main(argv=sys.argv[1:]):
    myapp = UrlAccessCheckApp()
    return myapp.run(argv)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

<|edits_diff|>
--- network_checker/url_access_checker/cli.py
+++ network_checker/url_access_checker/cli.py
@@ -12,6 +12,7 @@
 #    License for the specific language governing permissions and limitations
 #    under the License.

+import os
 import sys

 from cliff.commandmanager import CommandManager
<|current_version|>
#    Copyright 2015 Mirantis, 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 os
import sys

from cliff.commandmanager import CommandManager

from fuel_network_checker import base_app

class UrlAccessCheckApp(base_app.BaseApp):
    LOG_FILENAME = '/var/log/url_access_checker.log'

    def __init__(self):
        super(UrlAccessCheckApp, self).__init__(
            description='Url access check application',
            version='0.1',
            command_manager=CommandManager('urlaccesscheck'),
        )

def main(argv=sys.argv[1:]):
    myapp = UrlAccessCheckApp()
    return myapp.run(argv)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

<|next_version|>
#    Copyright 2015 Mirantis, 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 os
import sys
# fixed in cmd2 >=0.6.6
os.environ['EDITOR'] = '/usr/bin/nano'

from cliff.commandmanager import CommandManager

from fuel_network_checker import base_app

class UrlAccessCheckApp(base_app.BaseApp):
    LOG_FILENAME = '/var/log/url_access_checker.log'

    def __init__(self):
        super(UrlAccessCheckApp, self).__init__(
            description='Url access check application',
            version='0.1',
            command_manager=CommandManager('urlaccesscheck'),
        )

def main(argv=sys.argv[1:]):
    myapp = UrlAccessCheckApp()
    return myapp.run(argv)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


Test case when there's no riemann config

--- tests/test_config.py
+++ tests/test_config.py
@@ -12,9 +12,18 @@
                    })

+@fixture
+def incomplete_config():
+    return Config({})
+
+
 def test_base_config_get_riemann(base_config):
     assert isinstance(base_config.riemann, RiemannConfig)

 def test_base_config_interval(base_config):
     assert base_config.interval == 5
+
+
+def test_incomplete_config_get_riemann(incomplete_config):
+    assert isinstance(incomplete_config.riemann, RiemannConfig)

<|original_code|>
from pytest import fixture

from oshino.config import Config, RiemannConfig

@fixture
def base_config():
    return Config({"riemann": {"host": "localhost",
                               "port": 5555
                               },
                   "interval": 5
                   })

def test_base_config_get_riemann(base_config):
    assert isinstance(base_config.riemann, RiemannConfig)

def test_base_config_interval(base_config):
    assert base_config.interval == 5

<|edits_diff|>
--- tests/test_config.py
+++ tests/test_config.py
@@ -12,6 +12,11 @@
                    })

+@fixture
+def incomplete_config():
+    return Config({})
+
+
 def test_base_config_get_riemann(base_config):
     assert isinstance(base_config.riemann, RiemannConfig)

<|current_version|>
from pytest import fixture

from oshino.config import Config, RiemannConfig

@fixture
def base_config():
    return Config({"riemann": {"host": "localhost",
                               "port": 5555
                               },
                   "interval": 5
                   })

@fixture
def incomplete_config():
    return Config({})

def test_base_config_get_riemann(base_config):
    assert isinstance(base_config.riemann, RiemannConfig)

def test_base_config_interval(base_config):
    assert base_config.interval == 5

<|next_version|>
from pytest import fixture

from oshino.config import Config, RiemannConfig

@fixture
def base_config():
    return Config({"riemann": {"host": "localhost",
                               "port": 5555
                               },
                   "interval": 5
                   })

@fixture
def incomplete_config():
    return Config({})

def test_base_config_get_riemann(base_config):
    assert isinstance(base_config.riemann, RiemannConfig)

def test_base_config_interval(base_config):
    assert base_config.interval == 5

def test_incomplete_config_get_riemann(incomplete_config):
    assert isinstance(incomplete_config.riemann, RiemannConfig)


Fix race condition during `mimetypes` initialization.

Initial patch from Steven R. Loomis.
Closes #8629.

git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@9740 af82e41b-90c4-0310-8c96-b1721e28e2e2

--- trac/web/__init__.py
+++ trac/web/__init__.py
@@ -1,8 +1,14 @@
+# Workaround for http://bugs.python.org/issue6763 and
+# http://bugs.python.org/issue5853 thread issues
+import mimetypes
+mimetypes.init()
+
 # With mod_python we'll have to delay importing trac.web.api until
 # modpython_frontend.handler() has been called since the
 # PYTHON_EGG_CACHE variable is set from there
 #
 # TODO: Remove this once the Genshi zip_safe issue has been resolved.
+
 import os
 from pkg_resources import get_distribution
 if not os.path.isdir(get_distribution('genshi').location):

<|original_code|>
# With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE variable is set from there
#
# TODO: Remove this once the Genshi zip_safe issue has been resolved.
import os
from pkg_resources import get_distribution
if not os.path.isdir(get_distribution('genshi').location):
    try:
        import mod_python.apache
        import sys
        if 'trac.web.modpython_frontend' in sys.modules:
            from trac.web.api import *
    except ImportError:
        from trac.web.api import *
else:
    from trac.web.api import *

<|edits_diff|>
--- trac/web/__init__.py
+++ trac/web/__init__.py
@@ -1,3 +1,8 @@
+# Workaround for http://bugs.python.org/issue6763 and
+# http://bugs.python.org/issue5853 thread issues
+import mimetypes
+mimetypes.init()
+
 # With mod_python we'll have to delay importing trac.web.api until
 # modpython_frontend.handler() has been called since the
 # PYTHON_EGG_CACHE variable is set from there
<|current_version|>
# Workaround for http://bugs.python.org/issue6763 and
# http://bugs.python.org/issue5853 thread issues
import mimetypes
mimetypes.init()

# With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE variable is set from there
#
# TODO: Remove this once the Genshi zip_safe issue has been resolved.
import os
from pkg_resources import get_distribution
if not os.path.isdir(get_distribution('genshi').location):
    try:
        import mod_python.apache
        import sys
        if 'trac.web.modpython_frontend' in sys.modules:
            from trac.web.api import *
    except ImportError:
        from trac.web.api import *
else:
    from trac.web.api import *

<|next_version|>
# Workaround for http://bugs.python.org/issue6763 and
# http://bugs.python.org/issue5853 thread issues
import mimetypes
mimetypes.init()

# With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE variable is set from there
#
# TODO: Remove this once the Genshi zip_safe issue has been resolved.

import os
from pkg_resources import get_distribution
if not os.path.isdir(get_distribution('genshi').location):
    try:
        import mod_python.apache
        import sys
        if 'trac.web.modpython_frontend' in sys.modules:
            from trac.web.api import *
    except ImportError:
        from trac.web.api import *
else:
    from trac.web.api import *


Add 'All' option to lists

Add 'All' option to lists

--- extract_options.py
+++ extract_options.py
@@ -10,8 +10,11 @@
     doc = {}
     diner_options_collection = db.dineroptions
     doc['categories'] = diners_collection.distinct('category')
+    doc['categories'].insert(0, 'Tất cả')
     doc['cuisines'] = diners_collection.distinct('cuisine')
+    doc['cuisines'].insert(0, 'Tất cả')
     doc['districts'] = diners_collection.distinct('address.district')
+    doc['districts'].insert(0, 'Tất cả')

     doc['price_max'] = list(diners_collection.aggregate([{
         "$group":

<|original_code|>
from pymongo import MongoClient

def main():
    client = MongoClient()
    db = client.cityhotspots
    db.drop_collection('dineroptions')
    diners_collection = db.diners

    doc = {}
    diner_options_collection = db.dineroptions
    doc['categories'] = diners_collection.distinct('category')
    doc['cuisines'] = diners_collection.distinct('cuisine')
    doc['districts'] = diners_collection.distinct('address.district')

    doc['price_max'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$max": "$price_max"}
            }
    }]))[0]['value']
    doc['price_min'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$min": "$price_min"}
            }
    }]))[0]['value']

    diner_options_collection.insert(doc)

if __name__ == '__main__':
    main()

<|edits_diff|>
--- extract_options.py
+++ extract_options.py
@@ -10,7 +10,9 @@
     doc = {}
     diner_options_collection = db.dineroptions
     doc['categories'] = diners_collection.distinct('category')
+    doc['categories'].insert(0, 'Tất cả')
     doc['cuisines'] = diners_collection.distinct('cuisine')
+    doc['cuisines'].insert(0, 'Tất cả')
     doc['districts'] = diners_collection.distinct('address.district')

     doc['price_max'] = list(diners_collection.aggregate([{
<|current_version|>
from pymongo import MongoClient

def main():
    client = MongoClient()
    db = client.cityhotspots
    db.drop_collection('dineroptions')
    diners_collection = db.diners

    doc = {}
    diner_options_collection = db.dineroptions
    doc['categories'] = diners_collection.distinct('category')
    doc['categories'].insert(0, 'Tất cả')
    doc['cuisines'] = diners_collection.distinct('cuisine')
    doc['cuisines'].insert(0, 'Tất cả')
    doc['districts'] = diners_collection.distinct('address.district')

    doc['price_max'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$max": "$price_max"}
            }
    }]))[0]['value']
    doc['price_min'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$min": "$price_min"}
            }
    }]))[0]['value']

    diner_options_collection.insert(doc)

if __name__ == '__main__':
    main()

<|next_version|>
from pymongo import MongoClient

def main():
    client = MongoClient()
    db = client.cityhotspots
    db.drop_collection('dineroptions')
    diners_collection = db.diners

    doc = {}
    diner_options_collection = db.dineroptions
    doc['categories'] = diners_collection.distinct('category')
    doc['categories'].insert(0, 'Tất cả')
    doc['cuisines'] = diners_collection.distinct('cuisine')
    doc['cuisines'].insert(0, 'Tất cả')
    doc['districts'] = diners_collection.distinct('address.district')
    doc['districts'].insert(0, 'Tất cả')

    doc['price_max'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$max": "$price_max"}
            }
    }]))[0]['value']
    doc['price_min'] = list(diners_collection.aggregate([{
        "$group":
            {
                "_id": None,
                "value": {"$min": "$price_min"}
            }
    }]))[0]['value']

    diner_options_collection.insert(doc)

if __name__ == '__main__':
    main()


Fix doc building endpoint for gettext.

Fix doc building endpoint for gettext.

--- doc/ext/nova_autodoc.py
+++ doc/ext/nova_autodoc.py
@@ -1,4 +1,7 @@
+import gettext
 import os
+
+gettext.install('nova')

 from nova import utils

<|original_code|>
import os

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]

<|edits_diff|>
--- doc/ext/nova_autodoc.py
+++ doc/ext/nova_autodoc.py
@@ -1,3 +1,4 @@
+import gettext
 import os

 from nova import utils
<|current_version|>
import gettext
import os

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]

<|next_version|>
import gettext
import os

gettext.install('nova')

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]


Add missing import and explanation of failure

--- pymc/examples/glm_robust.py
+++ pymc/examples/glm_robust.py
@@ -1,8 +1,10 @@
 import numpy as np
+import sys

 try:
     import statsmodels.api as sm
 except ImportError:
+    print "Example requires statsmodels"
     sys.exit(0)

 from pymc import *

<|original_code|>
import numpy as np

try:
    import statsmodels.api as sm
except ImportError:
    sys.exit(0)

from pymc import *

# Generate data
size = 50
true_intercept = 1
true_slope = 2

x = np.linspace(0, 1, size)
y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size)

# Add outliers
x = np.append(x, [.1, .15, .2])
y = np.append(y, [8, 6, 9])

data_outlier = dict(x=x, y=y)

with Model() as model:
    family = glm.families.T(link=glm.links.Identity,
			                priors={'nu': 1.5,
				                    'lam': ('sigma', Uniform.dist(0, 20))})
    glm.glm('y ~ x', data_outlier, family=family)

def run(n=2000):
    if n == "short":
        n = 50
    import matplotlib.pyplot as plt

    with model:
        trace = sample(n, Slice(model.vars))

    plt.plot(x, y, 'x')
    glm.plot_posterior_predictive(trace)
    plt.show()

if __name__ == '__main__':
    run()

<|edits_diff|>
--- pymc/examples/glm_robust.py
+++ pymc/examples/glm_robust.py
@@ -1,4 +1,5 @@
 import numpy as np
+import sys

 try:
     import statsmodels.api as sm
<|current_version|>
import numpy as np
import sys

try:
    import statsmodels.api as sm
except ImportError:
    sys.exit(0)

from pymc import *

# Generate data
size = 50
true_intercept = 1
true_slope = 2

x = np.linspace(0, 1, size)
y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size)

# Add outliers
x = np.append(x, [.1, .15, .2])
y = np.append(y, [8, 6, 9])

data_outlier = dict(x=x, y=y)

with Model() as model:
    family = glm.families.T(link=glm.links.Identity,
			                priors={'nu': 1.5,
				                    'lam': ('sigma', Uniform.dist(0, 20))})
    glm.glm('y ~ x', data_outlier, family=family)

def run(n=2000):
    if n == "short":
        n = 50
    import matplotlib.pyplot as plt

    with model:
        trace = sample(n, Slice(model.vars))

    plt.plot(x, y, 'x')
    glm.plot_posterior_predictive(trace)
    plt.show()

if __name__ == '__main__':
    run()

<|next_version|>
import numpy as np
import sys

try:
    import statsmodels.api as sm
except ImportError:
    print "Example requires statsmodels"
    sys.exit(0)

from pymc import *

# Generate data
size = 50
true_intercept = 1
true_slope = 2

x = np.linspace(0, 1, size)
y = true_intercept + x*true_slope + np.random.normal(scale=.5, size=size)

# Add outliers
x = np.append(x, [.1, .15, .2])
y = np.append(y, [8, 6, 9])

data_outlier = dict(x=x, y=y)

with Model() as model:
    family = glm.families.T(link=glm.links.Identity,
			                priors={'nu': 1.5,
				                    'lam': ('sigma', Uniform.dist(0, 20))})
    glm.glm('y ~ x', data_outlier, family=family)

def run(n=2000):
    if n == "short":
        n = 50
    import matplotlib.pyplot as plt

    with model:
        trace = sample(n, Slice(model.vars))

    plt.plot(x, y, 'x')
    glm.plot_posterior_predictive(trace)
    plt.show()

if __name__ == '__main__':
    run()


Return self in Pipeline add_after and add_before

--- torchtext/data/pipeline.py
+++ torchtext/data/pipeline.py
@@ -23,9 +23,11 @@
         if not isinstance(pipeline, Pipeline):
             pipeline = Pipeline(pipeline)
         self.pipes = pipeline.pipes[:] + self.pipes[:]
+        return self

     def add_after(self, pipeline):
         """Add `pipeline` after this processing pipeline."""
         if not isinstance(pipeline, Pipeline):
             pipeline = Pipeline(pipeline)
         self.pipes = self.pipes[:] + pipeline.pipes[:]
+        return self

<|original_code|>
class Pipeline(object):
    """Defines a pipeline for transforming sequence data."""

    def __init__(self, convert_token=None):
        if convert_token is not None:
            self.convert_token = convert_token
        else:
            self.convert_token = lambda x: x
        self.pipes = [self]

    def __call__(self, x, *args):
        for pipe in self.pipes:
            x = pipe.call(x)
        return x

    def call(self, x, *args):
        if isinstance(x, list):
            return [self(tok, *args) for tok in x]
        return self.convert_token(x, *args)

    def add_before(self, pipeline):
        """Add `pipeline` before this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = pipeline.pipes[:] + self.pipes[:]

    def add_after(self, pipeline):
        """Add `pipeline` after this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = self.pipes[:] + pipeline.pipes[:]

<|edits_diff|>
--- torchtext/data/pipeline.py
+++ torchtext/data/pipeline.py
@@ -23,6 +23,7 @@
         if not isinstance(pipeline, Pipeline):
             pipeline = Pipeline(pipeline)
         self.pipes = pipeline.pipes[:] + self.pipes[:]
+        return self

     def add_after(self, pipeline):
         """Add `pipeline` after this processing pipeline."""
<|current_version|>
class Pipeline(object):
    """Defines a pipeline for transforming sequence data."""

    def __init__(self, convert_token=None):
        if convert_token is not None:
            self.convert_token = convert_token
        else:
            self.convert_token = lambda x: x
        self.pipes = [self]

    def __call__(self, x, *args):
        for pipe in self.pipes:
            x = pipe.call(x)
        return x

    def call(self, x, *args):
        if isinstance(x, list):
            return [self(tok, *args) for tok in x]
        return self.convert_token(x, *args)

    def add_before(self, pipeline):
        """Add `pipeline` before this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = pipeline.pipes[:] + self.pipes[:]
        return self

    def add_after(self, pipeline):
        """Add `pipeline` after this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = self.pipes[:] + pipeline.pipes[:]

<|next_version|>
class Pipeline(object):
    """Defines a pipeline for transforming sequence data."""

    def __init__(self, convert_token=None):
        if convert_token is not None:
            self.convert_token = convert_token
        else:
            self.convert_token = lambda x: x
        self.pipes = [self]

    def __call__(self, x, *args):
        for pipe in self.pipes:
            x = pipe.call(x)
        return x

    def call(self, x, *args):
        if isinstance(x, list):
            return [self(tok, *args) for tok in x]
        return self.convert_token(x, *args)

    def add_before(self, pipeline):
        """Add `pipeline` before this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = pipeline.pipes[:] + self.pipes[:]
        return self

    def add_after(self, pipeline):
        """Add `pipeline` after this processing pipeline."""
        if not isinstance(pipeline, Pipeline):
            pipeline = Pipeline(pipeline)
        self.pipes = self.pipes[:] + pipeline.pipes[:]
        return self


Add drake in the PYTHONPATH for the tests.

--- _build/drake-build.py
+++ _build/drake-build.py
@@ -1,7 +1,13 @@
 #!/usr/bin/python

+import os
 import sys
+
 sys.path.append('../src')
+if 'PYTHONPATH' in os.environ:
+  os.environ['PYTHONPATH'] = '../src:%s' % os.environ['PYTHONPATH']
+else:
+  os.environ['PYTHONPATH'] = '../src'

 import drake

<|original_code|>
#!/usr/bin/python

import sys
sys.path.append('../src')

import drake

drake.run('..')

<|edits_diff|>
--- _build/drake-build.py
+++ _build/drake-build.py
@@ -1,6 +1,8 @@
 #!/usr/bin/python

+import os
 import sys
+
 sys.path.append('../src')

 import drake
<|current_version|>
#!/usr/bin/python

import os
import sys

sys.path.append('../src')

import drake

drake.run('..')

<|next_version|>
#!/usr/bin/python

import os
import sys

sys.path.append('../src')
if 'PYTHONPATH' in os.environ:
  os.environ['PYTHONPATH'] = '../src:%s' % os.environ['PYTHONPATH']
else:
  os.environ['PYTHONPATH'] = '../src'

import drake

drake.run('..')


Reset learners password when user is unGDPRed/unretired via django admin.

--- openedx/core/djangoapps/user_api/accounts/forms.py
+++ openedx/core/djangoapps/user_api/accounts/forms.py
@@ -4,6 +4,7 @@

 from django import forms
 from django.core.exceptions import ValidationError
+from openedx.core.djangoapps.user_api.accounts.utils import generate_password

 class RetirementQueueDeletionForm(forms.Form):
@@ -33,6 +34,8 @@

         # Load the user record using the retired email address -and- change the email address back.
         retirement.user.email = retirement.original_email
+        # Reset users password so they can request a password reset and log in again.
+        retirement.user.set_password(generate_password(length=25))
         retirement.user.save()

         # Delete the user retirement status record.

<|original_code|>
"""
Django forms for accounts
"""

from django import forms
from django.core.exceptions import ValidationError

class RetirementQueueDeletionForm(forms.Form):
    """
    Admin form to facilitate learner retirement cancellation
    """
    cancel_retirement = forms.BooleanField(required=True)

    def save(self, retirement):
        """
        When the form is POSTed we double-check the retirment status
        and perform the necessary steps to cancel the retirement
        request.
        """
        if retirement.current_state.state_name != 'PENDING':
            self.add_error(
                None,
                # Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
                # state. Example: FORUMS_COMPLETE
                "Retirement requests can only be cancelled for users in the PENDING state."
                " Current request state for '{original_username}': {current_state}".format(
                    original_username=retirement.original_username,
                    current_state=retirement.current_state.state_name
                )
            )
            raise ValidationError('Retirement is in the wrong state!')

        # Load the user record using the retired email address -and- change the email address back.
        retirement.user.email = retirement.original_email
        retirement.user.save()

        # Delete the user retirement status record.
        # No need to delete the accompanying "permanent" retirement request record - it gets done via Django signal.
        retirement.delete()

<|edits_diff|>
--- openedx/core/djangoapps/user_api/accounts/forms.py
+++ openedx/core/djangoapps/user_api/accounts/forms.py
@@ -4,6 +4,7 @@

 from django import forms
 from django.core.exceptions import ValidationError
+from openedx.core.djangoapps.user_api.accounts.utils import generate_password

 class RetirementQueueDeletionForm(forms.Form):
<|current_version|>
"""
Django forms for accounts
"""

from django import forms
from django.core.exceptions import ValidationError
from openedx.core.djangoapps.user_api.accounts.utils import generate_password

class RetirementQueueDeletionForm(forms.Form):
    """
    Admin form to facilitate learner retirement cancellation
    """
    cancel_retirement = forms.BooleanField(required=True)

    def save(self, retirement):
        """
        When the form is POSTed we double-check the retirment status
        and perform the necessary steps to cancel the retirement
        request.
        """
        if retirement.current_state.state_name != 'PENDING':
            self.add_error(
                None,
                # Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
                # state. Example: FORUMS_COMPLETE
                "Retirement requests can only be cancelled for users in the PENDING state."
                " Current request state for '{original_username}': {current_state}".format(
                    original_username=retirement.original_username,
                    current_state=retirement.current_state.state_name
                )
            )
            raise ValidationError('Retirement is in the wrong state!')

        # Load the user record using the retired email address -and- change the email address back.
        retirement.user.email = retirement.original_email
        retirement.user.save()

        # Delete the user retirement status record.
        # No need to delete the accompanying "permanent" retirement request record - it gets done via Django signal.
        retirement.delete()

<|next_version|>
"""
Django forms for accounts
"""

from django import forms
from django.core.exceptions import ValidationError
from openedx.core.djangoapps.user_api.accounts.utils import generate_password

class RetirementQueueDeletionForm(forms.Form):
    """
    Admin form to facilitate learner retirement cancellation
    """
    cancel_retirement = forms.BooleanField(required=True)

    def save(self, retirement):
        """
        When the form is POSTed we double-check the retirment status
        and perform the necessary steps to cancel the retirement
        request.
        """
        if retirement.current_state.state_name != 'PENDING':
            self.add_error(
                None,
                # Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
                # state. Example: FORUMS_COMPLETE
                "Retirement requests can only be cancelled for users in the PENDING state."
                " Current request state for '{original_username}': {current_state}".format(
                    original_username=retirement.original_username,
                    current_state=retirement.current_state.state_name
                )
            )
            raise ValidationError('Retirement is in the wrong state!')

        # Load the user record using the retired email address -and- change the email address back.
        retirement.user.email = retirement.original_email
        # Reset users password so they can request a password reset and log in again.
        retirement.user.set_password(generate_password(length=25))
        retirement.user.save()

        # Delete the user retirement status record.
        # No need to delete the accompanying "permanent" retirement request record - it gets done via Django signal.
        retirement.delete()


Add helper to load a single test case.

Add helper to load a single test case.

--- hunittest/utils.py
+++ hunittest/utils.py
@@ -7,6 +7,7 @@
 import re
 from enum import Enum
 from contextlib import contextmanager
+import unittest

 def pyname_join(seq):
@@ -58,3 +59,8 @@
         return os.getcwd()
     except FileNotFoundError:
         return None
+
+def load_single_test_case(test_name):
+    test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name))
+    assert len(test_suite) == 1
+    return test_suite[0]

<|original_code|>
# -*- encoding: utf-8 -*-
"""Utility routines
"""

import os
import re
from enum import Enum
from contextlib import contextmanager

def pyname_join(seq):
    return ".".join(seq)

def is_pkgdir(dirpath):
    return os.path.isdir(dirpath) \
        and os.path.isfile(os.path.join(dirpath, "__init__.py"))

def mod_split(modname):
    mo = re.match(r"^(.+)\.(.*)$", modname)
    if not mo:
        raise ValueError("invalid python path identifier")
    return (mo.group(1), mo.group(2))

def is_empty_generator(generator):
    try:
        next(generator)
    except StopIteration:
        return True
    else:
        return False

class AutoEnum(Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

def mkdir_p(path):
    try:
        os.makedirs(path)
    except FileExistsError:
        pass

@contextmanager
def protect_cwd(dirpath=None):
    saved_cwd = os.getcwd()
    if dirpath is not None:
        os.chdir(dirpath)
    try:
        yield
    finally:
        os.chdir(saved_cwd)

def safe_getcwd():
    try:
        return os.getcwd()
    except FileNotFoundError:
        return None

<|edits_diff|>
--- hunittest/utils.py
+++ hunittest/utils.py
@@ -7,6 +7,7 @@
 import re
 from enum import Enum
 from contextlib import contextmanager
+import unittest

 def pyname_join(seq):
<|current_version|>
# -*- encoding: utf-8 -*-
"""Utility routines
"""

import os
import re
from enum import Enum
from contextlib import contextmanager
import unittest

def pyname_join(seq):
    return ".".join(seq)

def is_pkgdir(dirpath):
    return os.path.isdir(dirpath) \
        and os.path.isfile(os.path.join(dirpath, "__init__.py"))

def mod_split(modname):
    mo = re.match(r"^(.+)\.(.*)$", modname)
    if not mo:
        raise ValueError("invalid python path identifier")
    return (mo.group(1), mo.group(2))

def is_empty_generator(generator):
    try:
        next(generator)
    except StopIteration:
        return True
    else:
        return False

class AutoEnum(Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

def mkdir_p(path):
    try:
        os.makedirs(path)
    except FileExistsError:
        pass

@contextmanager
def protect_cwd(dirpath=None):
    saved_cwd = os.getcwd()
    if dirpath is not None:
        os.chdir(dirpath)
    try:
        yield
    finally:
        os.chdir(saved_cwd)

def safe_getcwd():
    try:
        return os.getcwd()
    except FileNotFoundError:
        return None

<|next_version|>
# -*- encoding: utf-8 -*-
"""Utility routines
"""

import os
import re
from enum import Enum
from contextlib import contextmanager
import unittest

def pyname_join(seq):
    return ".".join(seq)

def is_pkgdir(dirpath):
    return os.path.isdir(dirpath) \
        and os.path.isfile(os.path.join(dirpath, "__init__.py"))

def mod_split(modname):
    mo = re.match(r"^(.+)\.(.*)$", modname)
    if not mo:
        raise ValueError("invalid python path identifier")
    return (mo.group(1), mo.group(2))

def is_empty_generator(generator):
    try:
        next(generator)
    except StopIteration:
        return True
    else:
        return False

class AutoEnum(Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

def mkdir_p(path):
    try:
        os.makedirs(path)
    except FileExistsError:
        pass

@contextmanager
def protect_cwd(dirpath=None):
    saved_cwd = os.getcwd()
    if dirpath is not None:
        os.chdir(dirpath)
    try:
        yield
    finally:
        os.chdir(saved_cwd)

def safe_getcwd():
    try:
        return os.getcwd()
    except FileNotFoundError:
        return None

def load_single_test_case(test_name):
    test_suite = list(unittest.defaultTestLoader.loadTestsFromName(test_name))
    assert len(test_suite) == 1
    return test_suite[0]


Add a 'counter_to_iterable' utility function

--- logger/utilities.py
+++ logger/utilities.py
@@ -5,6 +5,7 @@
 __all__ = ["pick", "is_dunder", "convert_to_od"]

 import collections
+import itertools

 def pick(arg, default):
     """Handler for default versus given argument."""
@@ -17,3 +18,8 @@
 def convert_to_od(mapping, order):
     """Convert mapping to an OrderedDict instance using order."""
     return collections.OrderedDict([(i, mapping[i]) for i in order])
+
+def counter_to_iterable(counter):
+    """Convert a counter to an iterable / iterator."""
+    for item in itertools.starmap(itertools.repeat, counter):
+        yield from item

<|original_code|>
#!/usr/bin/env python3

"""Small utility functions for use in various places."""

__all__ = ["pick", "is_dunder", "convert_to_od"]

import collections

def pick(arg, default):
    """Handler for default versus given argument."""
    return default if arg is None else arg

def is_dunder(name):
    """Return True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2])

def convert_to_od(mapping, order):
    """Convert mapping to an OrderedDict instance using order."""
    return collections.OrderedDict([(i, mapping[i]) for i in order])

<|edits_diff|>
--- logger/utilities.py
+++ logger/utilities.py
@@ -5,6 +5,7 @@
 __all__ = ["pick", "is_dunder", "convert_to_od"]

 import collections
+import itertools

 def pick(arg, default):
     """Handler for default versus given argument."""
<|current_version|>
#!/usr/bin/env python3

"""Small utility functions for use in various places."""

__all__ = ["pick", "is_dunder", "convert_to_od"]

import collections
import itertools

def pick(arg, default):
    """Handler for default versus given argument."""
    return default if arg is None else arg

def is_dunder(name):
    """Return True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2])

def convert_to_od(mapping, order):
    """Convert mapping to an OrderedDict instance using order."""
    return collections.OrderedDict([(i, mapping[i]) for i in order])

<|next_version|>
#!/usr/bin/env python3

"""Small utility functions for use in various places."""

__all__ = ["pick", "is_dunder", "convert_to_od"]

import collections
import itertools

def pick(arg, default):
    """Handler for default versus given argument."""
    return default if arg is None else arg

def is_dunder(name):
    """Return True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2])

def convert_to_od(mapping, order):
    """Convert mapping to an OrderedDict instance using order."""
    return collections.OrderedDict([(i, mapping[i]) for i in order])

def counter_to_iterable(counter):
    """Convert a counter to an iterable / iterator."""
    for item in itertools.starmap(itertools.repeat, counter):
        yield from item


Add teams field in MakerScienceProfileResource

--- makerscience_profile/api.py
+++ makerscience_profile/api.py
@@ -6,10 +6,13 @@
 from dataserver.authentication import AnonymousApiKeyAuthentication
 from accounts.api import ProfileResource
 from scout.api import PostalAddressResource
+from projects.api import ProjectTeamResource

 class MakerScienceProfileResource(ModelResource):
     parent = fields.OneToOneField(ProfileResource, 'parent', full=True)
     location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
+
+    teams = fields.ToManyField(ProjectTeamResource, 'parent__projectteam_set', full=True, null=True)

     class Meta:
         queryset = MakerScienceProfile.objects.all()

<|original_code|>
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource

class MakerScienceProfileResource(ModelResource):
    parent = fields.OneToOneField(ProfileResource, 'parent', full=True)
    location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)

    class Meta:
        queryset = MakerScienceProfile.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'makerscience/profile'
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()
        always_return_data = True
        filtering = {
            'parent' : ALL_WITH_RELATIONS,
        }

    def dehydrate(self, bundle):
        bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
        return bundle

<|edits_diff|>
--- makerscience_profile/api.py
+++ makerscience_profile/api.py
@@ -6,6 +6,7 @@
 from dataserver.authentication import AnonymousApiKeyAuthentication
 from accounts.api import ProfileResource
 from scout.api import PostalAddressResource
+from projects.api import ProjectTeamResource

 class MakerScienceProfileResource(ModelResource):
     parent = fields.OneToOneField(ProfileResource, 'parent', full=True)
<|current_version|>
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
from projects.api import ProjectTeamResource

class MakerScienceProfileResource(ModelResource):
    parent = fields.OneToOneField(ProfileResource, 'parent', full=True)
    location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)

    class Meta:
        queryset = MakerScienceProfile.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'makerscience/profile'
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()
        always_return_data = True
        filtering = {
            'parent' : ALL_WITH_RELATIONS,
        }

    def dehydrate(self, bundle):
        bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
        return bundle

<|next_version|>
from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
from projects.api import ProjectTeamResource

class MakerScienceProfileResource(ModelResource):
    parent = fields.OneToOneField(ProfileResource, 'parent', full=True)
    location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)

    teams = fields.ToManyField(ProjectTeamResource, 'parent__projectteam_set', full=True, null=True)

    class Meta:
        queryset = MakerScienceProfile.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'makerscience/profile'
        authentication = AnonymousApiKeyAuthentication()
        authorization = DjangoAuthorization()
        always_return_data = True
        filtering = {
            'parent' : ALL_WITH_RELATIONS,
        }

    def dehydrate(self, bundle):
        bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
        return bundle