text:
package org.apache.tajo.worker;

import com.google.common.base.Preconditions;
import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.service.AbstractService;
import org.apache.tajo.QueryId;
import org.apache.tajo.QueryIdFactory;
import org.apache.tajo.TajoIdProtos;
import org.apache.tajo.TajoProtos;
import org.apache.tajo.conf.TajoConf;
import org.apache.tajo.ipc.ClientProtos;
import org.apache.tajo.ipc.QueryMasterClientProtocol;
import org.apache.tajo.master.querymaster.Query;
import org.apache.tajo.master.querymaster.QueryMasterTask;
import org.apache.tajo.rpc.BlockingRpcServer;
import org.apache.tajo.rpc.protocolrecords.PrimitiveProtos;
import org.apache.tajo.util.NetUtils;

import java.io.IOException;
import java.net.InetSocketAddress;

public class TajoWorkerClientService extends AbstractService {
  private static final Log LOG = LogFactory.getLog(TajoWorkerClientService.class);
  private final PrimitiveProtos.BoolProto BOOL_TRUE =
          PrimitiveProtos.BoolProto.newBuilder().setValue(true).build();
  private final PrimitiveProtos.BoolProto BOOL_FALSE =
          PrimitiveProtos.BoolProto.newBuilder().setValue(false).build();

  private BlockingRpcServer rpcServer;
  private InetSocketAddress bindAddr;
  private String addr;
  private int port;
  private TajoConf conf;
  private TajoWorker.WorkerContext workerContext;
  private TajoWorkerClientProtocolServiceHandler serviceHandler;

  public TajoWorkerClientService(TajoWorker.WorkerContext workerContext, int port) {
    super(TajoWorkerClientService.class.getName());

    this.port = port;
    this.workerContext = workerContext;
  }

  @Override
  public void init(Configuration conf) {
    Preconditions.checkArgument(conf instanceof TajoConf);
    this.conf = (TajoConf) conf;
    this.serviceHandler = new TajoWorkerClientProtocolServiceHandler();

    // init RPC Server in constructor cause Heartbeat Thread use bindAddr
    // Setup RPC server
    try {
      // TODO initial port num is value of config and find unused port with sequence
      InetSocketAddress initIsa = new InetSocketAddress("0.0.0.0", port);
      if (initIsa.getAddress() == null) {
        throw new IllegalArgumentException("Failed resolve of " + initIsa);
      }

      // TODO blocking/non-blocking??
      int workerNum = this.conf.getIntVar(TajoConf.ConfVars.WORKER_SERVICE_RPC_SERVER_WORKER_THREAD_NUM);
      this.rpcServer = new BlockingRpcServer(QueryMasterClientProtocol.class, serviceHandler, initIsa, workerNum);
      this.rpcServer.start();

      this.bindAddr = NetUtils.getConnectAddress(rpcServer.getListenAddress());
      this.addr = bindAddr.getHostName() + ":" + bindAddr.getPort();

      this.port = bindAddr.getPort();
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
    // Get the master address
    LOG.info(TajoWorkerClientService.class.getSimpleName() + " is bind to " + addr);

    super.init(conf);
  }

  @Override
  public void start() {
    super.start();
  }

  @Override
  public void stop() {
    LOG.info("TajoWorkerClientService stopping");
    if(rpcServer != null) {
      rpcServer.shutdown();
    }
    LOG.info("TajoWorkerClientService stopped");
    super.stop();
  }

  public InetSocketAddress getBindAddr() {
    return bindAddr;
  }

  public class TajoWorkerClientProtocolServiceHandler
          implements QueryMasterClientProtocol.QueryMasterClientProtocolService.BlockingInterface {
    @Override
    public PrimitiveProtos.BoolProto updateSessionVariables(
            RpcController controller,
            ClientProtos.UpdateSessionVariableRequest request) throws ServiceException {
      return null;
    }

    @Override
    public ClientProtos.GetQueryResultResponse getQueryResult(
            RpcController controller,
            ClientProtos.GetQueryResultRequest request) throws ServiceException {
      QueryId queryId = new QueryId(request.getQueryId());
      Query query = workerContext.getQueryMaster().getQueryMasterTask(queryId, true).getQuery();

      ClientProtos.GetQueryResultResponse.Builder builder = ClientProtos.GetQueryResultResponse.newBuilder();
      try {
        builder.setTajoUserName(UserGroupInformation.getCurrentUser().getUserName());
      } catch (IOException e) {
        LOG.warn("Can't get current user name");
      }

      if(query == null) {
        builder.setErrorMessage("No Query for " + queryId);
      } else {
        switch (query.getState()) {
          case QUERY_SUCCEEDED:
            builder.setTableDesc(query.getResultDesc().getProto());
            break;
          case QUERY_FAILED:
          case QUERY_ERROR:
            builder.setErrorMessage("Query " + queryId + " is failed");
          default:
            builder.setErrorMessage("Query " + queryId + " is still running");
        }
      }
      return builder.build();
    }

    @Override
    public ClientProtos.GetQueryStatusResponse getQueryStatus(
            RpcController controller,
            ClientProtos.GetQueryStatusRequest request) throws ServiceException {
      ClientProtos.GetQueryStatusResponse.Builder builder
              = ClientProtos.GetQueryStatusResponse.newBuilder();
      QueryId queryId = new QueryId(request.getQueryId());

      builder.setQueryId(request.getQueryId());

      if (queryId.equals(QueryIdFactory.NULL_QUERY_ID)) {
        builder.setResultCode(ClientProtos.ResultCode.OK);
        builder.setState(TajoProtos.QueryState.QUERY_SUCCEEDED);
      } else {
        QueryMasterTask queryMasterTask = workerContext.getQueryMaster().getQueryMasterTask(queryId);

        builder.setResultCode(ClientProtos.ResultCode.OK);
        builder.setQueryMasterHost(bindAddr.getHostName());
        builder.setQueryMasterPort(bindAddr.getPort());

        if (queryMasterTask == null) {
          queryMasterTask = workerContext.getQueryMaster().getQueryMasterTask(queryId, true);
        }
        if (queryMasterTask == null) {
          builder.setState(TajoProtos.QueryState.QUERY_NOT_ASSIGNED);
          return builder.build();
        }

        queryMasterTask.touchSessionTime();
        Query query = queryMasterTask.getQuery();

        builder.setState(query.getState());
        builder.setProgress(query.getProgress());
        builder.setSubmitTime(query.getAppSubmitTime());
        builder.setHasResult(
            !(queryMasterTask.getQueryTaskContext().getQueryContext().isCreateTable() ||
                queryMasterTask.getQueryTaskContext().getQueryContext().isInsert())
        );
        if (query.getState() == TajoProtos.QueryState.QUERY_SUCCEEDED) {
          builder.setFinishTime(query.getFinishTime());
        } else {
          builder.setFinishTime(System.currentTimeMillis());
        }
      }
      return builder.build();
    }

    @Override
    public PrimitiveProtos.BoolProto closeQuery (
            RpcController controller,
            TajoIdProtos.QueryIdProto request) throws ServiceException {
      final QueryId queryId = new QueryId(request);
      LOG.info("Stop Query:" + queryId);
      return BOOL_TRUE;
    }
  }
}


text:
package gzip

import (
	"compress/gzip"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

const (
	testResponse = "Gzip Test Response "
)

func newServer() *gin.Engine {
	router := gin.Default()
	router.Use(Gzip(DefaultCompression))
	router.GET("/", func(c *gin.Context) {
		c.Header("Content-Length", strconv.Itoa(len(testResponse)))
		c.String(200, testResponse)
	})
	return router
}

func TestGzip(t *testing.T) {
	req, _ := http.NewRequest("GET", "/", nil)
	req.Header.Add("Accept-Encoding", "gzip")

	w := httptest.NewRecorder()
	r := newServer()
	r.ServeHTTP(w, req)

	assert.Equal(t, w.Code, 200)
	assert.Equal(t, w.Header().Get("Content-Encoding"), "gzip")
	assert.Equal(t, w.Header().Get("Vary"), "Accept-Encoding")
	assert.Equal(t, w.Header().Get("Content-Length"), "0")
	assert.NotEqual(t, w.Body.Len(), 19)

	gr, err := gzip.NewReader(w.Body)
	assert.NoError(t, err)
	defer gr.Close()

	body, _ := ioutil.ReadAll(gr)
	assert.Equal(t, string(body), testResponse)
}

func TestGzipPNG(t *testing.T) {
	req, _ := http.NewRequest("GET", "/image.png", nil)
	req.Header.Add("Accept-Encoding", "gzip")

	router := gin.New()
	router.Use(Gzip(DefaultCompression))
	router.GET("/image.png", func(c *gin.Context) {
		c.String(200, "this is a PNG!")
	})

	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)

	assert.Equal(t, w.Code, 200)
	assert.Equal(t, w.Header().Get("Content-Encoding"), "")
	assert.Equal(t, w.Header().Get("Vary"), "")
	assert.Equal(t, w.Body.String(), "this is a PNG!")
}

func TestNoGzip(t *testing.T) {
	req, _ := http.NewRequest("GET", "/", nil)

	w := httptest.NewRecorder()
	r := newServer()
	r.ServeHTTP(w, req)

	assert.Equal(t, w.Code, 200)
	assert.Equal(t, w.Header().Get("Content-Encoding"), "")
	assert.Equal(t, w.Header().Get("Content-Length"), "19")
	assert.Equal(t, w.Body.String(), testResponse)
}

redpajama_set_name: RedPajamaGithub


text:
package com.fengdai.android.preferences;

import android.content.SharedPreferences;

import com.fengdai.android.json.JsonConverter;

/**
 * @author daifeng
 */
public class JsonPreference<T> extends AbstractPreference<T> {
    private T cache;
    private JsonConverter json;
    private Class<T> clazz;

    public JsonPreference(SharedPreferences sharedPreferences, String key, JsonConverter json,
                          Class<T> clazz) {
        super(sharedPreferences, key);
        this.clazz = clazz;
        this.json = json;
    }

    @Override
    protected T doGet() {
        if (this.cache != null) {
            return cache;
        }
        return json.fromJson(sharedPreferences.getString(key, null), clazz);
    }

    @Override
    public T get(T defValue) {
        if (this.cache != null) {
            return cache;
        }
        return super.get(defValue);
    }

    @Override
    public void set(T value) {
        this.cache = value;
        this.sharedPreferences.edit().putString(key, json.toJson(value)).apply();
    }
}


text:
namespace FakeItEasy.IntegrationTests
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using FakeItEasy.Configuration;
    using FakeItEasy.Core;
    using FakeItEasy.Tests.TestHelpers;
    using FluentAssertions;
    using Xunit;

    public class GeneralTests
    {
        public interface ITypeWithFakeableProperties
        {
            IEnumerable<object> Collection { get; }

            IFoo Foo { get; }
        }

        [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Required for testing.")]
        public interface IEmpty
        {
        }

        [Fact]
        public void Faked_object_with_fakeable_properties_should_have_fake_as_default_value()
        {
            // Arrange

            // Act
            var fake = A.Fake<ITypeWithFakeableProperties>();

            // Assert
            fake.Collection.Should().NotBeNull();
            fake.Foo.Should().NotBeNull();
        }

        [Fact]
        public void Faked_object_with_method_that_returns_fakeable_type_should_return_fake_by_default()
        {
            // Arrange
            var fake = A.Fake<IEnumerable<string>>();

            // Act
            var enumerator = fake.GetEnumerator();

            // Assert
            enumerator.Should().NotBeNull();
            Fake.GetFakeManager(enumerator).Should().NotBeNull();
        }

        [Fact]
        public void Faked_object_with_additional_attributes_should_create_a_type_with_those_attributes()
        {
            // Arrange

            // Act
            var fake = A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));

            // Assert
            fake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().HaveCount(1);
        }

        [Fact]
        public void Additional_attributes_should_not_be_added_to_the_next_fake()
        {
            // Arrange
            A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));

            // Act
            var secondFake = A.Fake<IFormattable>();

            // Assert
            secondFake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().BeEmpty();
        }

        [Fact]
        public void ErrorMessage_when_type_cannot_be_faked_should_specify_non_resolvable_constructor_arguments()
        {
            // Arrange

            // Act
            var exception = Record.Exception(() => A.Fake<NonResolvableType>());

            // Assert
            const string ExpectedMessage = @"
  The constructors with the following signatures were not tried:
    (FakeItEasy.IntegrationTests.IFoo, *FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)
    (*FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)

    Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.

";
            exception.Should()
                .BeAnExceptionOfType<FakeCreationException>().And
                .Message.Should().ContainModuloLineEndings(ExpectedMessage);
        }

        [Fact]
        public void ErrorMessage_when_configuring_void_call_that_cannot_be_configured_should_be_correct()
        {
            // Arrange
            var fake = A.Fake<TypeWithNonConfigurableMethod>();

            // Act
            var exception = Record.Exception(() =>
                A.CallTo(() => fake.NonVirtualVoidMethod(string.Empty, 1)).DoesNothing());

            // Assert
            exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
                .Message.Should().Contain("Non-virtual");
        }

        [Fact]
        public void ErrorMessage_when_configuring_function_call_that_cannot_be_configured_should_be_correct()
        {
            // Arrange
            var fake = A.Fake<TypeWithNonConfigurableMethod>();

            // Act
            var exception = Record.Exception(() =>
                A.CallTo(() => fake.NonVirtualFunction(string.Empty, 1)).Returns(10));

            // Assert
            exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
                .Message.Should().Contain("Non-virtual");
        }

        [Fact]
        public void ErrorMessage_when_configuring_generic_function_call_that_cannot_be_configured_should_be_correct()
        {
            // Arrange
            var fake = A.Fake<TypeWithNonConfigurableMethod>();

            // Act
            var exception = Record.Exception(() =>
                A.CallTo(() => fake.GenericNonVirtualFunction<int>()).Returns(10));

            // Assert
            exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
                .Message.Should().Contain("Non-virtual");
        }

        [Fact]
        public void Should_be_able_to_generate_class_fake_that_implements_additional_interface()
        {
            // Arrange
            var fake = A.Fake<FakeableClass>(x => x.Implements(typeof(IFoo)).Implements(typeof(IFormattable)));

            // Act

            // Assert
            fake.Should()
                .BeAssignableTo<IFoo>().And
                .BeAssignableTo<IFormattable>().And
                .BeAssignableTo<FakeableClass>();
        }

        [Fact]
        public void Should_be_able_to_generate_class_fake_that_implements_additional_interface_using_generic()
        {
            // Arrange
            var fake = A.Fake<FakeableClass>(x => x.Implements<IFoo>().Implements<IFormattable>());

            // Act

            // Assert
            fake.Should()
                .BeAssignableTo<IFoo>().And
                .BeAssignableTo<IFormattable>().And
                .BeAssignableTo<FakeableClass>();
        }

        [Fact]
        public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface()
        {
            // Arrange
            var fake = A.Fake<IFoo>(x => x.Implements(typeof(IFormatProvider)).Implements(typeof(IFormattable)));

            // Act

            // Assert
            fake.Should()
                .BeAssignableTo<IFoo>().And
                .BeAssignableTo<IFormattable>().And
                .BeAssignableTo<IFormatProvider>();
        }

        [Fact]
        public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface_using_generic()
        {
            // Arrange
            var fake = A.Fake<IFoo>(x => x.Implements<IFormatProvider>().Implements<IFormattable>());

            // Act

            // Assert
            fake.Should()
                .BeAssignableTo<IFoo>().And
                .BeAssignableTo<IFormattable>().And
                .BeAssignableTo<IFormatProvider>();
        }

        [Fact]
        public void FakeCollection_should_return_list_where_all_objects_are_fakes()
        {
            // Arrange

            // Act
            var result = A.CollectionOfFake<IFoo>(10);

            // Assert
            result.Should().BeAssignableTo<IList<IFoo>>().And
                .OnlyContain(foo => foo is object && Fake.GetFakeManager(foo) is object);
        }

        [Fact]
        public void DummyCollection_should_return_correct_number_of_dummies()
        {
            // Arrange

            // Act
            var result = A.CollectionOfDummy<IFoo>(10);

            // Assert
            result.Should().HaveCount(10);
        }

        [Fact]
        public void Returns_from_sequence_only_applies_the_number_as_many_times_as_the_number_of_specified_values()
        {
            // Arrange
            var foo = A.Fake<IFoo>();
            A.CallTo(() => foo.Baz()).Throws(new InvalidOperationException());
            A.CallTo(() => foo.Baz()).ReturnsNextFromSequence(1, 2);

            foo.Baz();
            foo.Baz();

            // Act
            var exception = Record.Exception(() => foo.Baz());

            // Assert
            exception.Should().BeAnExceptionOfType<InvalidOperationException>();
        }

        public class NonResolvableType
        {
            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")]
            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
            public NonResolvableType(IFoo foo, NoInstanceType bar)
            {
            }

            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
            protected NonResolvableType(NoInstanceType bar)
            {
            }
        }

        public class NoInstanceType
        {
            private NoInstanceType()
            {
            }
        }

        public class FakeableClass
        {
            public virtual void Foo()
            {
            }
        }

        public class TypeWithNonConfigurableMethod
        {
            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
            public void NonVirtualVoidMethod(string argument, int otherArgument)
            {
            }

            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
            [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
            public int NonVirtualFunction(string argument, int otherArgument)
            {
                return 1;
            }

            public T GenericNonVirtualFunction<T>() where T : struct => default;
        }
    }
}


text:
namespace gfx {
class ImageSkia;
}

class StatusIcon;

// Provides a cross-platform interface to the system's status tray, and exposes
// APIs to add/remove icons to the tray and attach context menus.
class StatusTray {
 public:
  enum StatusIconType {
    NOTIFICATION_TRAY_ICON = 0,
    MEDIA_STREAM_CAPTURE_ICON,
    BACKGROUND_MODE_ICON,
    OTHER_ICON,
    NAMED_STATUS_ICON_COUNT
  };

  // Static factory method that is implemented separately for each platform to
  // produce the appropriate platform-specific instance. Returns NULL if this
  // platform does not support status icons.
  static std::unique_ptr<StatusTray> Create();

  StatusTray(const StatusTray&) = delete;
  StatusTray& operator=(const StatusTray&) = delete;

  virtual ~StatusTray();

  // Creates a new StatusIcon. The StatusTray retains ownership of the
  // StatusIcon. Returns NULL if the StatusIcon could not be created.
  StatusIcon* CreateStatusIcon(StatusIconType type,
                               const gfx::ImageSkia& image,
                               const std::u16string& tool_tip);

  // Removes |icon| from this status tray.
  void RemoveStatusIcon(StatusIcon* icon);

 protected:
  using StatusIcons = std::vector<std::unique_ptr<StatusIcon>>;

  StatusTray();

  // Factory method for creating a status icon for this platform.
  virtual std::unique_ptr<StatusIcon> CreatePlatformStatusIcon(
      StatusIconType type,
      const gfx::ImageSkia& image,
      const std::u16string& tool_tip) = 0;

  // Returns the list of active status icons so subclasses can operate on them.
  const StatusIcons& status_icons() const { return status_icons_; }

 private:
  // List containing all active StatusIcons. The icons are owned by this
  // StatusTray.
  StatusIcons status_icons_;
};

#endif  // CHROME_BROWSER_STATUS_ICONS_STATUS_TRAY_H_


text:
#ifndef JUCE_OPENGLGRAPHICSCONTEXT_H_INCLUDED
#define JUCE_OPENGLGRAPHICSCONTEXT_H_INCLUDED

/** Creates a graphics context object that will render into the given OpenGL target.
    The caller is responsible for deleting this object when no longer needed.
*/
LowLevelGraphicsContext* createOpenGLGraphicsContext (OpenGLContext& target,
                                                      int width, int height);

/** Creates a graphics context object that will render into the given OpenGL target.
    The caller is responsible for deleting this object when no longer needed.
*/
LowLevelGraphicsContext* createOpenGLGraphicsContext (OpenGLContext& context,
                                                      OpenGLFrameBuffer& target);

/** Creates a graphics context object that will render into the given OpenGL target.
    The caller is responsible for deleting this object when no longer needed.
*/
LowLevelGraphicsContext* createOpenGLGraphicsContext (OpenGLContext& context,
                                                      unsigned int frameBufferID,
                                                      int width, int height);

//==============================================================================
/**
    Used to create custom shaders for use with an openGL 2D rendering context.

    Given a GL-based rendering context, you can write a fragment shader that applies some
    kind of per-pixel effect.
*/
struct JUCE_API  OpenGLGraphicsContextCustomShader
{
    /** Creates a custom shader.

        The shader code will not be compiled until actually needed, so it's OK to call this
        constructor when no GL context is active.

        The code should be a normal fragment shader. As well as the usual GLSL variables, there is
        also an automatically declared varying vec2 called "pixelPos", which indicates the pixel
        position within the graphics context of the pixel being drawn. There is also a varying value
        "pixelAlpha", which indicates the alpha by which the pixel should be multiplied, so that the
        edges of any clip-region masks are anti-aliased correctly.
    */
    OpenGLGraphicsContextCustomShader (const String& fragmentShaderCode);

    /** Destructor. */
    ~OpenGLGraphicsContextCustomShader();

    /** Returns the program, if it has been linked and is active.
        This can be called when you're about to use fillRect, to set up any uniforms/textures that
        the program may require.
    */
    OpenGLShaderProgram* getProgram (LowLevelGraphicsContext&) const;

    /** Applies the shader to a rectangle within the graphics context. */
    void fillRect (LowLevelGraphicsContext&, const Rectangle<int>& area) const;

    /** Attempts to compile the program if necessary, and returns an error message if it fails. */
    Result checkCompilation (LowLevelGraphicsContext&);

    /** Returns the code that was used to create this object. */
    const String& getFragmentShaderCode() const noexcept           { return code; }

private:
    String code, hashName;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLGraphicsContextCustomShader)
};

#endif   // JUCE_OPENGLGRAPHICSCONTEXT_H_INCLUDED


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Settings'
        db.create_table(u'sync_settings', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('action', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0, db_index=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
            ('start_row', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('end_row', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('model', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('show_in_quick_menu', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('processor', self.gf('django.db.models.fields.CharField')(default='XlsxProcessor', max_length=255)),
            ('worksheet', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('include_header', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('filename', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('buffer_file', self.gf('django.db.models.fields.files.FileField')(db_index=True, max_length=100, blank=True)),
            ('dataset', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('data_action', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('filter_dataset', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('filter_querystring', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('language', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('hide_translation_fields', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('create_fields', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('populate_from_file', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('include_related', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('edit_attributes', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'sync', ['Settings'])

        # Adding model 'Sequence'
        db.create_table(u'sync_sequence', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('buffer_file', self.gf('django.db.models.fields.files.FileField')(db_index=True, max_length=100, blank=True)),
            ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
        ))
        db.send_create_signal(u'sync', ['Sequence'])

        # Adding M2M table for field settings on 'Sequence'
        m2m_table_name = db.shorten_name(u'sync_sequence_settings')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('sequence', models.ForeignKey(orm[u'sync.sequence'], null=False)),
            ('settings', models.ForeignKey(orm[u'sync.settings'], null=False))
        ))
        db.create_unique(m2m_table_name, ['sequence_id', 'settings_id'])

        # Adding model 'Field'
        db.create_table(u'sync_field', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('position', self.gf('django.db.models.fields.PositiveIntegerField')(default=0, null=True, blank=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('attribute', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('skip', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('update', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('find', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('set_filter', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('set_value', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('find_filter', self.gf('django.db.models.fields.CharField')(default='exact', max_length=255, blank=True)),
            ('find_value', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('converters', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('settings', self.gf('django.db.models.fields.related.ForeignKey')(related_name='fields', to=orm['sync.Settings'])),
        ))
        db.send_create_signal(u'sync', ['Field'])

        # Adding model 'Context'
        db.create_table(u'sync_context', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('cell', self.gf('django.db.models.fields.CharField')(max_length=1000, blank=True)),
            ('value', self.gf('django.db.models.fields.CharField')(max_length=1000, blank=True)),
            ('settings', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='contexts', null=True, to=orm['sync.Settings'])),
        ))
        db.send_create_signal(u'sync', ['Context'])

        # Adding model 'Report'
        db.create_table(u'sync_report', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('action', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0, db_index=True)),
            ('buffer_file', self.gf('django.db.models.fields.files.FileField')(db_index=True, max_length=100, blank=True)),
            ('status', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1)),
            ('started_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('completed_at', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
            ('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('settings', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='reports', null=True, to=orm['sync.Settings'])),
        ))
        db.send_create_signal(u'sync', ['Report'])

        # Adding model 'Message'
        db.create_table(u'sync_message', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('position', self.gf('django.db.models.fields.PositiveIntegerField')(default=0, null=True, blank=True)),
            ('report', self.gf('django.db.models.fields.related.ForeignKey')(related_name='messages', to=orm['sync.Report'])),
            ('message', self.gf('django.db.models.fields.TextField')(max_length=10000)),
            ('step', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1)),
            ('input_position', self.gf('django.db.models.fields.CharField')(max_length=10, blank=True)),
            ('input_value', self.gf('django.db.models.fields.TextField')(max_length=60000, null=True, blank=True)),
            ('type', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0)),
        ))
        db.send_create_signal(u'sync', ['Message'])

    def backwards(self, orm):
        # Deleting model 'Settings'
        db.delete_table(u'sync_settings')

        # Deleting model 'Sequence'
        db.delete_table(u'sync_sequence')

        # Removing M2M table for field settings on 'Sequence'
        db.delete_table(db.shorten_name(u'sync_sequence_settings'))

        # Deleting model 'Field'
        db.delete_table(u'sync_field')

        # Deleting model 'Context'
        db.delete_table(u'sync_context')

        # Deleting model 'Report'
        db.delete_table(u'sync_report')

        # Deleting model 'Message'
        db.delete_table(u'sync_message')

    models = {
        u'sync.context': {
            'Meta': {'object_name': 'Context'},
            'cell': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'settings': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'contexts'", 'null': 'True', 'to': u"orm['sync.Settings']"}),
            'value': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'})
        },
        u'sync.field': {
            'Meta': {'ordering': "('position',)", 'object_name': 'Field'},
            'attribute': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'converters': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'find': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'find_filter': ('django.db.models.fields.CharField', [], {'default': "'exact'", 'max_length': '255', 'blank': 'True'}),
            'find_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'position': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
            'set_filter': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'set_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'settings': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'fields'", 'to': u"orm['sync.Settings']"}),
            'skip': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'update': ('django.db.models.fields.BooleanField', [], {'default': 'True'})
        },
        u'sync.message': {
            'Meta': {'ordering': "('position',)", 'object_name': 'Message'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'input_position': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
            'input_value': ('django.db.models.fields.TextField', [], {'max_length': '60000', 'null': 'True', 'blank': 'True'}),
            'message': ('django.db.models.fields.TextField', [], {'max_length': '10000'}),
            'position': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
            'report': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': u"orm['sync.Report']"}),
            'step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
            'type': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'})
        },
        u'sync.report': {
            'Meta': {'ordering': "('-id',)", 'object_name': 'Report'},
            'action': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
            'buffer_file': ('django.db.models.fields.files.FileField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}),
            'completed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'settings': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'reports'", 'null': 'True', 'to': u"orm['sync.Settings']"}),
            'started_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        },
        u'sync.sequence': {
            'Meta': {'object_name': 'Sequence'},
            'buffer_file': ('django.db.models.fields.files.FileField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'settings': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'sequences'", 'symmetrical': 'False', 'to': u"orm['sync.Settings']"})
        },
        u'sync.settings': {
            'Meta': {'ordering': "('-id',)", 'object_name': 'Settings'},
            'action': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
            'buffer_file': ('django.db.models.fields.files.FileField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}),
            'create_fields': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'data_action': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'dataset': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'edit_attributes': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'end_row': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'filter_dataset': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'filter_querystring': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'hide_translation_fields': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'include_header': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'include_related': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'populate_from_file': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'processor': ('django.db.models.fields.CharField', [], {'default': "'XlsxProcessor'", 'max_length': '255'}),
            'show_in_quick_menu': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'start_row': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'worksheet': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
        }
    }

    complete_apps = ['sync']


text:
Djheroku
========

Djheroku is a helper script that reads Heroku configuration from environment
variables and injects them to Django configuration.

.. image:: https://secure.travis-ci.org/fubaz/djheroku.png?branch=master
    :target: http://travis-ci.org/fubaz/djheroku
    :alt: Build Status

.. image:: https://coveralls.io/repos/ferrix/djheroku/badge.png
    :target: https://coveralls.io/r/ferrix/djheroku
    :alt: Test Coverage

.. image:: https://requires.io/github/fubaz/djheroku/requirements.svg?branch=master
     :target: https://requires.io/github/fubaz/djheroku/requirements/?branch=master
     :alt: Requirements Status

.. image:: https://img.shields.io/pypi/v/djheroku.svg
    :target: https://pypi.python.org/pypi/djheroku/
    :alt: Latest Version

.. image:: https://img.shields.io/pypi/wheel/djheroku.svg
    :target: https://pypi.python.org/pypi/djheroku/
    :alt: Wheel Status

.. image:: https://img.shields.io/pypi/l/djheroku.svg
    :target: https://pypi.python.org/pypi/djheroku/
    :alt: License

Autopilot for Heroku settings
-----------------------------

This is an easier way to control what Django does. Just add
a few lines to your settings.py::

    from djheroku import autopilot
    autopilot(vars())

Then you can make runtime changes to your application settings::

    heroku addons:add sendgrid
    heroku config:set ADDONS=sendgrid
    heroku addons:add memcachier
    heroku config:set ADDONS=sendgrid,memcachier

Djheroku will change the variables accordingly.

Configuration helpers
---------------------

Example::

    # settings.py
    from djheroku import sendgrid
    vars().update(sendgrid())

This is equivalent of typing in::

    # settings.py
    import os

    if 'SENDGRID_USERNAME' in os.environ and 'SENDGRID_PASSWORD' in os.environ:
        EMAIL_HOST = 'smtp.sendgrid.net'
        EMAIL_HOST_USER = os.environ['SENDGRID_USERNAME']
        EMAIL_HOST_PASSWORD = os.environ['SENDGRID_PASSWORD']
        EMAIL_PORT = 587
        EMAIL_USE_TLS = True

If any of the variables are not present, the configuration will be left as it
is. Currently there are two helpers: ``sendgrid()`` and ``mailgun()``.

Middleware
----------

There are three middleware classes in Djheroku. They are used to redirect
permanently from one URL to another.

* ``NoWwwMiddleware`` removed www. from URLs of incoming requests.
  The opposite is built-in functionality of Django. Enable this Middleware
  and set NO_WWW = True in settings.py to activate.
* ``PreferredDomainMiddleware`` redirects all domains directed to the
  application to a preferred one.
* ``ForceSSLMiddleware`` redirects all non-SSL connections to a secure
  connection.

Each of these middlewares does one thing only and combined they will lead
into three separate redirects or even a eternal loop if configured
properly wrong.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.koustuvsinha.testsensors" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".view.DisplaySensorListActivity"
            android:label="@string/title_activity_display_sensor_list" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".view.DisplayRawSensorDataActivity"
            android:label="@string/title_activity_display_raw_sensor_data" >
        </activity>

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="46bc9d79d134d135a207ce90633921b296ced28d" />

    </application>

</manifest>


text:
%% Poluation flow circle

populationsBefore = [300 500 200];
populationsTransitions = [150 15 135 ; % Neuron to stuff
  350 100 50; % Glia to stuff
  100 20 80]; % Noise to stuff
populationsAfter = sum(populationsTransitions);

fractionsBefore = populationsBefore/sum(populationsBefore);
fractionsAfter = populationsAfter/sum(populationsAfter);

fractionsNames = {'neuron', 'glia', 'noise'};
beforeAfterNames = {'basal', 'bicuculine'};
titleName = 'WT';

fractionTransfers = zeros(length(populationsBefore), length(populationsBefore), 2);
for i = 1:length(populationsBefore)
  for j = 1:length(populationsBefore)
    fractionTransfers(i,j, :) = [populationsTransitions(i,j)/populationsBefore(i), populationsTransitions(i,j)/populationsAfter(j)];
  end
end

rad1 = 0.95;
rad2 = rad1+0.1;
delta = 20e-3;
rad3 = rad1-0.025;
%$preFractor = 0.85;
expn = 0.5;
maxF = 0.9;
radText = rad2+0.05;
radTextInner = rad3-0.025;
N = length(populationsBefore)*2;
network.X = 1:N;
network.Y = 1:N;

Ncols = N/2;
cmap = parula(N+1);
cmap = cmap(2:end, :);
cmap = [cmap(1:2:end, :); cmap(2:2:end, :)];

cmapvals = floor(linspace(1, length(cmap), N));

createFigure(11.5*2,11.5*2);
hold on;
axis square;
box on;
%
xlim([-1.2 1.2]);
ylim([-1.2 1.2]);
set(gca,'XTick',[]);
set(gca,'YTick',[]);
yl = ylim;
plot([0 0], yl,'k--');

initialAngle = -pi/2;
% Modified to avoid overlap at 2PI
fractionEdgesBefore = [0, cumsum(fractionsBefore)];
fractionEdgesAfter = [0, cumsum(fractionsAfter)];

fractionEdgesBeforeWithDelta = [fractionEdgesBefore(1:end-1)+delta; fractionEdgesBefore(2:end)-delta];
fractionEdgesAfterWithDelta = [fractionEdgesAfter(1:end-1)+delta; fractionEdgesAfter(2:end)-delta];

anglesBefore = -fractionEdgesBeforeWithDelta*pi + initialAngle;
anglesAfter = fractionEdgesAfterWithDelta*pi + initialAngle;

% Ok, get the new angles
rads = zeros(N, 2);
for i = 1:N
    if(i <= N/2)
      rads(i, 1) = anglesBefore(1, i);
      rads(i, 2) = anglesBefore(2, i);
    else
      rads(i, 1) = anglesAfter(1, i-N/2);
      rads(i, 2) = anglesAfter(2, i-N/2);
    end
end

% Calculate the segmentet circle
for i = 1:N
    P = plot_arc(rads(i,1),rads(i,2),0,0,rad1,rad2,100);
    %set(P,'facecolor',cmap(cmapvals(i),:),'linewidth',1, 'edgecolor','k');
    set(P,'facecolor', cmap(cmapvals(i),:),'linewidth',1, 'edgecolor', cmap(cmapvals(i),:));

end

patchSize = [];
patchHandles = [];
% Quick pass to get patchSizes and then do them in order
for i = 1:N/2
  for j = 1:N/2
    fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
    fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
    cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
    cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];

    f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
    f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
    f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
    f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);
    patchSize = [patchSize; i, j, f2-f1];
  end
end

patchSize = sortrows(patchSize, -3);

for pit = 1:size(patchSize, 1)
  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
  fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
  cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
  cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];
  %cumsumFractionsBefore = [0 cumsum(fractionsBefore)];
  %cumsumFractionsAfter = [0 cumsum(fractionsAfter)];

  f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);

  radsBefore = -[f1 f2]*pi + initialAngle;
  radsAfter = [f3 f4]*pi + initialAngle;

  a = radsBefore(1);
  b = radsBefore(2);
  h = 0;
  k = 0;
  l = 100;
  t = linspace(a,b,l);
  x1 = rad3*cos(t) + h;
  y1 = rad3*sin(t) + k;
  %plot(x1, y1, 'Color', cmap(i, :));

  a = radsAfter(1);
  b = radsAfter(2);
  h = 0;
  k = 0;
  l = 100;
  t = linspace(a,b,l);
  x2 = rad3*cos(t) + h;
  y2 = rad3*sin(t) + k;

  % Change curvature depending on x position
  preFractor1 = maxF*(1-mean(abs([x1(1) x2(1)]))).^expn;
  preFractor2 = maxF*(1-mean(abs([x1(end) x2(end)]))).^expn;
  preFractor3 = maxF*(1-mean(abs([x1(1) x1(end) x2(1) x2(end)]))).^expn;

  [nx1, ny1] = getCurvedConnection([x1(1) x2(1)], [y1(1) y2(1)], preFractor1);
  [nx2, ny2] = getCurvedConnection([x1(end) x2(end)], [y1(end) y2(end)], preFractor2);

  % Now try the patch
  patchX = [x1, nx2, x2(end:-1:1), nx1(end:-1:1)];
  patchY = [y1, ny2, y2(end:-1:1), ny1(end:-1:1)];
  % Now the interpolating line for colors
  [nxI, nyI] = getCurvedConnection([x1(round(length(x1)/2)) x2(round(length(x2)/2))], [y1(round(length(y1)/2)) y2(round(length(y2)/2))], preFractor3);
  initialColor = cmap(i, :);
  finalColor = cmap(j+N/2, :);
  cI = zeros(length(nxI), 3);
  for cc = 1:3
    cI(:, cc) = initialColor(cc)+(0:(length(nxI)-1))/(length(nxI)-1)*(finalColor(cc)-initialColor(cc));
  end
  % Now get the associated patch interpolated color
  patchC = zeros(length(patchX), 1, 3);
%   for it = 1:length(patchX)
%     curX = patchX(it);
%     curY = patchY(it);
%     [~, closestP] = min((nxI-curX).^2+(nyI-curY).^2);
%     patchC(it, 1, :) = cI(closestP, :);
%   end
  closestP = [ones(size(x1)), 1:size(cI,1), ones(size(x1))*size(cI,1), size(cI,1):-1:1];
  patchC(:, 1, :) = cI(closestP, :);
  P = patch(patchX', patchY', patchC);
  set(P, 'edgecolor', 'none');
  patchHandles = [patchHandles; P];
  %plot(nxI, nyI, 'k');
end

% Now the texts

% First the titles
text(-1.2, 1.1, beforeAfterNames{1}, 'HorizontalAlignment', 'left', ...
  'FontSize', 16, 'FontWeight', 'bold');
text(1.2, 1.1, beforeAfterNames{2}, 'HorizontalAlignment', 'right', ...
  'FontSize', 16, 'FontWeight', 'bold');

text(0, 1.3, titleName, 'HorizontalAlignment', 'center', ...
  'FontSize', 20, 'FontWeight', 'bold');

% Now the populations
textPosBefore = fractionEdgesBefore(1:end-1)+diff(fractionEdgesBefore)/2;
textPosAfter = fractionEdgesAfter(1:end-1)+diff(fractionEdgesAfter)/2;

textAnglesBefore = -textPosBefore*pi + initialAngle;
textAnglesAfter = textPosAfter*pi + initialAngle;

for i = 1:N/2
    xt = radText*cos(textAnglesBefore(i));
    yt = radText*sin(textAnglesBefore(i));
    newName = {fractionsNames{i}; sprintf('%.0f%%',100*fractionsBefore(i))};
    %newName = {[fractionsNames{i} sprintf(' (%.0f%%)',100*fractionsBefore(i))]};
    a=text(xt, yt, newName, 'HorizontalAlignment', 'right', ...
      'FontWeight', 'bold', 'rotation', textAnglesBefore(i)/2/pi*360+180);
    xt = radText*cos(textAnglesAfter(i));
    yt = radText*sin(textAnglesAfter(i));
    newName = {fractionsNames{i}; sprintf('%.0f%%',100*fractionsAfter(i))};
    text(xt, yt, newName, 'HorizontalAlignment', 'left', ...
      'FontWeight', 'bold', 'rotation', textAnglesAfter(i)/2/pi*360);
end

% Now the innerfractions
for pit = 1:size(patchSize, 1)
  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
  fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
  cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
  cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];

  f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);

  radsBefore = -mean([f1 f2])*pi + initialAngle;
  radsAfter = mean([f3 f4])*pi + initialAngle;

  xt = radTextInner*cos(radsBefore);
  yt = radTextInner*sin(radsBefore);
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 1))};
  %newName = {[fractionsNames{i} sprintf(' (%.0f%%)',100*fractionsBefore(i))]};
  a=text(xt, yt, newName, 'HorizontalAlignment', 'left', ...
    'FontWeight', 'bold', 'rotation', radsBefore/2/pi*360+180);
  xt = radTextInner*cos(radsAfter);
  yt = radTextInner*sin(radsAfter);
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 2))};
  text(xt, yt, newName, 'HorizontalAlignment', 'right', ...
    'FontWeight', 'bold', 'rotation', radsAfter/2/pi*360);
end

%
axis off;

%%

fileName = 'figflow';
%opts = struct('FontMode','scaled','FontSizeMin', 2, 'FontSizeMax', 6, 'LineMode','scaled','Resolution',600);
opts = struct('FontMode','scaled', 'FontSize', 1, 'FontSizeMin', 2, 'LineMode','scaled','Resolution',600);
%opts = struct('FontMode','fixed', 'LineMode','scaled','Resolution',600);
exportfig(gcf,fileName,opts,'format','png','Color','rgb','Bounds','loose');close all;

%system(sprintf('epspdf %s.eps %s.pdf',fileName, fileName),'-echo');

%% Now we can generalize to arbitrary stuff
fractionsNames = {'neuron', 'glia', 'noise'};
beforeAfterNames = {'basal', 'bicuculine'};
titleName = 'WT';
rad1 = 0.95;
rad2 = rad1+0.1;
delta = 10e-3;
rad3 = rad1-0.025;
expn = 0.4;
maxF = 0.8;
radText = rad2+0.05;
radTextInner = rad3-0.025;

populationsBefore = [300 500 200];
populationsTransitions = [150 15 135 ; % Neuron to stuff
  350 100 50; % Glia to stuff
  100 20 80]; % Noise to stuff

% Hack to duplicate the stuff
populationsAfter = sum(populationsTransitions);
populations = [populationsBefore populationsAfter(end:-1:1)];
populationsTransitions = [zeros(size(populationsTransitions)), populationsTransitions(:,end:-1:1);
  zeros(size(populationsTransitions)), zeros(size(populationsTransitions))];

% Now no more hack - generalized
fractions = populations/sum(populations);
fractionsNames = [fractionsNames, fractionsNames(end:-1:1)];

fractionTransfers = zeros(length(populations), length(populations), 2);
for i = 1:length(populations)
  for j = 1:length(populations)
    fractionTransfers(i,j, :) = [populationsTransitions(i,j)/populations(i), populationsTransitions(i,j)/populations(j)];
  end
end

N = length(populations);
network.X = 1:N;
network.Y = 1:N;

cmap = isolum(N+1);
cmap = cmap(2:end, :);
% Also hack the colormap
cmap = [cmap(1:2:end, :); cmap(end:-2:2, :)];

cmapvals = floor(linspace(1, length(cmap), N));

hFig = figure('units', 'centimeters');
hFig.Position = [hFig.Position(1:2) 20 20];

hold on;
axis square;
box on;
%
xlim([-1.2 1.2]);
ylim([-1.2 1.2]);
set(gca,'XTick',[]);
set(gca,'YTick',[]);
yl = ylim;
plot([0 0], yl,'k--');

initialAngle = -pi/2;
% Modified to avoid overlap at 2PI
fractionEdges = [0, cumsum(fractions)];

fractionEdgesWithDelta = [fractionEdges(1:end-1)+delta; fractionEdges(2:end)-delta];

angles = -fractionEdgesWithDelta*2*pi + initialAngle;

% Ok, get the new angles
rads = zeros(N, 2);
for i = 1:N
      rads(i, 1) = angles(1, i);
      rads(i, 2) = angles(2, i);
end

% Calculate the segmentet circle
for i = 1:N
    P = plot_arc(rads(i,1),rads(i,2),0,0,rad1,rad2,100);
    %set(P,'facecolor',cmap(cmapvals(i),:),'linewidth',1, 'edgecolor','k');
    set(P,'facecolor', cmap(cmapvals(i),:),'linewidth',1, 'edgecolor', cmap(cmapvals(i),:));

end

patchSize = [];
patchHandles = [];
% Quick pass to get patchSizes and then do them in order
fractionSizes = diff(fractionEdgesWithDelta);
for i = 1:N
  for j = 1:N

    cumsumFractionsBefore = [cumsum(fractionTransfers(i, :, 1),'reverse') 0];
    cumsumFractionsAfter = [cumsum(fractionTransfers(:, j, 2),'reverse')' 0];

    f1 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j);
    f2 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j+1);
    f3 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i);
    f4 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i+1);
    patchSize = [patchSize; i, j, f2-f1];
  end
end

patchSize = sortrows(patchSize, 3);

for pit = 1:size(patchSize, 1)
  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  if(patchSize(pit, 3) == 0)
    continue;
  end
  cumsumFractionsBefore = [cumsum(fractionTransfers(i, :, 1),'reverse') 0];
  cumsumFractionsAfter = [cumsum(fractionTransfers(:, j, 2),'reverse')' 0];

  f1 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i+1);

  radsBefore = -[f1 f2]*2*pi + initialAngle;
  radsAfter = -[f3 f4]*2*pi + initialAngle;

  a = radsBefore(1);
  b = radsBefore(2);
  h = 0;
  k = 0;
  l = 100;
  t = linspace(a,b,l);
  x1 = rad3*cos(t) + h;
  y1 = rad3*sin(t) + k;

  a = radsAfter(1);
  b = radsAfter(2);
  h = 0;
  k = 0;
  l = 100;
  t = linspace(a,b,l);
  x2 = rad3*cos(t) + h;
  y2 = rad3*sin(t) + k;

  % Change curvature depending on x position
  preFractor1 = maxF*(1-mean(abs([x1(1) x2(1)]))).^expn;
  preFractor2 = maxF*(1-mean(abs([x1(end) x2(end)]))).^expn;
  preFractor3 = maxF*(1-mean(abs([x1(1) x1(end) x2(1) x2(end)]))).^expn;

  [nx1, ny1] = getCurvedConnection([x1(end) x2(1)], [y1(end) y2(1)], preFractor1);
  [nx2, ny2] = getCurvedConnection([x2(end) x1(1)], [y2(end) y1(1)], preFractor2);
  % Now try the patch
  patchX = [x1, nx1, x2, nx2];
  patchY = [y1, ny1, y2, ny2];

  % Now the interpolating line for colors
  [nxI, nyI] = getCurvedConnection([x1(round(length(x1)/2)) x2(round(length(x2)/2))], [y1(round(length(y1)/2)) y2(round(length(y2)/2))], preFractor3);
  initialColor = cmap(i, :);
  finalColor = cmap(j, :);
  cI = zeros(length(nxI), 3);
  for cc = 1:3
    cI(:, cc) = initialColor(cc)+(0:(length(nxI)-1))/(length(nxI)-1)*(finalColor(cc)-initialColor(cc));
  end
  % Now get the associated patch interpolated color
  patchC = zeros(length(patchX), 1, 3);

  closestP = [ones(size(x1)), 1:size(cI,1), ones(size(x1))*size(cI,1), size(cI,1):-1:1];
  patchC(:, 1, :) = cI(closestP, :);
  P = patch(patchX', patchY', patchC);
  set(P, 'edgecolor', 'none', 'FaceAlpha', 0.75);
  patchHandles = [patchHandles; P];
end
alpha = 0.5;

% Now the texts

% First the titles
text(-1.2, 1.1, beforeAfterNames{1}, 'HorizontalAlignment', 'left', ...
  'FontSize', 16, 'FontWeight', 'bold');
text(1.2, 1.1, beforeAfterNames{2}, 'HorizontalAlignment', 'right', ...
  'FontSize', 16, 'FontWeight', 'bold');

text(0, 1.3, titleName, 'HorizontalAlignment', 'center', ...
  'FontSize', 20, 'FontWeight', 'bold');

% Now the populations
textPos = fractionEdges(1:end-1)+diff(fractionEdges)/2;
textAngles = -textPos*2*pi + initialAngle;

for i = 1:N
    xt = radText*cos(textAngles(i));
    yt = radText*sin(textAngles(i));
    % Hack so the fractions are correct
    newName = {fractionsNames{i}; sprintf('%.0f%%',2*100*fractions(i))};
    if(xt > 0)
      angleAdd = 0;
      angleAlign = 'left';
    else
      angleAdd = 180;
      angleAlign = 'right';
    end
    a=text(xt, yt, newName, 'HorizontalAlignment', angleAlign, ...
      'FontWeight', 'bold', 'rotation', textAngles(i)/2/pi*360+angleAdd);
end

% Now the innerfractions
fractionSizes = diff(fractionEdgesWithDelta);
for pit = 1:size(patchSize, 1)
  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  if(patchSize(pit, 3) == 0)
    continue;
  end
  cumsumFractionsBefore = [cumsum(fractionTransfers(i, :, 1), 'reverse') 0];
  cumsumFractionsAfter = [cumsum(fractionTransfers(:, j, 2), 'reverse')' 0];

  f1 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesWithDelta(1, i)+fractionSizes(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesWithDelta(1, j)+fractionSizes(j)*cumsumFractionsAfter(i+1);

  radsBefore = -mean([f1 f2])*2*pi + initialAngle;
  radsAfter = -mean([f3 f4])*2*pi + initialAngle;

  xt = radTextInner*cos(radsBefore);
  yt = radTextInner*sin(radsBefore);
  if(xt > 0)
      angleAdd = 0;
      angleAlign = 'right';
    else
      angleAdd = 180;
      angleAlign = 'left';
  end
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 1))};

  a=text(xt, yt, newName, 'HorizontalAlignment', angleAlign, ...
    'FontWeight', 'bold', 'rotation', radsBefore/2/pi*360+angleAdd);

  xt = radTextInner*cos(radsAfter);
  yt = radTextInner*sin(radsAfter);
  if(xt > 0)
      angleAdd = 0;
      angleAlign = 'right';
    else
      angleAdd = 180;
      angleAlign = 'left';
  end
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 2))};
  text(xt, yt, newName, 'HorizontalAlignment', angleAlign, ...
    'FontWeight', 'bold', 'rotation', radsAfter/2/pi*360+angleAdd);
end

axis off;
%%

fileName = 'figflowfinal';
%opts = struct('FontMode','scaled','FontSizeMin', 2, 'FontSizeMax', 6, 'LineMode','scaled','Resolution',600);
opts = struct('FontMode','scaled', 'FontSize', 1, 'FontSizeMin', 2, 'LineMode','scaled','Resolution',600);
%opts = struct('FontMode','fixed', 'LineMode','scaled','Resolution',600);
exportfig(gcf,fileName,opts,'format','png','Color','rgb','Bounds','loose');close all;

%system(sprintf('epspdf %s.eps %s.pdf',fileName, fileName),'-echo');

%% Now for the lines

populationsBefore = [300 500 200];
populationsTransitions = [150 15 135 ; % Neuron to stuff
  350 100 50; % Glia to stuff
  100 20 80]; % Noise to stuff
populationsAfter = sum(populationsTransitions);

fractionsBefore = populationsBefore/sum(populationsBefore);
fractionsAfter = populationsAfter/sum(populationsAfter);

fractionsNames = {'neuron', 'glia', 'noise'};
beforeAfterNames = {'basal', 'bicuculine'};
titleName = 'WT';

fractionTransfers = zeros(length(populationsBefore), length(populationsBefore), 2);
for i = 1:length(populationsBefore)
  for j = 1:length(populationsBefore)
    fractionTransfers(i,j, :) = [populationsTransitions(i,j)/populationsBefore(i), populationsTransitions(i,j)/populationsAfter(j)];
  end
end

barPositions = [-1 1]*0.5;
barWidth = 0.1;

delta = 20e-3;
barGap = 0.015;
radTextGap = 0.01;
radTextInnerGap = 0.01;
sigmoidPrefactor = 0.75;
blackEdges = false;
N = length(populationsBefore);

Ncols = N*2;
%cmap = parula(Ncols+1);
cmap = isolum(Ncols+1);
cmap = cmap(2:end, :);
cmap = [cmap(1:2:end, :); cmap(2:2:end, :)];

cmapvals = floor(linspace(1, length(cmap), Ncols));

hFig = figure('units', 'centimeters');
hFig.Position = [hFig.Position(1:2) 30 30];

hold on;
axis equal;
box on;
%
xlim([-0.2 0.2]+barPositions);
ylim([-0.05 1.15]);
set(gca,'XTick',[]);
set(gca,'YTick',[]);
yl = ylim;
%%plot([0 0], yl,'k--');

% Modified to avoid overlap at 2PI
fractionEdgesBefore = [0, cumsum(fractionsBefore)];
fractionEdgesAfter = [0, cumsum(fractionsAfter)];

fractionEdgesBeforeWithDelta = [fractionEdgesBefore(1:end-1)+delta; fractionEdgesBefore(2:end)-delta];
fractionEdgesAfterWithDelta = [fractionEdgesAfter(1:end-1)+delta; fractionEdgesAfter(2:end)-delta];

% Create the bars
for i = 1:N
  xPatchBefore = [0 0 -1 -1]*barWidth+barPositions(1);
  yPatchBefore = [fractionEdgesBeforeWithDelta(1,i) fractionEdgesBeforeWithDelta(2,i) fractionEdgesBeforeWithDelta(2,i) fractionEdgesBeforeWithDelta(1,i)];
  xPatchAfter = [0 0 1 1]*barWidth+barPositions(2);
  yPatchAfter = [fractionEdgesAfterWithDelta(1,i) fractionEdgesAfterWithDelta(2,i) fractionEdgesAfterWithDelta(2,i) fractionEdgesAfterWithDelta(1,i)];
  P = patch(xPatchBefore, yPatchBefore, 'r');
  set(P,'facecolor', cmap(cmapvals(i),:),'linewidth',1, ...
    'edgecolor', cmap(cmapvals(i),:));
  if(blackEdges)
    P.EdgeColor = 'k';
  end
  P = patch(xPatchAfter, yPatchAfter, 'r');
  set(P,'facecolor', cmap(cmapvals(i+N),:),'linewidth',1, ...
    'edgecolor', cmap(cmapvals(i+N),:));
  if(blackEdges)
    P.EdgeColor = 'k';
  end
end

patchSize = [];
patchHandles = [];
% Quick pass to get patchSizes and then do them in order
for i = 1:N
  for j = 1:N
    fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
    fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
    cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
    cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];

    f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
    f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
    f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
    f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);
    patchSize = [patchSize; i, j, f2-f1];
  end
end

patchSize = sortrows(patchSize, -3);

for pit = 1:size(patchSize, 1)
  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
  fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
  cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
  cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];

  f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);

  radsBefore = [f1 f2];
  radsAfter = [f3 f4];

  xBefore = [1, 1]*barPositions(1)+barGap;
  xAfter = [1, 1]*barPositions(2)-barGap;
  yBefore = [f1 f2];
  yAfter = [f3 f4];

  [xLineDown, yLineDown] = getSigmoidConnection([xBefore(1) xAfter(1)], [yBefore(1) yAfter(1)], sigmoidPrefactor);
  [xLineUp, yLineUp] = getSigmoidConnection([xBefore(2) xAfter(2)], [yBefore(2) yAfter(2)], sigmoidPrefactor);

  patchX = [xLineDown xLineUp(end:-1:1)];
  patchY = [yLineDown yLineUp(end:-1:1)];

  % Now the interpolating line for colors
  [nxI, nyI] = getSigmoidConnection([mean(xBefore) mean(xAfter)], [mean(yBefore) mean(yAfter)], sigmoidPrefactor);
  initialColor = cmap(i, :);
  finalColor = cmap(j+N, :);

  cI = zeros(length(nxI), 3);
  for cc = 1:3
    cI(:, cc) = initialColor(cc)+(0:(length(nxI)-1))/(length(nxI)-1)*(finalColor(cc)-initialColor(cc));
  end
  % Now get the associated patch interpolated color
  patchC = zeros(length(patchX), 1, 3);
  closestP = [1:size(cI,1), size(cI,1):-1:1];

  patchC(:, 1, :) = cI(closestP, :);

  P = patch(patchX', patchY', patchC);

  if(blackEdges)
    P.EdgeColor = 'k';
  else
    set(P, 'edgecolor', 'none');
  end
  set(P, 'edgecolor', 'none', 'FaceAlpha', 0.75);
  patchHandles = [patchHandles; P];
end

% Now the texts
% First the titles
text(barPositions(1)-barWidth, 1.05, beforeAfterNames{1}, 'HorizontalAlignment', 'left', ...
  'FontSize', 16, 'FontWeight', 'bold');
text(barPositions(2)+barWidth, 1.05, beforeAfterNames{2}, 'HorizontalAlignment', 'right', ...
  'FontSize', 16, 'FontWeight', 'bold');

text(0, 1.1, titleName, 'HorizontalAlignment', 'center', ...
  'FontSize', 20, 'FontWeight', 'bold');

% Now the populations
textPosBefore = fractionEdgesBefore(1:end-1)+diff(fractionEdgesBefore)/2;
textPosAfter = fractionEdgesAfter(1:end-1)+diff(fractionEdgesAfter)/2;

for i = 1:N
    xt = barPositions(1)-barWidth-radTextGap;
    yt = textPosBefore(i);
    newName = {fractionsNames{i}; sprintf('%.0f%%',100*fractionsBefore(i))};
    %newName = {[fractionsNames{i} sprintf(' (%.0f%%)',100*fractionsBefore(i))]};
    a=text(xt, yt, newName, 'HorizontalAlignment', 'right', ...
      'FontSize', 12, 'FontWeight', 'bold');
    xt = barPositions(2)+barWidth+radTextGap;
    yt = textPosAfter(i);
    newName = {fractionsNames{i}; sprintf('%.0f%%',100*fractionsAfter(i))};
    text(xt, yt, newName, 'HorizontalAlignment', 'left', ...
      'FontSize', 12, 'FontWeight', 'bold');
end

% Now the innerfractions
for pit = 1:size(patchSize, 1)

  i = patchSize(pit, 1);
  j = patchSize(pit, 2);
  fractionSizesBefore = diff(fractionEdgesBeforeWithDelta);
  fractionSizesAfter = diff(fractionEdgesAfterWithDelta);
  cumsumFractionsBefore = [0 cumsum(fractionTransfers(i, :, 1))];
  cumsumFractionsAfter = [0 cumsum(fractionTransfers(:, j, 2))'];

  f1 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j);
  f2 = fractionEdgesBeforeWithDelta(1, i)+fractionSizesBefore(i)*cumsumFractionsBefore(j+1);
  f3 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i);
  f4 = fractionEdgesAfterWithDelta(1, j)+fractionSizesAfter(j)*cumsumFractionsAfter(i+1);

  xt = barPositions(1)+barGap+radTextInnerGap;
  yt = mean([f1 f2]);
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 1))};
  %newName = {[fractionsNames{i} sprintf(' (%.0f%%)',100*fractionsBefore(i))]};
  a=text(xt, yt, newName, 'HorizontalAlignment', 'left', ...
    'FontSize', 12, 'FontWeight', 'bold');
  xt = barPositions(2)-barGap-radTextInnerGap;
  yt = mean([f3 f4]);
  newName = {sprintf('%.0f%%',100*fractionTransfers(i, j, 2))};
  text(xt, yt, newName, 'HorizontalAlignment', 'right', ...
    'FontSize', 12, 'FontWeight', 'bold');
end

axis off;
%%

fileName = 'figflowSquarefinal';
%opts = struct('FontMode','scaled','FontSizeMin', 2, 'FontSizeMax', 6, 'LineMode','scaled','Resolution',600);
opts = struct('FontMode','scaled', 'FontSize', 1, 'FontSizeMin', 2, 'LineMode','scaled','Resolution',600);
%opts = struct('FontMode','fixed', 'LineMode','scaled','Resolution',600);
exportfig(gcf,fileName,opts,'format','png','Color','rgb','Bounds','loose');close all;


text:
package com.hazelcast.concurrent.atomicreference.operations;

import com.hazelcast.concurrent.atomicreference.AtomicReferenceContainer;
import com.hazelcast.core.IFunction;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.NodeEngine;

import static com.hazelcast.concurrent.atomicreference.AtomicReferenceDataSerializerHook.GET_AND_ALTER;

public class GetAndAlterOperation extends AbstractAlterOperation {

    public GetAndAlterOperation() {
    }

    public GetAndAlterOperation(String name, Data function) {
        super(name, function);
    }

    @Override
    public void run() throws Exception {
        NodeEngine nodeEngine = getNodeEngine();
        IFunction f = nodeEngine.toObject(function);
        AtomicReferenceContainer container = getReferenceContainer();

        response = container.get();
        Object input = nodeEngine.toObject(container.get());
        //noinspection unchecked
        Object output = f.apply(input);
        Data serializedOutput = nodeEngine.toData(output);
        shouldBackup = !isEquals(response, serializedOutput);
        if (shouldBackup) {
            container.set(serializedOutput);
            backup = serializedOutput;
        }
    }

    @Override
    public int getId() {
        return GET_AND_ALTER;
    }
}


text:
"""Module to select preferred estimator.

This is intended to be a simple script which evaluates what the user
has indicated as the best estimator in est.BestEstimator.MakeEstimator.
"""

import logging, sys
import Evaluator
from pyvol.experimental import BestEstimator

def Go(seed=64):
    """Function to evaluate best estimator

    INPUTS:

    -- seed=64:        Random seed to use for simulation.

    -------------------------------------------------------

    RETURNS:    Same as Evaluate.EvalEstimator plus estimator used.

    -------------------------------------------------------

    PURPOSE:    Evaluate the best estimator as indicated in
                BestEstimator.MakeEstimator.

    The following illustrates example usage:

>>> seed = 64 # random seed for simulations
>>> import EvaluateBestEstimator
>>> results = EvaluateBestEstimator.Go(seed=seed)
>>> import logging                                         # configure logging
>>> logging.addLevelName(logging.WARNING + 1, 'IMPORTANT') # so that test shows
>>> logging.getLogger('').setLevel(logging.WARNING + 1)    # up in log output
>>> logging.log(logging.WARNING + 1, '''
... Tested best estimator (%s) with seed=%s. Results:%c%s%c''' %
... (results[-1], seed, 10, results[0], 10))

    """
    estimator = BestEstimator.MakeEstimator()
    results = list(Evaluator.EvalEstimator(estimator, seed=seed))+[estimator]
    return results

if __name__ == '__main__':
    #If run as the main script, we simply run the evaulator
    logging.getLogger('').setLevel(logging.INFO)
    logging.info('Starting %s' % (sys.argv))
    if (len(sys.argv) == 1):
        userSeed = 64
    elif (len(sys.argv) == 2):
        userSeed = int(sys.argv[1])
    else:
        raise Exception('Invalid arguments. Usage:\n   %s [seed]\n' % (
            sys.argv[0]))
    userResults = Go(userSeed)
    print 'Estimator results:\n%s\n' % str(userResults[0])


text:
module Burning_Glass
  class ContactInformation
    attr_accessor :first_name, :middle_name, :last_name, :aristocratic_title, :form_of_address, :generation, :qualification, :address_line_1, :address_line_2, :city, :state, :country, :postal_code, :home_phone, :mobile_phone, :email, :website

    def self.parse(contact_information)
      return nil if contact_information.nil?
      result = self.new
      result.first_name = contact_information.css('name givenname').collect(&:text).join(" ")
      result.last_name = contact_information.css('name surname').collect(&:text).join(" ")
      result.aristocratic_title = contact_information.css('name honorific').collect(&:text).join(" ")
      result.qualification = contact_information.css('name namesuffix').collect(&:text).join(" ")

      address = contact_information.css('address street').collect(&:text)
      result.address_line_1 = address[0] if address.length > 0
      result.address_line_2 = address[1] if address.length > 1
      result.city = contact_information.css('address city').text rescue nil
      result.state = contact_information.css('address state').text rescue nil
      result.postal_code = contact_information.css('address postalcode').text rescue nil
      result.country = contact_information.css('address country').text rescue nil

      if !contact_information.css('phone').first.blank?
        result.home_phone = contact_information.css('phone').first.text rescue nil
      else
        result.home_phone = contact_information.css('phone home').first rescue nil
        end

      result.mobile_phone = contact_information.css('phone cell').first rescue nil

      result.website = contact_information.css('website').first rescue nil

      result.email = contact_information.css('email').first rescue nil

      result
    end
  end
end


text:
/*
 * 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.
 */
package io.trino.tests.product.launcher.cli;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Module;
import io.airlift.log.Logger;
import io.trino.tests.product.launcher.Extensions;
import io.trino.tests.product.launcher.LauncherModule;
import io.trino.tests.product.launcher.docker.ContainerUtil;
import io.trino.tests.product.launcher.env.DockerContainer;
import io.trino.tests.product.launcher.env.Environment;
import io.trino.tests.product.launcher.env.EnvironmentConfig;
import io.trino.tests.product.launcher.env.EnvironmentFactory;
import io.trino.tests.product.launcher.env.EnvironmentModule;
import io.trino.tests.product.launcher.env.EnvironmentOptions;
import org.testcontainers.DockerClientFactory;
import picocli.CommandLine.Command;
import picocli.CommandLine.ExitCode;

import javax.inject.Inject;

import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;

import static io.trino.tests.product.launcher.cli.Commands.runCommand;
import static io.trino.tests.product.launcher.env.EnvironmentContainers.TESTS;
import static io.trino.tests.product.launcher.env.EnvironmentContainers.isPrestoContainer;
import static io.trino.tests.product.launcher.env.EnvironmentListener.getStandardListeners;
import static java.util.Objects.requireNonNull;
import static picocli.CommandLine.Mixin;
import static picocli.CommandLine.Option;

@Command(
        name = "up",
        description = "Start an environment",
        usageHelpAutoWidth = true)
public final class EnvironmentUp
        implements Callable<Integer>
{
    private static final Logger log = Logger.get(EnvironmentUp.class);

    @Option(names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit")
    public boolean usageHelpRequested;

    @Mixin
    public EnvironmentOptions environmentOptions = new EnvironmentOptions();

    @Mixin
    public EnvironmentUpOptions environmentUpOptions = new EnvironmentUpOptions();

    private final Module additionalEnvironments;

    public EnvironmentUp(Extensions extensions)
    {
        this.additionalEnvironments = extensions.getAdditionalEnvironments();
    }

    @Override
    public Integer call()
    {
        return runCommand(
                ImmutableList.<Module>builder()
                        .add(new LauncherModule())
                        .add(new EnvironmentModule(environmentOptions, additionalEnvironments))
                        .add(environmentUpOptions.toModule())
                        .build(),
                EnvironmentUp.Execution.class);
    }

    public static class EnvironmentUpOptions
    {
        private static final String DEFAULT_VALUE = "(default: ${DEFAULT-VALUE})";

        @Option(names = "--background", description = "Keep containers running in the background once they are started " + DEFAULT_VALUE)
        public boolean background;

        @Option(names = "--environment", paramLabel = "<environment>", description = "Name of the environment to start", required = true)
        public String environment;

        @Option(names = "--option", paramLabel = "<option>", description = "Extra options to provide to environment (property can be used multiple times; format is key=value)")
        public Map<String, String> extraOptions = new HashMap<>();

        @Option(names = "--logs-dir", paramLabel = "<dir>", description = "Location of the exported logs directory " + DEFAULT_VALUE)
        public Optional<Path> logsDirBase;

        public Module toModule()
        {
            return binder -> binder.bind(EnvironmentUpOptions.class).toInstance(this);
        }
    }

    public static class Execution
            implements Callable<Integer>
    {
        private final EnvironmentFactory environmentFactory;
        private final boolean withoutPrestoMaster;
        private final boolean background;
        private final String environment;
        private final EnvironmentConfig environmentConfig;
        private final Optional<Path> logsDirBase;
        private final DockerContainer.OutputMode outputMode;
        private final Map<String, String> extraOptions;

        @Inject
        public Execution(EnvironmentFactory environmentFactory, EnvironmentConfig environmentConfig, EnvironmentOptions options, EnvironmentUpOptions environmentUpOptions)
        {
            this.environmentFactory = requireNonNull(environmentFactory, "environmentFactory is null");
            this.environmentConfig = requireNonNull(environmentConfig, "environmentConfig is null");
            this.withoutPrestoMaster = options.withoutPrestoMaster;
            this.background = environmentUpOptions.background;
            this.environment = environmentUpOptions.environment;
            this.outputMode = requireNonNull(options.output, "options.output is null");
            this.logsDirBase = requireNonNull(environmentUpOptions.logsDirBase, "environmentUpOptions.logsDirBase is null");
            this.extraOptions = ImmutableMap.copyOf(requireNonNull(environmentUpOptions.extraOptions, "environmentUpOptions.extraOptions is null"));
        }

        @Override
        public Integer call()
        {
            Optional<Path> environmentLogPath = logsDirBase.map(dir -> dir.resolve(environment));
            Environment.Builder builder = environmentFactory.get(environment, environmentConfig, extraOptions)
                    .setContainerOutputMode(outputMode)
                    .setLogsBaseDir(environmentLogPath)
                    .removeContainer(TESTS);

            if (withoutPrestoMaster) {
                builder.removeContainers(container -> isPrestoContainer(container.getLogicalName()));
            }

            log.info("Creating environment '%s' with configuration %s and options %s", environment, environmentConfig, extraOptions);
            Environment environment = builder.build(getStandardListeners(environmentLogPath));
            environment.start();

            if (background) {
                killContainersReaperContainer();
                return ExitCode.OK;
            }

            environment.awaitContainersStopped();
            environment.stop();

            return ExitCode.OK;
        }

        private static void killContainersReaperContainer()
        {
            log.info("Killing the testcontainers reaper container (Ryuk) so that environment can stay alive");
            ContainerUtil.killContainersReaperContainer(DockerClientFactory.lazyClient());
        }
    }
}