text:
package org.redisson;

import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;

import java.math.BigDecimal;
import java.util.*;

import org.redisson.async.AsyncOperation;
import org.redisson.async.OperationListener;
import org.redisson.async.ResultOperation;
import org.redisson.async.SyncOperation;
import org.redisson.connection.ConnectionManager;
import org.redisson.core.Predicate;
import org.redisson.core.RMap;

import com.lambdaworks.redis.RedisAsyncConnection;
import com.lambdaworks.redis.RedisConnection;
import com.lambdaworks.redis.output.MapScanResult;

/**
 * Distributed and concurrent implementation of {@link java.util.concurrent.ConcurrentMap}
 * and {@link java.util.Map}
 *
 * @author Nikita Koksharov
 *
 * @param <K> key
 * @param <V> value
 */
//TODO implement watching by keys instead of map name
public class RedissonMap<K, V> extends RedissonExpirable implements RMap<K, V> {

    protected RedissonMap(ConnectionManager connectionManager, String name) {
        super(connectionManager, name);
    }

    @Override
    public int size() {
        return connectionManager.read(getName(), new ResultOperation<Long, V>() {
            @Override
            public Future<Long> execute(RedisAsyncConnection<Object, V> async) {
                return async.hlen(getName());
            }
        }).intValue();
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public boolean containsKey(final Object key) {
        return connectionManager.read(getName(), new ResultOperation<Boolean, V>() {
            @Override
            public Future<Boolean> execute(RedisAsyncConnection<Object, V> async) {
                return async.hexists(getName(), key);
            }
        });
    }

    @Override
    public boolean containsValue(final Object value) {
        List<V> list = connectionManager.read(getName(), new ResultOperation<List<V>, V>() {
            @Override
            public Future<List<V>> execute(RedisAsyncConnection<Object, V> async) {
                return async.hvals(getName());
            }
        });
        return list.contains(value);
    }

    @Override
    public Map<K, V> getAll(final Set<K> keys) {
        if (keys.size() == 0) {
            return Collections.emptyMap();
        }
        final Object[] keysArray = keys.toArray();
        List<V> list = connectionManager.read(getName(), new ResultOperation<List<V>, V>() {
            @Override
            protected Future<List<V>> execute(RedisAsyncConnection<Object, V> async) {
                return async.hmget(getName(), keysArray);
            }
        });

        Map<K, V> result = new HashMap<K, V>(list.size());
        for (int index = 0; index < keysArray.length; index++) {
            V value = list.get(index);
            if (value == null) {
                continue;
            }
            result.put((K) keysArray[index], value);
        }
        return result;
    }

    @Override
    public V get(Object key) {
        return connectionManager.get(getAsync((K)key));
    }

    @Override
    public V put(K key, V value) {
        return connectionManager.get(putAsync(key, value));
    }

    @Override
    public V remove(Object key) {
        return connectionManager.get(removeAsync((K)key));
    }

    @Override
    public void putAll(final Map<? extends K, ? extends V> map) {
        connectionManager.write(getName(), new ResultOperation<String, Object>() {
            @Override
            public Future<String> execute(RedisAsyncConnection<Object, Object> async) {
                return async.hmset(getName(), (Map<Object, Object>) map);
            }
        });
    }

    @Override
    public void clear() {
        delete();
    }

    @Override
    public Set<K> keySet() {
        return (Set<K>) connectionManager.read(getName(), new ResultOperation<Set<Object>, V>() {
            @Override
            public Future<Set<Object>> execute(RedisAsyncConnection<Object, V> async) {
                return async.hkeys(getName());
            }
        });
    }

    @Override
    public Collection<V> values() {
        return connectionManager.read(getName(), new ResultOperation<List<V>, V>() {
            @Override
            public Future<List<V>> execute(RedisAsyncConnection<Object, V> async) {
                return async.hvals(getName());
            }
        });
    }

    @Override
    public Set<java.util.Map.Entry<K, V>> entrySet() {
        Map<Object, Object> map = connectionManager.read(getName(), new ResultOperation<Map<Object, Object>, Object>() {
            @Override
            public Future<Map<Object, Object>> execute(RedisAsyncConnection<Object, Object> async) {
                return async.hgetall(getName());
            }
        });

        Map<K, V> result = new HashMap<K, V>();
        for (java.util.Map.Entry<Object, Object> entry : map.entrySet()) {
            result.put((K)entry.getKey(), (V)entry.getValue());
        }
        return result.entrySet();
    }

    @Override
    public V putIfAbsent(final K key, final V value) {
//        while (true) {
//            Boolean res = connection.hsetnx(getName(), key, value);
//            if (!res) {
//                V result = (V) connection.hget(getName(), key);
//                if (result != null) {
//                    return result;
//                }
//            } else {
//                return null;
//            }
//        }

        return connectionManager.write(getName(), new AsyncOperation<V, V>() {
            @Override
            public void execute(final Promise<V> promise, final RedisAsyncConnection<Object, V> async) {
                final AsyncOperation<V, V> timeoutCallback = this;
                async.hsetnx(getName(), key, value).addListener(new OperationListener<V, V, Boolean>(promise, async, timeoutCallback) {
                    @Override
                    public void onOperationComplete(Future<Boolean> future) throws Exception {
                        if (future.get()) {
                            promise.setSuccess(null);
                            return;
                        }

                        async.hget(getName(), key).addListener(new OperationListener<V, V, V>(promise, async, timeoutCallback) {
                            @Override
                            public void onOperationComplete(Future<V> future) throws Exception {
                                V prev = future.get();
                                if (prev != null) {
                                    promise.setSuccess(prev);
                                } else {
                                    timeoutCallback.execute(promise, async);
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    private boolean isEquals(RedisConnection<Object, Object> connection, Object key, Object value) {
        Object val = connection.hget(getName(), key);
        return (value != null && value.equals(val)) || (value == null && val == null);
    }

    @Override
    public boolean remove(final Object key, final Object value) {
        return connectionManager.write(getName(), new SyncOperation<Object, Boolean>() {
            @Override
            public Boolean execute(RedisConnection<Object, Object> connection) {
                while (true) {
                    connection.watch(getName());
                    if (connection.hexists(getName(), key)
                            && isEquals(connection, key, value)) {
                        connection.multi();
                        connection.hdel(getName(), key);
                        if (connection.exec().size() == 1) {
                            return true;
                        }
                    } else {
                        connection.unwatch();
                        return false;
                    }
                }
            }
        });
    }

    @Override
    public boolean replace(final K key, final V oldValue, final V newValue) {
        return connectionManager.write(getName(), new SyncOperation<Object, Boolean>() {
            @Override
            public Boolean execute(RedisConnection<Object, Object> connection) {
                while (true) {
                    connection.watch(getName());
                    if (connection.hexists(getName(), key)
                            && isEquals(connection, key, oldValue)) {
                        connection.multi();
                        connection.hset(getName(), key, newValue);
                        if (connection.exec().size() == 1) {
                            return true;
                        }
                    } else {
                        connection.unwatch();
                        return false;
                    }
                }
            }
        });
    }

    @Override
    public V replace(final K key, final V value) {
        return connectionManager.write(getName(), new SyncOperation<V, V>() {
            @Override
            public V execute(RedisConnection<Object, V> connection) {
                while (true) {
                    connection.watch(getName());
                    if (connection.hexists(getName(), key)) {
                        V prev = connection.hget(getName(), key);
                        connection.multi();
                        connection.hset(getName(), key, value);
                        if (connection.exec().size() == 1) {
                            return prev;
                        }
                    } else {
                        connection.unwatch();
                        return null;
                    }
                }
            }
        });
    }

    @Override
    public Future<V> getAsync(final K key) {
        return connectionManager.readAsync(getName(), new ResultOperation<V, V>() {
            @Override
            public Future<V> execute(RedisAsyncConnection<Object, V> async) {
                return async.hget(getName(), key);
            }
        });
    }

    @Override
    public Future<V> putAsync(final K key, final V value) {
//        while (true) {
//            connection.watch(getName());
//            V prev = (V) connection.hget(getName(), key);
//            connection.multi();
//            connection.hset(getName(), key, value);
//            if (connection.exec().size() == 1) {
//                return prev;
//            }
//        }

        return connectionManager.writeAsync(getName(), new AsyncOperation<V, V>() {
            @Override
            public void execute(final Promise<V> promise, RedisAsyncConnection<Object, V> async) {
                putAsync(key, value, promise, async, this);
            }
        });
    }

    private void putAsync(final K key, final V value, final Promise<V> promise,
            final RedisAsyncConnection<Object, V> async, final AsyncOperation<V, V> timeoutCallback) {
        async.watch(getName()).addListener(new OperationListener<V, V, String>(promise, async, timeoutCallback) {
            @Override
            public void onOperationComplete(Future<String> future) throws Exception {

                async.hget(getName(), key).addListener(new OperationListener<V, V, V>(promise, async, timeoutCallback) {
                    @Override
                    public void onOperationComplete(Future<V> future) throws Exception {

                        final V prev = future.get();
                        async.multi().addListener(new OperationListener<V, V, String>(promise, async, timeoutCallback) {
                            @Override
                            public void onOperationComplete(Future<String> future) throws Exception {

                                async.hset(getName(), key, value).addListener(new OperationListener<V, V, Boolean>(promise, async, timeoutCallback) {
                                    @Override
                                    public void onOperationComplete(Future<Boolean> future) throws Exception {

                                        async.exec().addListener(new OperationListener<V, V, List<Object>>(promise, async, timeoutCallback) {
                                            @Override
                                            public void onOperationComplete(Future<List<Object>> future) throws Exception {

                                                if (future.get().size() == 1) {
                                                    promise.setSuccess(prev);
                                                } else {
                                                    timeoutCallback.execute(promise, async);
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }

        });
    }

    @Override
    public Future<V> removeAsync(final K key) {
//        while (true) {
//            connection.watch(getName());
//            V prev = (V) connection.hget(getName(), key);
//            connection.multi();
//            connection.hdel(getName(), key);
//            if (connection.exec().size() == 1) {
//                return prev;
//            }
//        }

        return connectionManager.writeAsync(getName(), new AsyncOperation<V, V>() {
            @Override
            public void execute(final Promise<V> promise, RedisAsyncConnection<Object, V> async) {
                removeAsync(key, promise, async, this);
            }
        });
    }

    private void removeAsync(final K key, final Promise<V> promise,
            final RedisAsyncConnection<Object, V> async, final AsyncOperation<V, V> timeoutCallback) {
        async.watch(getName()).addListener(new OperationListener<V, V, String>(promise, async, timeoutCallback) {
            @Override
            public void onOperationComplete(Future<String> future) throws Exception {

                async.hget(getName(), key).addListener(new OperationListener<V, V, V>(promise, async, timeoutCallback) {
                    @Override
                    public void onOperationComplete(Future<V> future) throws Exception {
                        final V prev = future.get();

                        async.multi().addListener(new OperationListener<V, V, String>(promise, async, timeoutCallback) {
                            @Override
                            public void onOperationComplete(Future<String> future) throws Exception {

                                async.hdel(getName(), key).addListener(new OperationListener<V, V, Long>(promise, async, timeoutCallback) {
                                    @Override
                                    public void onOperationComplete(Future<Long> future) throws Exception {

                                        async.exec().addListener(new OperationListener<V, V, List<Object>>(promise, async, timeoutCallback) {
                                            @Override
                                            public void onOperationComplete(Future<List<Object>> future) throws Exception {

                                                if (future.get().size() == 1) {
                                                    promise.setSuccess(prev);
                                                } else {
                                                    timeoutCallback.execute(promise, async);
                                                }
                                            }
                                        });

                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    }

    @Override
    public Future<Boolean> fastPutAsync(final K key, final V value) {
        return connectionManager.writeAsync(getName(), new ResultOperation<Boolean, V>() {
            @Override
            public Future<Boolean> execute(RedisAsyncConnection<Object, V> async) {
                return async.hset(getName(), key, value);
            }
        });
    }

    @Override
    public boolean fastPut(K key, V value) {
        return connectionManager.get(fastPutAsync(key, value));
    }

    @Override
    public Future<Long> fastRemoveAsync(final K ... keys) {
        if (keys != null && keys.length > 0) {
            return connectionManager.writeAsync(getName(), new ResultOperation<Long, V>() {
                @Override
                public Future<Long> execute(RedisAsyncConnection<Object, V> async) {
                    return async.hdel(getName(), keys);
                }
            });
        } else {
            return connectionManager.getGroup().next().newSucceededFuture(0L);
        }
    }

    @Override
    public long fastRemove(K ... keys) {
        return connectionManager.get(fastRemoveAsync(keys));
    }

    private MapScanResult<Object, V> scanIterator(final long startPos) {
        return connectionManager.read(getName(), new ResultOperation<MapScanResult<Object, V>, V>() {
            @Override
            public Future<MapScanResult<Object, V>> execute(RedisAsyncConnection<Object, V> async) {
                return async.hscan(getName(), startPos);
            }
        });
    }

    private Iterator<Map.Entry<K, V>> iterator() {
        return new Iterator<Map.Entry<K, V>>() {

            private Iterator<Map.Entry<K, V>> iter;
            private long iterPos = 0;

            private boolean removeExecuted;
            private Map.Entry<K,V> value;

            @Override
            public boolean hasNext() {
                if (iter == null
                        || (!iter.hasNext() && iterPos != 0)) {
                    MapScanResult<Object, V> res = scanIterator(iterPos);
                    iter = ((Map<K, V>)res.getMap()).entrySet().iterator();
                    iterPos = res.getPos();
                }
                return iter.hasNext();
            }

            @Override
            public Map.Entry<K, V> next() {
                if (!hasNext()) {
                    throw new NoSuchElementException("No such element at index");
                }

                value = iter.next();
                removeExecuted = false;
                return value;
            }

            @Override
            public void remove() {
                if (removeExecuted) {
                    throw new IllegalStateException("Element been already deleted");
                }

                // lazy init iterator
                hasNext();
                iter.remove();
                RedissonMap.this.fastRemove(value.getKey());
                removeExecuted = true;
            }

        };
    }

    @Override
    public Map<K, V> filterKeys(Predicate<K> predicate) {
        Map<K, V> result = new HashMap<K, V>();
        for (Iterator<Map.Entry<K, V>> iterator = iterator(); iterator.hasNext();) {
            Map.Entry<K, V> entry = iterator.next();
            if (predicate.apply(entry.getKey())) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

    @Override
    public Map<K, V> filterValues(Predicate<V> predicate) {
        Map<K, V> result = new HashMap<K, V>();
        for (Iterator<Map.Entry<K, V>> iterator = iterator(); iterator.hasNext();) {
            Map.Entry<K, V> entry = iterator.next();
            if (predicate.apply(entry.getValue())) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

    public Map<K, V> filterEntries(Predicate<Map.Entry<K, V>> predicate) {
        Map<K, V> result = new HashMap<K, V>();
        for (Iterator<Map.Entry<K, V>> iterator = iterator(); iterator.hasNext();) {
            Map.Entry<K, V> entry = iterator.next();
            if (predicate.apply(entry)) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

    @Override
    public V addAndGet(final K key, final V value) {
        String res = connectionManager.write(getName(), new ResultOperation<String, V>() {

            @Override
            protected Future<String> execute(RedisAsyncConnection<Object, V> async) {
                Number val = (Number) value;
                return async.hincrbyfloat(getName(), key, new BigDecimal(val.toString()).toPlainString());
            }
        });

        if (value instanceof Long) {
            Object obj = Long.parseLong(res);
            return (V)obj;
        }
        if (value instanceof Integer) {
            Object obj = Integer.parseInt(res);
            return (V)obj;
        }
        if (value instanceof Float) {
            Object obj = Float.parseFloat(res);
            return (V)obj;
        }
        if (value instanceof Double) {
            Object obj = Double.parseDouble(res);
            return (V)obj;
        }
        if (value instanceof BigDecimal) {
            Object obj = new BigDecimal(res);
            return (V)obj;
        }
        throw new IllegalStateException("Wrong value type!");
    }

}


text:
		{$lang->userblock}

		{$lang->cmd_blocklist}

		{$lang->cmd_ban_ip}

		{$lang->cmd_log}(debug)

		{$lang->userblock_board}

		{$lang->userblock_config}

		{$lang->userblock_grant_info}

		{$lang->userblock_design}

redpajama_set_name: RedPajamaGithub


text:
package com.libraries.heiko.gamebook;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.Settings;

import com.libraries.heiko.gamebook.tools.*;

/**
 * Created by heiko on 28.02.2016.
 */
public class ResourceManager
{
    private GameStack<GameResource> images;     // holds resources of the type 'image'
    private GameStack<GameResource> fonts;      // holds resources of the type 'font'
    private GameStack<GameResource> tilesets;   // holds resources of the type 'font'
    private GameFont tempFont;                  // hold a font to load it
    private Tileset tempTileset;               // hold a font to load it
    private GameStack<GameResource> tempStack;  // used to iterate trough resurce-stacks
    private GameResource tempResource;          // used to temporarily hold a new resource when adding it
    private GameBook book;                      // reference to the GameBook

    public ResourceManager(GameBook a_book)
    {
        this.book = a_book;
        this.images = new GameStack<GameResource>();
        this.fonts = new GameStack<GameResource>();
        this.tilesets = new GameStack<GameResource>();
        this.tempStack = new GameStack<GameResource>();
    }

    /*
        Function: GetImage
            Gets a previously stored image

        Parameter:
            a_id    - String    | ID of the stored image

        Returns:
            Bitmap -> - The requestes image
    */
    public Bitmap GetImage(String a_id)
    {
        return (Bitmap) this._GetResource(a_id, this.images);
    }

    /*
        Function: AddImage
            Stores an image using an id to later retrieve it

        Parameter:
            a_id    - String    | ID of the stored image
            a_image - Bitmap    | Image to store

        Returns:
            Bitmap -> - The image that just got stored
    */
    public Bitmap AddImage(String a_id, Bitmap a_image)
    {
        return (Bitmap) this._AddResource(a_id, this.images, a_image);
    }

    /*
        Function: AddImage
            Stores an image using an id to later retrieve it

        Parameter:
            a_id    - String    | ID of the stored image
            a_image - Resource  | Resource of the image to store

        Returns:
            Bitmap -> - The image that just got stored
    */
    public Bitmap AddImage(String a_id, int a_image)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = this.book.bitmapConfig;
        options.inScaled = false;
        return (Bitmap) this._AddResource(a_id, this.images, BitmapFactory.decodeResource(this.book.getContext().getResources(), a_image, options));
    }

    /*
        Function: AddImage
            Stores an image using an id to later retrieve it

        Parameter:
            a_id    - String    | ID of the stored image
            a_path  - String    | Path to the image to store

        Returns:
            Bitmap -> - The image that just got stored
    */
    public Bitmap AddImage(String a_id, String a_path)
    {
        return (Bitmap) this._AddResource(a_id, this.images, BitmapFactory.decodeFile(a_path));
    }

    /*
        Function: RemoveImage
            Removes a previously stored image from the ResourceManager

        Parameter:
            a_id    - String    | ID of the image to remove
    */
    public void RemoveImage(String a_id)
    {
        this._RemoveResource(a_id, this.images);
    }

    /*
        Function: AddFont
            Stores an font using an id to later retrieve it

        Parameter:
            a_id        - String    | ID of the stored font
            a_font      - String    | path of the font-file inside the assets-folder
            a_fontSize  - Integer   | FontSize to use
            a_padX      - Integer   | Letter-distance on the x-axis
            a_padY      - Integer   | Letter-distance in the y-axis

        Returns:
            GameFont -> - The Loaded font
    */
    public GameFont AddFont(String a_id, String a_font, int a_fontSize, int a_padX, int a_padY, int a_spaceX)
    {
        tempFont =  new GameFont(this.book.getContext().getAssets(), a_font, a_fontSize, a_padX, a_padY, a_spaceX);
        this._AddResource(a_id, this.fonts, tempFont);
        if (this.book.gameRenderer.oglReady == true)
        {
            tempFont.Load();
            tempFont.SetDisplayScale(this.book.gameRenderer.horzVertexRatio, this.book.gameRenderer.vertVertexRatio);
        }
        return (GameFont) this._GetResource(a_id, this.fonts);
    }

    /*
        Function: AddFont
            Stores an image using an id to later retrieve it. letter-padding is set to 2px

        Parameter:
            a_id        - String    | ID of the stored font
            a_font      - String    | path of the font-file inside the assets-folder
            a_fontSize  - Integer   | FontSize to use
            a_spaceX    - Integer   | FontSpacing to use

        Returns:
            GameFont -> - The Loaded font
    */
    public GameFont AddFont(String a_id, String a_font, int a_fontSize, int a_spaceX)
    {
        return this.AddFont(a_id, a_font, a_fontSize, 2, 2, a_spaceX);
    }

    /*
        Function: AddFont
            Stores an image using an id to later retrieve it. letter-padding is set to 2px

        Parameter:
            a_id        - String    | ID of the stored font
            a_font      - String    | path of the font-file inside the assets-folder
            a_fontSize  - Integer   | FontSize to use

        Returns:
            GameFont -> - The Loaded font
    */
    public GameFont AddFont(String a_id, String a_font, int a_fontSize)
    {
        return this.AddFont(a_id, a_font, a_fontSize, 2, 2, 0);
    }

    /*
        Function: RemoveImage
            Removes a previously stored font from the ResourceManager

        Parameter:
            a_id    - String    | ID of the font to remove
    */
    public void RemoveFont(String a_id)
    {
        this._RemoveResource(a_id, this.fonts);
    }

    /*
        Function: GetImage
            Gets a previously stored Tileset

        Parameter:
            a_id    - String    | ID of the stored Tileset

        Returns:
            Tileset -> - The requested Tileset
    */
    public Tileset GetTileset(String a_id)
    {
        return (Tileset) this._GetResource(a_id, this.tilesets);
    }

    /*
        Function: AddTileset
            Stores a tileset using an id to later retrieve it

        Parameter:
            a_id            - String    | ID of the stored tileset
            a_image         - Bitmap    | Image to use
            a_tileWidth     - Integer   | width of the tiles
            a_tileHeight    - Integer   | height of the tiles

        Returns:
            Tileset -> - The Tileset that just got stored
    */
    public Tileset AddTileset(String a_id, Bitmap a_image, int a_tileWidth, int a_tileHeight)
    {
        tempTileset = new Tileset(a_image, a_tileWidth, a_tileHeight);
        if (this.book.gameRenderer.oglReady == true)
            tempTileset.CreateTexture();

        return (Tileset) this._AddResource(a_id, this.tilesets, tempTileset);
    }

    /*
        Function: AddTileset
            Stores a tileset using an id to later retrieve it

        Parameter:
            a_id            - String    | ID of the stored tileset
            a_image         - Resource  | Resource of the image to use
            a_tileWidth     - Integer   | width of the tiles
            a_tileHeight    - Integer   | height of the tiles

        Returns:
            Tileset -> - The Tileset that just got stored
    */
    public Tileset AddTileset(String a_id, int a_image, int a_tileWidth, int a_tileHeight)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = this.book.bitmapConfig;
        options.inScaled = false;
        return this.AddTileset(a_id, BitmapFactory.decodeResource(this.book.getContext().getResources(), a_image, options), a_tileWidth, a_tileHeight);
    }

    /*
        Function: AddTileset
            Stores a tileset using an id to later retrieve it

        Parameter:
            a_id            - String    | ID of the stored tileset
            a_image         - String    | Path to the image to store
            a_tileWidth     - Integer   | width of the tiles
            a_tileHeight    - Integer   | height of the tiles

        Returns:
            Tileset -> - The Tileset that just got stored
    */
    public Tileset AddTileset(String a_id, String a_path, int a_tileWidth, int a_tileHeight)
    {
        return this.AddTileset(a_id, BitmapFactory.decodeFile(a_path), a_tileWidth, a_tileHeight);
    }

    /*
        Function: RemoveImage
            Removes a previously stored tileset from the ResourceManager

        Parameter:
            a_id    - String    | ID of the tileset to remove
    */
    public void RemoveTileset(String a_id)
    {
        this._RemoveResource(a_id, this.tilesets);
    }

    public void _OGLReady()
    {
        this.tempStack = this.fonts;
        while (this.tempStack.content != null)
        {
            if (!((GameFont) this.tempStack.content.resource).fontLoaded)
                ((GameFont) this.tempStack.content.resource).Load();

            this.tempStack = this.tempStack.next;
        }

        this.tempStack = this.tilesets;
        while (this.tempStack.content != null)
        {
            if (!((Tileset) this.tempStack.content.resource).textureCreated)
                ((Tileset) this.tempStack.content.resource).CreateTexture();

            this.tempStack = this.tempStack.next;
        }
    }

    public void _UpdateScreenDimensions(float a_horzVertexRatio, float a_vertVertexRatio)
    {
        this.tempStack = this.fonts;
        while (this.tempStack.content != null)
        {
            ((GameFont) this.tempStack.content.resource).SetDisplayScale(a_horzVertexRatio, a_vertVertexRatio);
            this.tempStack = this.tempStack.next;
        }
    }

    private Object _GetResource(String a_id, GameStack<GameResource> a_targetStack)
    {
        this.tempStack = a_targetStack;
        while (this.tempStack.content != null)
        {
            if (this.tempStack.content.id.equals(a_id))
                return this.tempStack.content.resource;

            this.tempStack = this.tempStack.next;
        }
        return null;
    }

    private Object _AddResource(String a_id, GameStack<GameResource> a_targetStack, Object a_resource)
    {
        if (this._GetResource(a_id, a_targetStack) != null)
            throw new RuntimeException("resource already registered: " + a_id);

        this.tempResource = new GameResource(a_id, a_resource);
        a_targetStack.push(this.tempResource);
        this.tempResource = null;
        return a_targetStack.peek().resource;
    }

    private void _RemoveResource(String a_id, GameStack<GameResource> a_targetStack)
    {
        this.tempStack = a_targetStack;
        while (this.tempStack.content != null)
        {
            if (this.tempStack.content.id.equals(a_id))
            {
                this.tempStack.pop();
                return;
            }

            this.tempStack = this.tempStack.next;
        }
    }

    class GameResource
    {
        String id;
        Object resource;
        public GameResource(String a_id)
        {
            this.id = a_id;
        }

        public GameResource(String a_id, Object a_resource)
        {
            this.id = a_id;
            this.resource = a_resource;
        }
    }
}


text:
package com.thoughtworks.go.plugin.access.analytics.V1.models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.Objects;

public class SupportedAnalytics {
    @Expose
    @SerializedName("type")
    private String type;

    @Expose
    @SerializedName("id")
    private String id;

    @Expose
    @SerializedName("title")
    private String title;

    public SupportedAnalytics(String type, String id, String title) {
        this.type = type;
        this.id = id;
        this.title = title;
    }

    public String getType() {
        return type;
    }

    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof SupportedAnalytics)) return false;
        SupportedAnalytics that = (SupportedAnalytics) o;
        return Objects.equals(getType(), that.getType()) &&
                Objects.equals(getId(), that.getId()) &&
                Objects.equals(getTitle(), that.getTitle());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getType(), getId(), getTitle());
    }
}


text:
<legend>

</legend>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<entity class-name="ejb_generated.CfIndicKeyw" label="Indicator Keywords" name="CFINDICKEYW">
<attributes>
<column-attribute field-name="id" hidden="true" key="true" label="ID" length="50" name="id" type="java.lang.Long"/>
<column-attribute field-name="a_keywords" hidden="false" key="false" label="Keywords" length="255" name="a_keywords" precision="0" type="java.lang.String"/>
<zoom-attribute class-name="ejb_generated.CfLang" field-name="cfindickeyw_language" label="Language" name="cfindickeyw_language" zoomed-by="id">
<column-ref label="Language ID" name="id"/>
</zoom-attribute>
<zoom-attribute class-name="ejb_generated.CfIndic" field-name="cfindickeyw_indicator" label="Indicator" name="cfindickeyw_indicator" zoomed-by="id">
<column-ref label="Indicator ID" name="id"/>
</zoom-attribute>
<column-attribute enum="TranslationKindIndicator_keywordsEnum" field-name="a_translation_kind" hidden="false" key="false" label="Translation Kind" length="1" name="a_translation_kind" precision="0" type="java.lang.String"/>
</attributes>
</entity>


text:
from ..errors import PardotAPIArgumentError

class ListMemberships(object):
    """
    A class to query and use Pardot list memberships.
    Prospect field reference: http://developer.pardot.com/kb/object-field-references#list-membership
    """

    def __init__(self, client):
        self.client = client

    def query(self, **kwargs):
        """
        Returns the list memberships matching the specified criteria parameters.
        Supported search criteria: http://developer.pardot.com/kb/api-version-4/list-memberships/#supported-search-criteria
        """
        response = self._get(path='/do/query', params=kwargs)

        # Ensure result['list_membership'] is a list, no matter what.
        result = response.get('result')
        if result['total_results'] == 0:
            result['list_membership'] = []
        elif result['total_results'] == 1:
            result['list_membership'] = [result['list_membership']]

        return result

    def create(self, list_id=None, prospect_id=None, **kwargs):
        """
        Creates a new list membership using the specified data. <list_id> is the Pardot list ID
        of the target list and <prospect_id> is the Pardot prospect ID of the target prospect.
        Opting out prospect from list may also be added with this request.
        """
        if not list_id:
            raise PardotAPIArgumentError('a list ID is required to create a list membership.')
        if not prospect_id:
            raise PardotAPIArgumentError('a prospect ID is required to create a list membership.')
        response = self._post(path='/do/create/list_id/{list_id}/prospect_id/{prospect_id}'.format(list_id=list_id,prospect_id=prospect_id), params=kwargs)
        return response

    def read(self, list_id=None, prospect_id=None, **kwargs):
        """
        Returns the data for the list membership specified by <list_id> and <prospect_id>.
        <list_id> is the Pardot list ID of the list and <prospect_id> is the Pardot prospect ID
        of the prospect for the target list membership.
        """
        if not list_id:
            raise PardotAPIArgumentError('a list id is required to read a list membership.')
        if not prospect_id:
            raise PardotAPIArgumentError('a prospect id is required to read a list membership.')
        response = self._post(path='/do/read/list_id/{list_id}/prospect_id/{prospect_id}'.format(list_id=list_id,prospect_id=prospect_id), params=kwargs)
        return response

    def read_by_id(self, id=None, **kwargs):
        """
        Returns the data for the list membership specified by <id>. <id> is the Pardot ID of the target list membership.
        """
        if not id:
            raise PardotAPIArgumentError('ID is required to read a list membership.')
        response = self._post(path='/do/read/id/{id}'.format(id=id), params=kwargs)
        return response

    def update(self, list_id=None, prospect_id=None, **kwargs):
        """
        Updates the provided data for a list membership specified by <list_id> and <prospect_id>.
        <list_id> is the Pardot list ID of the list and <prospect_id> is the Pardot prospect ID
        of the prospect for the target list membership. Fields that are not updated by the request remain unchanged.
        """
        if not list_id:
            raise PardotAPIArgumentError('a list ID is required to update a list membership.')
        if not prospect_id:
            raise PardotAPIArgumentError('a prospect ID is required to update a list membership.')
        response = self._post(path='/do/update/list_id/{list_id}/prospect_id/{prospect_id}'.format(list_id=list_id,prospect_id=prospect_id), params=kwargs)
        return response

    def update_by_id(self, id=None, **kwargs):
        """
        Updates the provided data for a list membership specified by <id>. <id> is the Pardot ID of the target list membership.
        Fields that are not updated by the request remain unchanged.
        """
        if not id:
            raise PardotAPIArgumentError('id is required to update a list membership.')
        response = self._post(path='/do/update/id/{id}'.format(id=id), params=kwargs)
        return response

    def delete(self, list_id=None, prospect_id=None, **kwargs):
        """
        Deletes the list membership specified by <list_id> and <prospect_id>.
        <list_id> is the Pardot list ID of the list and <prospect_id> is the Pardot prospect ID
        of the prospect for the target list membership. Returns HTTP 204 No Content on success.
        """
        if not list_id:
            raise PardotAPIArgumentError('a list ID is required to delete a list membership.')
        if not prospect_id:
            raise PardotAPIArgumentError('a prospect ID is required to delete a list membership.')
        response = self._post(path='/do/delete/list_id/{list_id}/prospect_id/{prospect_id}'.format(list_id=list_id,prospect_id=prospect_id), params=kwargs)
        if response == 204:
            return True
        return False

    def delete_by_id(self, id=None, **kwargs):
        """
        Deletes the list membership specified by <id>. <id> is the Pardot ID of the target list membership.
        Returns HTTP 204 No Content on success.
        """
        if not id:
            raise PardotAPIArgumentError('id is required to delete a list membership.')
        response = self._post(path='/do/delete/id/{id}'.format(id=id), params=kwargs)
        if response == 204:
            return True
        return False

    def _get(self, object_name='listMembership', path=None, params=None):
        """GET requests for the List Membership object."""
        if params is None:
            params = {}
        response = self.client.get(object_name=object_name, path=path, params=params)
        return response

    def _post(self, object_name='listMembership', path=None, params=None):
        """POST requests for the List Membership object."""
        if params is None:
            params = {}
        response = self.client.post(object_name=object_name, path=path, params=params)
        return response


text:
Forma de Pago

                 Seleccione la forma de pago y la periodicidal con la que se realizaran.

                <?php foreach ($estudiante as $key => $info) {?>

Nombre del estudiante: <?php echo $info['NomCompleto']?>

Nombre del tutor:

Cuenta:

                    <input type="hidden" id="FP"
                           data-mood='create'
                           data-ID='<?php echo $info['IDExp'];?>'
                           data-User='<?php echo $info['IdUsuario'];?>'
                           data-Descuento='<?php echo $info['DescntoColegiatura'];?>'
                           data-Recargo='<?php echo CalculaRecargo($info['IDExp']);?>'>
                    <input type="hidden" id="REguardar" value="">

Servicios Contratados

                        <?php echo getCatOpcionesCheckBoxes("CatServicio", "REservicio[]") ?>

                        <button class="btn btn-success pull-right" id="REguardar" data-save-ID="">

                                  Guardar

                        </button>

                <?php }?>


text:
// This file is automatically generated.

package adila.db;

/*
 * HTC Desire 816 dual sim
 *
 * DEVICE: htc_a5dwg
 * MODEL: HTC Desire 816 dual sim
 */
final class htc5fa5dwg_htc20desire2081620dual20sim {
    public static final String DATA = "HTC|Desire 816 dual sim|";
}


text:
package com.example.datacatalog;

// [START data_catalog_get_tag_template]
import com.google.cloud.datacatalog.v1.DataCatalogClient;
import com.google.cloud.datacatalog.v1.GetTagTemplateRequest;
import com.google.cloud.datacatalog.v1.TagTemplate;
import com.google.cloud.datacatalog.v1.TagTemplateName;
import java.io.IOException;

// Sample to get tag template
public class GetTagTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "MY_PROJECT_ID";
    String location = "MY_LOCATION";
    String tagTemplateId = "MY_TAG_TEMPLATE_ID";
    TagTemplateName tagTemplate = TagTemplateName.of(projectId, location, tagTemplateId);
    getTagTemplate(tagTemplate);
  }

  public static void getTagTemplate(TagTemplateName template) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DataCatalogClient client = DataCatalogClient.create()) {
      GetTagTemplateRequest request =
          GetTagTemplateRequest.newBuilder().setName(template.toString()).build();
      TagTemplate tagTemplate = client.getTagTemplate(request);
      System.out.println("Tag template retrieved successfully :" + tagTemplate.getName());
    }
  }
}
// [END data_catalog_get_tag_template]


text:
(function($) {

  var Pagination = Cell.create('Pagination');

  Pagination.prototype.initialize = function() {
    var _this = this;

    _this.page = _this.$target.data("page");
    _this.max = _this.$target.data("max");
    _this.form = _this.$target.find("form");

    _this.$target.on("click", '[data-pagination="prev"]', function(event) {
      if (_this.page == 1) {
        event.preventDefault();
        return;
      }
      _this.page--;
      Backlog.instances[0].refresh(true);
    });

    _this.$target.on("click", '[data-pagination="next"]', function(event) {
      if (_this.page == _this.max) {
        event.preventDefault();
        return;
      }
      _this.page++;
      Backlog.instances[0].refresh(true);
    });

    _this.$target.on("change", 'select', function() {
      _this.page = 1;
      Backlog.instances[0].refresh(true);
    });
  };

  Pagination.prototype.resetState = function(data) {
  };

  Pagination.prototype.options = function() {
    var _this = this;
    var pagination = _this.form.formParams()["pagination"];
    pagination.page = _this.page;

    return pagination;
  };
})(jQuery);


text:
package de.plushnikov.intellij.lombok.psi;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.impl.CheckUtil;
import com.intellij.psi.impl.light.LightMethod;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/**
 * @author Plushnikov Michail
 */
public class LombokLightMethodImpl extends LightMethod implements LombokLightMethod {

  private final PsiMethod myMethod;

  public LombokLightMethodImpl(@NotNull PsiManager manager, @NotNull PsiMethod valuesMethod, @NotNull PsiClass psiClass) {
    super(manager, valuesMethod, psiClass);
    myMethod = valuesMethod;
  }

  @Override
  public LombokLightMethod withNavigationElement(PsiElement navigationElement) {
    setNavigationElement(navigationElement);
    return this;
  }

  public PsiElement getParent() {
    PsiElement result = super.getParent();
    result = null != result ? result : getContainingClass();
    return result;
  }

  public PsiFile getContainingFile() {
    PsiClass containingClass = getContainingClass();
    return containingClass != null ? containingClass.getContainingFile() : null;
  }

  public PsiElement copy() {
    return new LombokLightMethodImpl(myManager, (PsiMethod) myMethod.copy(), getContainingClass());
  }

  public ASTNode getNode() {
    return myMethod.getNode();
  }

  @Override
  public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
    // just add new element to the containing class
    final PsiClass containingClass = getContainingClass();
    if (null != containingClass) {
      CheckUtil.checkWritable(containingClass);
      return containingClass.add(newElement);
    }
    return null;
  }

  @Override
  public void delete() throws IncorrectOperationException {
    // simple do nothing
  }

  @Override
  public void checkDelete() throws IncorrectOperationException {
    // simple do nothing
  }
}


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using Gtk;
using Perspex.Platform;

namespace Perspex.Gtk
{
    public class PopupImpl : WindowImpl, IPopupImpl
    {
        public PopupImpl()
            : base(WindowType.Popup)
        {
        }

        public void SetPosition(Point p)
        {
            Move((int)p.X, (int)p.Y);
        }
    }
}


text:
%% Ray trace optics model based on synthetic PSFs
%
% Illustrate a *ray trace* calculation uses space-varying and
% wavelength dependent point spread functions.  Sometimes these
% are generated by Zemax models, but they cal also be based on a
% synthetic ray trace data set.
%
% The synthetic point spreads generated here are bivariate
% normals that increase from center to periphery.
%
% See also: rtSynthetic
%
% (c) Imageval Consulting LLC, 2012

%%
ieInit

%% Create a test scene
scene = sceneCreate('point array',256);
% scene = sceneCreate('sweepfrequency',256); % An alternative

scene = sceneSet(scene,'h fov',3);
scene = sceneInterpolateW(scene,550:100:650);
ieAddObject(scene);
sceneWindow;

%% Build the optical image

oi = oiCreate('raytrace');
rtOptics = []; spreadLimits = [1 3]; xyRatio = 1.6;
rtOptics = rtSynthetic(oi,rtOptics,spreadLimits,xyRatio);
oi = oiSet(oi,'optics',rtOptics);
rtPSFVisualize(rtOptics);

%%
oi = oiCompute(oi,scene);
oi = oiSet(oi,'name','Synthetic-RT-Increasing-Gaussian');
ieAddObject(oi); oiWindow;

%% Show the PSF
rtPlot(oi,'psf',550,0);
rtPlot(oi,'psf',550,1);

%%


text:
<meta charset="UTF-8">
<title>com.github.rs3vans.krypto.java.io.InputStream - </title>
<link rel="stylesheet" href="../../style.css">

com.github.rs3vans.krypto / java.io.InputStream

Extensions for java.io.InputStream

toBytes

fun InputStream.toBytes(): Bytes

Extension function that converts an InputStream to an instance of Bytes.


text:
Categorical_property_pie_chart::Categorical_property_pie_chart(Geostat_grid* grid,
                                    Grid_categorical_property* cat_prop,
                                    Grid_continuous_property* weight_prop,
                                    Grid_filter* filter, QWidget *parent ) :
Chart_base(parent), grid_(grid), cat_prop_(cat_prop), weight_prop_(weight_prop), filter_(filter)
{

  QString title = QString("Pie chart for %1").arg(cat_prop_->name().c_str());

  this->setWindowTitle(title);
  this->setWindowIcon(QPixmap(":/icons/appli/Pixmaps/ar2gems-icon-256x256.png"));

  QSplitter* main_splitter = new QSplitter(Qt::Horizontal, this);

  QTabWidget* chart_tab = new QTabWidget(main_splitter);

  QSplitter* chart_splitter = new QSplitter(Qt::Vertical, chart_tab);

  chart_widget_ = new Chart_widget(chart_splitter);
  chart_control_ = new Chart_display_control( chart_splitter );
  chart_widget_->set_controler(chart_control_);

  chart_splitter->addWidget( chart_widget_ );
  chart_splitter->addWidget( chart_control_ );

  QVTKWidget* pie_widget = new QVTKWidget(chart_tab);
	vtkSmartPointer<vtkContextView> pie_context_view = vtkSmartPointer<vtkContextView>::New();
	pie_context_view->SetInteractor(pie_widget->GetInteractor());
	pie_widget->SetRenderWindow(pie_context_view->GetRenderWindow());
	pie_chart_ = vtkSmartPointer<vtkChartPie>::New();
	pie_context_view->GetScene()->AddItem(pie_chart_);

  chart_tab->addTab(pie_widget, "Pie" );
  chart_tab->addTab(chart_splitter, "Bars" );

  data_view_ = vtkSmartPointer<vtkQtTableView>::New();
  data_view_->GetWidget()->setParent(main_splitter);

  main_splitter->addWidget( chart_tab );
  main_splitter->addWidget( data_view_->GetWidget() );

  main_splitter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));

  QFrame* report_frame = new QFrame(this);
  QPushButton* view_report_button = new QPushButton("View Report",report_frame);
  QPushButton* save_report_button = new QPushButton("Save Report",report_frame);
  QPushButton* save_figure_button = new QPushButton("Save Figure",report_frame);
  QHBoxLayout* report_layout = new QHBoxLayout(report_frame);
  report_layout->addStretch();
  report_layout->addWidget(save_figure_button);
  report_layout->addWidget(save_report_button);
  report_layout->addWidget(view_report_button);
  report_frame->setLayout(report_layout);

  report_frame->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum));

  QVBoxLayout* main_layout = new QVBoxLayout(this);

  main_layout->addWidget(main_splitter);
  main_layout->addWidget(report_frame);

  this->setLayout(main_layout);

  this->build_value_table();
  this->build_plot();
  data_view_->SetRepresentationFromInput(table_);
  data_view_->Update();

  QTableView* table = dynamic_cast<QTableView*>(data_view_->GetWidget());
  bool ok = connect(table, SIGNAL(clicked(const QModelIndex &)), this, SLOT(cutoff_selected(const QModelIndex &)) );
  ok = connect( save_figure_button, SIGNAL(clicked()), chart_widget_, SLOT(save_figure()) );

}

void Categorical_property_pie_chart::build_value_table(){

  CategoricalPropertyDefinition* cdef = cat_prop_->get_category_definition();
  std::vector<double> proportions(cat_prop_->get_number_of_category(), 0.0);

  float sum_weight = 0.0;
  for(int i=0; i<cat_prop_->size(); ++i) {

    if( !cat_prop_->is_informed(i) ) continue;
    if(filter_ && !filter_->is_valid_nodeid(i)) continue;
    float weight = weight_prop_?weight_prop_->get_value(i):1;
    sum_weight += weight;

    int cat_id = cat_prop_->get_value(i);
    int cat_index = cdef->index_from_category_id( cat_id );

    proportions[cat_index]+=weight;

  }

  vtkSmartPointer<vtkFloatArray> proportion_array = vtkSmartPointer<vtkFloatArray>::New();
  proportion_array->SetName("Proportion");
  proportion_array->SetNumberOfValues(cat_prop_->get_number_of_category());

  vtkSmartPointer<vtkDoubleArray> index_array = vtkSmartPointer<vtkDoubleArray>::New();
  index_array->SetName("Category");
  index_array->SetNumberOfValues(cat_prop_->get_number_of_category());

  vtkSmartPointer<vtkStringArray> cat_name_array = vtkSmartPointer<vtkStringArray>::New();
  cat_name_array->SetName("Category Name");
  cat_name_array->SetNumberOfValues(cat_prop_->get_number_of_category());

  for(int i=0; i<proportion_array->GetNumberOfTuples(); ++i) {
    proportion_array->SetValue(i,proportions[i]/sum_weight);
    index_array->SetValue(i,i);
    cat_name_array->SetValue(i,cdef->get_category_name_from_index(i));
  }

  table_ = vtkSmartPointer<vtkTable>::New();
  table_->AddColumn(index_array);
  table_->AddColumn(cat_name_array);
  table_->AddColumn(proportion_array);

}

void Categorical_property_pie_chart::build_plot()
{

  vtkPlotBar* plot_bar = vtkPlotBar::SafeDownCast(chart_widget_->chart()->AddPlot(vtkChart::BAR ));
  plot_bar->SetInputData(table_,0,2);
  plot_bar->SetColor(0.2,0.2,0.8);

  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->SetMinimumLimit( -0.5 );
  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->SetMaximumLimit( table_->GetNumberOfRows() + 0.5 );
  //chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->SetBehavior(1);
  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->SetTitle("Category");

  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->SetCustomTickPositions(vtkDoubleArray::SafeDownCast(table_->GetColumn(0)),
                                                                           vtkStringArray::SafeDownCast( table_->GetColumn(1) ));
  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->GetLabelProperties()->SetOrientation(90);
  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->GetLabelProperties()->SetVerticalJustification(VTK_TEXT_CENTERED);
  chart_widget_->chart()->GetAxis(vtkAxis::BOTTOM)->GetLabelProperties()->SetJustification(VTK_TEXT_RIGHT);

  chart_widget_->chart()->GetAxis(vtkAxis::LEFT)->SetMinimumLimit( 0 );
  chart_widget_->chart()->GetAxis(vtkAxis::LEFT)->SetTitle(table_->GetColumnName(2));
  chart_widget_->chart()->GetAxis(vtkAxis::LEFT)->SetMaximumLimit(1);

  vtkPlotPie* plot_pie = vtkPlotPie::SafeDownCast(pie_chart_->AddPlot(0));
  plot_pie->SetInputData(table_);
  plot_pie->SetInputArray(0,"Proportion");
  plot_pie->SetLabels( vtkStringArray::SafeDownCast( table_->GetColumn(1) ) );
  pie_chart_->SetShowLegend(true);
  pie_chart_->SetTitle(cat_prop_->name().c_str());

   vtkSmartPointer<vtkColorSeries> color_series = vtkSmartPointer<vtkColorSeries>::New();
   color_series->ClearColors();
   int ncat = cat_prop_->get_number_of_category();
   const CategoricalPropertyDefinition* cdef = cat_prop_->get_category_definition();
   for(int i=0; i<ncat; ++i) {
     Color color = cdef->color_from_index(i);
     vtkColor3ub vtk_color(color.redF() * 255, color.greenF() * 255, color.blueF() * 255);
     color_series->AddColor(vtk_color);
   }

   plot_pie->SetColorSeries(color_series);

}


text:
package io.quarkus.it.kubernetes;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

import org.assertj.core.api.AbstractObjectAssert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Service;
import io.quarkus.test.ProdBuildResults;
import io.quarkus.test.ProdModeTestResults;
import io.quarkus.test.QuarkusProdModeTest;

public class OpenshiftV3Test {

    @RegisterExtension
    static final QuarkusProdModeTest config = new QuarkusProdModeTest()
            .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
            .setApplicationName("openshift-v3")
            .setApplicationVersion("0.1-SNAPSHOT")
            .withConfigurationResource("openshift-v3.properties");

    @ProdBuildResults
    private ProdModeTestResults prodModeTestResults;

    @Test
    public void assertGeneratedResources() throws IOException {
        Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
        assertThat(kubernetesDir)
                .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.json"))
                .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.yml"))
                .satisfies(p -> assertThat(p.toFile().listFiles()).hasSize(2));
        List<HasMetadata> openshiftList = DeserializationUtil
                .deserializeAsList(kubernetesDir.resolve("openshift.yml"));

        assertThat(openshiftList).filteredOn(h -> "DeploymentConfig".equals(h.getKind())).singleElement().satisfies(h -> {
            assertThat(h.getMetadata()).satisfies(m -> {
                assertThat(m.getName()).isEqualTo("openshift-v3");
                assertThat(m.getLabels().get("app.openshift.io/runtime")).isEqualTo("quarkus");
                assertThat(m.getLabels().get("app.kubernetes.io/name")).isEqualTo("openshift-v3");
                assertThat(m.getLabels().get("app")).isEqualTo("openshift-v3");
                assertThat(m.getNamespace()).isNull();
            });
            AbstractObjectAssert<?, ?> specAssert = assertThat(h).extracting("spec");
            specAssert.extracting("selector").isInstanceOfSatisfying(Map.class, selectorsMap -> {
                assertThat(selectorsMap).containsOnly(entry("app.kubernetes.io/name", "openshift-v3"),
                        entry("app.kubernetes.io/version", "0.1-SNAPSHOT"));
            });
        });

        assertThat(openshiftList).filteredOn(h -> "Service".equals(h.getKind())).singleElement().satisfies(h -> {
            assertThat(h).isInstanceOfSatisfying(Service.class, s -> {
                assertThat(s.getMetadata()).satisfies(m -> {
                    assertThat(m.getNamespace()).isNull();
                    assertThat(m.getLabels().get("app.kubernetes.io/name")).isEqualTo("openshift-v3");
                    assertThat(m.getLabels().get("app")).isEqualTo("openshift-v3");
                });

                assertThat(s.getSpec()).satisfies(spec -> {
                    assertThat(spec.getSelector()).containsOnly(entry("app.kubernetes.io/name", "openshift-v3"),
                            entry("app.kubernetes.io/version", "0.1-SNAPSHOT"));
                });
            });
        });
    }
}


text:
vtk_module(vtkFiltersCore
  GROUPS
    StandAlone
  DEPENDS
    vtkCommonExecutionModel
    vtkCommonSystem
    vtkCommonMisc
    vtkCommonTransforms
    vtkCommonMath
  TEST_DEPENDS
    vtkTestingRendering
    vtkInteractionStyle
    vtkIOLegacy
    vtkIOXML
    vtkImagingCore
    vtkFiltersGeneral
    vtkRendering${VTK_RENDERING_BACKEND}
  KIT
    vtkFilters
  )


text:
using Sharepoint.Client.Fluent.FluentBase;

namespace Sharepoint.Client.Fluent.Tests.TestImplementations.Common
{
    internal class SharepointFluentBaseImplementationForTests : SharepointFluentBase
    {
        internal SharepointFluentBaseImplementationForTests(ISharepointContext context) : base(context)
        {
        }

        internal ISharepointContext GetSharepointContext()
        {
            return this.sharepointContext;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>NFLogger: NFLogger() Category Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

NFLogger

Properties |
List of all members

NFLogger() Category Reference

Properties

NSInteger 	uploadInterval

id< NFLOGBehaviour > 	logBehaviour

The documentation for this category was generated from the following file:

/Users/nileshagrawal/Documents/workspace/interviewprojects/netflix/NFLogger/NFLogger/NFLogger.m

<address class="footer">
Generated by

 1.8.13
</address>


text:
#ifndef AliAnalysisTaskCheckSingleTrackJetRejection_cxx
#define AliAnalysisTaskCheckSingleTrackJetRejection_cxx

class AliJetHeader;
class AliESDEvent;
class AliAODEvent;
class AliAODJet;
class AliGenPythiaEventHeader;
class AliCFManager;

class TList;
class TChain;
class TH2F;
class TH1F;
class TH3F;
class TProfile;

#include "AliAnalysisTaskSE.h"
#include  "THnSparse.h" // cannot forward declare ThnSparseF
#include <TList.h>
#include <TH1F.h>
#include <TH2F.h>

class AliAnalysisTaskCheckSingleTrackJetRejection : public AliAnalysisTaskSE
{
	public:
		AliAnalysisTaskCheckSingleTrackJetRejection();
		AliAnalysisTaskCheckSingleTrackJetRejection(const char *name);
		virtual ~AliAnalysisTaskCheckSingleTrackJetRejection() {;}

		// Implementation of interface methods
		virtual void    UserCreateOutputObjects();
		virtual void    Init();
		virtual Bool_t  Notify();
		virtual void    UserExec(Option_t *option);
		virtual void    Terminate(Option_t *);
		virtual void    SetDebug(Int_t debug = 0) {fDebug = debug;}
		virtual void    SetAlgorithm(TString jf="ANTIKT"){JFAlg=jf;}
		virtual void    SetRadius(Float_t radius=0.4){Radius=radius;}
		virtual void    SetFilterMask(UInt_t filter=256){Filtermask=filter;}
		virtual void    SetBackSubMode(Int_t backM=0){BackM=backM;}
		virtual void    SetTrackPtCut(Float_t tPtcut=0){TrackPtcut=tPtcut;}
		virtual void    SetSkipCone(Int_t skipCone=0){SkipCone=skipCone;}
		virtual void    SetMC(Bool_t ismc=kFALSE){IsMC=ismc;}
    virtual void    FinishTaskOutput();
    virtual Bool_t  PythiaInfoFromFile(const char* currFile,Float_t &fXsec,Float_t &fTrials);
    //virtual Float_t GetTotalEvents(const char* currFile);
    virtual Double_t DeltaPhi(Double_t phi1,Double_t phi2);
    virtual Double_t DeltaR(Double_t phi1,Double_t phi2,Double_t eta1,Double_t eta2);

		enum {kNPTBINS=10};

		// 0 all jets
		// 1 all jet in eta window
		// 2 all jets with partner
		// 3 all jets in eta window with partner
		// 4 all jets with partner in eta window
		enum {kStep0 = 0, kStep1, kStep2, kStep3, kStep4,kMaxStep};

	private:
		AliAnalysisTaskCheckSingleTrackJetRejection(const AliAnalysisTaskCheckSingleTrackJetRejection &det); // not implemented
		AliAnalysisTaskCheckSingleTrackJetRejection& operator=(const AliAnalysisTaskCheckSingleTrackJetRejection &det); // not implemented

    Bool_t  JetSelected(AliAODJet *jet);

		Bool_t        fUseAODInput; // read jets from input AOD
		Bool_t        fFillAOD;     // option to fill AOD branch
		TString       fNonStdFile;
		TString       fJetBranch;   // jet branch to read

		AliAODEvent     *fAODIn;      // AOD event
		AliAODEvent     *fAODOut;      // AOD event
		AliAODExtension *fAODExtension;
		TString         JFAlg;
		Float_t         Radius;
		UInt_t          Filtermask;
		Int_t           BackM;
		Float_t         TrackPtcut;
		Int_t           SkipCone;
		Bool_t          IsMC;

		TList        *fHistList; // Output list
		Float_t       fxsec;
		Float_t       ftrial;
		Float_t       fJetRecEtaWindow;       // eta window for rec jets
		Float_t       fMinJetPt;              // limits the jet p_T in addition to what already is done in the jet finder, this is important for jet matching for JF with lo threshold

		TProfile     *fH1Xsec;
		TH1F         *fH1Trials;
		TH1F         *fH1Events;

		TH1F         *fH1jetMCAKT04_pt         [6];
		TH2F         *fH2jetMCAKT04_Jetpt_maxpt;
		TH1F         *fH1jetAKT04_pt           [6];
		TH2F         *fH2jetAKT04_Jetpt_maxpt  ;

		TH2F         *fH2jetMCAKT04_Eratio       [6];
		TH1F         *fH1jetMCAKT04_ptmatch        [6];

		ClassDef(AliAnalysisTaskCheckSingleTrackJetRejection, 13); // Analysis task for standard dijet analysis
};

#endif


text:
[![Version](https://img.shields.io/github/release/gabemdev/GMDKit.svg)](https://github.com/soffes/RateLimit/releases)
![Swift Version](https://img.shields.io/badge/swift-3.1.0-orange.svg)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![CocoaPods compatible](https://img.shields.io/cocoapods/v/GMDKit.svg)](https://cocoapods.org/pods/RateLimit)
[![License](https://img.shields.io/cocoapods/l/GMDKit.svg?style=flat)](http://cocoapods.org/pods/GMDKit)
[![Platform](https://img.shields.io/cocoapods/p/GMDKit.svg?style=flat)](http://cocoapods.org/pods/GMDKit)

## Usage

Pretty easy!

Open up the included [Xcode project](GMDKit.xcodeproj) for an [example app](Example).

## Installation
### CocoaPods

Add the following to your `Podfile`:

``` ruby
pod 'GMKit', :git => 'git@github.com:gabemdev/GMDKit.git'
```

Then run `pod install`.

## Contributing to this project
If you have feature requests or bug reports, feel free to help out by sending pull requests or by [creating new issues](https://github.com/gabemdev/GMDKit/issues/new).

Please take a moment to review the guidelines written by [Nicolas Gallagher](https://github.com/necolas/):

* [Bug reports](https://github.com/necolas/issue-guidelines/blob/master/CONTRIBUTING.md#bugs)
* [Feature requests](https://github.com/necolas/issue-guidelines/blob/master/CONTRIBUTING.md#features)
* [Pull requests](https://github.com/necolas/issue-guidelines/blob/master/CONTRIBUTING.md#pull-requests)

## Credits
GMDKit is brought to you by [Gabe Morales](http://gabemdev.com) and [contributors to the project](https://github.com/gabemdev/GMDKit/contributors).

If you're using GMKit in your project, attribution would be nice.

## License
GMKit is released under MIT License.


text:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="#xslt"?>
<!DOCTYPE xsl:stylesheet [<!ATTLIST xsl:stylesheet id ID #IMPLIED>]>
<xsl:stylesheet id="xslt" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="xsl:stylesheet[not(@xml-version)]//xsl:comment/text()">
<result><xsl:value-of select="translate(.,'pass','FAIL')"/></result>
<xsl:comment>PASS</xsl:comment>
</xsl:template>
</xsl:stylesheet>


text:
class PrefRegistrySimple;

namespace ash {

// Registers all Saml-related profile prefs.
void RegisterSamlProfilePrefs(PrefRegistrySimple* registry);

}  // namespace ash

// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos
// source migration is finished.
namespace chromeos {
using ::ash::RegisterSamlProfilePrefs;
}

#endif  // CHROME_BROWSER_ASH_LOGIN_SAML_SAML_PROFILE_PREFS_H_


text:
"use strict";
var LocalStorageService = (function () {
    function LocalStorageService($window) {
        this.$window = $window;
    }
    LocalStorageService.prototype.set = function (key, value) {
        this.$window.localStorage[key] = value;
    };
    LocalStorageService.prototype.get = function (key, defaultValue) {
        return this.$window.localStorage[key] || defaultValue;
    };
    LocalStorageService.prototype.remove = function (key) {
        this.$window.localStorage.removeItem(key);
    };
    LocalStorageService.prototype.setObject = function (key, value) {
        this.$window.localStorage[key] = JSON.stringify(value);
    };
    LocalStorageService.prototype.getObject = function (key, defaultValue) {
        var val = this.$window.localStorage[key];
        if (val === undefined)
            return defaultValue;
        return JSON.parse(val);
    };
    LocalStorageService.prototype.isDefined = function (key) {
        return this.$window.localStorage[key] !== undefined;
    };
    return LocalStorageService;
}());
var HighscoresService = (function () {
    function HighscoresService($localstorage) {
        this.$localstorage = $localstorage;
        this.highscores = this.$localstorage.getObject("highscores", {});
    }
    HighscoresService.prototype.highscoresMap = function () {
        return this.highscores;
    };
    HighscoresService.prototype.register = function (name, size, sortCrit) {
        if (this.highscores[name] === undefined)
            this.highscores[name] = { vals: [], size: size, sortCrit: sortCrit };
        else
            this.highscores[name].size = size;
        this.$localstorage.setObject('highscores', this.highscores);
    };
    HighscoresService.prototype.isInHighscore = function (name, val) {
        var h = this.highscores[name];
        if (h.vals.length < h.size)
            return true;
        if (h.sortCrit == '+')
            return _.sortedIndexBy(h.vals, { key: val }, 'key') < h.size;
        else
            return h.vals.some(function (el) {
                return val > el.key;
            });
    };
    HighscoresService.prototype.addToHighScore = function (name, data) {
        var h = this.highscores[name];
        var index = h.vals.length;
        if (h.sortCrit == '+') {
            index = _.sortedIndexBy(h.vals, data, 'key');
        }
        else if (h.sortCrit == '-') {
            h.vals.some(function (el, i) {
                if (data.key > el.key) {
                    index = i;
                    return true;
                }
                return false;
            });
        }
        h.vals.splice(index, 0, data);
        if (h.vals.length > h.size)
            h.vals.splice(h.size, 1);
        this.$localstorage.setObject('highscores', this.highscores);
    };
    HighscoresService.prototype.clear = function () {
        for (var _i = 0, _a = Object.keys(this.highscores); _i < _a.length; _i++) {
            var key = _a[_i];
            this.highscores[key].vals = [];
        }
        this.$localstorage.setObject('highscores', this.highscores);
    };
    return HighscoresService;
}());
angular.module('reverseApp.services', [])
    .factory('$localstorage', ['$window', function ($window) {
        return new LocalStorageService($window);
    }])
    .factory('highscores', ['$localstorage', function ($localstorage) {
        return new HighscoresService($localstorage);
    }]);
//# sourceMappingURL=services.js.map


text:
yii.formSubmitter = (function ($) {
    var pub = {
        // whether this module is currently active. If false, init() will not be called for this module
        // it will also not be called for all its child modules. If this property is undefined, it means true.
        isActive: true,
        init: function () {
            initDataMethod();
        },
        handleAction: function ($e) {
            var actionUrl = $e.data('action');
            if (actionUrl === undefined) {
                return true;
            }

            var $form = $e.closest('form');
            if ($form.length) {
                $form.attr('action', actionUrl);
            } else {
                return true;
            }

            var activeFormData = $form.data('yiiActiveForm');
            if (activeFormData) {
                // remember who triggers the form submission. This is used by yii.activeForm.js
                activeFormData.submitObject = $e;
            }

            $form.trigger('submit');

            return false;
        }
    };

    function initDataMethod()
    {
        var $document = $(document);
        // handle data-confirm and data-method for clickable elements
        $document.on('click.yii', yii.clickableSelector, function (event) {
            var $this = $(this);
            if (yii.allowAction($this)) {
                return pub.handleAction($this);
            } else {
                event.stopImmediatePropagation();
                return false;
            }
        });
    }

    return pub;
})(jQuery);

jQuery(document).ready(function () {
    yii.initModule(yii.formSubmitter);
});


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="prefetch" href="../../../../ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">

    <meta name="application-name" content="Python.org">
    <meta name="msapplication-tooltip" content="The official home of the Python Programming Language">
    <meta name="apple-mobile-web-app-title" content="Python.org">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="HandheldFriendly" content="True">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="cleartype" content="on">
    <meta http-equiv="imagetoolbar" content="false">

    <link href="../../../static/stylesheets/style.css" rel="stylesheet" type="text/css" title="default" />
    <link href="../../../static/stylesheets/mq.css" rel="stylesheet" type="text/css" media="not print, braille, embossed, speech, tty" />

    <link rel="icon" type="image/x-icon" href="https://www.python.org/static/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../../static/apple-touch-icon-144x144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../../static/apple-touch-icon-114x114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../../static/apple-touch-icon-72x72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../../../static/apple-touch-icon-precomposed.png">
    <link rel="apple-touch-icon" href="../../../static/apple-touch-icon-precomposed.png">

    <meta name="msapplication-TileImage" content="/static/metro-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3673a5">
    <meta name="msapplication-navbutton-color" content="#3673a5">

    <meta property="og:site_name" content="Python.org">
    <meta property="og:type" content="website">

    <title>PEP 265 -- Sorting Dictionaries by Value | Python.org</title>
    <meta property="og:title" content="Welcome to Python.org">

    <meta name="description" content="The official home of the Python Programming Language">
    <meta name="og:description" content="The official home of the Python Programming Language">
    <meta name="keywords" content="Python programming language object oriented web free open source software license documentation download community">
    <meta property="og:tag" content="Python programming language object oriented web free open source software license documentation download community">
    <meta property="og:published_time" content="">
    <meta property="og:modified_time" content="">
    <meta property="og:author" content="">
    <meta property="og:section" content="">
    <meta property="og:url" content="">
    <meta property="og:image" content="">
    <meta property="og:video" content="">

    <link rel="author" href="https://www.python.org/static/humans.txt">

Notice: While Javascript is not essential for this website, your interaction with the content will be limited. Please turn Javascript on for the full experience.

                    Skip to content

                    ▼ Close

        Python

        PSF

        Docs

        PyPI

        Jobs

        Community

                    ▲ The Python Network

                    ≡ Menu<form class="search-the-site" action="https://www.python.org/search/" method="get">
                        <fieldset title="Search Python.org">

                            Search This Site
                            <input id="id-search-field" name="q" type="search" role="textbox" class="search-field" placeholder="Search" value="" tabindex="1">

                            <button type="submit" name="submit" id="submit" class="search-button" title="Submit this Search" tabindex="3">
                                GO
                            </button>

                        </fieldset>
                    </form>

                                A A

Smaller

Larger

Reset

                                Socialize

Google+

Facebook

Twitter

Chat on IRC

                                Sign In

Sign Up / Register

Sign In

        About

Applications

Quotes

Getting Started

Help

        Downloads

All releases

Source code

Windows

Mac OS X

Other Platforms

License

Alternative Implementations

        Documentation

Docs

Audio/Visual Talks

Beginner's Guide

Developer's Guide

FAQ

Non-English Docs

PEP Index

Python Books

        Community

Diversity

IRC

Mailing Lists

Python Conferences

Special Interest Groups

Python Wiki

Python Logo

Merchandise

Community Awards

        Success Stories

Arts

Business

Education

Engineering

Government

Scientific

Software Development

        News

Python News

Community News

PSF News

PyCon News

        Events

Python Events

User Group Events

Python Events Archive

User Group Events Archive

Submit an Event

        Python>>>

        Python Developer's Guide>>>

        PEP Index>>>

PEP 265 -- Sorting Dictionaries by Value

PEP 265 -- Sorting Dictionaries by Value

      PEP:

      265

      Title:

      Sorting Dictionaries by Value

      Author:

      Grant Griffin <g2 at iowegian.com>

      Status:

      Rejected

      Type:

      Standards Track

      Created:

      8-Aug-2001

      Python-Version:

      2.2

      Post-History:

    Abstract

    This PEP suggests a "sort by value" operation for dictionaries.
    The primary benefit would be in terms of "batteries included"
    support for a common Python idiom which, in its current form, is
    both difficult for beginners to understand and cumbersome for all
    to implement.

    BDFL Pronouncement

    This PEP is rejected because the need for it has been largely
    fulfilled by Py2.4's sorted() builtin function:

        >>> sorted(d.iteritems(), key=itemgetter(1), reverse=True)
        [('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]

    or for just the keys:

        sorted(d, key=d.__getitem__, reverse=True)
        ['b', 'd', 'c', 'a', 'e']

    Also, Python 2.5's heapq.nlargest() function addresses the common use
    case of finding only a few of the highest valued items:

        >>> nlargest(2, d.iteritems(), itemgetter(1))
        [('b', 23), ('d', 17)]

    Motivation

    A common use of dictionaries is to count occurrences by setting
    the value of d[key] to 1 on its first occurrence, then increment
    the value on each subsequent occurrence.  This can be done several
    different ways, but the get() method is the most succinct:

            d[key] = d.get(key, 0) + 1

    Once all occurrences have been counted, a common use of the
    resulting dictionary is to print the occurrences in
    occurrence-sorted order, often with the largest value first.

    This leads to a need to sort a dictionary's items by value.  The
    canonical method of doing so in Python is to first use d.items()
    to get a list of the dictionary's items, then invert the ordering
    of each item's tuple from (key, value) into (value, key), then
    sort the list; since Python sorts the list based on the first item
    of the tuple, the list of (inverted) items is therefore sorted by
    value.  If desired, the list can then be reversed, and the tuples
    can be re-inverted back to (key, value).  (However, in my
    experience, the inverted tuple ordering is fine for most purposes,
    e.g. printing out the list.)

    For example, given an occurrence count of:

        >>> d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}

    we might do:

        >>> items = [(v, k) for k, v in d.items()]
        >>> items.sort()
        >>> items.reverse()             # so largest is first
        >>> items = [(k, v) for v, k in items]

    resulting in:

        >>> items
        [('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]

    which shows the list in by-value order, largest first.  (In this
    case, 'b' was found to have the most occurrences.)

    This works fine, but is "hard to use" in two aspects.  First,
    although this idiom is known to veteran Pythoneers, it is not at
    all obvious to newbies -- either in terms of its algorithm
    (inverting the ordering of item tuples) or its implementation
    (using list comprehensions -- which are an advanced Python
    feature.)  Second, it requires having to repeatedly type a lot of
    "grunge", resulting in both tedium and mistakes.

    We therefore would rather Python provide a method of sorting
    dictionaries by value which would be both easy for newbies to
    understand (or, better yet, not to _have to_ understand) and
    easier for all to use.

    Rationale

    As Tim Peters has pointed out, this sort of thing brings on the
    problem of trying to be all things to all people.  Therefore, we
    will limit its scope to try to hit "the sweet spot".  Unusual
    cases (e.g. sorting via a custom comparison function) can, of
    course, be handled "manually" using present methods.

    Here are some simple possibilities:

    The items() method of dictionaries can be augmented with new
    parameters having default values that provide for full
    backwards-compatibility:

        (1) items(sort_by_values=0, reversed=0)

    or maybe just:

        (2) items(sort_by_values=0)

    since reversing a list is easy enough.

    Alternatively, items() could simply let us control the (key, value)
    order:

        (3) items(values_first=0)

    Again, this is fully backwards-compatible.  It does less work than
    the others, but it at least eases the most complicated/tricky part
    of the sort-by-value problem: inverting the order of item tuples.
    Using this is very simple:

        items = d.items(1)
        items.sort()
        items.reverse()         # (if desired)

    The primary drawback of the preceding three approaches is the
    additional overhead for the parameter-less "items()" case, due to
    having to process default parameters.  (However, if one assumes
    that items() gets used primarily for creating sort-by-value lists,
    this is not really a drawback in practice.)

    Alternatively, we might add a new dictionary method which somehow
    embodies "sorting".  This approach offers two advantages.  First,
    it avoids adding overhead to the items() method.  Second, it is
    perhaps more accessible to newbies: when they go looking for a
    method for sorting dictionaries, they hopefully run into this one,
    and they will not have to understand the finer points of tuple
    inversion and list sorting to achieve sort-by-value.

    To allow the four basic possibilities of sorting by key/value and in
    forward/reverse order, we could add this method:

        (4) sorted_items(by_value=0, reversed=0)

    I believe the most common case would actually be "by_value=1,
    reversed=1", but the defaults values given here might lead to
    fewer surprises by users: sorted_items() would be the same as
    items() followed by sort().

    Finally (as a last resort), we could use:

        (5) items_sorted_by_value(reversed=0)

    Implementation

    The proposed dictionary methods would necessarily be implemented
    in C.  Presumably, the implementation would be fairly simple since
    it involves just adding a few calls to Python's existing
    machinery.

    Concerns

    Aside from the run-time overhead already addressed in
    possibilities 1 through 3, concerns with this proposal probably
    will fall into the categories of "feature bloat" and/or "code
    bloat".  However, I believe that several of the suggestions made
    here will result in quite minimal bloat, resulting in a good
    tradeoff between bloat and "value added".

    Tim Peters has noted that implementing this in C might not be
    significantly faster than implementing it in Python today.
    However, the major benefits intended here are "accessibility" and
    "ease of use", not "speed".  Therefore, as long as it is not
    noticeably slower (in the case of plain items(), speed need not be
    a consideration.

    References

    A related thread called "counting occurrences" appeared on
    comp.lang.python in August, 2001.  This included examples of
    approaches to systematizing the sort-by-value problem by
    implementing it as reusable Python functions and classes.

    Copyright

    This document has been placed in the public domain.

Source: https://hg.python.org/peps/file/tip/pep-0265.txt

        Tweets by @ThePSF

The PSF

The Python Software Foundation is the organization behind Python. Become a member of the PSF and help advance the software and our mission.

                    ▲ Back to Top

        About

Applications

Quotes

Getting Started

Help

        Downloads

All releases

Source code

Windows

Mac OS X

Other Platforms

License

Alternative Implementations

        Documentation

Docs

Audio/Visual Talks

Beginner's Guide

Developer's Guide

FAQ

Non-English Docs

PEP Index

Python Books

        Community

Diversity

IRC

Mailing Lists

Python Conferences

Special Interest Groups

Python Wiki

Python Logo

Merchandise

Community Awards

        Success Stories

Arts

Business

Education

Engineering

Government

Scientific

Software Development

        News

Python News

Community News

PSF News

PyCon News

        Events

Python Events

User Group Events

Python Events Archive

User Group Events Archive

Submit an Event

        Contributing

Developer's Guide

Issue Tracker

python-dev list

Core Mentorship

                    ▲ Back to Top

Help & General Contact

Diversity Initiatives

Submit Website Bug

                            Copyright ©2001-2015.
                             Python Software Foundation
                             Legal Statements
                             Privacy Policy


text:
.sc-title {
  padding-bottom: var(--default-padding);
  font-weight: var(--strong-font-weight);
  letter-spacing: var(--heading-letterspacing);
  font-size: var(--h1-font-size);
}