text:
package com.hazelcast.map.impl.proxy;

import com.hazelcast.concurrent.lock.LockProxySupport;
import com.hazelcast.concurrent.lock.LockServiceImpl;
import com.hazelcast.config.EntryListenerConfig;
import com.hazelcast.config.ListenerConfig;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapIndexConfig;
import com.hazelcast.config.MapPartitionLostListenerConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.EntryEventType;
import com.hazelcast.core.EntryView;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.core.IFunction;
import com.hazelcast.core.IMap;
import com.hazelcast.core.Member;
import com.hazelcast.core.PartitioningStrategy;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.MapInterceptor;
import com.hazelcast.map.impl.EntryEventFilter;
import com.hazelcast.map.impl.MapEntries;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.map.impl.MapServiceContext;
import com.hazelcast.map.impl.PartitionContainer;
import com.hazelcast.map.impl.event.MapEventPublisher;
import com.hazelcast.map.impl.operation.AddIndexOperation;
import com.hazelcast.map.impl.operation.AddInterceptorOperation;
import com.hazelcast.map.impl.operation.AwaitMapFlushOperation;
import com.hazelcast.map.impl.operation.IsEmptyOperationFactory;
import com.hazelcast.map.impl.operation.IsKeyLoadFinishedOperation;
import com.hazelcast.map.impl.operation.IsPartitionLoadedOperationFactory;
import com.hazelcast.map.impl.operation.MapOperation;
import com.hazelcast.map.impl.operation.MapOperationProvider;
import com.hazelcast.map.impl.operation.RemoveInterceptorOperation;
import com.hazelcast.map.impl.query.MapQueryEngine;
import com.hazelcast.map.impl.query.QueryEventFilter;
import com.hazelcast.map.impl.recordstore.RecordStore;
import com.hazelcast.map.listener.MapListener;
import com.hazelcast.map.listener.MapPartitionLostListener;
import com.hazelcast.monitor.LocalMapStats;
import com.hazelcast.monitor.impl.LocalMapStatsImpl;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.ClassLoaderUtil;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.spi.AbstractDistributedObject;
import com.hazelcast.spi.DefaultObjectNamespace;
import com.hazelcast.spi.EventFilter;
import com.hazelcast.spi.InitializingObject;
import com.hazelcast.spi.InternalCompletableFuture;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.OperationFactory;
import com.hazelcast.spi.OperationService;
import com.hazelcast.spi.annotation.Beta;
import com.hazelcast.spi.impl.BinaryOperationFactory;
import com.hazelcast.spi.partition.IPartition;
import com.hazelcast.spi.partition.IPartitionService;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.spi.properties.HazelcastProperty;
import com.hazelcast.spi.serialization.SerializationService;
import com.hazelcast.util.IterableUtil;
import com.hazelcast.util.MutableLong;
import com.hazelcast.util.ThreadUtil;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.config.MapIndexConfig.validateIndexAttribute;
import static com.hazelcast.core.EntryEventType.CLEAR_ALL;
import static com.hazelcast.map.impl.EntryRemovingProcessor.ENTRY_REMOVING_PROCESSOR;
import static com.hazelcast.map.impl.LocalMapStatsProvider.EMPTY_LOCAL_MAP_STATS;
import static com.hazelcast.map.impl.MapService.SERVICE_NAME;
import static com.hazelcast.util.ExceptionUtil.rethrow;
import static com.hazelcast.util.IterableUtil.nullToEmpty;
import static com.hazelcast.util.Preconditions.checkNotNull;
import static java.lang.Math.ceil;
import static java.lang.Math.log10;
import static java.lang.Math.min;

abstract class MapProxySupport extends AbstractDistributedObject<MapService> implements InitializingObject {

    protected static final String NULL_KEY_IS_NOT_ALLOWED = "Null key is not allowed!";
    protected static final String NULL_VALUE_IS_NOT_ALLOWED = "Null value is not allowed!";
    protected static final String NULL_PREDICATE_IS_NOT_ALLOWED = "Predicate should not be null!";
    protected static final String NULL_LISTENER_IS_NOT_ALLOWED = "Null listener is not allowed!";
    protected static final String NULL_AGGREGATOR_IS_NOT_ALLOWED = "Aggregator should not be null!";
    protected static final String NULL_PROJECTION_IS_NOT_ALLOWED = "Projection should not be null!";

    private static final int INITIAL_WAIT_LOAD_SLEEP_MILLIS = 10;
    private static final int MAXIMAL_WAIT_LOAD_SLEEP_MILLIS = 1000;

    /**
     * Defines the batch size for operations of {@link IMap#putAll(Map)} calls.
     *

     * A value of {@code 0} disables the batching and will send a single operation per member with all map entries.
     *

     * If you set this value too high, you may ran into OOME or blocked network pipelines due to huge operations.
     * If you set this value too low, you will lower the performance of the putAll() operation.
     */
    @Beta
    private static final HazelcastProperty MAP_PUT_ALL_BATCH_SIZE
            = new HazelcastProperty("hazelcast.map.put.all.batch.size", 0);

    /**
     * Defines the initial size of entry arrays per partition for {@link IMap#putAll(Map)} calls.
     *

     * {@link IMap#putAll(Map)} splits up the entries of the user input map per partition,
     * to eventually send the entries the correct target nodes.
     * So the method creates multiple arrays with map entries per partition.
     * This value determines how the initial size of these arrays is calculated.
     *

     * The default value of {@code 0} uses an educated guess, depending on the map size, which is a good overall strategy.
     * If you insert entries which don't match a normal partition distribution you should configure this factor.
     * The initial size is calculated by this formula:
     * {@code initialSize = ceil(MAP_PUT_ALL_INITIAL_SIZE_FACTOR * map.size() / PARTITION_COUNT)}
     *

     * As a rule of thumb you can try the following values:
     *

     *
{@code 10.0} for map sizes up to 500 entries

     *
{@code 5.0} for map sizes between 500 and 5000 entries

     *
{@code 1.5} for map sizes between up to 50000 entries

     *
{@code 1.0} for map sizes beyond 50000 entries

     *

     *

     * If you set this value too high, you will waste memory.
     * If you set this value too low, you will suffer from expensive {@link java.util.Arrays#copyOf} calls.
     */
    @Beta
    private static final HazelcastProperty MAP_PUT_ALL_INITIAL_SIZE_FACTOR
            = new HazelcastProperty("hazelcast.map.put.all.initial.size.factor", 0);

    protected final String name;
    protected final LocalMapStatsImpl localMapStats;
    protected final LockProxySupport lockSupport;
    protected final PartitioningStrategy partitionStrategy;
    protected final MapServiceContext mapServiceContext;
    protected final IPartitionService partitionService;
    protected final Address thisAddress;
    protected final OperationService operationService;
    protected final SerializationService serializationService;
    protected final boolean statisticsEnabled;
    protected final MapConfig mapConfig;
    protected final String localMemberUuid;

    // not final for testing purposes
    protected MapOperationProvider operationProvider;

    private final int putAllBatchSize;
    private final float putAllInitialSizeFactor;

    protected MapProxySupport(String name, MapService service, NodeEngine nodeEngine, MapConfig mapConfig) {
        super(nodeEngine, service);
        this.name = name;

        HazelcastProperties properties = nodeEngine.getProperties();

        this.mapServiceContext = service.getMapServiceContext();
        this.mapConfig = mapConfig;
        this.partitionStrategy = mapServiceContext.getPartitioningStrategy(mapConfig.getName(),
                mapConfig.getPartitioningStrategyConfig());
        this.localMapStats = mapServiceContext.getLocalMapStatsProvider().getLocalMapStatsImpl(name);
        this.partitionService = getNodeEngine().getPartitionService();
        this.lockSupport = new LockProxySupport(new DefaultObjectNamespace(SERVICE_NAME, name),
                LockServiceImpl.getMaxLeaseTimeInMillis(properties));
        this.operationProvider = mapServiceContext.getMapOperationProvider(name);
        this.operationService = nodeEngine.getOperationService();
        this.serializationService = nodeEngine.getSerializationService();
        this.thisAddress = nodeEngine.getClusterService().getThisAddress();
        this.statisticsEnabled = mapConfig.isStatisticsEnabled();
        // it is safe to cache local member uuid here because cluster start must be already completed
        this.localMemberUuid = mapServiceContext.getNodeEngine().getLocalMember().getUuid();

        this.putAllBatchSize = properties.getInteger(MAP_PUT_ALL_BATCH_SIZE);
        this.putAllInitialSizeFactor = properties.getFloat(MAP_PUT_ALL_INITIAL_SIZE_FACTOR);
    }

    @Override
    public void initialize() {
        initializeListeners();
        initializeIndexes();
        initializeMapStoreLoad();
    }

    private void initializeMapStoreLoad() {
        MapStoreConfig mapStoreConfig = getMapConfig().getMapStoreConfig();
        if (mapStoreConfig != null && mapStoreConfig.isEnabled()) {
            MapStoreConfig.InitialLoadMode initialLoadMode = mapStoreConfig.getInitialLoadMode();
            if (MapStoreConfig.InitialLoadMode.EAGER.equals(initialLoadMode)) {
                waitUntilLoaded();
            }
        }
    }

    private void initializeIndexes() {
        for (MapIndexConfig index : getMapConfig().getMapIndexConfigs()) {
            if (index.getAttribute() != null) {
                addIndex(index.getAttribute(), index.isOrdered());
            }
        }
    }

    private void initializeListeners() {
        MapConfig mapConfig = getMapConfig();

        for (EntryListenerConfig listenerConfig : mapConfig.getEntryListenerConfigs()) {
            MapListener listener = initializeListener(listenerConfig);
            if (listener != null) {
                if (listenerConfig.isLocal()) {
                    addLocalEntryListenerInternal(listener);
                } else {
                    addEntryListenerInternal(listener, null, listenerConfig.isIncludeValue());
                }
            }
        }

        for (MapPartitionLostListenerConfig listenerConfig : mapConfig.getPartitionLostListenerConfigs()) {
            MapPartitionLostListener listener = initializeListener(listenerConfig);
            if (listener != null) {
                addPartitionLostListenerInternal(listener);
            }
        }
    }

    private <T extends EventListener> T initializeListener(ListenerConfig listenerConfig) {
        T listener = getListenerImplOrNull(listenerConfig);

        if (listener instanceof HazelcastInstanceAware) {
            ((HazelcastInstanceAware) listener).setHazelcastInstance(getNodeEngine().getHazelcastInstance());
        }

        return listener;
    }

    @SuppressWarnings("unchecked")
    private <T extends EventListener> T getListenerImplOrNull(ListenerConfig listenerConfig) {
        EventListener implementation = listenerConfig.getImplementation();
        if (implementation != null) {

            // for this instanceOf check please see EntryListenerConfig#toEntryListener
            if (implementation instanceof EntryListenerConfig.MapListenerToEntryListenerAdapter) {
                return (T) ((EntryListenerConfig.MapListenerToEntryListenerAdapter) implementation).getMapListener();
            }

            return (T) implementation;
        }

        String className = listenerConfig.getClassName();
        if (className != null) {
            try {
                ClassLoader configClassLoader = getNodeEngine().getConfigClassLoader();
                return ClassLoaderUtil.newInstance(configClassLoader, className);
            } catch (Exception e) {
                throw rethrow(e);
            }
        }

        // returning null to preserve previous behavior
        return null;
    }

    protected Object getInternal(Data key) {
        // todo action for read-backup true is not well tested.
        if (getMapConfig().isReadBackupData()) {
            Object fromBackup = readBackupDataOrNull(key);
            if (fromBackup != null) {
                return fromBackup;
            }
        }
        MapOperation operation = operationProvider.createGetOperation(name, key);
        operation.setThreadId(ThreadUtil.getThreadId());
        return invokeOperation(key, operation);
    }

    private Data readBackupDataOrNull(Data key) {
        int partitionId = partitionService.getPartitionId(key);
        IPartition partition = partitionService.getPartition(partitionId, false);
        if (!partition.isOwnerOrBackup(thisAddress)) {
            return null;
        }
        PartitionContainer partitionContainer = mapServiceContext.getPartitionContainer(partitionId);
        RecordStore recordStore = partitionContainer.getExistingRecordStore(name);
        if (recordStore == null) {
            return null;
        }
        return recordStore.readBackupData(key);
    }

    protected InternalCompletableFuture<Data> getAsyncInternal(Data key) {
        int partitionId = partitionService.getPartitionId(key);

        MapOperation operation = operationProvider.createGetOperation(name, key);
        try {
            long startTime = System.currentTimeMillis();
            InternalCompletableFuture<Data> future = operationService
                    .createInvocationBuilder(SERVICE_NAME, operation, partitionId)
                    .setResultDeserialized(false)
                    .invoke();

            if (statisticsEnabled) {
                future.andThen(new IncrementStatsExecutionCallback<Data>(operation, startTime));
            }

            return future;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected Data putInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createPutOperation(name, key, value, getTimeInMillis(ttl, timeunit));
        return (Data) invokeOperation(key, operation);
    }

    protected boolean tryPutInternal(Data key, Data value, long timeout, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createTryPutOperation(name, key, value, getTimeInMillis(timeout, timeunit));
        return (Boolean) invokeOperation(key, operation);
    }

    protected Data putIfAbsentInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createPutIfAbsentOperation(name, key, value, getTimeInMillis(ttl, timeunit));
        return (Data) invokeOperation(key, operation);
    }

    protected void putTransientInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createPutTransientOperation(name, key, value, getTimeInMillis(ttl, timeunit));
        invokeOperation(key, operation);
    }

    private Object invokeOperation(Data key, MapOperation operation) {
        int partitionId = getNodeEngine().getPartitionService().getPartitionId(key);
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            Object result;
            if (statisticsEnabled) {
                long time = System.currentTimeMillis();
                Future future = operationService
                        .createInvocationBuilder(SERVICE_NAME, operation, partitionId)
                        .setResultDeserialized(false)
                        .invoke();
                result = future.get();
                mapServiceContext.incrementOperationStats(time, localMapStats, name, operation);
            } else {
                Future future = operationService.createInvocationBuilder(SERVICE_NAME, operation, partitionId)
                        .setResultDeserialized(false).invoke();
                result = future.get();
            }
            return result;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected InternalCompletableFuture<Data> putAsyncInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        int partitionId = getNodeEngine().getPartitionService().getPartitionId(key);
        MapOperation operation = operationProvider.createPutOperation(name, key, value, getTimeInMillis(ttl, timeunit));
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            long startTime = System.currentTimeMillis();
            InternalCompletableFuture<Data> future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);

            if (statisticsEnabled) {
                future.andThen(new IncrementStatsExecutionCallback<Data>(operation, startTime));
            }

            return future;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected InternalCompletableFuture<Data> setAsyncInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        int partitionId = getNodeEngine().getPartitionService().getPartitionId(key);
        MapOperation operation = operationProvider.createSetOperation(name, key, value, getTimeInMillis(ttl, timeunit));
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            return operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected boolean replaceInternal(Data key, Data expect, Data update) {
        MapOperation operation = operationProvider.createReplaceIfSameOperation(name, key, expect, update);
        return (Boolean) invokeOperation(key, operation);
    }

    protected Data replaceInternal(Data key, Data value) {
        MapOperation operation = operationProvider.createReplaceOperation(name, key, value);
        return (Data) invokeOperation(key, operation);
    }

    //warning: When UpdateEvent is fired it does *NOT* contain oldValue.
    //see this: https://github.com/hazelcast/hazelcast/pull/6088#issuecomment-136025968
    protected void setInternal(Data key, Data value, long ttl, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createSetOperation(name, key, value, timeunit.toMillis(ttl));
        invokeOperation(key, operation);
    }

    /**
     * Evicts a key from a map.
     *
     * @param key the key to evict
     * @return {@code true} if eviction was successful, {@code false} otherwise
     */
    protected boolean evictInternal(Data key) {
        MapOperation operation = operationProvider.createEvictOperation(name, key, false);
        return (Boolean) invokeOperation(key, operation);
    }

    protected void evictAllInternal() {
        try {
            Operation operation = operationProvider.createEvictAllOperation(name);
            BinaryOperationFactory factory = new BinaryOperationFactory(operation, getNodeEngine());
            Map<Integer, Object> resultMap = operationService.invokeOnAllPartitions(SERVICE_NAME, factory);

            int evictedCount = 0;
            for (Object object : resultMap.values()) {
                evictedCount += (Integer) object;
            }

            if (evictedCount > 0) {
                publishMapEvent(evictedCount, EntryEventType.EVICT_ALL);
            }

        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected void loadAllInternal(boolean replaceExistingValues) {
        int mapNamePartition = partitionService.getPartitionId(name);

        Operation operation = operationProvider.createLoadMapOperation(name, replaceExistingValues);
        Future loadMapFuture = operationService.invokeOnPartition(SERVICE_NAME, operation, mapNamePartition);

        try {
            loadMapFuture.get();
            waitUntilLoaded();
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    /**
     * Maps keys to corresponding partitions and sends operations to them.
     */
    protected void loadInternal(Iterable<Data> dataKeys, boolean replaceExistingValues) {
        Map<Integer, List<Data>> partitionIdToKeys = getPartitionIdToKeysMap(dataKeys);
        Iterable<Entry<Integer, List<Data>>> entries = partitionIdToKeys.entrySet();

        for (Entry<Integer, List<Data>> entry : entries) {
            Integer partitionId = entry.getKey();
            List<Data> correspondingKeys = entry.getValue();
            Operation operation = createLoadAllOperation(correspondingKeys, replaceExistingValues);
            operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
        }

        waitUntilLoaded();
    }

    protected <K> Iterable<Data> convertToData(Iterable<K> keys) {
        return IterableUtil.map(nullToEmpty(keys), new IFunction<K, Data>() {
            public Data apply(K key) {
                return toData(key);
            }
        });
    }

    private Operation createLoadAllOperation(List<Data> keys, boolean replaceExistingValues) {
        return operationProvider.createLoadAllOperation(name, keys, replaceExistingValues);
    }

    protected Data removeInternal(Data key) {
        MapOperation operation = operationProvider.createRemoveOperation(name, key, false);
        return (Data) invokeOperation(key, operation);
    }

    protected void deleteInternal(Data key) {
        MapOperation operation = operationProvider.createDeleteOperation(name, key);
        invokeOperation(key, operation);
    }

    protected boolean removeInternal(Data key, Data value) {
        MapOperation operation = operationProvider.createRemoveIfSameOperation(name, key, value);
        return (Boolean) invokeOperation(key, operation);
    }

    protected boolean tryRemoveInternal(Data key, long timeout, TimeUnit timeunit) {
        MapOperation operation = operationProvider.createTryRemoveOperation(name, key, getTimeInMillis(timeout, timeunit));
        return (Boolean) invokeOperation(key, operation);
    }

    protected void removeAllInternal(Predicate predicate) {
        OperationFactory operation = operationProvider.createPartitionWideEntryWithPredicateOperationFactory(name,
                ENTRY_REMOVING_PROCESSOR, predicate);
        try {
            operationService.invokeOnAllPartitions(SERVICE_NAME, operation);
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected InternalCompletableFuture<Data> removeAsyncInternal(Data key) {
        int partitionId = getNodeEngine().getPartitionService().getPartitionId(key);
        MapOperation operation = operationProvider.createRemoveOperation(name, key, false);
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            long startTime = System.currentTimeMillis();
            InternalCompletableFuture<Data> future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);

            if (statisticsEnabled) {
                future.andThen(new IncrementStatsExecutionCallback<Data>(operation, startTime));
            }

            return future;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected boolean containsKeyInternal(Data key) {
        int partitionId = partitionService.getPartitionId(key);
        MapOperation containsKeyOperation = operationProvider.createContainsKeyOperation(name, key);
        containsKeyOperation.setThreadId(ThreadUtil.getThreadId());
        containsKeyOperation.setServiceName(SERVICE_NAME);
        try {
            Future future = operationService.invokeOnPartition(SERVICE_NAME, containsKeyOperation, partitionId);
            return (Boolean) toObject(future.get());
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public void waitUntilLoaded() {
        try {
            int mapNamePartition = partitionService.getPartitionId(name);
            // first we have to check if key-load finished - otherwise the loading on other partitions might not have started.
            // In this case we can't invoke IsPartitionLoadedOperation -> they will return "true", but it won't be correct.

            int sleepDurationMillis = INITIAL_WAIT_LOAD_SLEEP_MILLIS;
            while (true) {
                Operation op = new IsKeyLoadFinishedOperation(name);
                Future<Boolean> loadingFuture = operationService.invokeOnPartition(SERVICE_NAME, op, mapNamePartition);
                if (loadingFuture.get()) {
                    break;
                }
                // sleep with some back-off
                TimeUnit.MILLISECONDS.sleep(sleepDurationMillis);
                sleepDurationMillis = (sleepDurationMillis * 2 < MAXIMAL_WAIT_LOAD_SLEEP_MILLIS)
                        ? sleepDurationMillis * 2 : MAXIMAL_WAIT_LOAD_SLEEP_MILLIS;
            }

            OperationFactory opFactory = new IsPartitionLoadedOperationFactory(name);
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, opFactory);
            // wait for all the data to be loaded on all partitions - wait forever
            waitAllTrue(results, opFactory);
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    private void waitAllTrue(Map<Integer, Object> results, OperationFactory operationFactory) throws InterruptedException {
        Iterator<Entry<Integer, Object>> iterator = results.entrySet().iterator();
        boolean isFinished = false;
        Set<Integer> retrySet = new HashSet<Integer>();
        while (!isFinished) {
            while (iterator.hasNext()) {
                Entry<Integer, Object> entry = iterator.next();
                if (Boolean.TRUE.equals(entry.getValue())) {
                    iterator.remove();
                } else {
                    retrySet.add(entry.getKey());
                }
            }
            if (retrySet.size() > 0) {
                results = retryPartitions(retrySet, operationFactory);
                iterator = results.entrySet().iterator();
                TimeUnit.SECONDS.sleep(1);
                retrySet.clear();
            } else {
                isFinished = true;
            }
        }
    }

    private Map<Integer, Object> retryPartitions(Collection<Integer> partitions, OperationFactory operationFactory) {
        try {
            return operationService.invokeOnPartitions(SERVICE_NAME, operationFactory, partitions);
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public int size() {
        try {
            OperationFactory sizeOperationFactory = operationProvider.createMapSizeOperationFactory(name);
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, sizeOperationFactory);
            int total = 0;
            for (Object result : results.values()) {
                Integer size = toObject(result);
                total += size;
            }
            return total;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public boolean containsValueInternal(Data dataValue) {
        try {
            OperationFactory operationFactory = operationProvider.createContainsValueOperationFactory(name, dataValue);
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, operationFactory);
            for (Object result : results.values()) {
                Boolean contains = toObject(result);
                if (contains) {
                    return true;
                }
            }
            return false;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public boolean isEmpty() {
        try {
            // TODO: we don't need to wait for all futures to complete, we can stop on the first returned false
            // also there is no need to make use of IsEmptyOperation, just use size to reduce the amount of code
            IsEmptyOperationFactory factory = new IsEmptyOperationFactory(name);
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, factory);
            for (Object result : results.values()) {
                if (!(Boolean) toObject(result)) {
                    return false;
                }
            }
            return true;
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected void getAllObjectInternal(List<Data> keys, List<Object> resultingKeyValuePairs) {
        if (keys == null || keys.isEmpty()) {
            return;
        }
        if (keys.isEmpty()) {
            return;
        }
        Collection<Integer> partitions = getPartitionsForKeys(keys);
        Map<Integer, Object> responses;
        try {
            OperationFactory operationFactory = operationProvider.createGetAllOperationFactory(name, keys);
            long time = System.currentTimeMillis();
            responses = operationService.invokeOnPartitions(SERVICE_NAME, operationFactory, partitions);
            for (Object response : responses.values()) {
                MapEntries entries = toObject(response);
                for (int i = 0; i < entries.size(); i++) {
                    resultingKeyValuePairs.add(toObject(entries.getKey(i)));
                    resultingKeyValuePairs.add(toObject(entries.getValue(i)));
                }
            }
            localMapStats.incrementGets(keys.size(), System.currentTimeMillis() - time);
        } catch (Exception e) {
            throw rethrow(e);
        }
    }

    private Collection<Integer> getPartitionsForKeys(Collection<Data> keys) {
        int partitions = partitionService.getPartitionCount();
        // TODO: is there better way to estimate the size?
        int capacity = min(partitions, keys.size());
        Set<Integer> partitionIds = new HashSet<Integer>(capacity);

        Iterator<Data> iterator = keys.iterator();
        while (iterator.hasNext() && partitionIds.size() < partitions) {
            Data key = iterator.next();
            partitionIds.add(partitionService.getPartitionId(key));
        }
        return partitionIds;
    }

    private Map<Integer, List<Data>> getPartitionIdToKeysMap(Iterable<Data> keys) {
        if (keys == null) {
            return Collections.emptyMap();
        }

        Map<Integer, List<Data>> idToKeys = new HashMap<Integer, List<Data>>();
        for (Data key : keys) {
            int partitionId = partitionService.getPartitionId(key);
            List<Data> keyList = idToKeys.get(partitionId);
            if (keyList == null) {
                keyList = new ArrayList<Data>();
                idToKeys.put(partitionId, keyList);
            }
            keyList.add(key);
        }
        return idToKeys;
    }

    private boolean isPutAllUseBatching(int mapSize) {
        // we check if the feature is enabled and if the map size is bigger than a single batch per member
        return (putAllBatchSize > 0 && mapSize > putAllBatchSize * getNodeEngine().getClusterService().getSize());
    }

    @SuppressWarnings("checkstyle:magicnumber")
    private int getPutAllInitialSize(boolean useBatching, int mapSize, int partitionCount) {
        if (mapSize == 1) {
            return 1;
        }
        if (useBatching) {
            return putAllBatchSize;
        }
        if (putAllInitialSizeFactor < 1) {
            // this is an educated guess for the initial size of the entries per partition, depending on the map size
            return (int) ceil(20f * mapSize / partitionCount / log10(mapSize));
        }
        return (int) ceil(putAllInitialSizeFactor * mapSize / partitionCount);
    }

    /**
     * This method will group all puts per partition and send a
     * {@link com.hazelcast.map.impl.operation.PutAllPartitionAwareOperationFactory} per member.
     *

     * If there are e.g. five keys for a single member, there will only be a single remote invocation
     * instead of having five remote invocations.
     *

     * There is also an optional support for batching to send smaller packages.
     * Takes care about {@code null} checks for keys and values.
     */
    @SuppressWarnings({"checkstyle:npathcomplexity", "UnnecessaryBoxing"})
    @SuppressFBWarnings(value = "DM_NUMBER_CTOR", justification = "we need a shared counter object for each member per partition")
    protected void putAllInternal(Map<?, ?> map) {
        try {
            int mapSize = map.size();
            if (mapSize == 0) {
                return;
            }

            boolean useBatching = isPutAllUseBatching(mapSize);
            int partitionCount = partitionService.getPartitionCount();
            int initialSize = getPutAllInitialSize(useBatching, mapSize, partitionCount);

            Map<Address, List<Integer>> memberPartitionsMap = partitionService.getMemberPartitionsMap();

            // init counters for batching
            MutableLong[] counterPerMember = null;
            Address[] addresses = null;
            if (useBatching) {
                counterPerMember = new MutableLong[partitionCount];
                addresses = new Address[partitionCount];
                for (Entry<Address, List<Integer>> addressListEntry : memberPartitionsMap.entrySet()) {
                    MutableLong counter = new MutableLong();
                    Address address = addressListEntry.getKey();
                    for (int partitionId : addressListEntry.getValue()) {
                        counterPerMember[partitionId] = counter;
                        addresses[partitionId] = address;
                    }
                }
            }

            // fill entriesPerPartition
            MapEntries[] entriesPerPartition = new MapEntries[partitionCount];
            for (Entry entry : map.entrySet()) {
                checkNotNull(entry.getKey(), NULL_KEY_IS_NOT_ALLOWED);
                checkNotNull(entry.getValue(), NULL_VALUE_IS_NOT_ALLOWED);

                Data keyData = toData(entry.getKey(), partitionStrategy);
                int partitionId = partitionService.getPartitionId(keyData);
                MapEntries entries = entriesPerPartition[partitionId];
                if (entries == null) {
                    entries = new MapEntries(initialSize);
                    entriesPerPartition[partitionId] = entries;
                }

                entries.add(keyData, toData(entry.getValue()));

                if (useBatching) {
                    long currentSize = ++counterPerMember[partitionId].value;
                    if (currentSize % putAllBatchSize == 0) {
                        List<Integer> partitions = memberPartitionsMap.get(addresses[partitionId]);
                        invokePutAllOperation(addresses[partitionId], partitions, entriesPerPartition);
                    }
                }
            }

            // invoke operations for entriesPerPartition
            for (Entry<Address, List<Integer>> entry : memberPartitionsMap.entrySet()) {
                invokePutAllOperation(entry.getKey(), entry.getValue(), entriesPerPartition);
            }
        } catch (Exception e) {
            throw rethrow(e);
        }
    }

    private void invokePutAllOperation(Address address, List<Integer> memberPartitions, MapEntries[] entriesPerPartition)
            throws Exception {
        int size = memberPartitions.size();
        int[] partitions = new int[size];
        int index = 0;
        for (Integer partitionId : memberPartitions) {
            if (entriesPerPartition[partitionId] != null) {
                partitions[index++] = partitionId;
            }
        }
        if (index == 0) {
            return;
        }
        // trim partition array to real size
        if (index < size) {
            partitions = Arrays.copyOf(partitions, index);
            size = index;
        }

        index = 0;
        MapEntries[] entries = new MapEntries[size];
        long totalSize = 0;
        for (int partitionId : partitions) {
            int batchSize = entriesPerPartition[partitionId].size();
            assert (putAllBatchSize == 0 || batchSize <= putAllBatchSize);
            entries[index++] = entriesPerPartition[partitionId];
            totalSize += batchSize;
            entriesPerPartition[partitionId] = null;
        }
        if (totalSize == 0) {
            return;
        }

        invokePutAllOperationFactory(address, totalSize, partitions, entries);
    }

    protected void invokePutAllOperationFactory(Address address, final long size, int[] partitions, MapEntries[] entries)
            throws Exception {
        OperationFactory factory = operationProvider.createPutAllOperationFactory(name, partitions, entries);
        final long time = System.currentTimeMillis();
        operationService.invokeOnPartitions(SERVICE_NAME, factory, partitions);
        localMapStats.incrementPuts(size, System.currentTimeMillis() - time);
    }

    // TODO: add a feature to mancenter to sync cache to db completely
    public void flush() {
        try {
            MapOperation mapFlushOperation = operationProvider.createMapFlushOperation(name);
            BinaryOperationFactory operationFactory = new BinaryOperationFactory(mapFlushOperation, getNodeEngine());
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, operationFactory);

            List<Future> futures = new ArrayList<Future>();
            for (Entry<Integer, Object> entry : results.entrySet()) {
                Integer partitionId = entry.getKey();
                Long count = ((Long) entry.getValue());
                if (count != 0) {
                    Operation operation = new AwaitMapFlushOperation(name, count);
                    futures.add(operationService.invokeOnPartition(MapService.SERVICE_NAME, operation, partitionId));
                }
            }

            for (Future future : futures) {
                future.get();
            }

        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public void clearInternal() {
        try {
            Operation clearOperation = operationProvider.createClearOperation(name);
            clearOperation.setServiceName(SERVICE_NAME);
            BinaryOperationFactory factory = new BinaryOperationFactory(clearOperation, getNodeEngine());
            Map<Integer, Object> resultMap = operationService.invokeOnAllPartitions(SERVICE_NAME, factory);

            int clearedCount = 0;
            for (Object object : resultMap.values()) {
                clearedCount += (Integer) object;
            }

            if (clearedCount > 0) {
                publishMapEvent(clearedCount, CLEAR_ALL);
            }

        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public String addMapInterceptorInternal(MapInterceptor interceptor) {
        NodeEngine nodeEngine = getNodeEngine();
        if (interceptor instanceof HazelcastInstanceAware) {
            ((HazelcastInstanceAware) interceptor).setHazelcastInstance(nodeEngine.getHazelcastInstance());
        }
        String id = mapServiceContext.generateInterceptorId(name, interceptor);
        Collection<Member> members = nodeEngine.getClusterService().getMembers();
        for (Member member : members) {
            try {
                AddInterceptorOperation op = new AddInterceptorOperation(id, interceptor, name);
                Future future = operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());
                future.get();
            } catch (Throwable t) {
                throw rethrow(t);
            }
        }
        return id;
    }

    public void removeMapInterceptorInternal(String id) {
        NodeEngine nodeEngine = getNodeEngine();
        mapServiceContext.removeInterceptor(name, id);
        Collection<Member> members = nodeEngine.getClusterService().getMembers();
        for (Member member : members) {
            try {
                if (member.localMember()) {
                    continue;
                }
                RemoveInterceptorOperation op = new RemoveInterceptorOperation(name, id);
                Future future = operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());
                future.get();
            } catch (Throwable t) {
                throw rethrow(t);
            }
        }
    }

    public String addLocalEntryListenerInternal(Object listener) {
        return mapServiceContext.addLocalEventListener(listener, name);
    }

    public String addLocalEntryListenerInternal(Object listener, Predicate predicate, Data key, boolean includeValue) {
        EventFilter eventFilter = new QueryEventFilter(includeValue, key, predicate);
        return mapServiceContext.addLocalEventListener(listener, eventFilter, name);
    }

    protected String addEntryListenerInternal(Object listener, Data key, boolean includeValue) {
        EventFilter eventFilter = new EntryEventFilter(includeValue, key);
        return mapServiceContext.addEventListener(listener, eventFilter, name);
    }

    protected String addEntryListenerInternal(Object listener, Predicate predicate, Data key, boolean includeValue) {
        EventFilter eventFilter = new QueryEventFilter(includeValue, key, predicate);
        return mapServiceContext.addEventListener(listener, eventFilter, name);
    }

    protected boolean removeEntryListenerInternal(String id) {
        return mapServiceContext.removeEventListener(name, id);
    }

    protected String addPartitionLostListenerInternal(MapPartitionLostListener listener) {
        return mapServiceContext.addPartitionLostListener(listener, name);
    }

    protected boolean removePartitionLostListenerInternal(String id) {
        return mapServiceContext.removePartitionLostListener(name, id);
    }

    protected EntryView getEntryViewInternal(Data key) {
        int partitionId = partitionService.getPartitionId(key);
        MapOperation operation = operationProvider.createGetEntryViewOperation(name, key);
        operation.setThreadId(ThreadUtil.getThreadId());
        operation.setServiceName(SERVICE_NAME);
        try {
            Future future = operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
            return (EntryView) toObject(future.get());
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public Data executeOnKeyInternal(Data key, EntryProcessor entryProcessor) {
        int partitionId = partitionService.getPartitionId(key);
        MapOperation operation = operationProvider.createEntryOperation(name, key, entryProcessor);
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            Future future = operationService
                    .createInvocationBuilder(SERVICE_NAME, operation, partitionId)
                    .setResultDeserialized(false)
                    .invoke();
            return (Data) future.get();
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public Map executeOnKeysInternal(Set<Data> keys, EntryProcessor entryProcessor) {
        // TODO: why are we not forwarding to executeOnKeysInternal(keys, entryProcessor, null) or some other kind of fake
        // callback? now there is a lot of code duplication
        Map<Object, Object> result = new HashMap<Object, Object>();
        Collection<Integer> partitionsForKeys = getPartitionsForKeys(keys);
        try {
            OperationFactory operationFactory = operationProvider.createMultipleEntryOperationFactory(name, keys, entryProcessor);
            Map<Integer, Object> results = operationService.invokeOnPartitions(SERVICE_NAME, operationFactory, partitionsForKeys);
            for (Object object : results.values()) {
                if (object != null) {
                    MapEntries mapEntries = (MapEntries) object;
                    mapEntries.putAllToMap(serializationService, result);
                }
            }
        } catch (Throwable t) {
            throw rethrow(t);
        }
        return result;
    }

    public InternalCompletableFuture<Object> executeOnKeyInternal(
            Data key, EntryProcessor entryProcessor, ExecutionCallback<Object> callback) {
        int partitionId = partitionService.getPartitionId(key);
        MapOperation operation = operationProvider.createEntryOperation(name, key, entryProcessor);
        operation.setThreadId(ThreadUtil.getThreadId());
        try {
            if (callback == null) {
                return operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId);
            } else {
                return operationService
                        .createInvocationBuilder(SERVICE_NAME, operation, partitionId)
                        .setExecutionCallback(new MapExecutionCallbackAdapter(callback))
                        .invoke();
            }
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    /**
     * {@link IMap#executeOnEntries(EntryProcessor, Predicate)}
     */
    public void executeOnEntriesInternal(EntryProcessor entryProcessor, Predicate predicate, List<Data> result) {
        try {
            OperationFactory operation
                    = operationProvider.createPartitionWideEntryWithPredicateOperationFactory(name, entryProcessor, predicate);
            Map<Integer, Object> results = operationService.invokeOnAllPartitions(SERVICE_NAME, operation);
            for (Object object : results.values()) {
                if (object != null) {
                    MapEntries mapEntries = (MapEntries) object;
                    for (int i = 0; i < mapEntries.size(); i++) {
                        result.add(mapEntries.getKey(i));
                        result.add(mapEntries.getValue(i));
                    }
                }
            }
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    protected <T> T toObject(Object object) {
        return serializationService.toObject(object);
    }

    protected Data toData(Object object, PartitioningStrategy partitioningStrategy) {
        return serializationService.toData(object, partitioningStrategy);
    }

    public void addIndex(String attribute, boolean ordered) {
        validateIndexAttribute(attribute);
        try {
            AddIndexOperation addIndexOperation = new AddIndexOperation(name, attribute, ordered);
            operationService.invokeOnAllPartitions(SERVICE_NAME, new BinaryOperationFactory(addIndexOperation, getNodeEngine()));
        } catch (Throwable t) {
            throw rethrow(t);
        }
    }

    public LocalMapStats getLocalMapStats() {
        if (!mapConfig.isStatisticsEnabled()) {
            return EMPTY_LOCAL_MAP_STATS;
        }
        return mapServiceContext.getLocalMapStatsProvider().createLocalMapStats(name);
    }

    private void publishMapEvent(int numberOfAffectedEntries, EntryEventType eventType) {
        MapEventPublisher mapEventPublisher = mapServiceContext.getMapEventPublisher();
        mapEventPublisher.publishMapEvent(thisAddress, name, eventType, numberOfAffectedEntries);
    }

    protected long getTimeInMillis(long time, TimeUnit timeunit) {
        long timeInMillis = timeunit.toMillis(time);
        if (time > 0 && timeInMillis == 0) {
            timeInMillis = 1;
        }
        return timeInMillis;
    }

    protected MapQueryEngine getMapQueryEngine() {
        return mapServiceContext.getMapQueryEngine(name);
    }

    protected boolean isMapStoreEnabled() {
        MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
        return mapStoreConfig != null && mapStoreConfig.isEnabled();
    }

    protected MapConfig getMapConfig() {
        return mapConfig;
    }

    @Override
    public final String getName() {
        return name;
    }

    @Override
    public final String getServiceName() {
        return SERVICE_NAME;
    }

    public PartitioningStrategy getPartitionStrategy() {
        return partitionStrategy;
    }

    private class MapExecutionCallbackAdapter implements ExecutionCallback<Object> {

        private final ExecutionCallback<Object> executionCallback;

        MapExecutionCallbackAdapter(ExecutionCallback<Object> executionCallback) {
            this.executionCallback = executionCallback;
        }

        @Override
        public void onResponse(Object response) {
            executionCallback.onResponse(toObject(response));
        }

        @Override
        public void onFailure(Throwable t) {
            executionCallback.onFailure(t);
        }
    }

    private class IncrementStatsExecutionCallback<T> implements ExecutionCallback<T> {

        private final MapOperation operation;
        private final long startTime;

        IncrementStatsExecutionCallback(MapOperation operation, long startTime) {
            this.operation = operation;
            this.startTime = startTime;
        }

        @Override
        public void onResponse(T response) {
            mapServiceContext.incrementOperationStats(startTime, localMapStats, name, operation);
        }

        @Override
        public void onFailure(Throwable t) {
        }
    }

    public void setOperationProvider(MapOperationProvider operationProvider) {
        this.operationProvider = operationProvider;
    }

    public MapOperationProvider getOperationProvider() {
        return operationProvider;
    }

    public int getTotalBackupCount() {
        return mapConfig.getBackupCount() + mapConfig.getAsyncBackupCount();
    }
}


text:
package org.usfirst.frc.team910.robot.Subsystems;

import org.usfirst.frc.team910.robot.IO.Inputs;
import org.usfirst.frc.team910.robot.IO.Outputs;

public class Climber {
	private Outputs out;
	private Inputs in;

	private static final double SHIFT_FACTOR = 0.6;
	private static final double CLIMB_POWER = 1;
	private static final double REVERSE_CLIMB_POWER = 0.15;

	public Climber(Outputs out, Inputs in) {
		this.out = out;
		this.in = in;
	}

	public void run() {
		if (in.autoClimb || in.autoGear || in.autoShoot || in.autoHopper) {

		} else if (in.reverseButton && in.climbButton) {
			climb(-REVERSE_CLIMB_POWER);
		} else if (in.climbButton) {
			if(in.shift){
				climb(CLIMB_POWER * SHIFT_FACTOR);
			} else {
				climb(CLIMB_POWER);
			}
		} else {
			climb(0);

		}
	}

	public void climb(double climbPower) { // TODO: stop when we hit the top
		out.setClimbPower(climbPower);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

class ServiceBuilder{

    public function getService($service){
        return array('name' => $service->service_trigger);
    }

}


text:
using Mirabeau.uTransporter.Builders;

using Umbraco.Core.Models;

namespace Mirabeau.uTransporter.UnitTests.Stubs
{
    public class ContentTypeWithoutAliasBuilder : ContentTypeBuilder
    {
        public ContentTypeWithoutAliasBuilder(int parentId)
            : base(parentId)
        {
        }

        public override IContentType Build()
        {
            IContentType contentType = new ContentType(_parentId);
            contentType.Name = _name;
            contentType.AllowedAsRoot = _allowedAtRoot;
            contentType.AllowedTemplates = _allowedTemplates;
            contentType.Description = _description;
            contentType.Icon = _icon;
            contentType.Thumbnail = _thumbnail;
            contentType.SetDefaultTemplate(_defaultTemplate);

            return contentType;
        }
    }
}


text:
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import * as ReactRouter from 'react-router'
import * as H from 'history'
import { createContainer, query, BodyRenderer } from '@phenomic/preset-react-app/lib/client';

interface RouterProvidedContainerProps {
  children:React.ReactElement<any>,
  location:H.Location,
  router:H.History,
  route:ReactRouter.PlainRoute,
  routes:ReactRouter.PlainRoute[],
  params:any,
  routeParams:any,
  page:{status:string, node:any},
  isLoading:boolean
}

const BlogPost = (props:RouterProvidedContainerProps) => {
  return (

      {props.page.node &&

          <BodyRenderer>{props.page.node.body}</BodyRenderer>

}

  )
}

const BlogPostContainer = createContainer(BlogPost, (props:any) => ({
  page: query({ collection: 'posts', id: props.params.splat })
}));

export default BlogPostContainer


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cosmos.Sys.FileSystem.FAT32
{
    public class DirectoryTable
    {
        FAT fat;
        uint cluster;
        public DirectoryTable(FAT fat, uint cluster)
        {
            this.fat = fat;
            this.cluster = cluster;
        }

    }
}


text:
namespace ui {

// The data associated with an accessibility tree that's global to the
// tree and not associated with any particular node in the tree.
struct AX_BASE_EXPORT AXTreeData {
  AXTreeData();
  AXTreeData(const AXTreeData& other);
  virtual ~AXTreeData();

  // Return a string representation of this data, for debugging.
  virtual std::string ToString() const;

  // This is a simple serializable struct. All member variables should be
  // public and copyable.

  // The globally unique ID of this accessibility tree.
  AXTreeID tree_id;

  // The ID of the accessibility tree that this tree is contained in, if any.
  AXTreeID parent_tree_id;

  // The ID of the accessibility tree that has focus. This is typically set
  // on the root frame in a frame tree.
  AXTreeID focused_tree_id;

  // Attributes specific to trees that are web frames.
  std::string doctype;
  bool loaded = false;
  float loading_progress = 0.0f;
  std::string mimetype;
  std::string title;
  std::string url;

  // The node with keyboard focus within this tree, if any, or
  // kInvalidAXNodeID if no node in this tree has focus.
  AXNodeID focus_id = kInvalidAXNodeID;

  // The current text selection within this tree, if any, expressed as the
  // node ID and character offset of the anchor (selection start) and focus
  // (selection end). If the offset could correspond to a position on two
  // different lines, sel_upstream_affinity means the cursor is on the first
  // line, otherwise it's on the second line.
  // Most use cases will want to use ui::OwnerTree::GetUnignoredSelection.
  bool sel_is_backward = false;
  AXNodeID sel_anchor_object_id = kInvalidAXNodeID;
  int32_t sel_anchor_offset = -1;
  ax::mojom::TextAffinity sel_anchor_affinity;
  AXNodeID sel_focus_object_id = kInvalidAXNodeID;
  int32_t sel_focus_offset = -1;
  ax::mojom::TextAffinity sel_focus_affinity;

  // The node that's used as the root scroller. On some platforms
  // like Android we need to ignore accessibility scroll offsets for
  // that node and get them from the viewport instead.
  AXNodeID root_scroller_id = kInvalidAXNodeID;

  // Metadata from an HTML HEAD, such as <meta> tags. Stored here
  // unparsed because the only applications that need these just want
  // raw strings. Only included if the kHTMLMetadata AXMode is enabled.
  std::vector<std::string> metadata;
};

AX_BASE_EXPORT bool operator==(const AXTreeData& lhs, const AXTreeData& rhs);
AX_BASE_EXPORT bool operator!=(const AXTreeData& lhs, const AXTreeData& rhs);

}  // namespace ui

#endif  // UI_ACCESSIBILITY_AX_TREE_DATA_H_


text:
using System;
using NUnit.Framework;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers.Bases;
using net.authorize.sample;
using System.IO;
using System.Reflection;
using AuthorizeNet;
using net.authorize.sample.PaymentTransactions;
using System.Threading;
using net.authorize.sample.CustomerProfiles;
using net.authorize.sample.MobileInappTransactions;
#if NETCOREAPP2_0
using AuthorizeNet.Utilities;
#endif

namespace SampleCodeTest
{
    [TestFixture]
    public class TestRunner
    {
        string apiLoginId = Constants.API_LOGIN_ID;
        string transactionKey = Constants.TRANSACTION_KEY;
        string TransactionID = Constants.TRANSACTION_ID;
        string payerID = Constants.PAYER_ID;

        static CryptoRandom r = new CryptoRandom();

        private static string GetEmail()
        {
            return r.Next(1000, 89999999) + "@test.com";
        }

        private static decimal GetAmount()
        {
            return r.Next(10, 200);
        }

        private static short GetMonth()
        {
            return (Int16)r.Next(7, 365);
        }

        [Test]
        public void TestAllSampleCodes()
        {

#if NETCOREAPP2_0
            // DOTNET CORE SPECIFIC
            #region DOTNET CORE SPECIFIC

            ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
            ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpUseProxy = AuthorizeNet.Environment.getBooleanProperty(AuthorizeNet.Utilities.Constants.HttpsUseProxy);

            if(ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpUseProxy)
            {
                ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpUseProxy = AuthorizeNet.Environment.getBooleanProperty(AuthorizeNet.Utilities.Constants.HttpsUseProxy);
                ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpsProxyUsername = AuthorizeNet.Environment.GetProperty(AuthorizeNet.Utilities.Constants.HttpsProxyUsername);
                ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpsProxyPassword = AuthorizeNet.Environment.GetProperty(AuthorizeNet.Utilities.Constants.HttpsProxyPassword);
                ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpProxyHost = AuthorizeNet.Environment.GetProperty(AuthorizeNet.Utilities.Constants.HttpsProxyHost);
                ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpProxyPort = AuthorizeNet.Environment.getIntProperty(AuthorizeNet.Utilities.Constants.HttpsProxyPort);
            }

            #endregion
#endif

            try
            {
                string fileName = Constants.CONFIG_FILE;
                using (StreamReader reader = File.OpenText(fileName))
                {
                    TestRunner tr = new TestRunner();
                    var numRetries = 3;

                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] items = line.Split('\t');

                        string apiName = items[0];
                        string isDependent = items[1];
                        string shouldApiRun = items[2];

                        if (!shouldApiRun.Equals("1"))
                            continue;

                        Console.WriteLine(new String('-', 20));
                        Console.WriteLine("Running test case for :: " + apiName);
                        Console.WriteLine(new String('-', 20));
                        ANetApiResponse response = null;
                        for (int i = 0; i < numRetries; ++i)
                        {
                            try
                            {
                                if (isDependent.Equals("0"))
                                {
                                    response = InvokeRunMethod(apiName);
                                }
                                else
                                {
                                    response = (ANetApiResponse)typeof(TestRunner).GetMethod("Test" + apiName).Invoke(tr, new Object[] { });
                                }

                                if ((response != null) && (response.messages.resultCode == messageTypeEnum.Ok))
                                    break;
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(apiName);
                                Console.WriteLine(e.ToString());
                            }
                        }
                        Assert.IsNotNull(response);
                        Assert.AreEqual(response.messages.resultCode, messageTypeEnum.Ok);
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public ANetApiResponse InvokeRunMethod(string className)
        {
            string namespaceString = "net.authorize.sample.";

            if (className.Equals(typeof(UpdateSplitTenderGroup).Name))
                namespaceString = namespaceString + "PaymentTransactions.";

            if (className.Equals(typeof(CreateAnApplePayTransaction).Name))
                namespaceString = namespaceString + "ApplePayTransactions.";
            Type classType = null;
#if NETCOREAPP2_0
            classType = Type.GetType(namespaceString + className + ",SampleCode_DotNet_Core");
#else
               classType = Type.GetType(namespaceString + className + ",SampleCode");
#endif
            return (ANetApiResponse)classType.GetMethod("Run").Invoke(null, new Object[] { apiLoginId, transactionKey });
        }

        public ANetApiResponse TestValidateCustomerPaymentProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var customerPaymentProfile = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            var validateResponse = ValidateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId, customerPaymentProfile.customerPaymentProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return validateResponse;
        }

        public ANetApiResponse TestCaptureFundsAuthorizedThroughAnotherChannel()
        {
            return CaptureFundsAuthorizedThroughAnotherChannel.Run(apiLoginId, transactionKey, GetAmount());
        }

        public ANetApiResponse TestDebitBankAccount()
        {
            return DebitBankAccount.Run(apiLoginId, transactionKey, GetAmount());
        }

        public ANetApiResponse TestUpdateCustomerShippingAddress()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var shippingResponse = (createCustomerShippingAddressResponse)CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, response.customerProfileId);
            var updateResponse = (updateCustomerShippingAddressResponse)UpdateCustomerShippingAddress.Run(apiLoginId, transactionKey, response.customerProfileId, shippingResponse.customerAddressId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return updateResponse;
        }

        public ANetApiResponse TestUpdateCustomerProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var updateResponse = UpdateCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return updateResponse;
        }

        public ANetApiResponse TestUpdateCustomerPaymentProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var paymentProfileResponse = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            var updateResponse = UpdateCustomerPaymentProfile.Run(apiLoginId, transactionKey,
                response.customerProfileId, paymentProfileResponse.customerPaymentProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return updateResponse;
        }

        public ANetApiResponse TestGetCustomerShippingAddress()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var shippingResponse = (createCustomerShippingAddressResponse)CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, response.customerProfileId);

            var getResponse = GetCustomerShippingAddress.Run(apiLoginId, transactionKey,
                response.customerProfileId, shippingResponse.customerAddressId);

            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            return getResponse;
        }

        public ANetApiResponse TestGetCustomerProfileIds()
        {
            return GetCustomerProfileIds.Run(apiLoginId, transactionKey);
        }

        public ANetApiResponse TestGetCustomerProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var profileResponse = GetCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return profileResponse;
        }

        public ANetApiResponse TestGetAcceptCustomerProfilePage()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var profileResponse = GetAcceptCustomerProfilePage.Run(apiLoginId, transactionKey, response.customerProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return profileResponse;
        }

        public ANetApiResponse TestGetCustomerPaymentProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var paymentProfileResponse = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            var getResponse = GetCustomerPaymentProfile.Run(apiLoginId, transactionKey,
                response.customerProfileId, paymentProfileResponse.customerPaymentProfileId);

            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            return getResponse;
        }

        public ANetApiResponse TestDeleteCustomerShippingAddress()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var shippingResponse = (createCustomerShippingAddressResponse)CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, response.customerProfileId);
            var deleteResponse = DeleteCustomerShippingAddress.Run(apiLoginId, transactionKey,
                response.customerProfileId, shippingResponse.customerAddressId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return deleteResponse;
        }

        public ANetApiResponse TestDeleteCustomerProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            return DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
        }

        public ANetApiResponse TestDeleteCustomerPaymentProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var paymentProfileResponse = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            var deleteResponse = DeleteCustomerPaymentProfile.Run(apiLoginId, transactionKey,
                response.customerProfileId, paymentProfileResponse.customerPaymentProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return deleteResponse;
        }

        public ANetApiResponse TestCreateCustomerShippingAddress()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var shippingResponse = (createCustomerShippingAddressResponse)CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, response.customerProfileId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return shippingResponse;
        }

        public ANetApiResponse TestAuthorizeCreditCard()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            return response;
        }

        public ANetApiResponse TestCreateCustomerProfileFromTransaction()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            var profileResponse = (createCustomerProfileResponse)CreateCustomerProfileFromTransaction.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, profileResponse.customerProfileId);

            return profileResponse;
        }

        public ANetApiResponse TestGetTransactionDetails()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            return GetTransactionDetails.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
        }

        public ANetApiResponse TestChargeCreditCard()
        {
            return ChargeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
        }

        public ANetApiResponse TestCapturePreviouslyAuthorizedgetAmount()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            return CapturePreviouslyAuthorizedAmount.Run(apiLoginId, transactionKey, GetAmount(), response.transactionResponse.transId);
        }

        public ANetApiResponse TestRefund()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            response = (createTransactionResponse)CapturePreviouslyAuthorizedAmount.Run(apiLoginId, transactionKey, GetAmount(), response.transactionResponse.transId);
            return RefundTransaction.Run(apiLoginId, transactionKey, GetAmount(), response.transactionResponse.transId);
        }

        public ANetApiResponse TestVoid()
        {
            var response = (createTransactionResponse)AuthorizeCreditCard.Run(apiLoginId, transactionKey, GetAmount());
            return VoidTransaction.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
        }

        public ANetApiResponse TestCreditBankAccount()
        {
            return CreditBankAccount.Run(apiLoginId, transactionKey, TransactionID);
        }

        public ANetApiResponse TestChargeCustomerProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var paymentProfileResponse = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
            var chargeResponse = ChargeCustomerProfile.Run(apiLoginId, transactionKey,
                response.customerProfileId, paymentProfileResponse.customerPaymentProfileId, GetAmount());
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, response.customerProfileId);

            return chargeResponse;
        }

        public ANetApiResponse TestPayPalAuthorizeOnly()
        {
            return PayPalAuthorizeOnly.Run(apiLoginId, transactionKey, GetAmount());
        }

        public ANetApiResponse TestPayPalVoid()
        {
            var response = (createTransactionResponse)PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, GetAmount());
            return PayPalVoid.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
        }

        public ANetApiResponse TestPayPalAuthorizeCapture()
        {
            return PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, GetAmount());
        }

        public ANetApiResponse TestPayPalAuthorizeCaptureContinued()
        {
            var response = (createTransactionResponse)PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, GetAmount());
            return PayPalAuthorizeCaptureContinued.Run(apiLoginId, transactionKey, response.transactionResponse.transId, payerID);
        }

        public ANetApiResponse TestPayPalAuthorizeOnlyContinued()
        {
            return PayPalAuthorizeOnlyContinued.Run(apiLoginId, transactionKey, TransactionID, payerID);
        }

        public ANetApiResponse TestPayPalCredit()
        {
            return PayPalCredit.Run(apiLoginId, transactionKey, TransactionID);
        }

        public ANetApiResponse TestPayPalGetDetails()
        {
            var response = (createTransactionResponse)PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, GetAmount());
            return PayPalGetDetails.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
        }

        public ANetApiResponse TestPayPalPriorAuthorizationCapture()
        {
            var response = (createTransactionResponse)PayPalAuthorizeCapture.Run(apiLoginId, transactionKey, GetAmount());
            return PayPalPriorAuthorizationCapture.Run(apiLoginId, transactionKey, response.transactionResponse.transId);
        }

        public ANetApiResponse TestCancelSubscription()
        {
            var response = (ARBCreateSubscriptionResponse)CreateSubscription.Run(apiLoginId, transactionKey, GetMonth());
            return CancelSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);
        }

        public ANetApiResponse TestCreateSubscriptionFromCustomerProfile()
        {
            var profileResponse = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            var paymentProfileResponse = (createCustomerPaymentProfileResponse)CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, profileResponse.customerProfileId);
            var shippingResponse = (createCustomerShippingAddressResponse)CreateCustomerShippingAddress.Run(apiLoginId, transactionKey, profileResponse.customerProfileId);

            Thread.Sleep(10000);

            var response = (ARBCreateSubscriptionResponse)CreateSubscriptionFromCustomerProfile.Run(apiLoginId, transactionKey, GetMonth(),
                profileResponse.customerProfileId, paymentProfileResponse.customerPaymentProfileId,
                shippingResponse.customerAddressId);

            CancelSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);
            DeleteCustomerProfile.Run(apiLoginId, transactionKey, profileResponse.customerProfileId);
            return response;
        }

        public ANetApiResponse TestCreateSubscription()
        {
            var response = (ARBCreateSubscriptionResponse)CreateSubscription.Run(apiLoginId, transactionKey, GetMonth());
            CancelSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);

            return response;
        }

        public ANetApiResponse TestGetSubscriptionStatus()
        {
            var response = (ARBCreateSubscriptionResponse)CreateSubscription.Run(apiLoginId, transactionKey, GetMonth());
            var subscriptionResponse = GetSubscriptionStatus.Run(apiLoginId, transactionKey, response.subscriptionId);

            return subscriptionResponse;
        }

        public ANetApiResponse TestGetSubscription()
        {
            var response = (ARBCreateSubscriptionResponse)CreateSubscription.Run(apiLoginId, transactionKey, GetMonth());
            var getResponse = GetSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);
            CancelSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);
            return getResponse;
        }

        public ANetApiResponse TestUpdateSubscription()
        {
            var response = (ARBCreateSubscriptionResponse)CreateSubscription.Run(apiLoginId, transactionKey, GetMonth());
            var updateResponse = UpdateSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);
            CancelSubscription.Run(apiLoginId, transactionKey, response.subscriptionId);

            return updateResponse;
        }

        public ANetApiResponse TestCreateCustomerProfile()
        {
            return CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
        }

        public ANetApiResponse TestCreateCustomerPaymentProfile()
        {
            var response = (createCustomerProfileResponse)CreateCustomerProfile.Run(apiLoginId, transactionKey, GetEmail());
            return CreateCustomerPaymentProfile.Run(apiLoginId, transactionKey, response.customerProfileId);
        }

        public ANetApiResponse TestCreateAnApplePayTransaction()
        {
            var response = (createTransactionResponse)CreateAnApplePayTransaction.Run(apiLoginId, transactionKey, GetAmount());
            return response;
        }
        public ANetApiResponse TestCreateAnAndroidPayTransaction()
        {
            var response = (createTransactionResponse)CreateAnAndroidPayTransaction.Run(apiLoginId, transactionKey, GetAmount());
            return response;
        }
        public ANetApiResponse TestCreateAnAcceptTransaction()
        {
            var response = (createTransactionResponse)CreateAnAcceptTransaction.Run(apiLoginId, transactionKey, GetAmount());
            return response;
        }

        public ANetApiResponse TestGetAnAcceptPaymentPage()
        {
            return GetAnAcceptPaymentPage.Run(apiLoginId, transactionKey, GetAmount());
        }

    }
}


text:
<!DOCTYPE html>

<link rel="import" href="/tracing/ui/base/deep_utils.html">
<link rel="import" href="/tracing/base/units/time.html">
<link rel="import" href="/tracing/base/units/time_duration.html">

<polymer-element name="tr-ui-u-time-duration-span">
  <template>

    ⚠
  </template>

</polymer-element>


text:
layout: post
category: [Technology]
title: Facebook Technology Study I
tagline: by Jian
tags: [Facebook, Architecture, Technology]
---

As is known to us all, Facebook is world class big tech company which is engaging in connecting the world with its various open source software and open source hardware. So far Facebook has had 296 open source projects on GitHub with 10+ Million Lines of code, 265k Followers and 43k Forks. This airticle is going to introduce the general open source software infrastructure of Facebook.
<!--more-->

> Open source is very important for Facebook. Being open is better than being close. Being connection is better than being isolation. Bellow is a short list of facebook's open source software in the last 6 months.

```
grocery-delivery
ig-json-parser
xhp-bootstrap
parseapplinksanalytics
fbcuda
mcrouter
errgroup
third-party
fb-adb
flow
css-layout
httpdown
riftdk1
jsx
vim-flow
flux
dfuse
thpp
immutable-js
fblualib
rpool
osquery
fatal
ds2
proxygen : layer 7 load balancer
fbpca
stats
rebound-js
runcmd
asyncdisplaykit
neti
fbcunn
f8developerconferenceapp
parse-facebook-user-session
parseui-ios
parse-php-sdk
facebook-python-ads-sdk
oss-performance
taste-tester
presto-odbc
between-meals
neti-cookbook
```

Facebook mainly focus on 4 main softwares: data infrastructure like "Presto" and "rocksdb", server runtime like "proxygen" and "HHVM", web framework like "javascript", mobile tools and libraries.

RocksDB is an embeddable persistent key-value store for fast storage. RocksDB can also be the foundation for a client-server database but our current focus is on embedded workloads.

Presto is an open source distributed SQL query engine for running interactive analytic queries against data sources of all sizes ranging from gigabytes to petabytes.

Why open source is very important?

In the year 2004, facebook start with LAMP frame (Linux, Apache, Mysql, PHP),  now it's like a giant LAMP website with third degree scale. Engineers has done a lot to improve the LAMP and memcache.  you had to make it scale. For example, first we use Mysql, then we need to scale it, then need improve it, even replace it. After we release it, we continue using it, it become a loop.

How facebook contribute?

Hardware: Facebook open a hardware project called "open compute project", you can buy those hardware from OEM, they don't have secret anymore.

OCP data center design: mechanical design, electronical design.

---


text:
"use strict";

describe("web/tag", function () {

    function Attribute (namespace, name, value) {
        this._namespace = namespace;
        this._name = name;
        this._value = value;
    }

    Attribute.prototype = {
        _namespace: "",
        _name: "",
        _value: undefined
    };

    function Node (ownerDocument, namespace, name) {
        this.ownerDocument = ownerDocument;
        this._namespace = namespace;
        this.nodeName = name;
        this._attributes = [];
        this._children = [];
    }

    Node.prototype = {
        ownerDocument: null,
        _namespace: "",
        nodeName: "",
        _attributes: [],
        _children: [],
        appendChild: function (child) {
            this._children.push(child);
            return child;
        },
        setAttribute: function (name, value) {
            this._attributes.push(new Attribute("", name, value));
        },
        setAttributeNS: function (namespace, name, value) {
            this._attributes.push(new Attribute(namespace, name, value));
        },
        _hasAttribute: function (namespace, name) {
            var result;
            this._attributes.every(function (attribute) {
                if (attribute._namespace === namespace && attribute._name === name) {
                    result = attribute._value;
                    return false;
                }
                return true;
            });
            return result;
        }
    };

    var mockDocument = {
        createElement: function (nodeName) {
            return new Node(this, "", nodeName);
        },
        createElementNS: function (namespace, nodeName) {
            return new Node(this, namespace, nodeName);
        },
        createTextNode: function (text) {
            return text;
        }
    };

    describe("gpf.web.createTagFunction", function () {

        it("requires node name when calling the function", function () {
            var exceptionCaught;
            try {
                gpf.web.createTagFunction();
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof gpf.Error.MissingNodeName);
        });

        it("creates shortcut for tag generation", function () {
            var div = gpf.web.createTagFunction("div");
            assert(div("Hello World!").toString() === "
Hello World!
");
        });

        it("generates closed tags when empty", function () {
            var div = gpf.web.createTagFunction("div");
            assert(div().toString() === "
");
        });

        it("supports tree building (parameters)", function () {
            var div = gpf.web.createTagFunction("div"),
                span = gpf.web.createTagFunction("span"),
                tree = div({className: "test1"}, "Hello ", span({className: "test2"}, "World!"));
            assert(tree.toString() === "
Hello World!
");
        });

        it("supports tree building (array parameter)", function () {
            var div = gpf.web.createTagFunction("div"),
                span = gpf.web.createTagFunction("span"),
                tree = div({width: "80%"}, "Hello ", [span("Wor"), span("ld!")]);
            assert(tree.toString() === "
Hello World!
");
        });

        it("allows DOM injection", function () {
            var mockNode = mockDocument.createElement("any"),
                div = gpf.web.createTagFunction("div"),
                span = gpf.web.createTagFunction("span"),
                tree = div({className: "test"}, "Hello ", span("World!")),
                result = tree.appendTo(mockNode);
            assert(result instanceof Node);
            assert(result.ownerDocument === mockDocument);
            assert(result.nodeName === "div");
            assert(result._hasAttribute("", "class") === "test");
            assert(result._children.length === 2);
            assert(result._children[0] === "Hello ");
            assert(result._children[1] instanceof Node);
            assert(result._children[1]._children[0] === "World!");
        });

        describe("Namespace handling", function () {

            it("permits namespaces for node appending", function () {
                var mockNode = mockDocument.createElement("any"),
                    svgImage = gpf.web.createTagFunction("svg:image"),
                    tree = svgImage({x: 0, y: 0, "xlink:href": "test.png"}),
                    result = tree.appendTo(mockNode);
                assert(result instanceof Node);
                assert(result.ownerDocument === mockDocument);
                assert(result.nodeName === "image");
                assert(result._namespace === "http://www.w3.org/2000/svg");
                assert(result._hasAttribute("http://www.w3.org/1999/xlink", "href") === "test.png");
                assert(result._hasAttribute("", "x") === 0);
            });

            it("fails if namespace is unknown", function () {
                var mockNode = mockDocument.createElement("any"),
                    svgImage = gpf.web.createTagFunction("svg2:image"),
                    tree = svgImage({x: 0, y: 0, "xlink:href": "test.png"}),
                    exceptionCaught;
                try {
                    tree.appendTo(mockNode);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof gpf.Error.UnknownNamespacePrefix);
            });

            it("fails when used for string generation", function () {
                var svgImage = gpf.web.createTagFunction("svg:image"),
                    tree = svgImage({x: 0, y: 0, "xlink:href": "test.png"}),
                    exceptionCaught;
                try {
                    tree.toString();
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof gpf.Error.UnableToUseNamespaceInString);
            });

        });

    });

});


text:
package org.apache.batik.css.engine.value.css2;

import org.apache.batik.css.engine.value.IdentifierManager;
import org.apache.batik.css.engine.value.StringMap;
import org.apache.batik.css.engine.value.Value;
import org.apache.batik.css.engine.value.ValueConstants;
import org.apache.batik.css.engine.value.ValueManager;
import org.apache.batik.util.CSSConstants;
import org.apache.batik.util.SVGTypes;

/**
 * This class provides a manager for the 'font-variant' property values.
 *
 * @author Stephane Hillion
 * @version $Id$
 */
public class FontVariantManager extends IdentifierManager {

    /**
     * The identifier values.
     */
    protected static final StringMap values = new StringMap();
    static {
        values.put(CSSConstants.CSS_NORMAL_VALUE,
                   ValueConstants.NORMAL_VALUE);
        values.put(CSSConstants.CSS_SMALL_CAPS_VALUE,
                   ValueConstants.SMALL_CAPS_VALUE);
    }

    /**
     * Implements {@link
     * org.apache.batik.css.engine.value.ValueManager#isInheritedProperty()}.
     */
    public boolean isInheritedProperty() {
        return true;
    }

    /**
     * Implements {@link ValueManager#isAnimatableProperty()}.
     */
    public boolean isAnimatableProperty() {
        return true;
    }

    /**
     * Implements {@link ValueManager#isAdditiveProperty()}.
     */
    public boolean isAdditiveProperty() {
        return false;
    }

    /**
     * Implements {@link ValueManager#getPropertyType()}.
     */
    public int getPropertyType() {
        return SVGTypes.TYPE_IDENT;
    }

    /**
     * Implements {@link
     * org.apache.batik.css.engine.value.ValueManager#getPropertyName()}.
     */
    public String getPropertyName() {
        return CSSConstants.CSS_FONT_VARIANT_PROPERTY;
    }

    /**
     * Implements {@link
     * org.apache.batik.css.engine.value.ValueManager#getDefaultValue()}.
     */
    public Value getDefaultValue() {
        return ValueConstants.NORMAL_VALUE;
    }

    /**
     * Implements {@link IdentifierManager#getIdentifiers()}.
     */
    public StringMap getIdentifiers() {
        return values;
    }
}


text:
/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#ifndef __GTK_EDITABLE_H__
#define __GTK_EDITABLE_H__

#include <gdk/gdk.h>
#include <gtk/gtkwidget.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define GTK_TYPE_EDITABLE             (gtk_editable_get_type ())
#define GTK_EDITABLE(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_EDITABLE, GtkEditable))
#define GTK_EDITABLE_CLASS(vtable)    (G_TYPE_CHECK_CLASS_CAST ((vtable), GTK_TYPE_EDITABLE, GtkEditableClass))
#define GTK_IS_EDITABLE(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_EDITABLE))
#define GTK_IS_EDITABLE_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), GTK_TYPE_EDITABLE))
#define GTK_EDITABLE_GET_CLASS(inst)  (G_TYPE_INSTANCE_GET_INTERFACE ((inst), GTK_TYPE_EDITABLE, GtkEditableClass))

typedef struct _GtkEditable       GtkEditable;         /* Dummy typedef */
typedef struct _GtkEditableClass  GtkEditableClass;

struct _GtkEditableClass
{
  GTypeInterface		   base_iface;

  /* signals */
  void (* insert_text)              (GtkEditable    *editable,
				     const gchar    *text,
				     gint            length,
				     gint           *position);
  void (* delete_text)              (GtkEditable    *editable,
				     gint            start_pos,
				     gint            end_pos);
  void (* changed)                  (GtkEditable    *editable);

  /* vtable */
  void (* do_insert_text)           (GtkEditable    *editable,
				     const gchar    *text,
				     gint            length,
				     gint           *position);
  void (* do_delete_text)           (GtkEditable    *editable,
				     gint            start_pos,
				     gint            end_pos);

  gchar* (* get_chars)              (GtkEditable    *editable,
				     gint            start_pos,
				     gint            end_pos);
  void (* set_selection_bounds)     (GtkEditable    *editable,
				     gint            start_pos,
				     gint            end_pos);
  gboolean (* get_selection_bounds) (GtkEditable    *editable,
				     gint           *start_pos,
				     gint           *end_pos);
  void (* set_position)             (GtkEditable    *editable,
				     gint            position);
  gint (* get_position)             (GtkEditable    *editable);
};

GType    gtk_editable_get_type             (void) G_GNUC_CONST;
void     gtk_editable_select_region        (GtkEditable *editable,
					    gint         start,
					    gint         end);
gboolean gtk_editable_get_selection_bounds (GtkEditable *editable,
					    gint        *start,
					    gint        *end);
void     gtk_editable_insert_text          (GtkEditable *editable,
					    const gchar *new_text,
					    gint         new_text_length,
					    gint        *position);
void     gtk_editable_delete_text          (GtkEditable *editable,
					    gint         start_pos,
					    gint         end_pos);
gchar*   gtk_editable_get_chars            (GtkEditable *editable,
					    gint         start_pos,
					    gint         end_pos);
void     gtk_editable_cut_clipboard        (GtkEditable *editable);
void     gtk_editable_copy_clipboard       (GtkEditable *editable);
void     gtk_editable_paste_clipboard      (GtkEditable *editable);
void     gtk_editable_delete_selection     (GtkEditable *editable);
void     gtk_editable_set_position         (GtkEditable *editable,
					    gint         position);
gint     gtk_editable_get_position         (GtkEditable *editable);
void     gtk_editable_set_editable         (GtkEditable *editable,
					    gboolean     is_editable);
gboolean gtk_editable_get_editable         (GtkEditable *editable);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __GTK_EDITABLE_H__ */