text:
import React, { Component } from 'react';
// eslint-disable-next-line
import DialerPanel from 'ringcentral-widgets/components/DialerPanel';
import styles from './styles.scss';
/**
 * A example of `DialerPanel`
 */
class DialerPanelDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      toNumber: '',
    };
  }

  onCall = () => {
    alert("click 'onCall'");
  };

  keepToNumber = (toNumber) => {
    this.setState({
      toNumber,
    });
  };
  render() {
    return (
      <div
        style={{
          position: 'relative',
          height: '500px',
          width: '300px',
          border: '1px solid #f3f3f3',
        }}
      >
        <DialerPanel
          className={styles.root}
          currentLocale="en-US"
          isWebphoneMode
          onCallButtonClick={this.onCall}
          onToNumberChange={this.keepToNumber}
          toNumber={this.state.toNumber}
          fromNumber="123456789"
          fromNumbers={[
            {
              phoneNumber: '123456789',
              usageType: 'Company',
            },
          ]}
          changeFromNumber={() => null}
          callButtonDisabled={false}
          recipient={{
            phoneNumber: '1234',
            name: 'Test',
          }}
          searchContactList={[]}
          searchContact={() => null}
          clearToNumber={() => null}
          setRecipient={() => null}
          clearRecipient={() => null}
        />
      </div>
    );
  }
}

export default DialerPanelDemo;


text:
PKG = 'test_rospy'

import sys, time
import unittest

import rospy, rostest
from test_rospy.srv import *

SERVICE_BEFORE = 'service_order_before'
SERVICE_AFTER  = 'service_order_after'

FAKE_SECRET = 123456

WAIT_TIMEOUT = 10.0 #s

def handle_empty_req(req):
    print("Returning fake_secret")
    return EmptyReqSrvResponse(FAKE_SECRET)

def service_before():
    s = rospy.Service(SERVICE_BEFORE, EmptyReqSrv, handle_empty_req)
    rospy.init_node('service_before')
    rospy.spin()

# #530: verify that init_node can occur after service declarations
def service_after():
    rospy.init_node('service_after')
    s = rospy.Service(SERVICE_AFTER, EmptyReqSrv, handle_empty_req)
    rospy.spin()

class TestServiceOrder(unittest.TestCase):

    def _test(self, name, srv, req):
        rospy.wait_for_service(name, WAIT_TIMEOUT)
        s = rospy.ServiceProxy(name, srv)
        resp = s.call(req)
        self.assert_(resp is not None)
        return resp
    def test_before(self):
        resp = self._test(SERVICE_BEFORE, EmptyReqSrv,
                          EmptyReqSrvRequest())
        self.assertEquals(FAKE_SECRET, resp.fake_secret,
                          "fake_secret fields is not set as expected")
    def test_after(self):
        resp = self._test(SERVICE_AFTER, EmptyReqSrv,
                          EmptyReqSrvRequest())
        self.assertEquals(FAKE_SECRET, resp.fake_secret,
                          "fake_secret fields is not set as expected")

if __name__ == '__main__':
    if '--before' in sys.argv:
        service_before()
    elif '--after' in sys.argv:
        service_after()
    else:
        rostest.run(PKG, 'rospy_service_decl_order', TestServiceOrder, sys.argv)

redpajama_set_name: RedPajamaGithub


text:
package com.github.weisj.darklaf.ui.text;

import javax.swing.*;

import com.github.weisj.darklaf.ui.demo.DemoExecutor;

public class TextPaneDemo extends TextComponentDemo<JTextPane> {

    public static void main(final String[] args) {
        DemoExecutor.showDemo(new TextPaneDemo());
    }

    @Override
    protected JTextPane createTextComponent() {
        return new JTextPane();
    }

    @Override
    public String getName() {
        return "TextPane Demo";
    }
}


text:
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state

class SkiaBuildbotMobilePage(page_module.Page):

  def __init__(self, url, page_set):
    super(SkiaBuildbotMobilePage, self).__init__(
        url=url,
        name=url,
        page_set=page_set,
        shared_page_state_class=shared_page_state.SharedMobilePageState)
    self.archive_data_file = 'data/skia_amazon_mobile.json'

  def RunNavigateSteps(self, action_runner):
    action_runner.Navigate(self.url)
    action_runner.Wait(15)

class SkiaAmazonMobilePageSet(story.StorySet):
  """ Pages designed to represent the median, not highly optimized web """

  def __init__(self):
    super(SkiaAmazonMobilePageSet, self).__init__(
      archive_data_file='data/skia_amazon_mobile.json')

    urls_list = [
      # go/skia-skps-3-2019
      'https://www.amazon.com/s?k=nicolas+cage&ref=is_box_',
    ]

    for url in urls_list:
      self.AddStory(SkiaBuildbotMobilePage(url, self))


text:
using System;
using System.Collections.Generic;
using Gallio.Common.IO;
using Gallio.Common.Xml;
using Gallio.Icarus.Events;
using Gallio.Icarus.Properties;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.UI.Common.Policies;
using Gallio.UI.Events;

namespace Gallio.Icarus.Projects
{
    public class ProjectUserOptionsController : IProjectUserOptionsController, Handles<ProjectLoaded>,
        Handles<TreeViewCategoryChanged>
    {
        private readonly IEventAggregator eventAggregator;
        private readonly IFileSystem fileSystem;
        private readonly IXmlSerializer xmlSerializer;
        private readonly IUnhandledExceptionPolicy unhandledExceptionPolicy;

        private bool unsavedChanges;

        public IEnumerable<string> CollapsedNodes { get; private set; }
        public string TreeViewCategory { get; private set; }

        public ProjectUserOptionsController(IEventAggregator eventAggregator, IFileSystem fileSystem,
            IXmlSerializer xmlSerializer, IUnhandledExceptionPolicy unhandledExceptionPolicy)
        {
            this.eventAggregator = eventAggregator;
            this.fileSystem = fileSystem;
            this.xmlSerializer = xmlSerializer;
            this.unhandledExceptionPolicy = unhandledExceptionPolicy;

            TreeViewCategory = UserOptions.DefaultTreeViewCategory;
            CollapsedNodes = new List<string>();
        }

        public void LoadUserOptions(string projectLocation)
        {
            var projectUserOptionsFile = projectLocation + UserOptions.Extension;
            var userOptions = new UserOptions();

            if (fileSystem.FileExists(projectUserOptionsFile))
            {
                try
                {
                    userOptions = xmlSerializer.LoadFromXml<UserOptions>(projectUserOptionsFile);
                }
                catch (Exception ex)
                {
                    unhandledExceptionPolicy.Report(Resources.UserOptionsController_Failed_to_load_user_options_, ex);
                }
            }

            TreeViewCategory = userOptions.TreeViewCategory;
            eventAggregator.Send(this, new TreeViewCategoryChanged(TreeViewCategory));

            CollapsedNodes = userOptions.CollapsedNodes;

            eventAggregator.Send(this, new UserOptionsLoaded());
        }

        public void SaveUserOptions(string projectName, IProgressMonitor subProgressMonitor)
        {
            if (unsavedChanges == false)
                return;

            var projectUserOptionsFile = projectName + UserOptions.Extension;
            var userOptions = new UserOptions
            {
                TreeViewCategory = TreeViewCategory,
                CollapsedNodes = new List<string>(CollapsedNodes)
            };

            xmlSerializer.SaveToXml(userOptions, projectUserOptionsFile);

            eventAggregator.Send(this, new UserOptionsSaved());
        }

        public void SetCollapsedNodes(IEnumerable<string> collapsedNodes)
        {
            CollapsedNodes = collapsedNodes;
            unsavedChanges = true;
        }

        public void Handle(ProjectLoaded @event)
        {
            LoadUserOptions(@event.ProjectLocation);
        }

        public void Handle(TreeViewCategoryChanged @event)
        {
            var treeViewCategory = @event.TreeViewCategory;

            if (TreeViewCategory == treeViewCategory)
                return;

            TreeViewCategory = treeViewCategory;
            unsavedChanges = true;
        }
    }
}


text:
package com.twu.biblioteca.model;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UserTest {

    @Test
    public void shouldReturnTrueIfLoginDetailsMatch() {
        User user = new User("001-2015", "001-2015", "Student1", "student@gmail.com", "1234567890", false);

        assertEquals(true, user.hasLoginCredentials("001-2015", "001-2015"));
    }
}


text:
`java.time.format.DateTimeFormatter` permet de convertir les dates :
- transformer un objet date en chaine de caractères : `format()`
- parser une chaine de caractères en date : `parse()`

```java
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
```
```java
String input = "2016 03 17";
LocalDate parsedDate = LocalDate.parse(input, formatter);
```


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.NodeStoppingException;
import org.apache.ignite.internal.pagemem.wal.record.delta.PartitionMetaStateRecord;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.CacheGroupContext;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.processors.cache.GridCacheConcurrentMapImpl;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
import org.apache.ignite.internal.processors.cache.GridCacheMapEntry;
import org.apache.ignite.internal.processors.cache.GridCacheMapEntryFactory;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPreloader;
import org.apache.ignite.internal.processors.cache.extras.GridCacheObsoleteEntryExtras;
import org.apache.ignite.internal.processors.cache.persistence.CacheDataRow;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.processors.query.GridQueryRowCacheCleaner;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.lang.GridIterator;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.util.deque.FastSizeDeque;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_CACHE_REMOVED_ENTRIES_TTL;
import static org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_OBJECT_UNLOADED;
import static org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager.CacheDataStore;
import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.EVICTED;
import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.LOST;
import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.MOVING;
import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.OWNING;
import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.RENTING;

/**
 * Key partition.
 */
public class GridDhtLocalPartition extends GridCacheConcurrentMapImpl implements Comparable<GridDhtLocalPartition>, GridReservable {
    /** */
    private static final GridCacheMapEntryFactory ENTRY_FACTORY = new GridCacheMapEntryFactory() {
        @Override public GridCacheMapEntry create(
            GridCacheContext ctx,
            AffinityTopologyVersion topVer,
            KeyCacheObject key
        ) {
            return new GridDhtCacheEntry(ctx, topVer, key);
        }
    };

    /** Maximum size for delete queue. */
    public static final int MAX_DELETE_QUEUE_SIZE = Integer.getInteger(IGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE, 200_000);

    /** ONLY FOR TEST PURPOSES: force test checkpoint on partition eviction. */
    private static boolean forceTestCheckpointOnEviction = IgniteSystemProperties.getBoolean("TEST_CHECKPOINT_ON_EVICTION", false);

    /** ONLY FOR TEST PURPOSES: partition id where test checkpoint was enforced during eviction. */
    static volatile Integer partWhereTestCheckpointEnforced;

    /** Maximum size for {@link #rmvQueue}. */
    private final int rmvQueueMaxSize;

    /** Removed items TTL. */
    private final long rmvdEntryTtl;

    /** Static logger to avoid re-creation. */
    private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>();

    /** Logger. */
    private static volatile IgniteLogger log;

    /** Partition ID. */
    private final int id;

    /** State. 32 bits - size, 16 bits - reservations, 13 bits - reserved, 3 bits - GridDhtPartitionState. */
    @GridToStringExclude
    private final AtomicLong state = new AtomicLong((long)MOVING.ordinal() << 32);

    /** Evict guard. Must be CASed to -1 only when partition state is EVICTED. */
    @GridToStringExclude
    private final AtomicInteger evictGuard = new AtomicInteger();

    /** Rent future. */
    @GridToStringExclude
    private final GridFutureAdapter<?> rent;

    /** Clear future. */
    @GridToStringExclude
    private final ClearFuture clearFuture;

    /** */
    @GridToStringExclude
    private final GridCacheSharedContext ctx;

    /** */
    @GridToStringExclude
    private final CacheGroupContext grp;

    /** Create time. */
    @GridToStringExclude
    private final long createTime = U.currentTimeMillis();

    /** Lock. */
    @GridToStringExclude
    private final ReentrantLock lock = new ReentrantLock();

    /** */
    @GridToStringExclude
    private final ConcurrentMap<Integer, CacheMapHolder> cacheMaps;

    /** */
    @GridToStringExclude
    private final CacheMapHolder singleCacheEntryMap;

    /** Remove queue. */
    @GridToStringExclude
    private final FastSizeDeque<RemovedEntryHolder> rmvQueue = new FastSizeDeque<>(new ConcurrentLinkedDeque<>());

    /** Group reservations. */
    @GridToStringExclude
    private final CopyOnWriteArrayList<GridDhtPartitionsReservation> reservations = new CopyOnWriteArrayList<>();

    /** */
    @GridToStringExclude
    private volatile CacheDataStore store;

    /** Set if failed to move partition to RENTING state due to reservations, to be checked when
     * reservation is released. */
    private volatile boolean delayedRenting;

    /** Set if partition must be cleared in MOVING state. */
    private volatile boolean clear;

    /** Set if topology update sequence should be updated on partition destroy. */
    private boolean updateSeqOnDestroy;

    /**
     * @param ctx Context.
     * @param grp Cache group.
     * @param id Partition ID.
     */
    @SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor")
    GridDhtLocalPartition(GridCacheSharedContext ctx,
        CacheGroupContext grp,
        int id) {
        super(ENTRY_FACTORY);

        this.id = id;
        this.ctx = ctx;
        this.grp = grp;

        log = U.logger(ctx.kernalContext(), logRef, this);

        if (grp.sharedGroup()) {
            singleCacheEntryMap = null;
            cacheMaps = new ConcurrentHashMap<>();
        }
        else {
            singleCacheEntryMap = new CacheMapHolder(grp.singleCacheContext(), createEntriesMap());
            cacheMaps = null;
        }

        rent = new GridFutureAdapter<Object>() {
            @Override public String toString() {
                return "PartitionRentFuture [part=" + GridDhtLocalPartition.this + ']';
            }
        };

        clearFuture = new ClearFuture();

        int delQueueSize = grp.systemCache() ? 100 :
            Math.max(MAX_DELETE_QUEUE_SIZE / grp.affinity().partitions(), 20);

        rmvQueueMaxSize = U.ceilPow2(delQueueSize);

        rmvdEntryTtl = Long.getLong(IGNITE_CACHE_REMOVED_ENTRIES_TTL, 10_000);

        try {
            store = grp.offheap().createCacheDataStore(id);

            // Log partition creation for further crash recovery purposes.
            if (grp.walEnabled())
                ctx.wal().log(new PartitionMetaStateRecord(grp.groupId(), id, state(), updateCounter()));

            // Inject row cache cleaner on store creation
            // Used in case the cache with enabled SqlOnheapCache is single cache at the cache group
            if (ctx.kernalContext().query().moduleEnabled()) {
                GridQueryRowCacheCleaner cleaner = ctx.kernalContext().query().getIndexing()
                    .rowCacheCleaner(grp.groupId());

                if (store != null && cleaner != null)
                    store.setRowCacheCleaner(cleaner);
            }
        }
        catch (IgniteCheckedException e) {
            // TODO ignite-db
            throw new IgniteException(e);
        }
    }

    /**
     * @return Entries map.
     */
    private ConcurrentMap<KeyCacheObject, GridCacheMapEntry> createEntriesMap() {
        return new ConcurrentHashMap<>(Math.max(10, GridCacheAdapter.DFLT_START_CACHE_SIZE / grp.affinity().partitions()),
            0.75f,
            Runtime.getRuntime().availableProcessors() * 2);
    }

    /** {@inheritDoc} */
    @Override public int internalSize() {
        if (grp.sharedGroup()) {
            int size = 0;

            for (CacheMapHolder hld : cacheMaps.values())
                size += hld.map.size();

            return size;
        }

        return singleCacheEntryMap.map.size();
    }

    /** {@inheritDoc} */
    @Override protected CacheMapHolder entriesMap(GridCacheContext cctx) {
        if (grp.sharedGroup())
            return cacheMapHolder(cctx);

        return singleCacheEntryMap;
    }

    /** {@inheritDoc} */
    @Nullable @Override protected CacheMapHolder entriesMapIfExists(Integer cacheId) {
        return grp.sharedGroup() ? cacheMaps.get(cacheId) : singleCacheEntryMap;
    }

    /**
     * @param cctx Cache context.
     * @return Map holder.
     */
    private CacheMapHolder cacheMapHolder(GridCacheContext cctx) {
        assert grp.sharedGroup();

        CacheMapHolder hld = cacheMaps.get(cctx.cacheIdBoxed());

        if (hld != null)
            return hld;

        CacheMapHolder  old = cacheMaps.putIfAbsent(cctx.cacheIdBoxed(), hld = new CacheMapHolder(cctx, createEntriesMap()));

        if (old != null)
            hld = old;

        return hld;
    }

    /**
     * @return Data store.
     */
    public CacheDataStore dataStore() {
        return store;
    }

    /**
     * Adds group reservation to this partition.
     *
     * @param r Reservation.
     * @return {@code false} If such reservation already added.
     */
    public boolean addReservation(GridDhtPartitionsReservation r) {
        assert (getPartState(state.get())) != EVICTED : "we can reserve only active partitions";
        assert (getReservations(state.get())) != 0 : "partition must be already reserved before adding group reservation";

        return reservations.addIfAbsent(r);
    }

    /**
     * @param r Reservation.
     */
    public void removeReservation(GridDhtPartitionsReservation r) {
        if (!reservations.remove(r))
            throw new IllegalStateException("Reservation was already removed.");
    }

    /**
     * @return Partition ID.
     */
    public int id() {
        return id;
    }

    /**
     * @return Create time.
     */
    long createTime() {
        return createTime;
    }

    /**
     * @return Partition state.
     */
    public GridDhtPartitionState state() {
        return getPartState(state.get());
    }

    /**
     * @return Reservations.
     */
    public int reservations() {
        return getReservations(state.get());
    }

    /**
     * @return {@code True} if partition is empty.
     */
    public boolean isEmpty() {
        return store.fullSize() == 0 && internalSize() == 0;
    }

    /**
     * @return If partition is moving or owning or renting.
     */
    public boolean valid() {
        GridDhtPartitionState state = state();

        return state == MOVING || state == OWNING || state == RENTING;
    }

    /**
     * @param entry Entry to remove.
     */
    void onRemoved(GridDhtCacheEntry entry) {
        assert entry.obsolete() : entry;

        // Make sure to remove exactly this entry.
        removeEntry(entry);

        // Attempt to evict.
        tryContinueClearing();
    }

    /**
     * @param cacheId Cache ID.
     * @param key Key.
     * @param ver Version.
     */
    private void removeVersionedEntry(int cacheId, KeyCacheObject key, GridCacheVersion ver) {
        CacheMapHolder hld = grp.sharedGroup() ? cacheMaps.get(cacheId) : singleCacheEntryMap;

        GridCacheMapEntry entry = hld != null ? hld.map.get(key) : null;

        if (entry != null && entry.markObsoleteVersion(ver))
            removeEntry(entry);
    }

    /**
     *
     */
    public void cleanupRemoveQueue() {
        while (rmvQueue.sizex() >= rmvQueueMaxSize) {
            RemovedEntryHolder item = rmvQueue.pollFirst();

            if (item != null)
                removeVersionedEntry(item.cacheId(), item.key(), item.version());
        }

        if (!grp.isDrEnabled()) {
            RemovedEntryHolder item = rmvQueue.peekFirst();

            while (item != null && item.expireTime() < U.currentTimeMillis()) {
                item = rmvQueue.pollFirst();

                if (item == null)
                    break;

                removeVersionedEntry(item.cacheId(), item.key(), item.version());

                item = rmvQueue.peekFirst();
            }
        }
    }

    /**
     * @param cacheId cacheId Cache ID.
     * @param key Removed key.
     * @param ver Removed version.
     */
    public void onDeferredDelete(int cacheId, KeyCacheObject key, GridCacheVersion ver) {
        cleanupRemoveQueue();

        rmvQueue.add(new RemovedEntryHolder(cacheId, key, ver, rmvdEntryTtl));
    }

    /**
     * Locks partition.
     */
    @SuppressWarnings({"LockAcquiredButNotSafelyReleased"})
    public void lock() {
        lock.lock();
    }

    /**
     * Unlocks partition.
     */
    public void unlock() {
        lock.unlock();
    }

    /**
     * Reserves a partition so it won't be cleared or evicted.
     *
     * @return {@code True} if reserved.
     */
    @Override public boolean reserve() {
        while (true) {
            long state = this.state.get();

            if (getPartState(state) == EVICTED)
                return false;

            long newState = setReservations(state, getReservations(state) + 1);

            if (this.state.compareAndSet(state, newState))
                return true;
        }
    }

    /**
     * Releases previously reserved partition.
     */
    @Override public void release() {
        release0(0);
    }

    /** {@inheritDoc} */
    @Override protected void release(int sizeChange, CacheMapHolder hld, GridCacheEntryEx e) {
        if (grp.sharedGroup() && sizeChange != 0)
            hld.size.addAndGet(sizeChange);

        release0(sizeChange);
    }

    /**
     * @param sizeChange Size change delta.
     */
    private void release0(int sizeChange) {
        while (true) {
            long state = this.state.get();

            int reservations = getReservations(state);

            if (reservations == 0)
                return;

            assert getPartState(state) != EVICTED : getPartState(state);

            long newState = setReservations(state, --reservations);
            newState = setSize(newState, getSize(newState) + sizeChange);

            assert getSize(newState) == getSize(state) + sizeChange;

            // Decrement reservations.
            if (this.state.compareAndSet(state, newState)) {
                // If no more reservations try to continue delayed renting or clearing process.
                if (reservations == 0) {
                    if (delayedRenting)
                        rent(true);
                    else
                        tryContinueClearing();
                }

                break;
            }
        }
    }

    /**
     * @param stateToRestore State to restore.
     */
    public void restoreState(GridDhtPartitionState stateToRestore) {
        state.set(setPartState(state.get(),stateToRestore));
    }

    /**
     * @param state Current aggregated value.
     * @param toState State to switch to.
     * @return {@code true} if cas succeeds.
     */
    private boolean casState(long state, GridDhtPartitionState toState) {
        if (grp.persistenceEnabled() && grp.walEnabled()) {
            synchronized (this) {
                boolean update = this.state.compareAndSet(state, setPartState(state, toState));

                if (update)
                    try {
                        ctx.wal().log(new PartitionMetaStateRecord(grp.groupId(), id, toState, updateCounter()));
                    }
                    catch (IgniteCheckedException e) {
                        U.error(log, "Error while writing to log", e);
                    }

                return update;
            }
        }
        else
            return this.state.compareAndSet(state, setPartState(state, toState));
    }

    /**
     * @return {@code True} if transitioned to OWNING state.
     */
    boolean own() {
        while (true) {
            long state = this.state.get();

            GridDhtPartitionState partState = getPartState(state);

            if (partState == RENTING || partState == EVICTED)
                return false;

            if (partState == OWNING)
                return true;

            assert partState == MOVING || partState == LOST;

            if (casState(state, OWNING)) {
                if (log.isDebugEnabled())
                    log.debug("Owned partition: " + this);

                return true;
            }
        }
    }

    /**
     * Forcibly moves partition to a MOVING state.
     */
    public void moving() {
        while (true) {
            long state = this.state.get();

            GridDhtPartitionState partState = getPartState(state);

            assert partState == OWNING || partState == RENTING : "Only partitions in state OWNING or RENTING can be moved to MOVING state";

            if (casState(state, MOVING)) {
                if (log.isDebugEnabled())
                    log.debug("Forcibly moved partition to a MOVING state: " + this);

                break;
            }
        }
    }

    /**
     * @return {@code True} if partition state changed.
     */
    boolean markLost() {
        while (true) {
            long state = this.state.get();

            GridDhtPartitionState partState = getPartState(state);

            if (partState == LOST)
                return false;

            if (casState(state, LOST)) {
                if (log.isDebugEnabled())
                    log.debug("Marked partition as LOST: " + this);

                return true;
            }
        }
    }

    /**
     * Initiates partition eviction process.
     *
     * If partition has reservations, eviction will be delayed and continued after all reservations will be released.
     *
     * @param updateSeq If {@code true} topology update sequence will be updated after eviction is finished.
     * @return Future to signal that this node is no longer an owner or backup.
     */
    public IgniteInternalFuture<?> rent(boolean updateSeq) {
        long state0 = this.state.get();

        GridDhtPartitionState partState = getPartState(state0);

        if (partState == RENTING || partState == EVICTED)
            return rent;

        delayedRenting = true;

        if (getReservations(state0) == 0 && casState(state0, RENTING)) {
            delayedRenting = false;

            if (log.isDebugEnabled())
                log.debug("Moved partition to RENTING state: " + this);

            // Evict asynchronously, as the 'rent' method may be called
            // from within write locks on local partition.
            clearAsync0(updateSeq);
        }

        return rent;
    }

    /**
     * Starts clearing process asynchronously if it's requested and not running at the moment.
     * Method may finish clearing process ahead of time if partition is empty and doesn't have reservations.
     *
     * @param updateSeq Update sequence.
     */
    private void clearAsync0(boolean updateSeq) {
        long state = this.state.get();

        GridDhtPartitionState partState = getPartState(state);

        boolean evictionRequested = partState == RENTING || delayedRenting;
        boolean clearingRequested = partState == MOVING && clear;

        if (!evictionRequested && !clearingRequested)
            return;

        boolean reinitialized = clearFuture.initialize(updateSeq, evictionRequested);

        // Clearing process is already running at the moment. No needs to run it again.
        if (!reinitialized)
            return;

        // Try fast eviction
        if (isEmpty() && getSize(state) == 0 && !grp.queriesEnabled()
                && getReservations(state) == 0 && !groupReserved()) {

            if (partState == RENTING && casState(state, EVICTED) || clearingRequested) {
                clearFuture.finish();

                if (state() == EVICTED && markForDestroy()) {
                    updateSeqOnDestroy = updateSeq;

                    destroy();
                }

                return;
            }
        }

        ctx.evict().evictPartitionAsync(grp,this);
    }

    /**
     * Initiates single clear process if partition is in MOVING state.
     * Method does nothing if clear process is already running.
     */
    public void clearAsync() {
        if (state() != MOVING)
            return;

        clear = true;

        clearAsync0(false);
    }

    /**
     * Continues delayed clearing of partition if possible.
     * Clearing may be delayed because of existing reservations.
     */
    void tryContinueClearing() {
        clearAsync0(true);
    }

    /**
     * @return {@code true} If there is a group reservation.
     */
    private boolean groupReserved() {
        for (GridDhtPartitionsReservation reservation : reservations) {
            if (!reservation.invalidate())
                return true; // Failed to invalidate reservation -> we are reserved.
        }

        return false;
    }

    /**
     * @return {@code true} if evicting thread was added.
     */
    private boolean addEvicting() {
        while (true) {
            int cnt = evictGuard.get();

            if (cnt != 0)
                return false;

            if (evictGuard.compareAndSet(cnt, cnt + 1)) {

                return true;
            }
        }
    }

    /**
     * @return {@code true} if no thread evicting partition at the moment.
     */
    private boolean clearEvicting() {
        boolean free;

        while (true) {
            int cnt = evictGuard.get();

            assert cnt > 0;

            if (evictGuard.compareAndSet(cnt, cnt - 1)) {
                free = cnt == 1;

                break;
            }
        }

        return free;
    }

    /**
     * @return {@code True} if partition is safe to destroy.
     */
    public boolean markForDestroy() {
        while (true) {
            int cnt = evictGuard.get();

            if (cnt != 0)
                return false;

            if (evictGuard.compareAndSet(0, -1))
                return true;
        }
    }

    /**
     * Moves partition state to {@code EVICTED} if possible.
     * and initiates partition destroy process after successful moving partition state to {@code EVICTED} state.
     *
     * @param updateSeq If {@code true} increment update sequence on cache group topology after successful eviction.
     */
    private void finishEviction(boolean updateSeq) {
        long state0 = this.state.get();

        GridDhtPartitionState state = getPartState(state0);

        if (state == EVICTED || (isEmpty() && getSize(state0) == 0 && getReservations(state0) == 0 && state == RENTING && casState(state0, EVICTED))) {
            if (log.isDebugEnabled())
                log.debug("Evicted partition: " + this);

            updateSeqOnDestroy = updateSeq;
        }
    }

    /**
     * Destroys partition data store and invokes appropriate callbacks.
     */
    public void destroy() {
        assert state() == EVICTED : this;
        assert evictGuard.get() == -1;

        grp.onPartitionEvicted(id);

        destroyCacheDataStore();

        rent.onDone();

        ((GridDhtPreloader)grp.preloader()).onPartitionEvicted(this, updateSeqOnDestroy);

        clearDeferredDeletes();
    }

    /**
     * Awaits completion of partition destroy process in case of {@code EVICTED} partition state.
     */
    public void awaitDestroy() {
        if (state() != EVICTED)
            return;

        final long timeout = 10_000;

        for (;;) {
            try {
                rent.get(timeout);

                break;
            }
            catch (IgniteFutureTimeoutCheckedException ignored) {
                U.warn(log, "Failed to await partition destroy within timeout " + this);
            }
            catch (IgniteCheckedException e) {
                throw new IgniteException("Failed to await partition destroy " + this, e);
            }
        }
    }

    /**
     * Adds listener on {@link #clearFuture} finish.
     *
     * @param lsnr Listener.
     */
    public void onClearFinished(IgniteInClosure<? super IgniteInternalFuture<?>> lsnr) {
        clearFuture.listen(lsnr);
    }

    /**
     * @return {@code True} if clearing process is running at the moment on the partition.
     */
    public boolean isClearing() {
        return !clearFuture.isDone();
    }

    /**
     * Tries to start partition clear process {@link GridDhtLocalPartition#clearAll(EvictionContext)}).
     * Only one thread is allowed to do such process concurrently.
     * At the end of clearing method completes {@code clearFuture}.
     *
     * @return {@code false} if clearing is not started due to existing reservations.
     * @throws NodeStoppingException If node is stopping.
     */
    public boolean tryClear(EvictionContext evictionCtx) throws NodeStoppingException {
        if (clearFuture.isDone())
            return true;

        long state = this.state.get();

        if (getReservations(state) != 0 || groupReserved())
            return false;

        if (addEvicting()) {
            try {
                // Attempt to evict partition entries from cache.
                long clearedEntities = clearAll(evictionCtx);

                if (log.isDebugEnabled())
                    log.debug("Partition is cleared [clearedEntities=" + clearedEntities + ", part=" + this + "]");
            }
            catch (NodeStoppingException e) {
                clearFuture.finish(e);

                throw e;
            }
            finally {
                boolean free = clearEvicting();

                if (free)
                    clearFuture.finish();
            }
        }

        return true;
    }

    /**
     * Release created data store for this partition.
     */
    private void destroyCacheDataStore() {
        try {
            grp.offheap().destroyCacheDataStore(dataStore());
        }
        catch (IgniteCheckedException e) {
            log.error("Unable to destroy cache data store on partition eviction [id=" + id + "]", e);
        }
    }

    /**
     * On partition unlock callback.
     * Tries to continue delayed partition clearing.
     */
    void onUnlock() {
        tryContinueClearing();
    }

    /**
     * @param topVer Topology version.
     * @return {@code True} if local node is primary for this partition.
     */
    public boolean primary(AffinityTopologyVersion topVer) {
        List<ClusterNode> nodes = grp.affinity().cachedAffinity(topVer).get(id);

        return !nodes.isEmpty() && ctx.localNode().equals(nodes.get(0));
    }

    /**
     * @param topVer Topology version.
     * @return {@code True} if local node is backup for this partition.
     */
    public boolean backup(AffinityTopologyVersion topVer) {
        List<ClusterNode> nodes = grp.affinity().cachedAffinity(topVer).get(id);

        return nodes.indexOf(ctx.localNode()) > 0;
    }

    /**
     * @param cacheId ID of cache initiated counter update.
     * @param topVer Topology version for current operation.
     * @return Next update index.
     */
    long nextUpdateCounter(int cacheId, AffinityTopologyVersion topVer, boolean primary, @Nullable Long primaryCntr) {
        long nextCntr = store.nextUpdateCounter();

        if (grp.sharedGroup())
            grp.onPartitionCounterUpdate(cacheId, id, primaryCntr != null ? primaryCntr : nextCntr, topVer, primary);

        return nextCntr;
    }

    /**
     * @return Current update index.
     */
    public long updateCounter() {
        return store.updateCounter();
    }

    /**
     * @return Initial update counter.
     */
    public long initialUpdateCounter() {
        return store.initialUpdateCounter();
    }

    /**
     * @param val Update index value.
     */
    public void updateCounter(long val) {
        store.updateCounter(val);
    }

    /**
     * @param val Initial update index value.
     */
    public void initialUpdateCounter(long val) {
        store.updateInitialCounter(val);
    }

    /**
     * @return Total size of all caches.
     */
    public long fullSize() {
        return store.fullSize();
    }

    /**
     * Removes all entries and rows from this partition.
     *
     * @return Number of rows cleared from page memory.
     * @throws NodeStoppingException If node stopping.
     */
    private long clearAll(EvictionContext evictionCtx) throws NodeStoppingException {
        GridCacheVersion clearVer = ctx.versions().next();

        GridCacheObsoleteEntryExtras extras = new GridCacheObsoleteEntryExtras(clearVer);

        boolean rec = grp.eventRecordable(EVT_CACHE_REBALANCE_OBJECT_UNLOADED);

        if (grp.sharedGroup()) {
            for (CacheMapHolder hld : cacheMaps.values())
                clear(hld.map, extras, rec);
        }
        else
            clear(singleCacheEntryMap.map, extras, rec);

        long cleared = 0;

        final int stopCheckingFreq = 1000;

        CacheMapHolder hld = grp.sharedGroup() ? null : singleCacheEntryMap;

        try {
            GridIterator<CacheDataRow> it0 = grp.offheap().partitionIterator(id);

            while (it0.hasNext()) {
                ctx.database().checkpointReadLock();

                try {
                    CacheDataRow row = it0.next();

                    // Do not clear fresh rows in case of single partition clearing.
                    if (row.version().compareTo(clearVer) >= 0 && (state() == MOVING && clear))
                        continue;

                    if (grp.sharedGroup() && (hld == null || hld.cctx.cacheId() != row.cacheId()))
                        hld = cacheMapHolder(ctx.cacheContext(row.cacheId()));

                    assert hld != null;

                    GridCacheMapEntry cached = putEntryIfObsoleteOrAbsent(
                        hld,
                        hld.cctx,
                        grp.affinity().lastVersion(),
                        row.key(),
                        true,
                        false);

                    if (cached instanceof GridDhtCacheEntry && ((GridDhtCacheEntry)cached).clearInternal(clearVer, extras)) {
                        removeEntry(cached);

                        if (rec && !hld.cctx.config().isEventsDisabled()) {
                            hld.cctx.events().addEvent(cached.partition(),
                                cached.key(),
                                ctx.localNodeId(),
                                (IgniteUuid)null,
                                null,
                                EVT_CACHE_REBALANCE_OBJECT_UNLOADED,
                                null,
                                false,
                                cached.rawGet(),
                                cached.hasValue(),
                                null,
                                null,
                                null,
                                false);
                        }

                        cleared++;
                    }

                    // For each 'stopCheckingFreq' cleared entities check clearing process to stop.
                    if (cleared % stopCheckingFreq == 0 && evictionCtx.shouldStop())
                        return cleared;
                }
                catch (GridDhtInvalidPartitionException e) {
                    assert isEmpty() && state() == EVICTED : "Invalid error [e=" + e + ", part=" + this + ']';

                    break; // Partition is already concurrently cleared and evicted.
                }
                finally {
                    ctx.database().checkpointReadUnlock();
                }
            }

            if (forceTestCheckpointOnEviction) {
                if (partWhereTestCheckpointEnforced == null && cleared >= fullSize()) {
                    ctx.database().forceCheckpoint("test").finishFuture().get();

                    log.warning("Forced checkpoint by test reasons for partition: " + this);

                    partWhereTestCheckpointEnforced = id;
                }
            }
        }
        catch (NodeStoppingException e) {
            if (log.isDebugEnabled())
                log.debug("Failed to get iterator for evicted partition: " + id);

            throw e;
        }
        catch (IgniteCheckedException e) {
            U.error(log, "Failed to get iterator for evicted partition: " + id, e);
        }

        return cleared;
    }

    /**
     * Removes all cache entries from specified {@code map}.
     *
     * @param map Map to clear.
     * @param extras Obsolete extras.
     * @param evt Unload event flag.
     * @throws NodeStoppingException If current node is stopping.
     */
    private void clear(ConcurrentMap<KeyCacheObject, GridCacheMapEntry> map,
        GridCacheObsoleteEntryExtras extras,
        boolean evt) throws NodeStoppingException {
        Iterator<GridCacheMapEntry> it = map.values().iterator();

        while (it.hasNext()) {
            GridCacheMapEntry cached = null;

            ctx.database().checkpointReadLock();

            try {
                cached = it.next();

                if (cached instanceof GridDhtCacheEntry && ((GridDhtCacheEntry)cached).clearInternal(extras.obsoleteVersion(), extras)) {
                    removeEntry(cached);

                    if (!cached.isInternal()) {
                        if (evt) {
                            grp.addCacheEvent(cached.partition(),
                                cached.key(),
                                ctx.localNodeId(),
                                EVT_CACHE_REBALANCE_OBJECT_UNLOADED,
                                null,
                                false,
                                cached.rawGet(),
                                cached.hasValue(),
                                false);
                        }
                    }
                }
            }
            catch (GridDhtInvalidPartitionException e) {
                assert isEmpty() && state() == EVICTED : "Invalid error [e=" + e + ", part=" + this + ']';

                break; // Partition is already concurrently cleared and evicted.
            }
            catch (NodeStoppingException e) {
                if (log.isDebugEnabled())
                    log.debug("Failed to clear cache entry for evicted partition: " + cached.partition());

                throw e;
            }
            catch (IgniteCheckedException e) {
                U.error(log, "Failed to clear cache entry for evicted partition: " + cached, e);
            }
            finally {
                ctx.database().checkpointReadUnlock();
            }
        }
    }

    /**
     * Removes all deferred delete requests from {@code rmvQueue}.
     */
    private void clearDeferredDeletes() {
        for (RemovedEntryHolder e : rmvQueue)
            removeVersionedEntry(e.cacheId(), e.key(), e.version());
    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        return id;
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"OverlyStrongTypeCast"})
    @Override public boolean equals(Object obj) {
        return obj instanceof GridDhtLocalPartition && (obj == this || ((GridDhtLocalPartition)obj).id() == id);
    }

    /** {@inheritDoc} */
    @Override public int compareTo(@NotNull GridDhtLocalPartition part) {
        if (part == null)
            return 1;

        return Integer.compare(id, part.id());
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridDhtLocalPartition.class, this,
            "grp", grp.cacheOrGroupName(),
            "state", state(),
            "reservations", reservations(),
            "empty", isEmpty(),
            "createTime", U.format(createTime));
    }

    /** {@inheritDoc} */
    @Override public int publicSize(int cacheId) {
        if (grp.sharedGroup()) {
            CacheMapHolder hld = cacheMaps.get(cacheId);

            return hld != null ? hld.size.get() : 0;
        }

        return getSize(state.get());
    }

    /** {@inheritDoc} */
    @Override public void incrementPublicSize(@Nullable CacheMapHolder hld, GridCacheEntryEx e) {
        if (grp.sharedGroup()) {
            if (hld == null)
                hld = cacheMapHolder(e.context());

            hld.size.incrementAndGet();
        }

        while (true) {
            long state = this.state.get();

            if (this.state.compareAndSet(state, setSize(state, getSize(state) + 1)))
                return;
        }
    }

    /** {@inheritDoc} */
    @Override public void decrementPublicSize(@Nullable CacheMapHolder hld, GridCacheEntryEx e) {
        if (grp.sharedGroup()) {
            if (hld == null)
                hld = cacheMapHolder(e.context());

            hld.size.decrementAndGet();
        }

        while (true) {
            long state = this.state.get();

            assert getPartState(state) != EVICTED;

            if (this.state.compareAndSet(state, setSize(state, getSize(state) - 1)))
                return;
        }
    }

    /**
     * @param cacheId Cache ID.
     */
    void onCacheStopped(int cacheId) {
        assert grp.sharedGroup() : grp.cacheOrGroupName();

        for (Iterator<RemovedEntryHolder> it = rmvQueue.iterator(); it.hasNext();) {
            RemovedEntryHolder e = it.next();

            if (e.cacheId() == cacheId)
                it.remove();
        }

        cacheMaps.remove(cacheId);
    }

    /**
     * @param state Composite state.
     * @return Partition state.
     */
    private static GridDhtPartitionState getPartState(long state) {
        return GridDhtPartitionState.fromOrdinal((int)(state & (0x0000000000000007L)));
    }

    /**
     * @param state Composite state to update.
     * @param partState Partition state.
     * @return Updated composite state.
     */
    private static long setPartState(long state, GridDhtPartitionState partState) {
        return (state & (~0x0000000000000007L)) | partState.ordinal();
    }

    /**
     * @param state Composite state.
     * @return Reservations.
     */
    private static int getReservations(long state) {
        return (int)((state & 0x00000000FFFF0000L) >> 16);
    }

    /**
     * @param state Composite state to update.
     * @param reservations Reservations to set.
     * @return Updated composite state.
     */
    private static long setReservations(long state, int reservations) {
        return (state & (~0x00000000FFFF0000L)) | (reservations << 16);
    }

    /**
     * @param state Composite state.
     * @return Size.
     */
    private static int getSize(long state) {
        return (int)((state & 0xFFFFFFFF00000000L) >> 32);
    }

    /**
     * @param state Composite state to update.
     * @param size Size to set.
     * @return Updated composite state.
     */
    private static long setSize(long state, int size) {
        return (state & (~0xFFFFFFFF00000000L)) | ((long)size << 32);
    }

    /**
     * Removed entry holder.
     */
    private static class RemovedEntryHolder {
        /** */
        private final int cacheId;

        /** Cache key */
        private final KeyCacheObject key;

        /** Entry version */
        private final GridCacheVersion ver;

        /** Entry expire time. */
        private final long expireTime;

        /**
         * @param cacheId Cache ID.
         * @param key Key.
         * @param ver Entry version.
         * @param ttl TTL.
         */
        private RemovedEntryHolder(int cacheId, KeyCacheObject key, GridCacheVersion ver, long ttl) {
            this.cacheId = cacheId;
            this.key = key;
            this.ver = ver;

            expireTime = U.currentTimeMillis() + ttl;
        }

        /**
         * @return Cache ID.
         */
        int cacheId() {
            return cacheId;
        }

        /**
         * @return Key.
         */
        KeyCacheObject key() {
            return key;
        }

        /**
         * @return Version.
         */
        GridCacheVersion version() {
            return ver;
        }

        /**
         * @return item expired time
         */
        long expireTime() {
            return expireTime;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(RemovedEntryHolder.class, this);
        }
    }

    /**
     * Future is needed to control partition clearing process.
     * Future can be used both for single clearing or eviction processes.
     */
    class ClearFuture extends GridFutureAdapter<Boolean> {
        /** Flag indicates that eviction callback was registered on the current future. */
        private volatile boolean evictionCbRegistered;

        /** Flag indicates that clearing callback was registered on the current future. */
        private volatile boolean clearingCbRegistered;

        /** Flag indicates that future with all callbacks was finished. */
        private volatile boolean finished;

        /**
         * Constructor.
         */
        ClearFuture() {
            onDone();
            finished = true;
        }

        /**
         * Registers finish eviction callback on the future.
         *
         * @param updateSeq If {@code true} update topology sequence after successful eviction.
         */
        private void registerEvictionCallback(boolean updateSeq) {
            if (evictionCbRegistered)
                return;

            synchronized (this) {
                // Double check
                if (evictionCbRegistered)
                    return;

                evictionCbRegistered = true;

                // Initiates partition eviction and destroy.
                listen(f -> {
                    try {
                        // Check for errors.
                        f.get();

                        finishEviction(updateSeq);
                    }
                    catch (Exception e) {
                        rent.onDone(e);
                    }

                    evictionCbRegistered = false;
                });
            }
        }

        /**
         * Registers clearing callback on the future.
         */
        private void registerClearingCallback() {
            if (clearingCbRegistered)
                return;

            synchronized (this) {
                // Double check
                if (clearingCbRegistered)
                    return;

                clearingCbRegistered = true;

                // Recreate cache data store in case of allowed fast eviction, and reset clear flag.
                listen(f -> {
                    clear = false;

                    clearingCbRegistered = false;
                });
            }
        }

        /**
         * Successfully finishes the future.
         */
        public void finish() {
            synchronized (this) {
                onDone();
                finished = true;
            }
        }

        /**
         * Finishes the future with error.
         *
         * @param t Error.
         */
        public void finish(Throwable t) {
            synchronized (this) {
                onDone(t);
                finished = true;
            }
        }

        /**
         * Reuses future if it's done.
         * Adds appropriate callbacks to the future in case of eviction or single clearing.
         *
         * @param updateSeq Update sequence.
         * @param evictionRequested If {@code true} adds eviction callback, in other case adds single clearing callback.
         * @return {@code true} if future has been reinitialized.
         */
        public boolean initialize(boolean updateSeq, boolean evictionRequested) {
            // In case of running clearing just try to add missing callbacks to avoid extra synchronization.
            if (!finished) {
                if (evictionRequested)
                    registerEvictionCallback(updateSeq);
                else
                    registerClearingCallback();

                return false;
            }

            synchronized (this) {
                boolean done = isDone();

                if (done) {
                    reset();

                    finished = false;
                    evictionCbRegistered = false;
                    clearingCbRegistered = false;
                }

                if (evictionRequested)
                    registerEvictionCallback(updateSeq);
                else
                    registerClearingCallback();

                return done;
            }
        }
    }
}


text:
![](grouped_full.png)

Example:

```
/// Bar chart example
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;

class GroupedBarChart extends StatelessWidget {
  final List<charts.Series> seriesList;
  final bool animate;

  GroupedBarChart(this.seriesList, {this.animate});

  factory GroupedBarChart.withSampleData() {
    return new GroupedBarChart(
      _createSampleData(),
      // Disable animations for image tests.
      animate: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new charts.BarChart(
      seriesList,
      animate: animate,
      barGroupingType: charts.BarGroupingType.grouped,
    );
  }

  /// Create series list with multiple series
  static List<charts.Series<OrdinalSales, String>> _createSampleData() {
    final desktopSalesData = [
      new OrdinalSales('2014', 5),
      new OrdinalSales('2015', 25),
      new OrdinalSales('2016', 100),
      new OrdinalSales('2017', 75),
    ];

    final tableSalesData = [
      new OrdinalSales('2014', 25),
      new OrdinalSales('2015', 50),
      new OrdinalSales('2016', 10),
      new OrdinalSales('2017', 20),
    ];

    final mobileSalesData = [
      new OrdinalSales('2014', 10),
      new OrdinalSales('2015', 15),
      new OrdinalSales('2016', 50),
      new OrdinalSales('2017', 45),
    ];

    return [
      new charts.Series<OrdinalSales, String>(
        id: 'Desktop',
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        data: desktopSalesData,
      ),
      new charts.Series<OrdinalSales, String>(
        id: 'Tablet',
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        data: tableSalesData,
      ),
      new charts.Series<OrdinalSales, String>(
        id: 'Mobile',
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        data: mobileSalesData,
      ),
    ];
  }
}

/// Sample ordinal data type.
class OrdinalSales {
  final String year;
  final int sales;

  OrdinalSales(this.year, this.sales);
}
```


text:
#import <AppKit/NSColor-Private.h>
#import <AppKit/NSColor_whiteCalibrated.h>
#import <AppKit/NSColor_rgbCalibrated.h>
#import <AppKit/NSColor_whiteDevice.h>
#import <AppKit/NSColor_rgbDevice.h>
#import <AppKit/NSColor_cmykDevice.h>
#import <AppKit/NSColor_catalog.h>
#import <AppKit/NSRaise.h>

#import <AppKit/NSGraphics.h>
#import <AppKit/NSGraphicsContext.h>

#import <AppKit/NSPasteboard.h>
#import <Foundation/NSKeyedArchiver.h>

#import <AppKit/NSDisplay.h>

@interface NSDisplay(revelation)
-(void) _addSystemColor: (NSColor *) color forName: (NSString *) name;
@end

@implementation NSColor

-(void)encodeWithCoder:(NSCoder *)coder {
   NSUnimplementedMethod();
}

-initWithCoder:(NSCoder *)coder {
   if([coder allowsKeyedCoding]){
    NSKeyedUnarchiver *keyed=(NSKeyedUnarchiver *)coder;
    int                colorSpace=[keyed decodeIntForKey:@"NSColorSpace"];
    NSColor           *result;

    switch(colorSpace){

     case 1:{
// NSComponents data
// NSCustomColorSpace NSColorSpace
       NSUInteger    length;
       const uint8_t *rgb=[keyed decodeBytesForKey:@"NSRGB" returnedLength:&length];
       NSString   *string=[NSString stringWithCString:rgb length:length];
       NSArray    *components=[string componentsSeparatedByString:@" "];
       float       values[4]={0,0,0,1};
       int         i,count=[components count];

       for(i=0;i<count && i<4;i++)
        values[i]=[[components objectAtIndex:i] floatValue];

       result=[NSColor colorWithCalibratedRed:values[0] green:values[1] blue:values[2] alpha:values[3]];
      }
      break;

     case 2:{
       NSUInteger    length;
       const uint8_t *rgb=[keyed decodeBytesForKey:@"NSRGB" returnedLength:&length];
       NSString   *string=[NSString stringWithCString:rgb length:length];
       NSArray    *components=[string componentsSeparatedByString:@" "];
       float       values[4]={0,0,0,1};
       int         i,count=[components count];

       for(i=0;i<count && i<4;i++)
        values[i]=[[components objectAtIndex:i] floatValue];

       result=[NSColor colorWithDeviceRed:values[0] green:values[1] blue:values[2] alpha:values[3]];
      }
      break;

     case 3:{
       NSUInteger    length;
       const uint8_t *white=[keyed decodeBytesForKey:@"NSWhite" returnedLength:&length];
       NSString   *string=[NSString stringWithCString:white length:length-1];
       NSArray    *components=[string componentsSeparatedByString:@" "];
       float       values[2]={0,1};
       int         i,count=[components count];

       for(i=0;i<count && i<2;i++)
        values[i]=[[components objectAtIndex:i] floatValue];

       result=[NSColor colorWithCalibratedWhite:values[0] alpha:values[1]];
      }
      break;

     case 4:{
       NSUInteger    length;
       const uint8_t *white=[keyed decodeBytesForKey:@"NSWhite" returnedLength:&length];
       NSString   *string=[NSString stringWithCString:white length:length];
       NSArray    *components=[string componentsSeparatedByString:@" "];
       float       values[2]={0,1};
       int         i,count=[components count];

       for(i=0;i<count && i<2;i++)
        values[i]=[[components objectAtIndex:i] floatValue];

       result=[NSColor colorWithDeviceWhite:values[0] alpha:values[1]];
      }
      break;

     case 5:{
// NSComponents data
// NSCustomColorSpace NSColorSpace
       NSUInteger    length;
       const uint8_t *cmyk=[keyed decodeBytesForKey:@"NSCMYK" returnedLength:&length];
       NSString   *string=[NSString stringWithCString:cmyk length:length];
       NSArray    *components=[string componentsSeparatedByString:@" "];
       float       values[5]={0,0,0,0,1};
       int         i,count=[components count];

       for(i=0;i<count && i<5;i++)
        values[i]=[[components objectAtIndex:i] floatValue];

       result=[NSColor colorWithDeviceCyan:values[0] magenta:values[1] yellow:values[2] black:values[3] alpha:values[4]];
      }
      break;

     case 6:{
       NSString *catalogName=[keyed decodeObjectForKey:@"NSCatalogName"];
       NSString *colorName=[keyed decodeObjectForKey:@"NSColorName"];
       NSColor  *color=[keyed decodeObjectForKey:@"NSColor"];

       if([catalogName isEqualToString: @"System"]) {
	   NSDisplay *display = [NSDisplay currentDisplay];
	   result = [display colorWithName: colorName];
	   if(!result) {
	       result = color;
	       [display _addSystemColor: result forName: colorName];
	   }
       } else {
	   result = [NSColor colorWithCatalogName: catalogName colorName: colorName];
	   if(!result) {
	       result=color;
	   }
       }
      }
      break;

     default:
      NSLog(@"-[%@ %s] unknown color space %d",isa,sel_getName(_cmd),colorSpace);
      result=[NSColor blackColor];
      break;
    }

    return [result retain];
   }

   else {
    [NSException raise:NSInvalidArgumentException format:@"%@ can not initWithCoder:%@",isa,[coder class]];
    return nil;
   }
}

-copyWithZone:(NSZone *)zone {
   return [self retain];
}

+(NSColor *)alternateSelectedControlColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"alternateSelectedControlColor"];
}

+(NSColor *)alternateSelectedControlTextColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"alternateSelectedControlTextColor"];
}

+ (NSColor *)keyboardFocusIndicatorColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"keyboardFocusIndicatorColor"];
}

+(NSColor *)highlightColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"highlightColor"];
}

+(NSColor *)shadowColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"shadowColor"];
}

+(NSColor *)gridColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"gridColor"];
}

+(NSColor *)controlColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlColor"];
}

+(NSColor *)selectedControlColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"selectedControlColor"];
}

+(NSColor *)secondarySelectedControlColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"secondarySelectedControlColor"];
}

+(NSColor *)controlTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlTextColor"];
}

+(NSColor *)selectedControlTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"selectedControlTextColor"];
}

+(NSColor *)disabledControlTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"disabledControlTextColor"];
}

+(NSColor *)controlBackgroundColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlBackgroundColor"];
}

+(NSColor *)controlDarkShadowColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlDarkShadowColor"];
}

+(NSColor *)controlHighlightColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlHighlightColor"];
}

+(NSColor *)controlLightHighlightColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlLightHighlightColor"];
}

+(NSColor *)controlShadowColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"controlShadowColor"];
}

// overwrite this, if you need a different set of alternating background colors
// NOTE: the list may contain more then two colors
+(NSArray *)controlAlternatingRowBackgroundColors {
   return [NSArray arrayWithObjects:
    [NSColor whiteColor],
    [NSColor colorWithCalibratedRed:0.90 green:0.95 blue:1.0 alpha:1.0],
    nil];
}

+(NSColor *)textColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"textColor"];
}

+(NSColor *)textBackgroundColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"textBackgroundColor"];
}

+(NSColor *)selectedTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"selectedTextColor"];
}

+(NSColor *)selectedTextBackgroundColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"selectedTextBackgroundColor"];
}

+(NSColor *)headerColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"headerColor"];
}

+(NSColor *)headerTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"headerTextColor"];
}

+(NSColor *)scrollBarColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"scrollBarColor"];
}

+(NSColor *)knobColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"knobColor"];
}

+(NSColor *)selectedKnobColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"selectedKnobColor"];
}

+(NSColor *)windowBackgroundColor {
   return [NSColor controlColor];
}

+(NSColor *)windowFrameColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"windowFrameColor"];
}

+ (NSColor *)selectedMenuItemColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"selectedMenuItemColor"];
}

+ (NSColor *)selectedMenuItemTextColor {
    return [NSColor colorWithCatalogName:@"System" colorName:@"selectedMenuItemTextColor"];
}

+(NSColor *)menuBackgroundColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"menuBackgroundColor"];
}

+(NSColor *)menuItemTextColor {
   return [NSColor colorWithCatalogName:@"System" colorName:@"menuItemTextColor"];
}

+(NSColor *)clearColor {
   return [NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0];
}

+(NSColor *)blackColor {
   return [NSColor_whiteCalibrated blackColor];
}

+(NSColor *)blueColor {
   return [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:1.0 alpha:1.0];
}

+(NSColor *)brownColor {
   return [NSColor colorWithCalibratedRed:0.6 green:0.4 blue:0.2 alpha:1.0];
}

+(NSColor *)cyanColor {
   return [NSColor colorWithCalibratedRed:0.0 green:1.0 blue:1.0 alpha:1.0];
}

+(NSColor *)darkGrayColor {
   return [NSColor_whiteCalibrated darkGrayColor];
}

+(NSColor *)grayColor {
   return [NSColor_whiteCalibrated grayColor];
}

+(NSColor *)greenColor {
   return [NSColor colorWithCalibratedRed:0.0 green:1.0 blue:0.0 alpha:1.0];
}

+(NSColor *)lightGrayColor {
   return [NSColor_whiteCalibrated lightGrayColor];
}

+(NSColor *)magentaColor {
   return [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:1.0 alpha:1.0];
}

+(NSColor *)orangeColor {
   return [NSColor colorWithCalibratedRed:1.0 green:0.5 blue:0.0 alpha:1.0];
}

+(NSColor *)purpleColor {
   return [NSColor colorWithCalibratedRed:0.5 green:0.0 blue:0.5 alpha:1.0];
}

+(NSColor *)redColor {
   return [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:1.0];
}

+(NSColor *)whiteColor {
   return [NSColor_whiteCalibrated whiteColor];
}

+(NSColor *)yellowColor {
   return [NSColor colorWithCalibratedRed:1.0 green:1.0 blue:0.0 alpha:1.0];
}

+(NSColor *)colorWithDeviceWhite:(float)white alpha:(float)alpha {
   return [NSColor_whiteDevice colorWithGray:white alpha:alpha];
}

+(NSColor *)colorWithDeviceRed:(float)red green:(float)green blue:(float)blue alpha:(float)alpha {
   return [NSColor_rgbDevice colorWithRed:red green:green blue:blue alpha:alpha];
}

+(NSColor *)colorWithDeviceHue:(float)hue saturation:(float)saturation brightness:(float)brightness alpha:(float)alpha {
   return [NSColor_rgbDevice colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
}

+(NSColor *)colorWithDeviceCyan:(float)cyan magenta:(float)magenta yellow:(float)yellow black:(float)black alpha:(float)alpha {
   return [NSColor_cmykDevice colorWithCyan:cyan magenta:magenta yellow:yellow black:black alpha:alpha];
}

+(NSColor *)colorWithCalibratedWhite:(float)white alpha:(float)alpha {
   return [NSColor_whiteCalibrated colorWithGray:white alpha:alpha];
}

+(NSColor *)colorWithCalibratedRed:(float)red green:(float)green blue:(float)blue alpha:(float)alpha {
   return [NSColor_rgbCalibrated colorWithRed:red green:green blue:blue alpha:alpha];
}

+(NSColor *)colorWithCalibratedHue:(float)hue saturation:(float)saturation brightness:(float)brightness alpha:(float)alpha {
   return [NSColor_rgbCalibrated colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
}

+(NSColor *)colorWithCatalogName:(NSString *)catalogName colorName:(NSString *)colorName {
   return [NSColor_catalog colorWithCatalogName:catalogName colorName:colorName];
}

+(NSColor *)colorFromPasteboard:(NSPasteboard *)pasteboard {
   NSData *data=[pasteboard dataForType:NSColorPboardType];

   return [NSUnarchiver unarchiveObjectWithData:data];
}

+(NSColor *)colorWithPatternImage:(NSImage *)image
{
   NSUnimplementedMethod();
   return [self lightGrayColor];
}

-(NSString *)colorSpaceName {
   NSInvalidAbstractInvocation();
   return nil;
}

-(NSInteger)numberOfComponents {
   CGColorRef colorRef=[self createCGColorRef];
   NSInteger result=CGColorGetNumberOfComponents(colorRef);
   CGColorRelease(colorRef);
   return result;
}

-(void)getComponents:(CGFloat *)components {
   CGColorRef colorRef=[self createCGColorRef];
   NSInteger  i,count=CGColorGetNumberOfComponents(colorRef);
   const CGFloat *comps=CGColorGetComponents(colorRef);

   for(i=0;i<count;i++)
    components[i]=comps[i];

   CGColorRelease(colorRef);
}

-(void)getWhite:(float *)white alpha:(float *)alpha {
    NSInvalidAbstractInvocation();
}

-(void)getRed:(float *)red green:(float *)green blue:(float *)blue alpha:(float *)alpha {
   NSInvalidAbstractInvocation();
}

-(void)getHue:(float *)hue saturation:(float *)saturation brightness:(float *)brightness alpha:(float *)alpha {
   NSInvalidAbstractInvocation();
}

-(void)getCyan:(float *)cyan magenta:(float *)magenta yellow:(float *)yellow black:(float *)black alpha:(float *)alpha {
    NSInvalidAbstractInvocation();
}

-(float)whiteComponent {
    float white;

    [self getWhite:&white alpha:NULL];
    return white;
}

-(float)redComponent {
   float red;

   [self getRed:&red green:NULL blue:NULL alpha:NULL];

   return red;
}

-(float)greenComponent {
   float green;

   [self getRed:NULL green:&green blue:NULL alpha:NULL];

   return green;
}

-(float)blueComponent {
   float blue;

   [self getRed:NULL green:NULL blue:&blue alpha:NULL];

   return blue;
}

-(float)hueComponent {
   float hue;

   [self getHue:&hue saturation:NULL brightness:NULL alpha:NULL];

   return hue;
}

-(float)saturationComponent {
   float saturation;

   [self getHue:NULL saturation:&saturation brightness:NULL alpha:NULL];

   return saturation;
}

-(float)brightnessComponent {
   float brightness;

   [self getHue:NULL saturation:NULL brightness:&brightness alpha:NULL];

   return brightness;
}

-(float)cyanComponent {
    float cyan;

    [self getCyan:&cyan magenta:NULL yellow:NULL black:NULL alpha:NULL];
    return cyan;
}

-(float)magentaComponent {
    float magenta;

    [self getCyan:NULL magenta:&magenta yellow:NULL black:NULL alpha:NULL];
    return magenta;
}

-(float)yellowComponent {
    float yellow;

    [self getCyan:NULL magenta:NULL yellow:&yellow black:NULL alpha:NULL];
    return yellow;
}

-(float)blackComponent {
    float black;

    [self getCyan:NULL magenta:NULL yellow:NULL black:&black alpha:NULL];
    return black;
}

-(float)alphaComponent {
    return 1.0;
}

-(NSColor *)colorWithAlphaComponent:(float)alpha {
   if (alpha >= 1.0) return self;
   return nil;
}

-(NSColor *)colorUsingColorSpaceName:(NSString *)colorSpace {
    return [self colorUsingColorSpaceName:colorSpace device:nil];
}

-(NSColor *)colorUsingColorSpaceName:(NSString *)colorSpace device:(NSDictionary *)device {
   if([[self colorSpaceName] isEqualToString:colorSpace])
    return self;

   //NSLog(@"Warning, ignoring differences between color space %@ and %@", colorSpace, [self colorSpaceName]);
   return self;
}

-(NSColor *)blendedColorWithFraction:(float)fraction ofColor:(NSColor *)color {
   NSColor *primary=[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
   NSColor *secondary=[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];

   if(primary==nil || secondary==nil)
    return nil;
   else {
    float pr,pg,pb,pa;
    float sr,sg,sb,sa;
    float rr,rg,rb,ra;

    [primary getRed:&pr green:&pg blue:&pb alpha:&pa];
    [secondary getRed:&sr green:&sg blue:&sb alpha:&sa];

    rr=pr*fraction+sr*(1-fraction);
    rg=pg*fraction+sg*(1-fraction);
    rb=pb*fraction+sb*(1-fraction);
    ra=pa*fraction+sa*(1-fraction);

    return [NSColor colorWithCalibratedRed:rr green:rg blue:rb alpha:ra];
   }
}

-(void)set {
    [self setStroke];
    [self setFill];
}

-(void)setFill {
    NSInvalidAbstractInvocation();
}

-(void)setStroke {
    NSInvalidAbstractInvocation();
}

-(void)drawSwatchInRect:(NSRect)rect {
    [self setFill];
    NSRectFill(rect);
}

-(void)writeToPasteboard:(NSPasteboard *)pasteboard {
   NSData *data=[NSArchiver archivedDataWithRootObject:self];

   [pasteboard setData:data forType:NSColorPboardType];
}

@end


text:
module Smartcard::Iso
  # Shortcut for Smartcard::Iso::AutoConfigurator#auto_transport
  def self.auto_transport
    Smartcard::Iso::AutoConfigurator.auto_transport
  end
end


text:
<!DOCTYPE html>
<html lang="en" ng-app="homeApp" style="height: 100%;">
<head>
    <title>Dr.R</title>
    <link rel="icon" href="img/logo.png" />
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/navi.css">
    <link rel="stylesheet" href="css/findnavi.css">
    <link rel="stylesheet" href="css/sign-in.css">
    <link rel="stylesheet" href="css/triangle.css">
    <link rel="stylesheet" href="css/dashboard.css">
    <link rel="stylesheet" href="css/custom_animation.css">
    <link rel="stylesheet" href="bower_components/angular-chart.js/dist/angular-chart.css">
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="bower_components/a0-angular-storage/dist/angular-storage.js"></script>
    <script src="bower_components/ng-file-upload/ng-file-upload.js"></script>
    <script src="bower_components/ng-file-upload-shim/ng-file-upload-shim.js"></script>
    <script src="bower_components/ng-file-upload/ng-file-upload.js"></script>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/jqcloud2/dist/jqcloud.min.js"></script>
    <script src="bower_components/angular-scroll/angular-scroll.js"></script>
    <script src="bower_components/Chart.js/Chart.js"></script>
    <script src="bower_components/angular-confirm-modal/angular-confirm.js"></script>

    <script src="js/controller/FindPassController.js"></script>
    <script src="js/controller/JoinController.js"></script>
    <script src="js/controller/LeftSidebarController.js"></script>
    <script src="js/controller/LoginController.js"></script>
    <script src="js/controller/IndexController.js"></script>
    <script src="js/controller/DiaryController.js"></script>
    <script src="js/controller/DiaryManageController.js"></script>
    <script src="js/controller/PatientEvaluateController.js"></script>
    <script src="js/controller/PatientListController.js"></script>
    <script src="js/controller/PatientManageController.js"></script>
    <script src="js/controller/StatusController.js"></script>
    <script src="js/controller/DiaryDetailController.js"></script>

    <!--<script type="text/javascript" src="/app/js/table/tableExport.js"></script>-->
    <!--<script type="text/javascript" src="/app/js/table/jquery.base64.js"></script>-->
    <script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
     <script src="js/app.js"></script>
    <style>
        /* Remove the navbar's default margin-bottom and rounded borders */
        .navbar {
            margin-bottom: 0;
            border-radius: 0;
        }

        /* Set height of the grid so .sidenav can be 100% (adjust as needed) */
        .row.content {height: 100%;
            margin-bottom: 50px;
            background-color: #E9EBEE;
        }

        footer {
            background-color: #555;
            color: white;
            padding: 15px;
        }

        /* On small screens, set height to 'auto' for sidenav and grid */
        @media screen and (max-width: 767px) {
            .sidenav {
                height: auto;
                padding: 15px;
            }
            .row.content {height:auto;
                background-color: #E9EBEE;}
        }
    </style>

    <script>

        $(document).ready(function() {
            $('#closeform1').click(function() {
                $("#signupform").each(function () {
                    this.reset();
                })
            });

            $('.modal').on('hidden.bs.modal', function(){
                $(this).find('form')[0].reset();
            });
            $("#btn1").click(function(){
                $("#li1").addClass("active");
                $("#men1").addClass("in active");
                $("#li2").removeClass("active");
                $("#men2").removeClass("in active");
                $("#li3").removeClass("active");
                $("#men3").removeClass("in active");
                $("#homenav").removeClass("active");
                $("#aboutnav").removeClass("active");
                $("#menunav").removeClass("active");
            });
            $("#btn2").click(function(){
                $("#li2").addClass("active");
                $("#men2").addClass("in active");
                $("#li1").removeClass("active");
                $("#men1").removeClass("in active");
                $("#li3").removeClass("active");
                $("#men3").removeClass("in active");
                $("#homenav").removeClass("active");
                $("#aboutnav").removeClass("active");
                $("#menunav").removeClass("active");
            });
            $("#btn3").click(function(){
                $("#men3").addClass("in active");
                $("#li3").addClass("active");
                $("#li1").removeClass("active");
                $("#men1").removeClass("in active");
                $("#li2").removeClass("active");
                $("#men2").removeClass("in active");
                $("#homenav").removeClass("active");
                $("#aboutnav").removeClass("active");
                $("#menunav").removeClass("active");
            });
        });
    </script>
    <style>
        .carousel-inner > .item > img,
        .carousel-inner > .item > a > img {
            width: 100%;
            margin: auto;
        }
    </style>

<body ui-view  style="background-color:rgb(64, 189, 183);height: 100%;">
</body>

<script src="angular-jqcloud.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/app.js"></script>
<script src="js/ui-bootstrap-tpls-1.3.3.min.js"></script>
<script type="text/javascript" src="http://beneposto.pl/jqueryrotate/js/jQueryRotateCompressed.js"></script>
<script src="bower_components/angular-chart.js/dist/angular-chart.js"></script>

</html>


text:
package org.apache.nifi.processors.standard.util;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Deque;
import java.util.LinkedList;
import java.util.regex.Matcher;

import org.apache.nifi.processor.Processor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ProtocolCommandEvent;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ftp.FTPClient;

/**
 *
 */
public class FTPUtils {

    private static final Log logger = LogFactory.getLog(FTPUtils.class);

    public static final String CONNECTION_MODE_KEY = "connection.mode";//optional(active local)
    public static final String ACTIVE_LOCAL_CONNECTION_MODE = "active_local";
    public static final String PASSIVE_LOCAL_CONNECTION_MODE = "passive_local";

    public static final String TRANSFER_MODE_KEY = "transfer.mode";//optional(binary)
    public static final String BINARY_TRANSFER_MODE = "binary";
    public static final String ASCII_TRANSFER_MODE = "ascii";

    public static final String REMOTE_HOST_KEY = "remote.host";//required
    public static final String REMOTE_USER_KEY = "remote.user";//required
    public static final String REMOTE_PASSWORD_KEY = "remote.password";//required
    public static final String REMOTE_PORT_KEY = "remote.port"; //optional (default port)

    public static final String NETWORK_DATA_TIMEOUT_KEY = "network.data.timeout";
    public static final String NETWORK_SOCKET_TIMEOUT_KEY = "network.socket.timeout";

    /**
     * Creates a new FTPClient connected to an FTP server. The following properties must exist:
     *
Required Properties:
     *
remote.host - The hostname or IP address of the FTP server to connect to

     *
remote.user - The username of the account to authenticate with

     *
remote.password = The password for the username to authenticate with

     *

     *
Optional Properties:
     *
remote.port - The port on the FTP server to connect to. Defaults to FTP default.

     *
transfer.mode - The type of transfer for this connection ('ascii', 'binary'). Defaults to 'binary'

     *
connection.mode - The type of FTP connection to make ('active_local', 'passive_local'). Defaults to 'active_local'. In active_local the server initiates 'data connections' to the client
     * where in passive_local the client initiates 'data connections' to the server.

     *
network.data.timeout - Default is 0. Sets the timeout in milliseconds for waiting to establish a new 'data connection' (not a control connection) when in ACTIVE_LOCAL mode. Also, this
     * establishes the amount of time to wait on read calls on the data connection in either mode. A value of zero means do not timeout. Users should probably set a value here unless using very
     * reliable communications links or else risk indefinite hangs that require a restart.

     *
network.socket.timeout - Default is 0. Sets the timeout in milliseconds to use when creating a new control channel socket and also a timeout to set when reading from a control socket. A
     * value of zero means do not timeout. Users should probably set a value here unless using very reliable communications links or else risk indefinite hangs that require a restart.

     *

     *
     * @param conf conf
     * @param monitor if provided will be used to monitor FTP commands processed but may be null
     * @return FTPClient connected to FTP server as configured
     * @throws NullPointerException if either argument is null
     * @throws IllegalArgumentException if a required property is missing
     * @throws NumberFormatException if any argument that must be an int cannot be converted to int
     * @throws IOException if some problem occurs connecting to FTP server
     */
    public static FTPClient connect(final FTPConfiguration conf, final ProtocolCommandListener monitor) throws IOException {
        if (null == conf) {
            throw new NullPointerException();
        }

        final String portVal = conf.port;
        final int portNum = (null == portVal) ? -1 : Integer.parseInt(portVal);
        final String connectionModeVal = conf.connectionMode;
        final String connectionMode = (null == connectionModeVal) ? ACTIVE_LOCAL_CONNECTION_MODE : connectionModeVal;
        final String transferModeVal = conf.transferMode;
        final String transferMode = (null == transferModeVal) ? BINARY_TRANSFER_MODE : transferModeVal;
        final String networkDataTimeoutVal = conf.dataTimeout;
        final int networkDataTimeout = (null == networkDataTimeoutVal) ? 0 : Integer.parseInt(networkDataTimeoutVal);
        final String networkSocketTimeoutVal = conf.connectionTimeout;
        final int networkSocketTimeout = (null == networkSocketTimeoutVal) ? 0 : Integer.parseInt(networkSocketTimeoutVal);

        final FTPClient client = new FTPClient();
        if (networkDataTimeout > 0) {
            client.setDataTimeout(networkDataTimeout);
        }
        if (networkSocketTimeout > 0) {
            client.setDefaultTimeout(networkSocketTimeout);
        }
        client.setRemoteVerificationEnabled(false);
        if (null != monitor) {
            client.addProtocolCommandListener(monitor);
        }
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getByAddress(conf.remoteHostname, null);
        } catch (final UnknownHostException uhe) {
        }
        if (inetAddress == null) {
            inetAddress = InetAddress.getByName(conf.remoteHostname);
        }

        if (portNum < 0) {
            client.connect(inetAddress);
        } else {
            client.connect(inetAddress, portNum);
        }
        if (networkDataTimeout > 0) {
            client.setDataTimeout(networkDataTimeout);
        }
        if (networkSocketTimeout > 0) {
            client.setSoTimeout(networkSocketTimeout);
        }
        final boolean loggedIn = client.login(conf.username, conf.password);
        if (!loggedIn) {
            throw new IOException("Could not login for user '" + conf.username + "'");
        }
        if (connectionMode.equals(ACTIVE_LOCAL_CONNECTION_MODE)) {
            client.enterLocalActiveMode();
        } else if (connectionMode.equals(PASSIVE_LOCAL_CONNECTION_MODE)) {
            client.enterLocalPassiveMode();
        }
        boolean transferModeSet = false;
        if (transferMode.equals(ASCII_TRANSFER_MODE)) {
            transferModeSet = client.setFileType(FTPClient.ASCII_FILE_TYPE);
        } else {
            transferModeSet = client.setFileType(FTPClient.BINARY_FILE_TYPE);
        }
        if (!transferModeSet) {
            throw new IOException("Unable to set transfer mode to type " + transferMode);
        }

        return client;
    }

    public static class FTPCommandMonitor implements ProtocolCommandListener {

        final Processor processor;

        public FTPCommandMonitor(final Processor _processor) {
            this.processor = _processor;
        }

        @Override
        public void protocolCommandSent(final ProtocolCommandEvent event) {
            if (logger.isDebugEnabled()) {
                logger.debug(processor + " : " + event.getMessage().trim());
            }
        }

        @Override
        public void protocolReplyReceived(final ProtocolCommandEvent event) {
            if (logger.isDebugEnabled()) {
                logger.debug(processor + " : " + event.getMessage().trim());
            }
        }

    }

    /**
     * Handles the logic required to change to the given directory RELATIVE TO THE CURRENT DIRECTORY which can include creating new directories needed.
     *
     * This will first attempt to change to the full path of the given directory outright. If that fails, then it will attempt to change from the top of the tree of the given directory all the way
     * down to the final leaf node of the given directory.
     *
     * @param client - the ftp client with an already active connection
     * @param dirPath - the path to change or create directories to
     * @param createDirs - if true will attempt to create any missing directories
     * @param processor - used solely for targeting logging output.
     * @throws IOException if any access problem occurs
     */
    public static void changeWorkingDirectory(final FTPClient client, final String dirPath, final boolean createDirs, final Processor processor) throws IOException {
        final String currentWorkingDirectory = client.printWorkingDirectory();
        final File dir = new File(dirPath);
        logger.debug(processor + " attempting to change directory from " + currentWorkingDirectory + " to " + dir.getPath());
        boolean dirExists = false;
        final String forwardPaths = dir.getPath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("/"));
        //always use forward paths for long string attempt
        try {
            dirExists = client.changeWorkingDirectory(forwardPaths);
            if (dirExists) {
                logger.debug(processor + " changed working directory to '" + forwardPaths + "' from '" + currentWorkingDirectory + "'");
            } else {
                logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '" + currentWorkingDirectory + "' so trying the hard way.");
            }
        } catch (final IOException ioe) {
            logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '" + currentWorkingDirectory + "' so trying the hard way.");
        }
        if (!dirExists) {  //couldn't navigate directly...begin hard work
            final Deque<String> stack = new LinkedList<>();
            File fakeFile = new File(dir.getPath());
            do {
                stack.push(fakeFile.getName());
            } while ((fakeFile = fakeFile.getParentFile()) != null);

            String dirName = null;
            while ((dirName = stack.peek()) != null) {
                stack.pop();
                //find out if exists, if not make it if configured to do so or throw exception
                dirName = ("".equals(dirName.trim())) ? "/" : dirName;
                boolean exists = false;
                try {
                    exists = client.changeWorkingDirectory(dirName);
                } catch (final IOException ioe) {
                    exists = false;
                }
                if (!exists && createDirs) {
                    logger.debug(processor + " creating new directory and changing to it " + dirName);
                    client.makeDirectory(dirName);
                    if (!(client.makeDirectory(dirName) || client.changeWorkingDirectory(dirName))) {
                        throw new IOException(processor + " could not create and change to newly created directory " + dirName);
                    } else {
                        logger.debug(processor + " successfully changed working directory to " + dirName);
                    }
                } else if (!exists) {
                    throw new IOException(processor + " could not change directory to '" + dirName + "' from '" + currentWorkingDirectory + "'");
                }
            }
        }
    }

    public static class FTPConfiguration {

        private String remoteHostname;
        private String username;
        private String port;
        private String connectionTimeout;
        private String dataTimeout;
        private String password;
        private String connectionMode;
        private String transferMode;

        public FTPConfiguration() {

        }

        public void setRemoteHostname(final String val) {
            this.remoteHostname = val;
        }

        public String getRemoteHostname() {
            return remoteHostname;
        }

        public void setUsername(final String val) {
            this.username = val;
        }

        public String getUsername() {
            return username;
        }

        public void setPort(final String val) {
            this.port = val;
        }

        public String getPort() {
            return port;
        }

        public void setConnectionTimeout(final String val) {
            this.connectionTimeout = val;
        }

        public void setDataTimeout(final String val) {
            this.dataTimeout = val;
        }

        public void setPassword(final String val) {
            this.password = val;
        }

        public void setConnectionMode(final String val) {
            this.connectionMode = val;
        }

        public void setTransferMode(final String val) {
            this.transferMode = val;
        }

    }

}


text:
namespace offline_pages {

// This is the class which is a singleton for offline page model
// to get client policies based on namespaces.
class ClientPolicyController {
 public:
  ClientPolicyController();
  ~ClientPolicyController();

  // Generates a client policy from the input values.
  static const OfflinePageClientPolicy MakePolicy(
      const std::string& name_space,
      LifetimePolicy::LifetimeType lifetime_type,
      const base::TimeDelta& expiration_period,
      size_t page_limit,
      size_t pages_allowed_per_url);

  // Get the client policy for |name_space|.
  const OfflinePageClientPolicy& GetPolicy(const std::string& name_space) const;

  // Returns a list of all known namespaces.
  std::vector<std::string> GetAllNamespaces() const;

  // Returns whether pages for |name_space| should be removed on cache reset.
  bool IsRemovedOnCacheReset(const std::string& name_space) const;

  // Returns whether pages for |name_space| are shown in Download UI.
  bool IsSupportedByDownload(const std::string& name_space) const;
  const std::vector<std::string>& GetNamespacesSupportedByDownload() const;

  // Returns whether pages for |name_space| are shown in recent tabs UI,
  // currently only available on NTP.
  bool IsShownAsRecentlyVisitedSite(const std::string& name_space) const;
  const std::vector<std::string>& GetNamespacesShownAsRecentlyVisitedSite()
      const;

  // Returns whether pages for |name_space| should never be shown outside the
  // tab they were generated in.
  bool IsRestrictedToOriginalTab(const std::string& name_space) const;
  const std::vector<std::string>& GetNamespacesRestrictedToOriginalTab() const;

  void AddPolicyForTest(const std::string& name_space,
                        const OfflinePageClientPolicyBuilder& builder);

 private:
  // The map from name_space to a client policy. Will be generated
  // as pre-defined values for now.
  std::map<std::string, OfflinePageClientPolicy> policies_;

  // Memoizing results.
  mutable std::unique_ptr<std::vector<std::string>> download_namespace_cache_;
  mutable std::unique_ptr<std::vector<std::string>> recent_tab_namespace_cache_;
  mutable std::unique_ptr<std::vector<std::string>> show_in_original_tab_cache_;

  DISALLOW_COPY_AND_ASSIGN(ClientPolicyController);
};

}  // namespace offline_pages

#endif  // COMPONENTS_OFFLINE_PAGES_CORE_CLIENT_POLICY_CONTROLLER_H_