text:
import { Observable } from '../Observable';
import { ReplaySubject } from '../ReplaySubject';
import { IScheduler } from '../Scheduler';
import { multicast } from './multicast';
import { ConnectableObservable } from '../observable/ConnectableObservable';
import { UnaryFunction, MonoTypeOperatorFunction, OperatorFunction } from '../interfaces';

/* tslint:disable:max-line-length */
export function publishReplay<T>(bufferSize?: number, windowTime?: number, scheduler?: IScheduler): UnaryFunction<Observable<T>, ConnectableObservable<T>>;
export function publishReplay<T>(bufferSize?: number, windowTime?: number, selector?: MonoTypeOperatorFunction<T>, scheduler?: IScheduler): MonoTypeOperatorFunction<T>;
export function publishReplay<T, R>(bufferSize?: number, windowTime?: number, selector?: OperatorFunction<T, R>, scheduler?: IScheduler): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */

export function publishReplay<T, R>(bufferSize?: number,
                                    windowTime?: number,
                                    selectorOrScheduler?: IScheduler | OperatorFunction<T, R>,
                                    scheduler?: IScheduler): UnaryFunction<Observable<T>, ConnectableObservable<R> | Observable<R>> {

  if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
    scheduler = selectorOrScheduler;
  }

  const selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
  const subject = new ReplaySubject<T>(bufferSize, windowTime, scheduler);

  return (source: Observable<T>) => multicast(() => subject, selector)(source) as Observable<R> | ConnectableObservable<R>;
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
description: "「Stay hungry. Stay foolish.」"
---

{% for post in paginator.posts %}

            {{ post.title }}

        {% if post.subtitle %}

            {{ post.subtitle }}

        {% endif %}

            {{ post.content | strip_html | truncate:200 }}

{% endfor %}


text:
from django.conf import settings

DEFAULT_TEMPLATE = "auditcare/auditcare_config_broken.html"

def login_template():
    return getattr(settings, 'LOGIN_TEMPLATE', DEFAULT_TEMPLATE)

def logout_template():
    return getattr(settings, 'LOGGEDOUT_TEMPLATE', DEFAULT_TEMPLATE)

def to_django_header(value):
    """Convert header name to a key to be used with `request.META`"""
    return 'HTTP_' + value.upper().replace('-', '_')


text:
@layout('template.main')

<?php
    $title = $course->name;
    $subtitle = 'Create a Subject';
?>

@section('content')
    @if ($isNew == true)
        {{ Form::open(URL::current()) }}

        {{ Form::hidden('course_id',$course->id) }}

        {{ $errors->first('code', '
:message
') }}

{{ Form::label('code', 'Subject Code') }}

{{ Form::text('code', Input::old('code')) }}

        {{ $errors->first('name', '
:message
') }}

{{ Form::label('name', 'Subject Name') }}

{{ Form::text('name', Input::old('name')) }}

        {{ $errors->first('description', '
:message
') }}

{{ Form::label('description', 'Desciption') }}

{{ Form::textarea('description', Input::old('description'), array('class'=>'field span11','rows'=>'10')) }}

{{ Form::submit('Create Subject') }}

        {{ Form::close() }}
    @else
        {{ Form::open(URL::current(), 'PUT') }}
        {{ Form::hidden('course_id',$course->id) }}

        {{ $errors->first('code', '
:message
') }}

{{ Form::label('code', 'Subject Code') }}

{{ Form::text('code', Input::old('code', $info->code)) }}

        {{ $errors->first('name', '
:message
') }}

{{ Form::label('name', 'Subject Name') }}

{{ Form::text('name', Input::old('name', $info->name)) }}

        {{ $errors->first('description', '
:message
') }}

{{ Form::label('description', 'Desciption') }}

{{ Form::textarea('description', Input::old('description', $info->description), array('class'=>'field span11', 'rows'=>'10')) }}

{{ Form::submit('Update Subject') }}

    @endif
@endsection


text:
namespace MediaShare.Web.Infrastructure.Mapping
{

    using AutoMapper;

    public interface IHaveCustomMappings
    {
        void CreateMappings(IConfiguration configuration);
    }
}


text:
function out = sliceFi(in,bits,offset)
for i=1:length(in)
    element_chosen=in(i);
    out_bin(i,:) = element_chosen.bin;
end

inds=offset:(offset+bits-1);
out=bin2dec(out_bin(:,inds));
end


text:
package org.zstack.storage.primary.local;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusListCallBack;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.Q;
import org.zstack.core.db.SQLBatch;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.HasThreadContext;
import org.zstack.header.core.Completion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.host.HostConstant;
import org.zstack.header.host.MigrateVmOnHypervisorMsg;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImageConstant.ImageMediaType;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.image.ImageStatus;
import org.zstack.header.image.ImageVO;
import org.zstack.header.log.NoLogging;
import org.zstack.header.message.MessageReply;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.storage.snapshot.VolumeSnapshotTree;
import org.zstack.header.storage.snapshot.VolumeSnapshotVO;
import org.zstack.header.storage.snapshot.VolumeSnapshotVO_;
import org.zstack.header.vm.VmInstanceConstant;
import org.zstack.header.vm.VmInstanceSpec;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMHostAsyncHttpCallMsg;
import org.zstack.kvm.KVMHostAsyncHttpCallReply;
import org.zstack.kvm.KVMHostVO;
import org.zstack.storage.primary.local.LocalStorageKvmBackend.*;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.function.Function;
import org.zstack.utils.logging.CLogger;

import javax.persistence.TypedQuery;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.Callable;

import static org.zstack.core.Platform.operr;
import static org.zstack.utils.CollectionDSL.list;

/**
 * Created by frank on 10/24/2015.
 */
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class LocalStorageKvmMigrateVmFlow extends NoRollbackFlow {
    private static final CLogger logger = Utils.getLogger(LocalStorageKvmMigrateVmFlow.class);

    @Autowired
    private DatabaseFacade dbf;
    @Autowired
    private CloudBus bus;
    @Autowired
    private ThreadFacade thdf;
    @Autowired
    private LocalStorageFactory localStorageFactory;

    public static final String VERIFY_SNAPSHOT_CHAIN_PATH = "/localstorage/snapshot/verifychain";
    public static final String REBASE_SNAPSHOT_BACKING_FILES_PATH = "/localstorage/snapshot/rebasebackingfiles";
    public static final String COPY_TO_REMOTE_BITS_PATH = "/localstorage/copytoremote";

    public static class SnapshotTO {
        public String path;
        public String parentPath;
        public String snapshotUuid;
    }

    public static class VerifySnapshotChainCmd extends LocalStorageKvmBackend.AgentCommand {
        public List<SnapshotTO> snapshots;
    }

    public static class RebaseSnapshotBackingFilesCmd extends LocalStorageKvmBackend.AgentCommand {
        public List<SnapshotTO> snapshots;
    }

    public static class CopyBitsFromRemoteCmd extends LocalStorageKvmBackend.AgentCommand implements HasThreadContext, Serializable {
        public String sendCommandUrl;
        public List<String> paths;
        public String dstIp;
        @NoLogging
        public String dstPassword;
        public String dstUsername;
        public Integer dstPort = 22;
        public String stage;
        public String volumeUuid;
    }

    static class BackingImage {
        String uuid;
        String path;
        Long size;
        String md5;
    }

    @Override
    public void run(final FlowTrigger next, Map data) {
        final VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
        final String srcHostUuid = spec.getVmInventory().getHostUuid();
        final String dstHostUuid = spec.getDestHost().getUuid();

        SimpleQuery<LocalStorageResourceRefVO> q = dbf.createQuery(LocalStorageResourceRefVO.class);
        q.add(LocalStorageResourceRefVO_.resourceUuid, Op.EQ, spec.getVmInventory().getRootVolumeUuid());
        final LocalStorageResourceRefVO ref = q.find();

        final List<VolumeInventory> volumesOnLocalStorage = getVolumeOnLocalStorage(spec);

        FlowChain chain = FlowChainBuilder.newShareFlowChain();
        chain.setName(String.format("migrate-vm-%s-on-localstorage-%s", spec.getVmInventory().getUuid(), ref.getPrimaryStorageUuid()));
        chain.then(new ShareFlow() {
            long requiredSize = 0;
            LocalStorageKvmBackend backend;
            StorageMigrationPolicy storageMigrationPolicy = StorageMigrationPolicy.FullCopy;
            BackingImage backingImage = new BackingImage();
            List<VolumeSnapshotTree> snapshotTrees = new ArrayList<VolumeSnapshotTree>();
            List<VolumeSnapshotInventory> allSnapshots;

            boolean downloadImage;
            ImageVO image;
            VolumeInventory rootVolume;

            final String destIp;
            final String username;
            final String password;
            final int port;

            {
                for (VolumeInventory vol : volumesOnLocalStorage) {
                    requiredSize += vol.getSize();

                    SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class);
                    q.add(VolumeSnapshotVO_.volumeUuid, Op.EQ, vol.getUuid());
                    List<VolumeSnapshotVO> vos = q.list();
                    if (!vos.isEmpty()) {
                        Map<String, List<VolumeSnapshotVO>> m = new HashMap<String, List<VolumeSnapshotVO>>();

                        for (VolumeSnapshotVO vo : vos) {
                            requiredSize += vo.getSize();
                            m.computeIfAbsent(vo.getTreeUuid(), k -> new ArrayList<>()).add(vo);
                        }

                        for (List<VolumeSnapshotVO> l : m.values()) {
                            VolumeSnapshotTree tree = VolumeSnapshotTree.fromVOs(l);
                            snapshotTrees.add(tree);
                        }

                        allSnapshots =  VolumeSnapshotInventory.valueOf(vos);
                    }
                }

                rootVolume = spec.getVmInventory().getRootVolume();
                backend = new LocalStorageKvmBackend(dbf.findByUuid(rootVolume.getPrimaryStorageUuid(), PrimaryStorageVO.class));
                String imageUuid = rootVolume.getRootImageUuid();
                if (imageUuid == null) {
                    downloadImage = false;
                } else {
                    image = dbf.findByUuid(imageUuid, ImageVO.class);
                    downloadImage = !(image == null || image.getMediaType() == ImageMediaType.ISO
                            || image.getStatus() == ImageStatus.Deleted);
                }

                KVMHostVO dstHost = dbf.findByUuid(dstHostUuid, KVMHostVO.class);
                destIp = localStorageFactory.getDestMigrationAddress(srcHostUuid, dstHostUuid);
                username = dstHost.getUsername();
                password = dstHost.getPassword();
                port = dstHost.getPort();
            }

            @Override
            public void setup() {
                if (downloadImage) {
                    flow(new NoRollbackFlow() {
                        String __name__ = "download-image-to-cache";

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            DownloadImageToPrimaryStorageCacheMsg msg = new DownloadImageToPrimaryStorageCacheMsg();
                            msg.setImage(ImageInventory.valueOf(image));
                            msg.setHostUuid(dstHostUuid);
                            msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                            bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                            bus.send(msg, new CloudBusCallBack(trigger) {
                                @Override
                                public void run(MessageReply reply) {
                                    if (!reply.isSuccess()) {
                                        trigger.fail(reply.getError());
                                        return;
                                    }

                                    DownloadImageToPrimaryStorageCacheReply r = reply.castReply();
                                    storageMigrationPolicy = StorageMigrationPolicy.IncCopy;
                                    backingImage.uuid = image.getUuid();
                                    backingImage.path = r.getInstallPath();
                                    trigger.next();
                                }
                            });
                        }
                    });
                } else {
                    flow(new NoRollbackFlow() {
                        String __name__ = "get-base-image-cache-of-root-volume";

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            GetVolumeBaseImagePathCmd cmd = new GetVolumeBaseImagePathCmd();
                            cmd.volumeInstallDir = backend.makeVolumeInstallDir(rootVolume);
                            cmd.imageCacheDir = backend.getCachedImageDir();
                            cmd.volumeUuid = rootVolume.getUuid();
                            callKvmHost(srcHostUuid, ref.getPrimaryStorageUuid(), LocalStorageKvmBackend.GET_BASE_IMAGE_PATH, cmd, GetVolumeBaseImagePathRsp.class, new ReturnValueCompletion<GetVolumeBaseImagePathRsp>(trigger) {
                                @Override
                                public void success(GetVolumeBaseImagePathRsp rsp) {
                                    if (rsp.path != null && backend.isCachedImageUrl(rsp.path)) {
                                        backingImage.path = rsp.path;
                                        backingImage.size = rsp.size;
                                    }
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    logger.error(String.format("cannot get volume base image %s, skip and continue", errorCode.getDetails()));
                                    trigger.next();
                                }
                            });
                        }
                    });

                    flow(new Flow() {
                        String __name__ = "reserve-capacity-for-base-image-cache-on-dst-host";

                        boolean s = false;

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            if (backingImage.path == null) {
                                logger.debug("no base image cache, skip this flow");
                                trigger.next();
                                return;
                            }

                            reserveStorageCapacityOnHost(dstHostUuid, ref.getPrimaryStorageUuid(), backingImage.size, new Completion(trigger) {
                                @Override
                                public void success() {
                                    s = true;
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(errorCode);
                                }
                            });
                        }

                        @Override
                        public void rollback(final FlowRollback trigger, Map data) {
                            if (s) {
                                returnStorageCapacityToHost(dstHostUuid, ref.getPrimaryStorageUuid(), backingImage.size);
                            }

                            trigger.rollback();
                        }
                    });

                    flow(new NoRollbackFlow() {
                        String __name__ = "get-md5-of-base-image-cache";

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            if (backingImage.path == null) {
                                logger.debug("no base image cache, skip this flow");
                                trigger.next();
                                return;
                            }

                            GetMd5Cmd cmd = new GetMd5Cmd();
                            GetMd5TO to = new GetMd5TO();
                            to.resourceUuid = "backing-file";
                            to.path = backingImage.path;
                            cmd.md5s = list(to);

                            callKvmHost(srcHostUuid, ref.getPrimaryStorageUuid(), LocalStorageKvmBackend.GET_MD5_PATH, cmd, GetMd5Rsp.class, new ReturnValueCompletion<GetMd5Rsp>(trigger) {
                                @Override
                                public void success(GetMd5Rsp rsp) {
                                    backingImage.md5 = rsp.md5s.get(0).md5;
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(errorCode);
                                }
                            });
                        }
                    });

                    flow(new Flow() {
                        String __name__ = "migrate-base-image-cache";

                        boolean s = false;

                        private void migrate(final FlowTrigger trigger) {
                            // sync here for migrating multiple volumes having the same backing file
                            thdf.chainSubmit(new ChainTask(trigger) {
                                @Override
                                public String getSyncSignature() {
                                    return String.format("migrate-base-image-cache-%s-to-host-%s", backingImage.path, dstHostUuid);
                                }

                                @Override
                                public void run(final SyncTaskChain chain) {
                                    final CopyBitsFromRemoteCmd cmd = new CopyBitsFromRemoteCmd();
                                    cmd.dstIp = destIp;
                                    cmd.dstUsername = username;
                                    cmd.dstPassword = password;
                                    cmd.dstPort = port;
                                    cmd.paths = list(backingImage.path);
                                    cmd.volumeUuid = rootVolume.getUuid();

                                    callKvmHost(srcHostUuid, ref.getPrimaryStorageUuid(), COPY_TO_REMOTE_BITS_PATH, cmd, AgentResponse.class,
                                            new ReturnValueCompletion<AgentResponse>(trigger, chain) {
                                        @Override
                                        public void success(AgentResponse rsp) {
                                            s = true;
                                            trigger.next();
                                            chain.next();
                                        }

                                        @Override
                                        public void fail(ErrorCode errorCode) {
                                            trigger.fail(errorCode);
                                            chain.next();
                                        }
                                    });
                                }

                                @Override
                                public String getName() {
                                    return getSyncSignature();
                                }
                            });
                        }

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            if (backingImage.path == null) {
                                logger.debug("no base image cache, skip this flow");
                                trigger.next();
                                return;
                            }

                            checkIfExistOnDst(new ReturnValueCompletion<Boolean>(trigger) {
                                @Override
                                public void success(Boolean existing) {
                                    if (existing) {
                                        // DO NOT set success = true here, otherwise the rollback
                                        // will delete the backing file which belongs to others on the dst host
                                        logger.debug(String.format("found %s on the dst host[uuid:%s], don't copy it",
                                                backingImage.path, dstHostUuid));
                                        trigger.next();
                                    } else {
                                        migrate(trigger);
                                    }

                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(errorCode);
                                }
                            });
                        }

                        private void checkIfExistOnDst(final ReturnValueCompletion<Boolean> completion) {
                            CheckBitsCmd cmd = new CheckBitsCmd();
                            cmd.path = backingImage.path;

                            callKvmHost(dstHostUuid, ref.getPrimaryStorageUuid(), LocalStorageKvmBackend.CHECK_BITS_PATH,
                                    cmd, CheckBitsRsp.class, new ReturnValueCompletion<CheckBitsRsp>(completion) {
                                @Override
                                public void success(CheckBitsRsp rsp) {
                                    completion.success(rsp.existing);
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    completion.fail(errorCode);
                                }
                            });
                        }

                        @Override
                        public void rollback(FlowRollback trigger, Map data) {
                            if (s) {
                                LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                                msg.setPath(backingImage.path);
                                msg.setHostUuid(dstHostUuid);
                                msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                                bus.send(msg, new CloudBusCallBack(null) {
                                    @Override
                                    public void run(MessageReply reply) {
                                        if (!reply.isSuccess()) {
                                            //TODO add GC
                                            logger.warn(String.format("failed to delete %s on the host[uuid:%s] of local storage[uuid:%s], %s",
                                                    backingImage.path, dstHostUuid, ref.getPrimaryStorageUuid(), reply.getError()));
                                        }
                                    }
                                });
                            }

                            trigger.rollback();
                        }
                    });

                    flow(new NoRollbackFlow() {
                        String __name__ = "check-md5-of-base-image-cache-on-dst-host";

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            if (backingImage.path == null) {
                                logger.debug("no base image cache, skip this flow");
                                trigger.next();
                                return;
                            }

                            Md5TO to = new Md5TO();
                            to.resourceUuid = "backing-file";
                            to.path = backingImage.path;
                            to.md5 = backingImage.md5;

                            CheckMd5sumCmd cmd = new CheckMd5sumCmd();
                            cmd.md5s = list(to);

                            callKvmHost(dstHostUuid, ref.getPrimaryStorageUuid(), LocalStorageKvmBackend.CHECK_MD5_PATH,
                                    cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                                @Override
                                public void success(AgentResponse returnValue) {
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(errorCode);
                                }
                            });
                        }
                    });

                    flow(new Flow() {
                        String __name__ = "build-base-image-cache-record-if-need";

                        boolean s;
                        ImageCacheVO vo;
                        ImageCacheShadowVO shadow;

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            if (backingImage.path == null) {
                                logger.debug("no base image cache, skip this flow");
                                trigger.next();
                                return;
                            }

                            LocalStorageUtils.InstallPath path = new LocalStorageUtils.InstallPath();
                            path.installPath = backingImage.path;
                            path.hostUuid = dstHostUuid;
                            String fullPath = path.makeFullPath();

                            new SQLBatch(){
                                @Override
                                protected void scripts() {
                                    if (!q(ImageCacheVO.class).eq(ImageCacheVO_.installUrl, fullPath).isExists()) {
                                        s = true;
                                        vo = new ImageCacheVO();
                                        vo.setState(ImageCacheState.ready);
                                        vo.setMediaType(ImageMediaType.RootVolumeTemplate);
                                        vo.setImageUuid(rootVolume.getRootImageUuid());
                                        vo.setPrimaryStorageUuid(rootVolume.getPrimaryStorageUuid());
                                        vo.setSize(backingImage.size);
                                        vo.setMd5sum(backingImage.md5);
                                        vo.setInstallUrl(fullPath);
                                        vo = persist(vo);
                                        shadow = q(ImageCacheShadowVO.class).eq(ImageCacheShadowVO_.installUrl, fullPath).find();
                                        Optional.ofNullable(shadow).ifPresent(this::remove);
                                    }
                                }
                            }.execute();

                            trigger.next();
                        }

                        @Override
                        public void rollback(FlowRollback trigger, Map data) {
                            if (s) {
                                new SQLBatch() {
                                    @Override
                                    protected void scripts() {
                                        Optional.ofNullable(vo).ifPresent(this::remove);
                                        Optional.ofNullable(shadow).ifPresent(it -> {it.setId(0); persist(it);});
                                    }
                                }.execute();
                            }

                            trigger.rollback();
                        }
                    });
                }

                flow(new Flow() {
                    String __name__ = "reserve-capacity-on-host";

                    boolean s = false;

                    @Override
                    public void run(final FlowTrigger trigger, Map data) {
                        reserveStorageCapacityOnHost(dstHostUuid, ref.getPrimaryStorageUuid(), requiredSize, new Completion(trigger) {
                            @Override
                            public void success() {
                                s = true;
                                trigger.next();
                            }

                            @Override
                            public void fail(ErrorCode errorCode) {
                                trigger.fail(errorCode);
                            }
                        });
                    }

                    @Override
                    public void rollback(FlowRollback trigger, Map data) {
                        if (s) {
                            returnStorageCapacityToHost(dstHostUuid, ref.getPrimaryStorageUuid(), requiredSize);
                        }

                        trigger.rollback();
                    }
                });

                if (!snapshotTrees.isEmpty()) {
                    List<Flow> flows = createFlowsForSnapshot(volumesOnLocalStorage, snapshotTrees, srcHostUuid, dstHostUuid, backingImage);
                    for (Flow f : flows) {
                        flow(f);
                    }
                } else {
                    flow(new Flow() {
                        String __name__ = "create-volumes-on-dst-host";

                        List<VolumeInventory> successVolumes = new ArrayList<VolumeInventory>();

                        @Override
                        public void run(final FlowTrigger trigger, Map data) {
                            List<LocalStorageCreateEmptyVolumeMsg> msgs = CollectionUtils.transformToList(volumesOnLocalStorage, new Function<LocalStorageCreateEmptyVolumeMsg, VolumeInventory>() {
                                @Override
                                public LocalStorageCreateEmptyVolumeMsg call(VolumeInventory arg) {
                                    LocalStorageCreateEmptyVolumeMsg msg = new LocalStorageCreateEmptyVolumeMsg();
                                    msg.setHostUuid(dstHostUuid);
                                    msg.setVolume(arg);

                                    if (VolumeType.Root.toString().equals(arg.getType())) {
                                        msg.setBackingFile(backingImage.path);
                                    }

                                    msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                    bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                                    return msg;
                                }
                            });

                            bus.send(msgs, 1, new CloudBusListCallBack(trigger) {
                                @Override
                                public void run(List<MessageReply> replies) {
                                    for (MessageReply r : replies) {
                                        if (!r.isSuccess()) {
                                            trigger.fail(r.getError());
                                            return;
                                        }

                                        successVolumes.add(volumesOnLocalStorage.get(replies.indexOf(r)));
                                    }

                                    trigger.next();
                                }
                            });
                        }

                        @Override
                        public void rollback(FlowRollback trigger, Map data) {
                            if (!successVolumes.isEmpty()) {
                                List<LocalStorageDirectlyDeleteBitsMsg> msgs = CollectionUtils.transformToList(successVolumes, new Function<LocalStorageDirectlyDeleteBitsMsg, VolumeInventory>() {
                                    @Override
                                    public LocalStorageDirectlyDeleteBitsMsg call(VolumeInventory arg) {
                                        LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                                        msg.setHostUuid(dstHostUuid);
                                        msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                        msg.setPath(arg.getInstallPath());
                                        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                                        return msg;
                                    }
                                });

                                bus.send(msgs);
                            }

                            trigger.rollback();
                        }
                    });
                }

                flow(new NoRollbackFlow() {
                    String __name__ = "migrate-vm";

                    @Override
                    public void run(final FlowTrigger trigger, Map data) {
                        MigrateVmOnHypervisorMsg msg = new MigrateVmOnHypervisorMsg();
                        msg.setVmInventory(spec.getVmInventory());
                        msg.setDestHostInventory(spec.getDestHost());
                        msg.setSrcHostUuid(spec.getVmInventory().getHostUuid());
                        msg.setStorageMigrationPolicy(storageMigrationPolicy);
                        bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, spec.getDestHost().getUuid());
                        bus.send(msg, new CloudBusCallBack(trigger) {
                            @Override
                            public void run(MessageReply reply) {
                                if (reply.isSuccess()) {
                                    trigger.next();
                                } else {
                                    trigger.fail(reply.getError());
                                }
                            }
                        });
                    }
                });

                flow(new NoRollbackFlow() {
                    String __name__ = "update-volumes-info-in-db-to-dst-host";

                    private void updateVolumesInfo(final List<String> volUuids) {
                        new SQLBatch() {
                            @Override
                            protected void scripts() {
                                List<LocalStorageResourceRefVO> oldRefs = sql(
                                        "select ref" +
                                                " from LocalStorageResourceRefVO ref" +
                                                " where ref.resourceUuid in (:resourceUuids)" +
                                                " and ref.resourceType = :resourceType",
                                        LocalStorageResourceRefVO.class)
                                        .param("resourceUuids", volUuids)
                                        .param("resourceType", VolumeVO.class.getSimpleName())
                                        .list();

                                for (final LocalStorageResourceRefVO ref : oldRefs) {
                                    LocalStorageResourceRefVO newRef = new LocalStorageResourceRefVO();
                                    newRef.setHostUuid(dstHostUuid);
                                    newRef.setResourceUuid(ref.getResourceUuid());
                                    newRef.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                    newRef.setResourceType(ref.getResourceType());
                                    newRef.setSize(ref.getSize());
                                    newRef.setCreateDate(ref.getCreateDate());
                                    dbf.getEntityManager().persist(newRef);
                                    dbf.getEntityManager().remove(ref);
                                }
                            }
                        }.execute();
                    }

                    @Override
                    public void run(FlowTrigger trigger, Map data) {
                        List<String> volUuids = CollectionUtils.transformToList(volumesOnLocalStorage,
                                VolumeInventory::getUuid
                        );

                        updateVolumesInfo(volUuids);

                        trigger.next();
                    }
                });

                if (!snapshotTrees.isEmpty()) {
                    flow(new NoRollbackFlow() {
                        String __name__ = "update-snapshots-info-in-db-to-dst-host";

                        private void updateSnapshotsInfo(final List<String> spUuids) {
                            new SQLBatch() {
                                @Override
                                protected void scripts() {
                                    List<LocalStorageResourceRefVO> oldRefs = sql(
                                            "select ref" +
                                                    " from LocalStorageResourceRefVO ref" +
                                                    " where ref.resourceUuid in (:resourceUuids)" +
                                                    " and ref.resourceType = :resourceType",
                                            LocalStorageResourceRefVO.class)
                                            .param("resourceUuids", spUuids)
                                            .param("resourceType", VolumeSnapshotVO.class.getSimpleName())
                                            .list();

                                    for (final LocalStorageResourceRefVO ref : oldRefs) {
                                        LocalStorageResourceRefVO newRef = new LocalStorageResourceRefVO();
                                        newRef.setHostUuid(dstHostUuid);
                                        newRef.setResourceUuid(ref.getResourceUuid());
                                        newRef.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                        newRef.setResourceType(ref.getResourceType());
                                        newRef.setSize(ref.getSize());
                                        newRef.setCreateDate(ref.getCreateDate());
                                        dbf.getEntityManager().persist(newRef);
                                        dbf.getEntityManager().remove(ref);
                                    }
                                }
                            }.execute();
                        }

                        @Override
                        public void run(FlowTrigger trigger, Map data) {
                            List<String> spUuids = CollectionUtils.transformToList(allSnapshots,
                                    VolumeSnapshotInventory::getUuid
                            );

                            updateSnapshotsInfo(spUuids);

                            trigger.next();
                        }
                    });

                    flow(new NoRollbackFlow() {
                        String __name__ = "delete-snapshots-on-src-host";

                        @Override
                        public void run(FlowTrigger trigger, Map data) {
                            List<LocalStorageDirectlyDeleteBitsMsg> msgs = CollectionUtils.transformToList(allSnapshots, new Function<LocalStorageDirectlyDeleteBitsMsg, VolumeSnapshotInventory>() {
                                @Override
                                public LocalStorageDirectlyDeleteBitsMsg call(VolumeSnapshotInventory sp) {
                                    LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                                    msg.setHostUuid(srcHostUuid);
                                    msg.setPath(sp.getPrimaryStorageInstallPath());
                                    msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                    bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                                    return msg;
                                }
                            });

                            bus.send(msgs, new CloudBusListCallBack(null) {
                                @Override
                                public void run(List<MessageReply> replies) {
                                    for (MessageReply r : replies) {
                                        VolumeSnapshotInventory sp = allSnapshots.get(replies.indexOf(r));
                                        if (!r.isSuccess()) {
                                            //TODO add GC
                                            logger.warn(String.format("failed to delete the snapshot[%s] on the local primary storage[uuid:%s], %s",
                                                    sp.getPrimaryStorageInstallPath(), ref.getPrimaryStorageUuid(), r.getError()));
                                        }
                                    }
                                }
                            });

                            trigger.next();
                        }
                    });
                }

                flow(new NoRollbackFlow() {
                    String __name__ = "delete-volumes-on-src-host";

                    @Override
                    public void run(FlowTrigger trigger, Map data) {
                        List<LocalStorageDirectlyDeleteBitsMsg> msgs = CollectionUtils.transformToList(volumesOnLocalStorage, new Function<LocalStorageDirectlyDeleteBitsMsg, VolumeInventory>() {
                            @Override
                            public LocalStorageDirectlyDeleteBitsMsg call(VolumeInventory arg) {
                                LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                                msg.setHostUuid(srcHostUuid);
                                msg.setPath(arg.getInstallPath());
                                msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                                bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                                return msg;
                            }
                        });

                        bus.send(msgs, new CloudBusListCallBack(null) {
                            @Override
                            public void run(List<MessageReply> replies) {
                                for (MessageReply r : replies) {
                                    if (!r.isSuccess()) {
                                        //TODO: add GC
                                        VolumeInventory vol = volumesOnLocalStorage.get(replies.indexOf(r));
                                        logger.warn(String.format("failed to delete the volume[%s] in the host[uuid:%s] for the local" +
                                                        " primary storage[uuid:%s] during after the vm[uuid:%s] migrated to the host[uuid:%s, ip:%s], %s",
                                                vol.getUuid(), srcHostUuid, ref.getPrimaryStorageUuid(), spec.getVmInventory().getUuid(), dstHostUuid,
                                                spec.getDestHost().getManagementIp(), r.getError()));
                                    }
                                }
                            }
                        });

                        trigger.next();
                    }
                });

                flow(new NoRollbackFlow() {
                    String __name__ = "return-capacity-to-src-host";

                    @Override
                    public void run(FlowTrigger trigger, Map data) {
                        LocalStorageReturnHostCapacityMsg msg = new LocalStorageReturnHostCapacityMsg();
                        msg.setHostUuid(srcHostUuid);
                        msg.setPrimaryStorageUuid(ref.getPrimaryStorageUuid());
                        msg.setSize(requiredSize);
                        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, ref.getPrimaryStorageUuid());
                        bus.send(msg, new CloudBusCallBack(null) {
                            @Override
                            public void run(MessageReply reply) {
                                //TODO
                                if (!reply.isSuccess()) {
                                    logger.warn(String.format("failed to return capacity[%s] to the host[uuid:%s] of the local" +
                                            " primary storage[uuid:%s], %s", requiredSize, srcHostUuid, ref.getPrimaryStorageUuid(), reply.getError()));
                                }
                            }
                        });

                        trigger.next();
                    }
                });

                done(new FlowDoneHandler(next) {
                    @Override
                    public void handle(Map data) {
                        next.next();
                    }
                });

                error(new FlowErrorHandler(next) {
                    @Override
                    public void handle(ErrorCode errCode, Map data) {
                        next.fail(errCode);
                    }
                });
            }
        }).start();
    }

    private void returnStorageCapacityToHost(final String dstHostUuid, final String primaryStorageUuid, final Long size) {
        LocalStorageReturnHostCapacityMsg msg = new LocalStorageReturnHostCapacityMsg();
        msg.setHostUuid(dstHostUuid);
        msg.setSize(size);
        msg.setPrimaryStorageUuid(primaryStorageUuid);
        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, primaryStorageUuid);
        bus.send(msg, new CloudBusCallBack(null) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    //TODO recalculate host capacity
                    logger.warn(String.format("failed to return capacity[%s] to the host[uuid:%s] of local storage[uuid:%s], %s",
                            size, dstHostUuid, primaryStorageUuid, reply.getError()));
                }
            }
        });
    }

    private void reserveStorageCapacityOnHost(String dstHostUuid, String psUuid, Long size, final Completion completion) {
        LocalStorageReserveHostCapacityMsg msg = new LocalStorageReserveHostCapacityMsg();
        msg.setHostUuid(dstHostUuid);
        msg.setSize(size);
        msg.setPrimaryStorageUuid(psUuid);
        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, psUuid);
        bus.send(msg, new CloudBusCallBack(completion) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    completion.fail(reply.getError());
                } else {
                    completion.success();
                }
            }
        });
    }

    private <T extends AgentResponse> void callKvmHost(final String hostUuid, final String psUuid, String path, AgentCommand cmd, final Class<T> rspType, final ReturnValueCompletion<T> completion) {
        cmd.storagePath = Q.New(PrimaryStorageVO.class).
                eq(PrimaryStorageVO_.uuid, psUuid).
                select(PrimaryStorageVO_.url).
                findValue();
        cmd.primaryStorageUuid = psUuid;
        KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
        msg.setCommand(cmd);
        msg.setPath(path);
        msg.setHostUuid(hostUuid);
        bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid);
        bus.send(msg, new CloudBusCallBack(completion) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    completion.fail(reply.getError());
                    return;
                }

                KVMHostAsyncHttpCallReply r = reply.castReply();
                T rsp = r.toResponse(rspType);
                if (!rsp.isSuccess()) {
                    completion.fail(operr("operation error, because:%s", rsp.getError()));
                    return;
                }

                if (rsp.getTotalCapacity() != null && rsp.getAvailableCapacity() != null) {
                    new LocalStorageCapacityUpdater().updatePhysicalCapacityByKvmAgentResponse(psUuid, hostUuid, rsp);
                }

                completion.success(rsp);
            }
        });
    }

    private List<Flow> createFlowsForSnapshot(List<VolumeInventory> volumesOnLocalStorage,
                                              List<VolumeSnapshotTree> snapshotTrees, final String srcHostUuid,
                                              final String dstHostUuid, final BackingImage image) {
        List<Flow> flows = new ArrayList<Flow>();

        class VSPair {
            VolumeInventory volume;
            List<VolumeSnapshotTree> snapshotTrees;
            VolumeSnapshotInventory latest;
        }

        List<VSPair> volumeHasSnapshots = new ArrayList<VSPair>();
        List<VolumeInventory> volumeNoSnapshots = new ArrayList<VolumeInventory>();

        KVMHostVO dstHost = dbf.findByUuid(dstHostUuid, KVMHostVO.class);
        final String destIp = localStorageFactory.getDestMigrationAddress(srcHostUuid, dstHostUuid);
        final String username = dstHost.getUsername();
        final String password = dstHost.getPassword();
        final int port = dstHost.getPort();

        for (final VolumeInventory vol : volumesOnLocalStorage) {
            final List<VolumeSnapshotTree> trees = CollectionUtils.transformToList(snapshotTrees, new Function<VolumeSnapshotTree, VolumeSnapshotTree>() {
                @Override
                public VolumeSnapshotTree call(VolumeSnapshotTree arg) {
                    return arg.getVolumeUuid().equals(vol.getUuid()) ? arg : null;
                }
            });

            if (!trees.isEmpty()) {
                VSPair p = new VSPair();
                p.volume = vol;
                p.snapshotTrees = trees;
                p.latest = new Callable<VolumeSnapshotInventory>() {
                    @Override
                    @Transactional(readOnly = true)
                    public VolumeSnapshotInventory call() {
                        String sql = "select sp from VolumeSnapshotVO sp, VolumeSnapshotTreeVO tree where sp.treeUuid = tree.uuid" +
                                " and tree.current = :c and sp.latest = :l and tree.volumeUuid = :volUuid";
                        TypedQuery<VolumeSnapshotVO> q = dbf.getEntityManager().createQuery(sql, VolumeSnapshotVO.class);
                        q.setParameter("c", true);
                        q.setParameter("l", true);
                        q.setParameter("volUuid", vol.getUuid());

                        if(q.getResultList().isEmpty()){
                            return null;
                        }

                        VolumeSnapshotVO vo = q.getSingleResult();
                        return VolumeSnapshotInventory.valueOf(vo);
                    }
                }.call();

                volumeHasSnapshots.add(p);
            } else {
                volumeNoSnapshots.add(vol);
            }
        }

        for (final VSPair p : volumeHasSnapshots) {
            final List<VolumeSnapshotInventory> children = new ArrayList<VolumeSnapshotInventory>();
            for (VolumeSnapshotTree t : p.snapshotTrees) {
                children.addAll(t.getRoot().getDescendants());
            }

            final List<SnapshotTO> snapshotTOs = CollectionUtils.transformToList(children, new Function<SnapshotTO, VolumeSnapshotInventory>() {
                @Override
                public SnapshotTO call(final VolumeSnapshotInventory s) {
                    SnapshotTO to = new SnapshotTO();
                    to.path = s.getPrimaryStorageInstallPath();
                    to.snapshotUuid = s.getUuid();
                    if (s.getParentUuid() != null) {
                        to.parentPath = CollectionUtils.find(children, new Function<String, VolumeSnapshotInventory>() {
                            @Override
                            public String call(VolumeSnapshotInventory arg) {
                                return arg.getUuid().equals(s.getParentUuid()) ? arg.getPrimaryStorageInstallPath() : null;
                            }
                        });
                    }
                    return to;
                }
            });

            class Context {
                List<Md5TO> md5s;
            }

            final Context context = new Context();

            flows.add(new NoRollbackFlow() {
                String __name__ = String.format("verify-snapshot-integrity-of-volume-%s-on-src-host", p.volume.getUuid());

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    VerifySnapshotChainCmd cmd = new VerifySnapshotChainCmd();
                    cmd.snapshots = snapshotTOs;
                    callKvmHost(srcHostUuid, p.volume.getPrimaryStorageUuid(), VERIFY_SNAPSHOT_CHAIN_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                        @Override
                        public void success(AgentResponse returnValue) {
                            trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                            trigger.fail(errorCode);
                        }
                    });
                }
            });

            flows.add(new NoRollbackFlow() {
                String __name__ = "get-snapshot-md5";

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    GetMd5Cmd cmd = new GetMd5Cmd();
                    cmd.md5s = CollectionUtils.transformToList(children, new Function<GetMd5TO, VolumeSnapshotInventory>() {
                        @Override
                        public GetMd5TO call(VolumeSnapshotInventory arg) {
                            GetMd5TO to = new GetMd5TO();
                            to.path = arg.getPrimaryStorageInstallPath();
                            to.resourceUuid = arg.getUuid();
                            return to;
                        }
                    });

                    callKvmHost(srcHostUuid, p.volume.getPrimaryStorageUuid(), LocalStorageKvmBackend.GET_MD5_PATH, cmd,
                            GetMd5Rsp.class, new ReturnValueCompletion<GetMd5Rsp>(trigger) {
                        @Override
                        public void success(GetMd5Rsp rsp) {
                            context.md5s = rsp.md5s;
                            trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                            trigger.fail(errorCode);
                        }
                    });
                }
            });

            flows.add(new Flow() {
                String __name__ = String.format("copy-snapshots-for-volume-%s-on-dst-host", p.volume.getUuid());

                List<VolumeSnapshotInventory> success = new ArrayList<VolumeSnapshotInventory>();
                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    CopyBitsFromRemoteCmd cmd = new CopyBitsFromRemoteCmd();
                    cmd.paths = CollectionUtils.transformToList(children, VolumeSnapshotInventory::getPrimaryStorageInstallPath);
                    cmd.dstIp = destIp;
                    cmd.dstPassword = password;
                    cmd.dstUsername = username;
                    cmd.dstPort = port;
                    cmd.volumeUuid = p.volume.getUuid();
                    callKvmHost(srcHostUuid, p.volume.getPrimaryStorageUuid(), COPY_TO_REMOTE_BITS_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                        @Override
                        public void success(AgentResponse returnValue) {
                            trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                            trigger.fail(errorCode);
                        }
                    });
                }

                @Override
                public void rollback(FlowRollback trigger, Map data) {
                    if (!success.isEmpty()) {
                        final List<LocalStorageDirectlyDeleteBitsMsg> msgs = CollectionUtils.transformToList(success, new Function<LocalStorageDirectlyDeleteBitsMsg, VolumeSnapshotInventory>() {
                            @Override
                            public LocalStorageDirectlyDeleteBitsMsg call(VolumeSnapshotInventory arg) {
                                LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                                msg.setHostUuid(dstHostUuid);
                                msg.setPrimaryStorageUuid(arg.getPrimaryStorageUuid());
                                msg.setPath(arg.getPrimaryStorageInstallPath());
                                bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, arg.getPrimaryStorageUuid());
                                return msg;
                            }
                        });

                        bus.send(msgs, new CloudBusListCallBack(null) {
                            @Override
                            public void run(List<MessageReply> replies) {
                                for (MessageReply r : replies) {
                                    if (!r.isSuccess()) {
                                        LocalStorageDirectlyDeleteBitsMsg msg = msgs.get(replies.indexOf(r));
                                        //TODO
                                        logger.warn(String.format("failed to delete %s on the local primary storage[uuid:%s], host[uuid:%s], %s",
                                                msg.getPath(), msg.getPrimaryStorageUuid(), msg.getHostUuid(), r.getError()));
                                    }
                                }
                            }
                        });
                    }

                    trigger.rollback();
                }
            });

            flows.add(new NoRollbackFlow() {
                String __name__ = "check-snapshots-md5-on-dst-host";

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    CheckMd5sumCmd cmd = new CheckMd5sumCmd();
                    cmd.md5s = context.md5s;

                    callKvmHost(dstHostUuid, p.volume.getPrimaryStorageUuid(), LocalStorageKvmBackend.CHECK_MD5_PATH,
                            cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                                @Override
                                public void success(AgentResponse returnValue) {
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(errorCode);
                                }
                            });
                }
            });

            flows.add(new Flow() {
                String __name__ = "create-volume-on-dst-host";

                boolean s = false;

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
                    cmd.setInstallUrl(p.volume.getInstallPath());
                    cmd.setSize(p.volume.getSize());
                    cmd.setVolumeUuid(p.volume.getUuid());

                    if (p.latest == null){
                        // volume has been reimage
                        cmd.setBackingFile(image.path);
                    } else {
                        cmd.setBackingFile(p.latest.getPrimaryStorageInstallPath());
                    }

                    callKvmHost(dstHostUuid, p.volume.getPrimaryStorageUuid(), LocalStorageKvmBackend.CREATE_EMPTY_VOLUME_PATH, cmd, CreateEmptyVolumeRsp.class,
                            new ReturnValueCompletion<CreateEmptyVolumeRsp>(trigger) {
                                @Override
                                public void success(CreateEmptyVolumeRsp returnValue) {
                                    s = true;
                                    trigger.next();
                                }

                                @Override
                                public void fail(ErrorCode errorCode) {
                                    trigger.fail(operr("unable to create an empty volume[uuid:%s, name:%s] on the kvm host[uuid:%s]",
                                                    p.volume.getUuid(), p.volume.getName(), dstHostUuid).causedBy(errorCode));
                                }
                            });
                }

                @Override
                public void rollback(FlowRollback trigger, Map data) {
                    if (s) {
                        LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                        msg.setHostUuid(dstHostUuid);
                        msg.setPrimaryStorageUuid(p.volume.getPrimaryStorageUuid());
                        msg.setPath(p.volume.getInstallPath());
                        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, p.volume.getPrimaryStorageUuid());

                        bus.send(msg, new CloudBusCallBack(null) {
                            @Override
                            public void run(MessageReply reply) {
                                //TODO GC
                                logger.warn(String.format("failed to delete %s on the local primary storage[uuid:%s], host[uuid:%s], %s",
                                        p.volume.getInstallPath(), p.volume.getPrimaryStorageUuid(), dstHostUuid, reply.getError()));
                            }
                        });
                    }

                    trigger.rollback();
                }
            });

            flows.add(new NoRollbackFlow() {
                String __name__ = String.format("rebase-backing-files-of-snapshots-of-volume-%s-on-dst-host", p.volume.getUuid());

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    RebaseSnapshotBackingFilesCmd cmd = new RebaseSnapshotBackingFilesCmd();
                    cmd.snapshots = snapshotTOs;
                    callKvmHost(dstHostUuid, p.volume.getPrimaryStorageUuid(), REBASE_SNAPSHOT_BACKING_FILES_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                        @Override
                        public void success(AgentResponse returnValue) {
                            trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                            trigger.fail(errorCode);
                        }
                    });
                }
            });

            flows.add(new NoRollbackFlow() {
                String __name__ = String.format("verify-backingfile-integrity-of-volume-%s-on-dst-host", p.volume.getUuid());

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    List<SnapshotTO> s = new ArrayList<SnapshotTO>(snapshotTOs);

                    // the volume links to the latest snapshot
                    SnapshotTO to = new SnapshotTO();

                    if (p.latest == null){
                        // volume has been reimage
                        to.parentPath = image.path;
                    } else {
                        to.parentPath = p.latest.getPrimaryStorageInstallPath();
                    }
                    to.path = p.volume.getInstallPath();
                    to.snapshotUuid = p.volume.getUuid();
                    s.add(to);

                    VerifySnapshotChainCmd cmd = new VerifySnapshotChainCmd();
                    cmd.snapshots = s;
                    callKvmHost(dstHostUuid, p.volume.getPrimaryStorageUuid(), VERIFY_SNAPSHOT_CHAIN_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(trigger) {
                        @Override
                        public void success(AgentResponse returnValue) {
                            trigger.next();
                        }

                        @Override
                        public void fail(ErrorCode errorCode) {
                            trigger.fail(errorCode);
                        }
                    });
                }
            });
        }

        for (final VolumeInventory vol : volumeNoSnapshots) {
            flows.add(new Flow() {
                String __name__ = String.format("create-no-snapshot-volume-%s-on-dst-host", vol.getUuid());

                boolean s = false;

                @Override
                public void run(final FlowTrigger trigger, Map data) {
                    LocalStorageCreateEmptyVolumeMsg msg = new LocalStorageCreateEmptyVolumeMsg();
                    msg.setHostUuid(dstHostUuid);
                    msg.setVolume(vol);

                    if (VolumeType.Root.toString().equals(vol.getType())) {
                        msg.setBackingFile(image.path);
                    }

                    msg.setPrimaryStorageUuid(vol.getPrimaryStorageUuid());
                    bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, vol.getPrimaryStorageUuid());
                    bus.send(msg, new CloudBusCallBack(trigger) {
                        @Override
                        public void run(MessageReply reply) {
                            if (!reply.isSuccess()) {
                                trigger.fail(reply.getError());
                            } else {
                                s = true;
                                trigger.next();
                            }
                        }
                    });
                }

                @Override
                public void rollback(FlowRollback trigger, Map data) {
                    if (s) {
                        LocalStorageDirectlyDeleteBitsMsg msg = new LocalStorageDirectlyDeleteBitsMsg();
                        msg.setHostUuid(dstHostUuid);
                        msg.setPath(vol.getInstallPath());
                        msg.setPrimaryStorageUuid(vol.getPrimaryStorageUuid());
                        bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, vol.getPrimaryStorageUuid());
                        bus.send(msg, new CloudBusCallBack(null) {
                            @Override
                            public void run(MessageReply r) {
                                if (!r.isSuccess()) {
                                    //TODO GC
                                    logger.warn(String.format("failed to delete %s on the local primary storage[uuid:%s], host[uuid:%s], %s",
                                            vol.getInstallPath(), vol.getPrimaryStorageUuid(), dstHostUuid, r.getError()));
                                }
                            }
                        });
                    }

                    trigger.rollback();
                }
            });
        }

        return flows;
    }

    @Transactional(readOnly = true)
    private List<VolumeInventory> getVolumeOnLocalStorage(VmInstanceSpec spec) {
        String sql = "select v from VolumeVO v, PrimaryStorageVO ps where v.primaryStorageUuid = ps.uuid" +
                " and ps.type = :type and v.vmInstanceUuid = :vmUuid and v.type != :memoryType";
        TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class);
        q.setParameter("type", LocalStorageConstants.LOCAL_STORAGE_TYPE);
        q.setParameter("vmUuid", spec.getVmInventory().getUuid());
        q.setParameter("memoryType", VolumeType.Memory);
        return VolumeInventory.valueOf(q.getResultList());
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include "base/bind.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "media/base/audio_parameters.h"
#include "media/base/fake_audio_render_callback.h"
#include "media/base/media_log.h"
#include "media/base/mock_audio_renderer_sink.h"
#include "media/blink/webaudiosourceprovider_impl.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/WebAudioSourceProviderClient.h"

using ::testing::_;

namespace media {

namespace {
const float kTestVolume = 0.25;
const int kSampleRate = 48000;

class WebAudioSourceProviderImplUnderTest : public WebAudioSourceProviderImpl {
 public:
  WebAudioSourceProviderImplUnderTest(
      scoped_refptr<SwitchableAudioRendererSink> sink)
      : WebAudioSourceProviderImpl(std::move(sink), new MediaLog()),
        fallback_sink_(new MockAudioRendererSink()) {}

  MockAudioRendererSink* fallback_sink() { return fallback_sink_.get(); }

 protected:
  scoped_refptr<SwitchableAudioRendererSink> CreateFallbackSink() override {
    return fallback_sink_;
  }

 private:
  ~WebAudioSourceProviderImplUnderTest() override = default;
  scoped_refptr<MockAudioRendererSink> fallback_sink_;

  DISALLOW_COPY_AND_ASSIGN(WebAudioSourceProviderImplUnderTest);
};

enum class WaspSinkStatus { WASP_SINK_OK, WASP_SINK_ERROR, WASP_SINK_NULL };

scoped_refptr<MockAudioRendererSink> CreateWaspMockSink(WaspSinkStatus status) {
  if (status == WaspSinkStatus::WASP_SINK_NULL)
    return nullptr;
  return new MockAudioRendererSink(status == WaspSinkStatus::WASP_SINK_OK
                                       ? OUTPUT_DEVICE_STATUS_OK
                                       : OUTPUT_DEVICE_STATUS_ERROR_INTERNAL);
}

}  // namespace

class WebAudioSourceProviderImplTest
    : public testing::TestWithParam<WaspSinkStatus>,
      public blink::WebAudioSourceProviderClient {
 public:
  WebAudioSourceProviderImplTest()
      : params_(AudioParameters::AUDIO_PCM_LINEAR,
                CHANNEL_LAYOUT_STEREO,
                kSampleRate,
                16,
                64),
        fake_callback_(0.1, kSampleRate),
        mock_sink_(CreateWaspMockSink(GetParam())),
        wasp_impl_(new WebAudioSourceProviderImplUnderTest(mock_sink_)),
        expected_sink_(GetParam() == WaspSinkStatus::WASP_SINK_OK
                           ? mock_sink_.get()
                           : wasp_impl_->fallback_sink()) {}

  virtual ~WebAudioSourceProviderImplTest() {}

  void CallAllSinkMethodsAndVerify(bool verify) {
    testing::InSequence s;

    EXPECT_CALL(*expected_sink_, Start()).Times(verify);
    wasp_impl_->Start();

    EXPECT_CALL(*expected_sink_, Play()).Times(verify);
    wasp_impl_->Play();

    EXPECT_CALL(*expected_sink_, Pause()).Times(verify);
    wasp_impl_->Pause();

    EXPECT_CALL(*expected_sink_, SetVolume(kTestVolume)).Times(verify);
    wasp_impl_->SetVolume(kTestVolume);

    EXPECT_CALL(*expected_sink_, Stop()).Times(verify);
    wasp_impl_->Stop();

    testing::Mock::VerifyAndClear(mock_sink_.get());
  }

  void SetClient(blink::WebAudioSourceProviderClient* client) {
    testing::InSequence s;

    if (client) {
      EXPECT_CALL(*expected_sink_, Stop());
      EXPECT_CALL(*this, setFormat(params_.channels(), params_.sample_rate()));
    }
    wasp_impl_->setClient(client);
    base::RunLoop().RunUntilIdle();

    testing::Mock::VerifyAndClear(mock_sink_.get());
    testing::Mock::VerifyAndClear(wasp_impl_->fallback_sink());
    testing::Mock::VerifyAndClear(this);
  }

  bool CompareBusses(const AudioBus* bus1, const AudioBus* bus2) {
    EXPECT_EQ(bus1->channels(), bus2->channels());
    EXPECT_EQ(bus1->frames(), bus2->frames());
    for (int ch = 0; ch < bus1->channels(); ++ch) {
      if (memcmp(bus1->channel(ch), bus2->channel(ch),
                 sizeof(*bus1->channel(ch)) * bus1->frames()) != 0) {
        return false;
      }
    }
    return true;
  }

  // blink::WebAudioSourceProviderClient implementation.
  MOCK_METHOD2(setFormat, void(size_t numberOfChannels, float sampleRate));

  // CopyAudioCB. Added forwarder method due to GMock troubles with scoped_ptr.
  MOCK_METHOD3(DoCopyAudioCB,
               void(AudioBus*, uint32_t frames_delayed, int sample_rate));
  void OnAudioBus(std::unique_ptr<AudioBus> bus,
                  uint32_t frames_delayed,
                  int sample_rate) {
    DoCopyAudioCB(bus.get(), frames_delayed, sample_rate);
  }

  int Render(AudioBus* audio_bus) {
    return wasp_impl_->RenderForTesting(audio_bus);
  }

  void ExpectUnhealthySinkToStop() {
    if (GetParam() == WaspSinkStatus::WASP_SINK_ERROR)
      EXPECT_CALL(*mock_sink_.get(), Stop());
  }

 protected:
  AudioParameters params_;
  FakeAudioRenderCallback fake_callback_;
  scoped_refptr<MockAudioRendererSink> mock_sink_;
  scoped_refptr<WebAudioSourceProviderImplUnderTest> wasp_impl_;
  MockAudioRendererSink* expected_sink_;
  base::MessageLoop message_loop_;

  DISALLOW_COPY_AND_ASSIGN(WebAudioSourceProviderImplTest);
};

TEST_P(WebAudioSourceProviderImplTest, SetClientBeforeInitialize) {
  // setClient() with a NULL client should do nothing if no client is set.
  wasp_impl_->setClient(NULL);

  // If |mock_sink_| is not null, it should be stopped during setClient(this).
  // If it is unhealthy, it should also be stopped during fallback in
  // Initialize().
  if (mock_sink_)
    EXPECT_CALL(*mock_sink_.get(), Stop())
        .Times(2 + static_cast<int>(GetParam()));

  wasp_impl_->setClient(this);
  base::RunLoop().RunUntilIdle();

  if (mock_sink_)
    EXPECT_CALL(*mock_sink_.get(), SetVolume(1)).Times(1);
  wasp_impl_->setClient(NULL);
  base::RunLoop().RunUntilIdle();

  wasp_impl_->setClient(this);
  base::RunLoop().RunUntilIdle();

  // When Initialize() is called after setClient(), the params should propagate
  // to the client via setFormat() during the call.
  EXPECT_CALL(*this, setFormat(params_.channels(), params_.sample_rate()));
  wasp_impl_->Initialize(params_, &fake_callback_);
  base::RunLoop().RunUntilIdle();

  // setClient() with the same client should do nothing.
  wasp_impl_->setClient(this);
  base::RunLoop().RunUntilIdle();
}

// Verify AudioRendererSink functionality w/ and w/o a client.
TEST_P(WebAudioSourceProviderImplTest, SinkMethods) {
  ExpectUnhealthySinkToStop();
  wasp_impl_->Initialize(params_, &fake_callback_);

  // Without a client all WASP calls should fall through to the underlying sink.
  CallAllSinkMethodsAndVerify(true);

  // With a client no calls should reach the Stop()'d sink.  Also, setClient()
  // should propagate the params provided during Initialize() at call time.
  SetClient(this);
  CallAllSinkMethodsAndVerify(false);

  // Removing the client should cause WASP to revert to the underlying sink.
  EXPECT_CALL(*expected_sink_, SetVolume(kTestVolume));
  SetClient(NULL);
  CallAllSinkMethodsAndVerify(true);
}

// Verify underlying sink state is restored after client removal.
TEST_P(WebAudioSourceProviderImplTest, SinkStateRestored) {
  ExpectUnhealthySinkToStop();
  wasp_impl_->Initialize(params_, &fake_callback_);

  // Verify state set before the client is set propagates back afterward.
  EXPECT_CALL(*expected_sink_, Start());
  wasp_impl_->Start();
  SetClient(this);

  EXPECT_CALL(*expected_sink_, SetVolume(1.0));
  EXPECT_CALL(*expected_sink_, Start());
  SetClient(NULL);

  // Verify state set while the client was attached propagates back afterward.
  SetClient(this);
  wasp_impl_->Play();
  wasp_impl_->SetVolume(kTestVolume);

  EXPECT_CALL(*expected_sink_, SetVolume(kTestVolume));
  EXPECT_CALL(*expected_sink_, Start());
  EXPECT_CALL(*expected_sink_, Play());
  SetClient(NULL);
}

// Test the AudioRendererSink state machine and its effects on provideInput().
TEST_P(WebAudioSourceProviderImplTest, ProvideInput) {
  ExpectUnhealthySinkToStop();
  std::unique_ptr<AudioBus> bus1 = AudioBus::Create(params_);
  std::unique_ptr<AudioBus> bus2 = AudioBus::Create(params_);

  // Point the WebVector into memory owned by |bus1|.
  blink::WebVector<float*> audio_data(static_cast<size_t>(bus1->channels()));
  for (size_t i = 0; i < audio_data.size(); ++i)
    audio_data[i] = bus1->channel(static_cast<int>(i));

  // Verify provideInput() works before Initialize() and returns silence.
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  wasp_impl_->Initialize(params_, &fake_callback_);
  SetClient(this);

  // Verify provideInput() is muted prior to Start() and no calls to the render
  // callback have occurred.
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
  ASSERT_EQ(fake_callback_.last_delay(), base::TimeDelta::Max());

  wasp_impl_->Start();

  // Ditto for Play().
  bus1->channel(0)[0] = 1;
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
  ASSERT_EQ(fake_callback_.last_delay(), base::TimeDelta::Max());

  wasp_impl_->Play();

  // Now we should get real audio data.
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_FALSE(CompareBusses(bus1.get(), bus2.get()));

  // Ensure volume adjustment is working.
  fake_callback_.reset();
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus2.get());
  bus2->Scale(kTestVolume);

  fake_callback_.reset();
  wasp_impl_->SetVolume(kTestVolume);
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Pause should return to silence.
  wasp_impl_->Pause();
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Ensure if a renderer properly fill silence for partial Render() calls by
  // configuring the fake callback to return half the data.  After these calls
  // bus1 is full of junk data, and bus2 is partially filled.
  wasp_impl_->SetVolume(1);
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus1.get());
  fake_callback_.reset();
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus2.get());
  bus2->ZeroFramesPartial(bus2->frames() / 2,
                          bus2->frames() - bus2->frames() / 2);
  fake_callback_.reset();
  fake_callback_.set_half_fill(true);
  wasp_impl_->Play();

  // Play should return real audio data again, but the last half should be zero.
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Stop() should return silence.
  wasp_impl_->Stop();
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->provideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
}

// Verify CopyAudioCB is called if registered.
TEST_P(WebAudioSourceProviderImplTest, CopyAudioCB) {
  ExpectUnhealthySinkToStop();

  testing::InSequence s;
  wasp_impl_->Initialize(params_, &fake_callback_);
  wasp_impl_->SetCopyAudioCallback(base::Bind(
      &WebAudioSourceProviderImplTest::OnAudioBus, base::Unretained(this)));

  const std::unique_ptr<AudioBus> bus1 = AudioBus::Create(params_);
  EXPECT_CALL(*this, DoCopyAudioCB(_, 0, params_.sample_rate())).Times(1);
  Render(bus1.get());

  wasp_impl_->ClearCopyAudioCallback();
  EXPECT_CALL(*this, DoCopyAudioCB(_, _, _)).Times(0);
  Render(bus1.get());

  testing::Mock::VerifyAndClear(mock_sink_.get());
}

INSTANTIATE_TEST_CASE_P(
    /* prefix intentionally left blank due to only one parameterization */,
    WebAudioSourceProviderImplTest,
    testing::Values(WaspSinkStatus::WASP_SINK_OK,
                    WaspSinkStatus::WASP_SINK_ERROR,
                    WaspSinkStatus::WASP_SINK_NULL));

}  // namespace media


text:
(function (ng, moment) {
    "use strict";
    ng.module("appointment.services", [])
        .factory("ScheduleService", [
            "$q", "MomentService", "MODEL",
            function ($q, moment, model) {
                return {
                    load: function (specialists, beginDate, endDate) {
                        var beginDateMoment = moment(beginDate);
                        var endDateMoment = moment(endDate);

                        // симуляция загрузки расписания с сервера
                        var beginTime = new Appointment.TimeStamp(8, 0);
                        var endTime = new Appointment.TimeStamp(20, 0);
                        var facilities = model.facilities;
                        var deferred = $q.defer();
                        var result = [];
                        var quotes1 = [
                            new Appointment.Quote("Доступно для записи", 1, new Appointment.TimeStamp(10, 0), new Appointment.TimeStamp(12, 0)),
                            new Appointment.Quote("Технол. перерыв", 2, new Appointment.TimeStamp(8, 0), new Appointment.TimeStamp(10, 0))
                        ];
                        var quotes2 = [
                            new Appointment.Quote("Доступно для записи", 1, new Appointment.TimeStamp(14, 20), new Appointment.TimeStamp(19, 55)),
                            new Appointment.Quote("Технол. перерыв", 2, new Appointment.TimeStamp(16, 20), new Appointment.TimeStamp(17, 5))
                        ];

                        var counter = 0;
                        ng.forEach(specialists, function (item) {
                            for (var day = beginDateMoment.clone(); day.isBefore(endDateMoment); day = day.add("days", 1)) {
                                var date = day.clone().toDate();
                                var records, schedule;

                                var place = new Appointment.Place(facilities[Math.floor(Math.random() * 3)], "" + Math.floor(Math.random() * 300));

                                if (counter++ % 2 === 1) {
                                    records = [
                                        new Appointment.Record(new Date(date), new Appointment.TimeStamp(10, 30), "Кукушкин Н.Г."),
                                        new Appointment.Record(new Date(date), new Appointment.TimeStamp(11, 0), "Петров Н.Г.")
                                    ];
                                    schedule = new Appointment.SpecialistPlaceDate(
                                        item, place, new Date(date), beginTime.addHours(0), endTime.addHours(-8), new Appointment.TimeStamp(0, 5), ng.copy(quotes1), records);
                                } else {
                                    records = [
                                        new Appointment.Record(new Date(date), new Appointment.TimeStamp(17, 30), "Петров Н.Г."),
                                        new Appointment.Record(new Date(date), new Appointment.TimeStamp(15, 30), "Кукушкин Н.Г."),
                                        new Appointment.Record(new Date(date), new Appointment.TimeStamp(15, 30), "Петров Н.Г.")
                                    ];
                                    schedule = new Appointment.SpecialistPlaceDate(
                                        item, place, new Date(date), beginTime.addHours(6), endTime.addHours(0), new Appointment.TimeStamp(0, 5), ng.copy(quotes2), records);
                                }
                                result.push(schedule);
                            }
                        });
                        deferred.resolve(result);
                        return deferred.promise;
                    }
                };
            }]).factory("MomentService", [ function () {
            return moment;
        }]);
})(angular, moment);


text:
:mod:`heapq` --- Heap queue algorithm
=====================================

.. module:: heapq
   :synopsis: Heap queue algorithm (a.k.a. priority queue).
.. moduleauthor:: Kevin O'Connor
.. sectionauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: François Pinard
.. sectionauthor:: Raymond Hettinger

**Source code:** :source:`Lib/heapq.py`

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

This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or
equal to any of its children.  This implementation uses arrays for which
``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
elements from zero.  For the sake of comparison, non-existing elements are
considered to be infinite.  The interesting property of a heap is that its
smallest element is always the root, ``heap[0]``.

The API below differs from textbook heap algorithms in two aspects: (a) We use
zero-based indexing.  This makes the relationship between the index for a node
and the indexes for its children slightly less obvious, but is more suitable
since Python uses zero-based indexing. (b) Our pop method returns the smallest
item, not the largest (called a "min heap" in textbooks; a "max heap" is more
common in texts because of its suitability for in-place sorting).

These two make it possible to view the heap as a regular Python list without
surprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the
heap invariant!

To create a heap, use a list initialized to ``[]``, or you can transform a
populated list into a heap via function :func:`heapify`.

The following functions are provided:

.. function:: heappush(heap, item)

   Push the value *item* onto the *heap*, maintaining the heap invariant.

.. function:: heappop(heap)

   Pop and return the smallest item from the *heap*, maintaining the heap
   invariant.  If the heap is empty, :exc:`IndexError` is raised.

.. function:: heappushpop(heap, item)

   Push *item* on the heap, then pop and return the smallest item from the
   *heap*.  The combined action runs more efficiently than :func:`heappush`
   followed by a separate call to :func:`heappop`.

.. function:: heapify(x)

   Transform list *x* into a heap, in-place, in linear time.

.. function:: heapreplace(heap, item)

   Pop and return the smallest item from the *heap*, and also push the new *item*.
   The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised.

   This one step operation is more efficient than a :func:`heappop` followed by
   :func:`heappush` and can be more appropriate when using a fixed-size heap.
   The pop/push combination always returns an element from the heap and replaces
   it with *item*.

   The value returned may be larger than the *item* added.  If that isn't
   desired, consider using :func:`heappushpop` instead.  Its push/pop
   combination returns the smaller of the two values, leaving the larger value
   on the heap.

The module also offers three general purpose functions based on heaps.

.. function:: merge(*iterables)

   Merge multiple sorted inputs into a single sorted output (for example, merge
   timestamped entries from multiple log files).  Returns an :term:`iterator`
   over the sorted values.

   Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does
   not pull the data into memory all at once, and assumes that each of the input
   streams is already sorted (smallest to largest).

.. function:: nlargest(n, iterable, key=None)

   Return a list with the *n* largest elements from the dataset defined by
   *iterable*.  *key*, if provided, specifies a function of one argument that is
   used to extract a comparison key from each element in the iterable:
   ``key=str.lower`` Equivalent to:  ``sorted(iterable, key=key,
   reverse=True)[:n]``

.. function:: nsmallest(n, iterable, key=None)

   Return a list with the *n* smallest elements from the dataset defined by
   *iterable*.  *key*, if provided, specifies a function of one argument that is
   used to extract a comparison key from each element in the iterable:
   ``key=str.lower`` Equivalent to:  ``sorted(iterable, key=key)[:n]``

The latter two functions perform best for smaller values of *n*.  For larger
values, it is more efficient to use the :func:`sorted` function.  Also, when
``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
functions.

Basic Examples
--------------

A `heapsort <http://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by
pushing all values onto a heap and then popping off the smallest values one at a
time::

   >>> def heapsort(iterable):
   ...     'Equivalent to sorted(iterable)'
   ...     h = []
   ...     for value in iterable:
   ...         heappush(h, value)
   ...     return [heappop(h) for i in range(len(h))]
   ...
   >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Heap elements can be tuples.  This is useful for assigning comparison values
(such as task priorities) alongside the main record being tracked::

    >>> h = []
    >>> heappush(h, (5, 'write code'))
    >>> heappush(h, (7, 'release product'))
    >>> heappush(h, (1, 'write spec'))
    >>> heappush(h, (3, 'create tests'))
    >>> heappop(h)
    (1, 'write spec')

Priority Queue Implementation Notes
-----------------------------------

A `priority queue <http://en.wikipedia.org/wiki/Priority_queue>`_ is common use
for a heap, and it presents several implementation challenges:

* Sort stability:  how do you get two tasks with equal priorities to be returned
  in the order they were originally added?

* Tuple comparison breaks for (priority, task) pairs if the priorities are equal
  and the tasks do not have a default comparison order.

* If the priority of a task changes, how do you move it to a new position in
  the heap?

* Or if a pending task needs to be deleted, how do you find it and remove it
  from the queue?

A solution to the first two challenges is to store entries as 3-element list
including the priority, an entry count, and the task.  The entry count serves as
a tie-breaker so that two tasks with the same priority are returned in the order
they were added. And since no two entry counts are the same, the tuple
comparison will never attempt to directly compare two tasks.

The remaining challenges revolve around finding a pending task and making
changes to its priority or removing it entirely.  Finding a task can be done
with a dictionary pointing to an entry in the queue.

Removing the entry or changing its priority is more difficult because it would
break the heap structure invariants.  So, a possible solution is to mark an
entry as invalid and optionally add a new entry with the revised priority::

    pq = []                         # the priority queue list
    counter = itertools.count(1)    # unique sequence count
    task_finder = {}                # mapping of tasks to entries
    INVALID = 0                     # mark an entry as deleted

    def add_task(priority, task, count=None):
        if count is None:
            count = next(counter)
        entry = [priority, count, task]
        task_finder[task] = entry
        heappush(pq, entry)

    def get_top_priority():
        while True:
            priority, count, task = heappop(pq)
            del task_finder[task]
            if count is not INVALID:
                return task

    def delete_task(task):
        entry = task_finder[task]
        entry[1] = INVALID

    def reprioritize(priority, task):
        entry = task_finder[task]
        add_task(priority, task, entry[1])
        entry[1] = INVALID

Theory
------

Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all
*k*, counting elements from 0.  For the sake of comparison, non-existing
elements are considered to be infinite.  The interesting property of a heap is
that ``a[0]`` is always its smallest element.

The strange invariant above is meant to be an efficient memory representation
for a tournament.  The numbers below are *k*, not ``a[k]``::

                                  0

                 1                                 2

         3               4                5               6

     7       8       9       10      11      12      13      14

   15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30

In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In an usual
binary tournament we see in sports, each cell is the winner over the two cells
it tops, and we can trace the winner down the tree to see all opponents s/he
had.  However, in many computer applications of such tournaments, we do not need
to trace the history of a winner. To be more memory efficient, when a winner is
promoted, we try to replace it by something else at a lower level, and the rule
becomes that a cell and the two cells it tops contain three different items, but
the top cell "wins" over the two topped cells.

If this heap invariant is protected at all time, index 0 is clearly the overall
winner.  The simplest algorithmic way to remove it and find the "next" winner is
to move some loser (let's say cell 30 in the diagram above) into the 0 position,
and then percolate this new 0 down the tree, exchanging values, until the
invariant is re-established. This is clearly logarithmic on the total number of
items in the tree. By iterating over all items, you get an O(n log n) sort.

A nice feature of this sort is that you can efficiently insert new items while
the sort is going on, provided that the inserted items are not "better" than the
last 0'th element you extracted.  This is especially useful in simulation
contexts, where the tree holds all incoming events, and the "win" condition
means the smallest scheduled time.  When an event schedule other events for
execution, they are scheduled into the future, so they can easily go into the
heap.  So, a heap is a good structure for implementing schedulers (this is what
I used for my MIDI sequencer :-).

Various structures for implementing schedulers have been extensively studied,
and heaps are good for this, as they are reasonably speedy, the speed is almost
constant, and the worst case is not much different than the average case.
However, there are other representations which are more efficient overall, yet
the worst cases might be terrible.

Heaps are also very useful in big disk sorts.  You most probably all know that a
big sort implies producing "runs" (which are pre-sorted sequences, which size is
usually related to the amount of CPU memory), followed by a merging passes for
these runs, which merging is often very cleverly organised [#]_. It is very
important that the initial sort produces the longest runs possible.  Tournaments
are a good way to that.  If, using all the memory available to hold a
tournament, you replace and percolate items that happen to fit the current run,
you'll produce runs which are twice the size of the memory for random input, and
much better for input fuzzily ordered.

Moreover, if you output the 0'th item on disk and get an input which may not fit
in the current tournament (because the value "wins" over the last output value),
it cannot fit in the heap, so the size of the heap decreases.  The freed memory
could be cleverly reused immediately for progressively building a second heap,
which grows at exactly the same rate the first heap is melting.  When the first
heap completely vanishes, you switch heaps and start a new run.  Clever and
quite effective!

In a word, heaps are useful memory structures to know.  I use them in a few
applications, and I think it is good to keep a 'heap' module around. :-)

.. rubric:: Footnotes

.. [#] The disk balancing algorithms which are current, nowadays, are more annoying
   than clever, and this is a consequence of the seeking capabilities of the disks.
   On devices which cannot seek, like big tape drives, the story was quite
   different, and one had to be very clever to ensure (far in advance) that each
   tape movement will be the most effective possible (that is, will best
   participate at "progressing" the merge).  Some tapes were even able to read
   backwards, and this was also used to avoid the rewinding time. Believe me, real
   good tape sorts were quite spectacular to watch! From all times, sorting has
   always been a Great Art! :-)