text:
#ifndef QSQLCACHEDRESULT_P_H
#define QSQLCACHEDRESULT_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "QtSql/qsqlresult.h"

QT_BEGIN_NAMESPACE

class QVariant;
template <typename T> class QVector;

class QSqlCachedResultPrivate;

class Q_SQL_EXPORT QSqlCachedResult: public QSqlResult
{
public:
    virtual ~QSqlCachedResult();

    typedef QVector<QVariant> ValueCache;

protected:
    QSqlCachedResult(const QSqlDriver * db);

    void init(int colCount);
    void cleanup();
    void clearValues();

    virtual bool gotoNext(ValueCache &values, int index) = 0;

    QVariant data(int i);
    bool isNull(int i);
    bool fetch(int i);
    bool fetchNext();
    bool fetchPrevious();
    bool fetchFirst();
    bool fetchLast();

    int colCount() const;
    ValueCache &cache();

    void virtual_hook(int id, void *data);
    void detachFromResultSet();
    void setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy policy);
private:
    bool cacheNext();
    QSqlCachedResultPrivate *d;
};

QT_END_NAMESPACE

#endif // QSQLCACHEDRESULT_P_H


text:
package com.findide.data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xf on 2017/11/23.
 */
public class Page<T> {
    public static final int DEFAULT_PAGE_SIZE = 30;

    protected int pageNo = 1; // 当前页, 默认为第1页
    protected int pageSize = DEFAULT_PAGE_SIZE; // 每页记录数
    protected long totalRecord = -1; // 总记录数, 默认为-1, 表示需要查询
    protected int totalPage = -1; // 总页数, 默认为-1, 表示需要计算

    protected List<T> results; // 当前页记录List形式

    protected Map<String, Object> params = new HashMap<String, Object>();//设置页面传递的查询参数

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
        computeTotalPage();
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
        computeTotalPage();
    }

    protected void computeTotalPage() {
        if (getPageSize() > 0 && getTotalRecord() > -1) {
            this.totalPage = (int) (getTotalRecord() % getPageSize() == 0 ? getTotalRecord() / getPageSize() : getTotalRecord() / getPageSize() + 1);
        }
    }

    public  int getOffset(){
        return  (pageNo-1)*pageSize;
    }
    public List<T> getResults() {
        return results;
    }

    public void setResults(List<T> results) {
        this.results = results;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder().append("Page [pageNo=").append(pageNo).append(", pageSize=").append(pageSize)
                .append(", totalRecord=").append(totalRecord < 0 ? "null" : totalRecord).append(", totalPage=")
                .append(totalPage < 0 ? "null" : totalPage).append(", curPageObjects=").append(results == null ? "null" : results.size()).append("]");
        return builder.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Text;
#if NETSTANDARD
using System.Runtime.InteropServices;
using SystemOSPlatform = System.Runtime.InteropServices.OSPlatform;
using SystemArchitecture = System.Runtime.InteropServices.Architecture;
#endif

namespace Knapcode.TorSharp
{
    /// <summary>
    /// Settings for how TorSharp behaves.
    /// </summary>
    public class TorSharpSettings
    {
        public static readonly string DefaultToolsDirectory = Path.Combine(Path.GetTempPath(), "Knapcode.TorSharp");

        private ToolRunnerType? _toolRunnerType;

        public TorSharpSettings()
        {
            ReloadTools = false;
            EnableSecurityProtocolsForFetcher = true;
            ZippedToolsDirectory = Path.Combine(DefaultToolsDirectory, "ZippedTools");
            ExtractedToolsDirectory = Path.Combine(DefaultToolsDirectory, "ExtractedTools");
            WaitForConnect = TimeSpan.FromSeconds(5);

#if NETSTANDARD
            if (RuntimeInformation.IsOSPlatform(SystemOSPlatform.Windows))
            {
                OSPlatform = TorSharpOSPlatform.Windows;
            }
            else if (RuntimeInformation.IsOSPlatform(SystemOSPlatform.Linux))
            {
                OSPlatform = TorSharpOSPlatform.Linux;
            }
            else
            {
                OSPlatform = TorSharpOSPlatform.Unknown;
            }

            switch (RuntimeInformation.ProcessArchitecture)
            {
                case SystemArchitecture.X86:
                    Architecture = TorSharpArchitecture.X86;
                    break;
                case SystemArchitecture.X64:
                    Architecture = TorSharpArchitecture.X64;
                    break;
                default:
                    Architecture = TorSharpArchitecture.Unknown;
                    break;
            }
#else
            OSPlatform = TorSharpOSPlatform.Windows;
            Architecture = Environment.Is64BitProcess ? TorSharpArchitecture.X64 : TorSharpArchitecture.X86;
#endif

            PrivoxySettings = new TorSharpPrivoxySettings();
            TorSettings = new TorSharpTorSettings();
        }

        /// <summary>
        /// If true, the tools (Tor and Privoxy) will be re-downloaded by <see cref="TorSharpToolFetcher"/> even if the
        /// latest version is already downloaded and will be re-extracted by <see cref="TorSharpProxy"/> even if the
        /// latest version is already extracted. This is disabled by default.
        /// </summary>
        public bool ReloadTools { get; set; }

        /// <summary>
        /// Enable all SSL/TLS protocol on <see cref="System.Net.ServicePointManager.SecurityProtocol"/> so that
        /// requests to fetch the tools don't fail due to protocol mismatches. This is enabled by default.
        /// </summary>
        public bool EnableSecurityProtocolsForFetcher { get; set; }

        /// <summary>
        /// The way in which tools should be run. The default is <see cref="ToolRunnerType.VirtualDesktop"/> on Windows
        /// so that the Privoxy and Tor windows are not visible and <see cref="ToolRunnerType.Simple"/> for other
        /// operating systems.
        /// </summary>
        public ToolRunnerType ToolRunnerType
        {
            get
            {
                var toolRunnerType = _toolRunnerType;
                if (toolRunnerType == null)
                {
                    if (OSPlatform == TorSharpOSPlatform.Windows
                        && Environment.OSVersion.Version >= new Version(6, 2))
                    {
                        return ToolRunnerType.VirtualDesktop;
                    }
                    else
                    {
                        return ToolRunnerType.Simple;
                    }
                }
                else
                {
                    return toolRunnerType.Value;
                }
            }

            set
            {
                _toolRunnerType = value;
            }
        }

        /// <summary>
        /// The directory to download the zipped tools. This defaults to <c>%TEMP%\Knapcode.TorSharp\ZippedTools</c>.
        /// </summary>
        public string ZippedToolsDirectory { get; set; }

        /// <summary>
        /// The directory to extract the tools to and run them from.  This defaults to
        /// <c>%TEMP%\Knapcode.TorSharp\ExtractedTools</c>.
        /// </summary>
        public string ExtractedToolsDirectory { get; set; }

        /// <summary>
        /// Instead of downloading the latest version of the tools in <see cref="TorSharpToolFetcher"/>, use any
        /// existing tools already downloaded to <see cref="ZippedToolsDirectory"/>.
        /// </summary>
        public bool UseExistingTools { get; set; }

        /// <summary>
        /// What strategy to use when fetching the latest version of a tool. This behavior matters when there are
        /// multiple URLs or feeds that a checked for a single tool.
        /// </summary>
        public ToolDownloadStrategy ToolDownloadStrategy { get; set; }

        /// <summary>
        /// The operating system that TorSharp should assume it is running on. This defaults to
        /// <see cref="TorSharpOSPlatform.Windows"/> on .NET Framework and is automatically detected on .NET Core.
        /// </summary>
        public TorSharpOSPlatform OSPlatform { get; set; }

        /// <summary>
        /// The CPU architecture that TorSharp should assume it is runnong on. This is automatically detected using the
        /// architecture of the process.
        /// </summary>
        public TorSharpArchitecture Architecture { get; set; }

        /// <summary>
        /// How long to wait for each tool to accept connections while starting up. This allows for the tools to start
        /// up before completing the initialization process. Defaults to 5 seconds. This can be completely disabled by
        /// setting this property to <see cref="TimeSpan.Zero"/>.
        /// </summary>
        public TimeSpan WaitForConnect { get; set; }

        /// <summary>
        /// Settings specific to Privoxy.
        /// </summary>
        public TorSharpPrivoxySettings PrivoxySettings { get; set; }

        /// <summary>
        /// Settings specific to Tor.
        /// </summary>
        public TorSharpTorSettings TorSettings { get; set; }

        [Obsolete("Use the " + nameof(TorSharpPrivoxySettings) + "." + nameof(TorSharpPrivoxySettings.Port) + " property instead.")]
        public int PrivoxyPort
        {
            get => PrivoxySettings?.Port ?? TorSharpPrivoxySettings.DefaultPort;
            set => EnsurePrivoxySettings().Port = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.SocksPort) + " property instead.")]
        public int TorSocksPort
        {
            get => TorSettings?.SocksPort ?? TorSharpTorSettings.DefaultSocksPort;
            set => EnsureTorSettings().SocksPort = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.ControlPort) + " property instead.")]
        public int TorControlPort
        {
            get => TorSettings?.ControlPort ?? TorSharpTorSettings.DefaultControlPort;
            set => EnsureTorSettings().ControlPort = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.ExitNodes) + " property instead.")]
        public string TorExitNodes
        {
            get => TorSettings?.ExitNodes;
            set => EnsureTorSettings().ExitNodes = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.StrictNodes) + " property instead.")]
        public bool? TorStrictNodes
        {
            get => TorSettings?.StrictNodes;
            set => EnsureTorSettings().StrictNodes = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.ControlPassword) + " property instead.")]
        public string TorControlPassword
        {
            get => TorSettings?.ControlPassword;
            set => EnsureTorSettings().ControlPassword = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.HashedControlPassword) + " property instead.")]
        public string HashedTorControlPassword
        {
            get => TorSettings?.HashedControlPassword;
            set => EnsureTorSettings().HashedControlPassword = value;
        }

        [Obsolete("Use the " + nameof(TorSharpTorSettings) + "." + nameof(TorSharpTorSettings.DataDirectory) + " property instead.")]
        public string TorDataDirectory
        {
            get => TorSettings?.DataDirectory;
            set => EnsureTorSettings().DataDirectory = value;
        }

        private TorSharpTorSettings EnsureTorSettings()
        {
            if (TorSettings == null)
            {
                TorSettings = new TorSharpTorSettings();
            }

            return TorSettings;
        }

        private TorSharpPrivoxySettings EnsurePrivoxySettings()
        {
            if (PrivoxySettings == null)
            {
                PrivoxySettings = new TorSharpPrivoxySettings();
            }

            return PrivoxySettings;
        }

        internal void RejectRuntime(string action)
        {
            var message = new StringBuilder();
            message.Append($"Cannot {action} on {OSPlatform} OS and {Architecture} architecture.");
#if NETSTANDARD
            message.Append($" OS description: {RuntimeInformation.OSDescription}.");
#endif
            throw new TorSharpException(message.ToString());
        }
    }
}


text:
SET DEFINE OFF;
ALTER TABLE AFW_25_PARMT_TYPE_PUBLC ADD (
  CONSTRAINT AFW_25_PARMT_TYPE_PUBLC_CK1
  CHECK (ref_type_publc is not null and ref_engin is null
 or
 ref_type_publc is null and ref_engin is not null)
  ENABLE VALIDATE)
/


text:
(function() {
    'use strict';

    /**
     * Route.
     */
    angular.module('coverageMonitor').config(
        [
            '$stateProvider',
            function ($stateProvider) {
                $stateProvider.state(
                    'home', {
                        url: '/',
                        templateUrl: 'pages/revision/list/list.html',
                        controller: 'ListCtrl'
                    }
                );
            }
        ]
    );

    /**
     * Controller.
     */
    angular.module('coverageMonitor').controller(
        'ListCtrl',
        [
            '$scope',
            'coverageMonitor.revisions',
            function ($scope, revisions) {

                $scope.revisionList = [];

                revisions.getList(
                    function(revisionList) {
                        $scope.revisionList = revisionList;
                    }
                );
            }
        ]
    );
})();


text:
@class MSURLSessionDataTask;

#import "MSRequest.h"

@interface MSGraphPostForwardRequest : MSRequest

@property (readonly) NSMutableURLRequest *mutableRequest;

- (instancetype)initWithComment:(NSString *)comment toRecipients:(NSArray *)toRecipients URL:(NSURL *)url options:(NSArray *)options client:(ODataBaseClient*)client;

- (MSURLSessionDataTask *)executeWithCompletion:(void (^)(NSDictionary *response, NSError *error))completionHandler;

@end


text:
package Examples;

import javax.swing.JOptionPane;

public class DlgSafeInput {

	private String value;
	private String input;

	// check number or not
	private boolean isDoouble(String val) {
		try {
			Double.parseDouble(val);
			return true;
		}
		catch(Exception e) {
			return false;
		}
	}
	private boolean isInteger(String val) {
		try {
			Integer.parseInt(val);
			return true;
		}
		catch(Exception e) {
			return false;
		}
	}

	// Get Integer number
	public int GetInteger(String msg) {

		while(true){
			input = JOptionPane.showInputDialog(null, msg);
			if(isInteger(input))
				return Integer.parseInt(input);
			// error....
			JOptionPane.showMessageDialog(null, "It's wrong type, please again!!");
		}
	}

	// Get Double number
	public double GetDouble(String msg) {

		while(true){
			input = JOptionPane.showInputDialog(null, msg);
			if(isDoouble(input))
				return Double.parseDouble(input);
			// error....
			JOptionPane.showMessageDialog(null, "It's wrong type, please again!!");
		}
	}

	// Get String input
	public String GetString(String msg) {

		input = JOptionPane.showInputDialog(null, msg);
		return input;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
CategoryElement (Apache Log4j 1.2.15 API)
</TITLE>

<META NAME="date" CONTENT="2007-08-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.log4j.lf5.viewer.categoryexplorer

Class CategoryElement

java.lang.Object
  org.apache.log4j.lf5.viewer.categoryexplorer.CategoryElement

public class CategoryElement
extends java.lang.Object

CategoryElement represents a single element or part of a Category.

Author:

Michael J. Sikorsky, Robert Shaw

Field Summary

protected  java.lang.String
_categoryTitle

Constructor Summary

CategoryElement()

CategoryElement(java.lang.String title)

Method Summary

 java.lang.String
getTitle()

 void
setTitle(java.lang.String title)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_categoryTitle

protected java.lang.String _categoryTitle

Constructor Detail

CategoryElement

public CategoryElement()

CategoryElement

public CategoryElement(java.lang.String title)

Method Detail

getTitle

public java.lang.String getTitle()

setTitle

public void setTitle(java.lang.String title)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 1999-2007 Apache Software Foundation. All Rights Reserved.


text:
extern "C" double BOOST_MATH_TR1_DECL boost_sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned n, double x) BOOST_MATH_C99_THROW_SPEC
{
   return c_policies::sph_neumann BOOST_PREVENT_MACRO_SUBSTITUTION(n, x);
}


text:
import os

from . import extensions
from .bot import Yutu
import pytumblr

def main():
    client = Yutu()
    client.load_extension("cogs")

    if 'YUTU_DEBUG' in os.environ:
        client.db.bind(provider='sqlite', filename=':memory:')
        client.tumblr = None  # FIXME
    else:
        client.db.bind(provider='postgres',
                       user=os.environ['POSTGRES_DB_USER'],
                       password=os.environ['POSTGRES_DB_PASS'],
                       database=os.environ['POSTGRES_DB'],
                       host=os.environ['POSTGRES_HOST'])
        client.tumblr = pytumblr.TumblrRestClient(
            os.environ['TUMBLR_CONSUMER_KEY'],
            os.environ['TUMBLR_CONSUMER_SECRET'],
            os.environ['TUMBLR_OAUTH_TOKEN'],
            os.environ['TUMBLR_OAUTH_SECRET']
        )

    client.db.generate_mapping(create_tables=True)

    client.run(os.environ['DISCORD_TOKEN'])


text:
package org.exist.storage;

import org.exist.dom.DocumentImpl;
import org.exist.dom.StoredNode;
import org.exist.numbering.NodeId;

public interface UpdateListener {

	// Notification types:

	/** Notification type: a document was added to a collection */
	public final static int ADD = 0;

	/** Notification type: a document has been updated */
	public final static int UPDATE = 1;

	/** Notification type: a document was removed */
	public final static int REMOVE = 2;

	/**
	 * Called whenever a document is updated within the database.
	 * Parameter event specifies the event type, i.e. one of {@link #ADD}, {@link #UPDATE}
	 * or {@link #REMOVE}.
	 *
	 * @param document
	 * @param event
	 */
	public void documentUpdated(DocumentImpl document, int event);

    /**
     * nodeMoved is called after a defragmentation run occurred for a document during which
     * the address and the nodeId of a node may have changed. Defragmentation
     * may only occur after a node update.
     *
     * @param oldNodeId
     * @param newNode
     */
    public void nodeMoved(NodeId oldNodeId, StoredNode newNode);

    /**
     * Called when the listener is removed from the notification service
     */
    public void unsubscribe();

    public void debug();
}


text:
package edu.mit.media.funf;

import static edu.mit.media.funf.AsyncSharedPrefs.async;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.os.PowerManager;
import android.util.Log;
import edu.mit.media.funf.probe.ProbeExceptions.UnstorableTypeException;

public final class Utils {

	public static final String TAG = "Funf";

	/**
	 * Should not be instantiated.  Used only as a namespace for static Utils functions
	 */
	private Utils() {

	}

	private static String getStoredBundleParamKey(final String key, final String paramKey) {
		return key + "__" + paramKey;
	}

	private static boolean isStoredBundleParamKey(final String key, final String storedParamKey) {
		final String prefix = key + "__";
		return key.startsWith(prefix);
	}

	private static String getBundleParamKey(final String key, final String storedParamKey) {
		final String prefix = key + "__";
		assert key.startsWith(prefix);
		return storedParamKey.substring(prefix.length());
	}

	/**
	 * Convenience function for adding the object form of primitives to a SharedPreferences
	 * @param editor
	 * @param key
	 * @param value Must be Boolean, Float, Integer, Long, String, or Bundle (bundles must only contain the same)
	 * @return
	 * @throws UnstorableTypeException
	 */
	public static SharedPreferences.Editor putInPrefs(SharedPreferences.Editor editor, String key, Object value) throws UnstorableTypeException {
		if (value == null) {
			editor.putString(key, null);
			return editor;
		}
		Class<?> valueClass = value.getClass();
		if (Boolean.class.isAssignableFrom(valueClass)) {
			editor.putBoolean(key, ((Boolean)value).booleanValue());
		} else if (Integer.class.isAssignableFrom(valueClass)) {
			editor.putInt(key, ((Integer) value).intValue());
		} else if (Float.class.isAssignableFrom(valueClass)) {
			editor.putFloat(key, ((Float) value).floatValue());
		} else if (Long.class.isAssignableFrom(valueClass)) {
			editor.putLong(key, ((Long) value).longValue());
		} else if (String.class.isAssignableFrom(valueClass)) {
			editor.putString(key, ((String) value));
		} else if (Bundle.class.isAssignableFrom(valueClass)) {
			// Serialize the bundle using the key as a prefix
			Bundle bundle = ((Bundle) value);
			for (String bundleKey : bundle.keySet()) {
				Object bundleValue = bundle.get(bundleKey);
				putInPrefs(editor, getStoredBundleParamKey(key, bundleKey), bundleValue);
			}
		} else {
			throw new UnstorableTypeException(valueClass);
		}
		return editor;
	}

	/**
	 * Parse a bundle from data stored in a SharedPreferences
	 * @param prefs
	 * @param key
	 * @return
	 */
	public static Bundle getBundleFromPrefs(SharedPreferences prefs, String key) {
		Bundle bundle = new Bundle();
		Map<String,?> prefsMap = prefs.getAll();
		for (String prefsKey : prefsMap.keySet()) {
			if (isStoredBundleParamKey(key, prefsKey)) {
				try {
					putInBundle(bundle, getBundleParamKey(key, prefsKey), prefsMap.get(prefsKey));
				} catch (UnstorableTypeException e) {
					Log.e(TAG, "Should never happen, since SharedPrefs stores only types Bundle can store: ",  e);
				}
			}
		}
		return bundle;
	}

	/**
	 * Convenience function for putting the object form of primitives into a Bundle
	 * @param bundle
	 * @param key
	 * @param value Must be Boolean, Float, Integer, Long, or String
	 * @throws UnstorableTypeException
	 */
	public static void putInBundle(Bundle bundle, String key, Object value) throws UnstorableTypeException {
		Class<?> valueClass = value.getClass();
		if (Boolean.class.isAssignableFrom(valueClass)) {
			bundle.putBoolean(key, ((Boolean)value).booleanValue());
		} else if (Short.class.isAssignableFrom(valueClass)) {
				bundle.putShort(key, ((Short) value).shortValue());
		} else if (Integer.class.isAssignableFrom(valueClass)) {
			bundle.putInt(key, ((Integer) value).intValue());
		} else if (Long.class.isAssignableFrom(valueClass)) {
			bundle.putLong(key, ((Long) value).longValue());
		} else if (Float.class.isAssignableFrom(valueClass)) {
			bundle.putFloat(key, ((Float) value).floatValue());
		} else if (Double.class.isAssignableFrom(valueClass)) {
			bundle.putDouble(key, ((Double) value).doubleValue());
		}  else if (String.class.isAssignableFrom(valueClass)) {
			bundle.putString(key, ((String) value));
		} else {
			throw new UnstorableTypeException(valueClass);
		}
	}

	/**
	 * Convenience function for joining strings using a delimeter
	 * @param strings
	 * @param delimeter
	 * @return
	 */
	public static String join(final Collection<?> strings, String delimeter) {
		if (delimeter == null) {
			delimeter = ",";
		}
		if (strings.isEmpty()) {
			return "";
		}
		StringBuffer joined = new StringBuffer();
		Iterator<?> stringIter = strings.iterator();
		joined.append(stringIter.next().toString());
		while (stringIter.hasNext()) {
			joined.append(delimeter);
			joined.append(stringIter.next().toString());
		}
		return joined.toString();
	}

	/**
	 * Convenience function for concatenating two arrays
	 * @param <T>
	 * @param first
	 * @param second
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[] concat(T[] first, T[] second) {
		T[] result = (T[])new Object[first.length + second.length];
		System.arraycopy(first, 0, result, 0, first.length);
		System.arraycopy(second, 0, result, first.length, second.length);
		return result;
	}

	public static Bundle[] copyBundleArray(Parcelable[] parcelables) {
		if (parcelables == null) {
			return new Bundle[0];
		}
		Bundle[] bundles = new Bundle[parcelables.length];
		System.arraycopy(parcelables, 0, bundles, 0, parcelables.length);
		return bundles;
	}

	public static Map<String,Object> getValues(final Bundle bundle) {
		HashMap<String, Object> values = new HashMap<String, Object>();
		if (bundle == null) {
			return values;
		}
		for (String key : bundle.keySet()) {
			values.put(key, bundle.get(key));
		}
		return values;
	}

	public static <T extends Parcelable> ArrayList<T> getArrayList(Bundle bundle, String key) {
		if (bundle == null) {
			return null;
		}
        Object o = bundle.get(key);
        try {
        	return (ArrayList<T>) o;
        } catch (ClassCastException e) {
        	try {
        		return new ArrayList<T>(Arrays.asList((T[])o));
        	} catch (ClassCastException e2) {
        		Log.w(TAG, "Unable to succesfully parse ArrayList from '" + key + "'");
                return null;
			}
        }
	}
	/**
	 * Convenience function for returning an empty string array if null is returned
	 * @param array
	 * @return
	 */
	public static String[] nonNullStrings(String[] array) {
		return (array == null) ? new String[] {} : array;
	}

	public static PowerManager.WakeLock getWakeLock(Context context) {
		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, context.getClass().getName());
		lock.acquire();
		return lock;
	}

	/**
	 * Useful function to coerce value to a long, no matter what type of object is in the bundle
	 * @param bundle
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static long getLong(Bundle bundle, String key, long defaultValue) {
		Object value = bundle.get(key);
		if (value instanceof Long) {
			return (Long)value;
		} else if (value instanceof Integer) {
			return ((Integer)value).longValue();
		} else if (value instanceof String) {
			try {
				return Long.valueOf((String)value);
			} catch (NumberFormatException e) {
				// We did our best, value is not a long
			}
		}
		return defaultValue;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getCursorData(Cursor cursor, int columnIndex, Class<T> dataType) {
		if (dataType.equals(String.class)) {
			return (T)cursor.getString(columnIndex);
		} else if (dataType.equals(Short.class)) {
			return (T) Short.valueOf(cursor.getShort(columnIndex));
		} else if (dataType.equals(Integer.class)) {
			return (T) Integer.valueOf(cursor.getInt(columnIndex));
		} else if (dataType.equals(Long.class)) {
			return (T) Long.valueOf(cursor.getLong(columnIndex));
		} else if (dataType.equals(Float.class)) {
			return (T) Float.valueOf(cursor.getFloat(columnIndex));
		} else if (dataType.equals(Double.class)) {
			return (T) Double.valueOf(cursor.getDouble(columnIndex));
		} else {
			return null;
		}
	}

	public static final String FUNF_UTILS_PREFS = "edu.mit.media.funf.Utils";
	public static final String INSTALLATION_UUID_KEY = "INSTALLATION_UUID";
	public static String uuid = null;
	public static String getInstallationId(Context context) {
		if (uuid == null) {
			SharedPreferences prefs = async(context.getSharedPreferences(FUNF_UTILS_PREFS, Context.MODE_PRIVATE));
			uuid = prefs.getString(INSTALLATION_UUID_KEY, null);
			if (uuid == null) {
				uuid = UUID.randomUUID().toString();
				prefs.edit().putString(INSTALLATION_UUID_KEY, uuid).commit();
			}
		}
		return uuid;
	}

	public static String getSdCardPath(Context context) {
		return new File(Environment.getExternalStorageDirectory(), context.getPackageName()) + "/";
	}

	/**
	 * Closes a stream, and swallows null cases our IOExceptions.
	 * @param stream
	 */
	public static boolean close(Closeable stream) {
		if(stream != null) {
			try {
				stream.close();
				return true;
			} catch (IOException e) {
				Log.e(TAG, "Error closing stream", e);
			}
		}
		return false;
	}

	public static long getTimestamp() {
		return millisToSeconds(System.currentTimeMillis());
	}

	public static long millisToSeconds(long millis) {
		return millis/1000L;
	}

	public static long secondsToMillis(long seconds) {
		return seconds*1000L;
	}
}


text:
from tastypie.resources import ModelResource

class MyBaseResource(ModelResource):
    def determine_format(self, request):
        '''Return JSON by default'''
        return 'application/json'


text:
function sceneSetGeomCFlag(geom, cflag)

% SceneML, Copyright (C) 2007, 2008  J.D. Yamokoski
% All rights reserved.
% Email: yamokosk at gmail dot com
%
% This library is free software; you can redistribute it and/or
% modify it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation; either version 2.1 of the License,
% or (at your option) any later version. The text of the GNU Lesser General
% Public License is included with this library in the file LICENSE.TXT.
%
% This library is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the file LICENSE.TXT for
% more details.

sceneml('SetGeomCFlag', geom, cflag);


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

namespace MobilePhone
{
    public class GSM
    {
        //fields
        private string manufacturer;
        private string model;
        private decimal? price;
        private string ownerName;
        private string ownerSurname;
        private Battery battery;
        private Display display;

        //=== Problem 9 ==> Add a property `CallHistory` in the `GSM` class to hold a list of the performed calls.
        private List<Call> callHistory = new List<Call>();

        //=== Problem 6 ==> Add a static field and a property `IPhone4S` in the GSM class to hold the information about iPhone 4S.
        private static GSM iPhone4S = new GSM("Apple", "iPhone 4S", 5.00M, "Gosho", "Peshov");

        //=== Problem 2 ==> Constructors
        /*  Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it).
        *	Assume that model and manufacturer are mandatory (the others are optional). All unknown data fill with null.*/
        public GSM(string manufacturer, string model)
        {
            this.Manufacturer = manufacturer;
            this.Model = model;
            this.Price = null;
            this.OwnerName = null;
            this.OwnerSurname = null;
            this.Battery = new Battery();
            this.Display = new Display();
        }

        public GSM(string manufacturer, string model, decimal? price)
            : this(manufacturer, model)
        {
            this.Price = price;
            this.OwnerName = null;
            this.OwnerSurname = null;
            this.Battery = new Battery();
            this.Display = new Display();
        }

        public GSM(string manufacturer, string model, decimal? price, string ownerName, string ownerSurname)
            : this(manufacturer, model, price)
        {
            this.OwnerName = ownerName;
            this.OwnerSurname = ownerSurname;
            this.Battery = new Battery();
            this.Display = new Display();
        }

        //=== Problem 5 ==> Properties
        /**	Use properties to encapsulate the data fields inside the `GSM`, `Battery` and `Display` classes.
        *	Ensure all fields hold correct data at any given time.*/

        public List<Call> CallHistory
        {
            get
            {
                return this.callHistory;
            }
            set
            {
                this.callHistory = value;
            }
        }

        public string Manufacturer
        {
            get { return this.manufacturer; }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("String cannot be null or empty!");
                }
                this.manufacturer = UppercaseWords(value);
            }
        }

        public string Model
        {
            get { return this.model; }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("String cannot be null or empty!");
                }
                this.model = value;
            }
        }

        public decimal? Price
        {
            get { return this.price; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException("Price could not be <= 0");
                }
                this.price = value;
            }
        }

        public string OwnerName
        {
            get { return this.ownerName; }
            set { this.ownerName = UppercaseWords(value); }
        }

        public string OwnerSurname
        {
            get { return this.ownerSurname; }
            set { this.ownerSurname = UppercaseWords(value); }
        }

        public Battery Battery
        {
            get { return this.battery; }
            set { this.battery = value; }
        }

        public Display Display
        {
            get { return this.display; }
            set { this.display = value; }
        }

        public GSM IPhone4S
        {
            get { return iPhone4S; }
        }

        //=== Problem 4 ==>  Add a method in the GSM class for displaying all information about it. Override ToString().

        public override string ToString()
        {
            string output = string.Format(
            "Mobile phone: {0}\r\nModel: {1}\r\nPrice: {2}\r\nOwner: {3} {4}\r\nBattery: {5} {6} {7} {8}\r\nDisplay size: {9}\r\nDisplay colors: {10}", this.Manufacturer, this.Model, this.Price, this.OwnerName, this.OwnerSurname, this.Battery.Type, this.Battery.BatteryModel, this.Battery.HoursIdle, this.Battery.HoursTalk, this.Display.Size, this.Display.Colors);

            if (this.CallHistory.Count > 0)
            {
                output+= "\r\n\r\nCall History:";

                int counter = 1;
                foreach (var call in CallHistory)
                {
                    output += string.Format("\r\n{0}. Date: {1}, Phone Num: {2}, Call Duration: {3}", counter, call.Date, call.PhoneNum, call.Duration);
                    ++counter;
                }
            }
            Console.WriteLine();
            return output;
        }

        //=== Problem 10 ==> Add methods in the `GSM` class for adding and deleting calls from the calls history. Add a method to clear the call history.
        public void AddCall(Call call)
        {
            CallHistory.Add(call);
        }

        public void DeleteCall(int indexOfCall)
        {
            callHistory.RemoveAt(indexOfCall);
        }

        public void ClearHistory()
        {
            callHistory.Clear();
        }

        //=== Method for correcting lowercase first letters
        public string UppercaseWords(string value)
        {
            if (value == null)
            {
                return "";
            }
            char[] array = value.ToCharArray();
            // Handle the first letter in the string.
            if (array.Length >= 1)
            {
                if (char.IsLower(array[0]))
                {
                    array[0] = char.ToUpper(array[0]);
                }
            }
            // Scan through the letters, checking for spaces.
            // ... Uppercase the lowercase letters following spaces.
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i - 1] == ' ')
                {
                    if (char.IsLower(array[i]))
                    {
                        array[i] = char.ToUpper(array[i]);
                    }
                }
            }
            return new string(array);
        }

        //=== Problem 11 ==> Call price
        /*	Add a method that calculates the total price of the calls in the call history.
        *	Assume the price per minute is fixed and is provided as a parameter.*/
        public decimal CallPrice(decimal pricePerMinute)
        {
            uint totalCallsInSeconds = 0;

            foreach (var call in CallHistory)
            {
                totalCallsInSeconds += call.Duration;
            }

            decimal totalPrice = ((decimal)totalCallsInSeconds / 60) * pricePerMinute;
            return totalPrice;
        }
    }

    public class Battery : Enumerations
    {
        private string batteryModel;
        private BatteryType? type;
        private double? hoursIdle;
        private double? hoursTalk;

        //constructors
        public Battery()
        {
            this.batteryModel = null;
            this.type = null;
            this.hoursIdle = null;
            this.hoursTalk = null;
        }

        //properties
        public string BatteryModel
        {
            get { return this.batteryModel; }
            set { this.BatteryModel = value; }
        }

        public double? HoursIdle
        {
            get { return this.hoursIdle; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException("Value could not be <= 0");
                }
                this.HoursIdle = value;
            }
        }

        public double? HoursTalk
        {
            get { return this.hoursTalk; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException("Value could not be <= 0");
                }
                this.HoursTalk = value;
            }
        }

        public BatteryType? Type
        {
            get { return this.type; }
            set { this.type = value; }
        }
    }

    public class Display
    {
        private double? size;
        private uint? numberOfColors;

        //constructor
        public Display()
        {
            this.size = null;
            this.numberOfColors = null;
        }

        public Display(double? size, uint? numberOfColors)
        {
            this.Size = size;
            this.Colors = numberOfColors;
        }

        //properties
        public double? Size
        {
            get { return this.size; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException("Value could not be <= 0");
                }
                this.size = value;
            }
        }

        public uint? Colors
        {
            get { return this.numberOfColors; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException("Value could not be <= 0");
                }
                this.numberOfColors = value;
            }
        }
    }
}


text:
from __future__ import print_function
import os
import ssl
import sys

import cassandra
from cassandra import auth
from cassandra.cluster import Cluster
import yaml

from cdeploy import cqlexecutor

class Migrator:
    def __init__(self, migrations_path, session):
        print('Reading migrations from {0}'.format(migrations_path))
        self.migrations_path = migrations_path
        self.session = session

    def run_migrations(self):
        cqlexecutor.CQLExecutor.init_table(self.session)

        top_version = self.get_top_version()

        def new_migration_filter(f):
            return (
                os.path.isfile(os.path.join(self.migrations_path, f)) and
                self.migration_version(f) > top_version
            )
        new_migrations = self.filter_migrations(new_migration_filter)

        [self.apply_migration(file_name) for file_name in new_migrations]

    def undo(self):
        top_version = self.get_top_version()
        if top_version == 0:
            return

        def top_version_filter(f):
            return (
                os.path.isfile(os.path.join(self.migrations_path, f)) and
                self.migration_version(f) == top_version
            )
        top_migration = list(self.filter_migrations(top_version_filter))[0]

        cqlexecutor.CQLExecutor.execute_undo(
            self.session,
            self.read_migration(top_migration)
        )
        cqlexecutor.CQLExecutor.rollback_schema_migration(self.session)
        print('  -> Migration {0} undone ({1})\n'.format(top_version,
                                                         top_migration))

    def get_top_version(self):
        result = cqlexecutor.CQLExecutor.get_top_version(self.session)
        top_version = result[0].version if len(result) > 0 else 0
        print('Current version is {0}'.format(top_version))
        return top_version

    def filter_migrations(self, filter_func):
        dir_list = os.listdir(self.migrations_path)
        if 'config' in dir_list:
            dir_list.remove('config')
        migration_dir_listing = sorted(dir_list, key=self.migration_version)
        return filter(
            filter_func,
            migration_dir_listing)

    def migration_version(self, file_name):
        return int(file_name.split('.')[0].split('_')[0])

    def apply_migration(self, file_name):
        migration_script = self.read_migration(file_name)
        version = self.migration_version(file_name)

        cqlexecutor.CQLExecutor.execute(self.session, migration_script)
        cqlexecutor.CQLExecutor.add_schema_migration(self.session, version)
        print('  -> Migration {0} applied ({1})\n'.format(version, file_name))

    def read_migration(self, file_name):
        migration_file = open(os.path.join(self.migrations_path, file_name))
        return migration_file.read()

DEFAULT_MIGRATIONS_PATH = './migrations'
CONFIG_FILE_PATH = 'config/cassandra.yml'

def main():
    if '--help' in sys.argv or '-h' in sys.argv:
        print('Usage: cdeploy [path/to/migrations] [--undo]')
        return

    undo = False
    if '--undo' in sys.argv:
        undo = True
        sys.argv.remove('--undo')

    migrations_path = (
        DEFAULT_MIGRATIONS_PATH if len(sys.argv) == 1 else sys.argv[1]
    )

    if (invalid_migrations_dir(migrations_path) or
            missing_config(migrations_path)):
        return

    config = load_config(migrations_path, os.getenv('ENV'))

    session = get_session(config)
    migrator = Migrator(migrations_path, session)

    if undo:
        migrator.undo()
    else:
        migrator.run_migrations()

def get_session(config):
    auth_provider = None
    if 'auth_enabled' in config and config['auth_enabled']:
        auth_provider = auth.PlainTextAuthProvider(
            username=config['auth_username'],
            password=config['auth_password'],
        )

    ssl_options = None
    if 'ssl_enabled' in config and config['ssl_enabled']:
        ssl_options = {
            'ca_certs': config['ssl_ca_certs'],
            'ssl_version': ssl.PROTOCOL_TLSv1,  # pylint: disable=E1101
        }

    cluster = Cluster(
        config['hosts'],
        auth_provider=auth_provider,
        ssl_options=ssl_options,
    )

    session = cluster.connect()

    try:
        session.set_keyspace(config['keyspace'])
    except cassandra.InvalidRequest:
        # Keyspace doesn't exist yet
        if 'create_keyspace' in config and config['create_keyspace']:
            create_keyspace(config, session)
        else:
            raise

    if 'consistency_level' in config:
        consistency_level = getattr(
            cassandra.ConsistencyLevel,
            config['consistency_level'],
        )
        session.default_consistency_level = consistency_level

    return session

def create_keyspace(config, session):
    session.execute(
        "CREATE KEYSPACE {0} WITH REPLICATION = {1};".format(
            config['keyspace'],
            config['replication_strategy']
        )
    )
    session.set_keyspace(config['keyspace'])

def invalid_migrations_dir(migrations_path):
    if not os.path.isdir(migrations_path):
        print('"{0}" is not a directory'.format(migrations_path))
        return True
    else:
        return False

def missing_config(migrations_path):
    config_path = config_file_path(migrations_path)
    if not os.path.exists(os.path.join(config_path)):
        print('Missing configuration file "{0}"'.format(config_path))
        return True
    else:
        return False

def config_file_path(migrations_path):
    return os.path.join(migrations_path, CONFIG_FILE_PATH)

def load_config(migrations_path, env):
    config_file = open(config_file_path(migrations_path))
    config = yaml.load(config_file)
    return config[env or 'development']

if __name__ == '__main__':
    main()


text:
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers

from . import models
from pdc.apps.common.fields import ChoiceSlugField
from pdc.apps.common.hacks import convert_str_to_int
from pdc.apps.common.serializers import StrictSerializerMixin
from pdc.apps.component.models import GlobalComponent
from pdc.apps.contact.models import Person
from pdc.apps.release import models as release_models

class RepoSerializer(StrictSerializerMixin, serializers.ModelSerializer):
    release_id       = serializers.CharField(source='variant_arch.variant.release.release_id')
    variant_uid      = serializers.CharField(source='variant_arch.variant.variant_uid')
    arch             = serializers.CharField(source='variant_arch.arch.name')
    service          = ChoiceSlugField(slug_field='name',
                                       queryset=models.Service.objects.all())
    repo_family      = ChoiceSlugField(slug_field='name',
                                       queryset=models.RepoFamily.objects.all())
    content_format   = ChoiceSlugField(slug_field='name',
                                       queryset=models.ContentFormat.objects.all())
    content_category = ChoiceSlugField(slug_field='name',
                                       queryset=models.ContentCategory.objects.all())
    name             = serializers.CharField()
    shadow           = serializers.BooleanField(required=False, default=False)
    product_id       = serializers.IntegerField(required=False, default=None, allow_null=True)

    class Meta:
        model = models.Repo
        fields = ('id', 'release_id', 'variant_uid', 'arch', 'service', 'repo_family',
                  'content_format', 'content_category', 'name', 'shadow', 'product_id')

    def validate(self, attrs):
        try:
            variant_arch = attrs.get('variant_arch', {})
            release_id  = variant_arch.get('variant', {}).get('release', {}).get('release_id', '')
            variant_uid = variant_arch.get('variant', {}).get('variant_uid', '')
            arch        = variant_arch.get('arch', {}).get('name', '')
            if self.instance and self.partial:
                variantarch = self.instance.variant_arch
                release_id = release_id or variantarch.variant.release.release_id
                variant_uid = variant_uid or variantarch.variant.variant_uid
                arch = arch or variantarch.arch.name
            attrs['variant_arch'] = release_models.VariantArch.objects.get(
                variant__release__release_id=release_id,
                variant__variant_uid=variant_uid,
                arch__name=arch
            )
        except ObjectDoesNotExist:
            raise serializers.ValidationError(
                'No VariantArch for release_id=%s, variant_uid=%s, arch=%s'
                % (release_id, variant_uid, arch)
            )
        if not self.instance:
            # Validate repo name.
            instance = models.Repo(**attrs)
            instance.clean()
            # Validate repo is unique.
            try:
                models.Repo.objects.get(**attrs)
                raise serializers.ValidationError(
                    'Repo with this Variant arch, Service, Repo family, Content format, '
                    'Content category, Name and Shadow already exists.'
                )
            except models.Repo.DoesNotExist:
                pass
        return super(RepoSerializer, self).validate(attrs)

class RepoField(serializers.RelatedField):
    """Serializer field for repository."""

    doc_format = """{
                            "arch": "string",
                            "content_category": "ContentCategory.name",
                            "content_format": "ContentFormat.name",
                            "id (read-only)": "int",
                            "name": "string",
                            "product_id (optional, default=null, nullable)": "int",
                            "release_id": "string",
                            "repo_family": "RepoFamily.name",
                            "service": "Service.name",
                            "shadow (optional, default=false)": "boolean",
                            "variant_uid": "string"
                        }"""
    writable_doc_format = '{"id": "int"}'
    queryset = models.Repo.objects.all()

    def to_representation(self, value):
        return RepoSerializer().to_representation(value)

    def to_internal_value(self, data):
        if not isinstance(data, dict):
            raise serializers.ValidationError({'detail': "Input [%s] must be a dict." % data})

        if data.keys() != ['id']:
            raise serializers.ValidationError({'detail': 'Only accepts {"id":"int"}'})

        repo_id = convert_str_to_int(data['id'])

        try:
            rc = models.Repo.objects.get(id=repo_id)
        except models.Repo.DoesNotExist:
            raise serializers.ValidationError({'detail': "Repo with id %s doesn't exist" % repo_id})

        return rc

class RepoFamilySerializer(StrictSerializerMixin, serializers.ModelSerializer):
    name          = serializers.CharField()
    description   = serializers.CharField()

    class Meta:
        model = models.RepoFamily
        fields = ("name", "description")

class ContentCategorySerializer(StrictSerializerMixin, serializers.ModelSerializer):

    class Meta:
        model = models.ContentCategory
        fields = ('name', 'description',)

class ContentFormatSerializer(StrictSerializerMixin, serializers.ModelSerializer):

    class Meta:
        model = models.ContentFormat
        fields = ('name', 'pdc_endpoint', 'description')

class ServiceSerializer(StrictSerializerMixin, serializers.ModelSerializer):

    class Meta:
        model = models.Service
        fields = ('name', 'description',)

class PushTargetSerializer(StrictSerializerMixin, serializers.ModelSerializer):
    name = serializers.CharField()
    description = serializers.CharField(allow_blank=True)
    host = serializers.CharField(allow_blank=True, required=False)
    service = ChoiceSlugField(slug_field='name', queryset=models.Service.objects.all())

    class Meta:
        model = models.PushTarget
        fields = ('id', 'name', 'description', 'service', 'host')

class MultiDestinationSerializer(StrictSerializerMixin, serializers.ModelSerializer):
    global_component = ChoiceSlugField(slug_field='name', queryset=GlobalComponent.objects.all())
    origin_repo = RepoField()
    destination_repo = RepoField()
    subscribers = ChoiceSlugField(slug_field='username', many=True, queryset=Person.objects.filter(active=True), default=[])
    active = serializers.BooleanField(default=True)

    class Meta:
        model = models.MultiDestination
        fields = (
            'id',
            'global_component',
            'origin_repo',
            'destination_repo',
            'subscribers',
            'active',
        )


text:
package com.example.LookerRefApp;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Getter
@Setter
public class SignedURLParams {

    private String nonce;
    private String external_user_id;
    private String first_name;
    private String last_name;
    private int session_length;
    private boolean force_logout_login;
    private String external_group_id;
    private ArrayList<Integer> group_ids;  // Array of integers [1,2]
    private String models;
    private List<String> permissions;
    private String access_filters = "{}";   //  Looker 3.10 this parameter was removed, but placeholder is required for signature
    private String user_attributes;
    private String user_timezone;
    private long time;
    private String signature;
}


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee180e35065">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States Bankruptcy Court Southern District of Florida</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2011-10-12</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2008-01-31</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 14.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254</identifier>
<identifier type="local">P0b002ee180e35065</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2011-10-12</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2014-09-25</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-flsb-0_07-bk-11254</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-flsb-0_07-bk-11254</accessId>
 <courtType>Bankruptcy</courtType>
 <courtCode>flsb</courtCode>
 <courtCircuit>11th</courtCircuit>
 <courtState>Florida</courtState>
 <courtSortOrder>3113</courtSortOrder>
 <caseNumber>0:07-bk-11254</caseNumber>
 <caseOffice>Fort Lauderdale</caseOffice>
 <party fullName="Caring Heart Home Health Corp., Inc." lastName="Caring Heart Home Health Corp., Inc." role="Debtor"></party>
 <party fullName="Office of the US Trustee" lastName="Office of the US Trustee" role="U.S. Trustee"></party>
 <party firstName="Nancy" fullName="Nancy Ceran" lastName="Ceran" role="Creditor"></party>
 <party fullName="Broward County Revenue Collection Division" lastName="Broward County Revenue Collection Division" role="Creditor"></party>
 <party firstName="Nanette" fullName="Nanette O'Donnell" lastName="O'Donnell" role="Patient Care Ombudsman"></party>
 <party fullName="Commercebank NA" lastName="Commercebank NA" role="Creditor"></party>
 <party fullName="IRS" lastName="IRS" role="Attorney"></party>
</extension>
<titleInfo>
 <title>Caring Heart Home Health Corp., Inc.</title>
 <partNumber>0:07-bk-11254</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254/content-detail.html</url>
</location>
<classification authority="sudocs">JU 14.15</classification>
<identifier type="preferred citation">0:07-bk-11254;07-11254</identifier>
<name type="corporate">
 <namePart>United States Bankruptcy Court Southern District of Florida</namePart>
 <namePart>11th Circuit</namePart>
 <namePart>Fort Lauderdale</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>Caring Heart Home Health Corp., Inc.</displayForm>
 <namePart type="family">Caring Heart Home Health Corp., Inc.</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Debtor</description>
</name>
<name type="personal">
 <displayForm>Office of the US Trustee</displayForm>
 <namePart type="family">Office of the US Trustee</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>U.S. Trustee</description>
</name>
<name type="personal">
 <displayForm>Nancy Ceran</displayForm>
 <namePart type="family">Ceran</namePart>
 <namePart type="given">Nancy</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Creditor</description>
</name>
<name type="personal">
 <displayForm>Broward County Revenue Collection Division</displayForm>
 <namePart type="family">Broward County Revenue Collection Division</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Creditor</description>
</name>
<name type="personal">
 <displayForm>Nanette O'Donnell</displayForm>
 <namePart type="family">O'Donnell</namePart>
 <namePart type="given">Nanette</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Patient Care Ombudsman</description>
</name>
<name type="personal">
 <displayForm>Commercebank NA</displayForm>
 <namePart type="family">Commercebank NA</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Creditor</description>
</name>
<name type="personal">
 <displayForm>IRS</displayForm>
 <namePart type="family">IRS</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Attorney</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-flsb-0_07-bk-11254</accessId>
 <courtType>Bankruptcy</courtType>
 <courtCode>flsb</courtCode>
 <courtCircuit>11th</courtCircuit>
 <courtState>Florida</courtState>
 <courtSortOrder>3113</courtSortOrder>
 <caseNumber>0:07-bk-11254</caseNumber>
 <caseOffice>Fort Lauderdale</caseOffice>
 <party fullName="Caring Heart Home Health Corp., Inc." lastName="Caring Heart Home Health Corp., Inc." role="Debtor"></party>
 <party fullName="Office of the US Trustee" lastName="Office of the US Trustee" role="U.S. Trustee"></party>
 <party firstName="Nancy" fullName="Nancy Ceran" lastName="Ceran" role="Creditor"></party>
 <party fullName="Broward County Revenue Collection Division" lastName="Broward County Revenue Collection Division" role="Creditor"></party>
 <party firstName="Nanette" fullName="Nanette O'Donnell" lastName="O'Donnell" role="Patient Care Ombudsman"></party>
 <party fullName="Commercebank NA" lastName="Commercebank NA" role="Creditor"></party>
 <party fullName="IRS" lastName="IRS" role="Attorney"></party>
 <state>Florida</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-flsb-0_07-bk-11254-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-0/mods.xml">
 <titleInfo>
  <title>Caring Heart Home Health Corp., Inc.</title>
  <subTitle>Order Denying Debtor's Motion to Extend Time Nunc Pro Tunc for Confirmation of Plan Pursuant to 11 USC Sec 1129(e)(Re: # 75). (Aarons, Micheline) Modified on 1/31/2008 to reflect as a tagged opinion (Cervino, Maria).</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2008-01-31</dateIssued>
</originInfo>
 <relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254/pdf/USCOURTS-flsb-0_07-bk-11254-0.pdf">
  <identifier type="FDsys Unique ID">D09002ee189ce644c</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-0</identifier>
 <identifier type="former granule identifier">flsb-0_07-bk-11254_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254/pdf/USCOURTS-flsb-0_07-bk-11254-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 0:07-bk-11254; Caring Heart Home Health Corp., Inc.; </searchTitle>
  <courtName>United States Bankruptcy Court Southern District of Florida</courtName>
  <state>Florida</state>
  <accessId>USCOURTS-flsb-0_07-bk-11254-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2008-01-31</dateIssued>
  <docketText>Order Denying Debtor's Motion to Extend Time Nunc Pro Tunc for Confirmation of Plan Pursuant to 11 USC Sec 1129(e)(Re: # 75). (Aarons, Micheline) Modified on 1/31/2008 to reflect as a tagged opinion (Cervino, Maria).</docketText>
</extension>
</relatedItem>
<relatedItem type="constituent" ID="id-USCOURTS-flsb-0_07-bk-11254-1" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-1/mods.xml">
 <titleInfo>
  <title>Caring Heart Home Health Corp., Inc.</title>
  <subTitle>Order Dismissing Case. Dismissal Shall Be with No Prejudice. [Filing Fee Balance Due: $0.00]. (Aarons, Micheline) Modified on 1/31/2008 to reflect as tagged opinion (Cervino, Maria).</subTitle>
  <partNumber>1</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2008-01-31</dateIssued>
</originInfo>
 <relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254/pdf/USCOURTS-flsb-0_07-bk-11254-1.pdf">
  <identifier type="FDsys Unique ID">D09002ee189ce644b</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-1</identifier>
 <identifier type="former granule identifier">flsb-0_07-bk-11254_1.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-flsb-0_07-bk-11254/USCOURTS-flsb-0_07-bk-11254-1/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-flsb-0_07-bk-11254/pdf/USCOURTS-flsb-0_07-bk-11254-1.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 0:07-bk-11254; Caring Heart Home Health Corp., Inc.; </searchTitle>
  <courtName>United States Bankruptcy Court Southern District of Florida</courtName>
  <state>Florida</state>
  <accessId>USCOURTS-flsb-0_07-bk-11254-1</accessId>
  <sequenceNumber>1</sequenceNumber>
  <dateIssued>2008-01-31</dateIssued>
  <docketText>Order Dismissing Case. Dismissal Shall Be with No Prejudice. [Filing Fee Balance Due: $0.00]. (Aarons, Micheline) Modified on 1/31/2008 to reflect as tagged opinion (Cervino, Maria).</docketText>
</extension>
</relatedItem>
</mods>


text:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { SELECT_USER } from '../actiontypes';
import { emptyUser } from '../constants';

function Users(props) {
    const { id, className } = props;
    const users = useSelector(state => state.users);
    const userid = useSelector(state => state.userid);
    const dispatch = useDispatch();

    return (
        <select id={id} className={className} onChange={e => dispatch(SELECT_USER(findSelectedUser(e, users)))} value={userid}>
            <option key="user_-1" value="-1" />
            {users.map((val) => <option key={'user_' + val.userid} value={val.userid}>{val.firstname + ' ' + val.lastname}</option>)}
        </select>
    );
}

export default Users;

function findSelectedUser(e, users) {
    const selectedUserId = parseInt(e.target.value);
    return users.find(u => u.userid === selectedUserId) || emptyUser;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

/**
 * Package containing the inner data models for AzureTrafficCollectorManagementClient. Azure Traffic Collector service.
 */
package com.azure.resourcemanager.networkfunction.fluent.models;


text:
from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable
import xml.etree.ElementTree as ET

from .argument import Argument, ArgumentType
from .description import Description
from .method import Method
from .printer import Printer

# For 'new_id' types with no 'interface'
NO_IFACE = "interface"
NO_IFACE_VERSION = "version"

@dataclass(frozen=True)
class Request(Method):
    """Scanner for request objects (client-side method)

    Required attributes: `name`

    Optional attributes: `type` and `since`

    Child elements: `description` and `arg`
    """

    method_type = "request"

    type: str | None

    @classmethod
    def parse(cls, element: ET.Element) -> Request:
        name = cls.parse_attribute(element, "name")
        if name in ("global", "import"):
            name += "_"

        return cls(
            name=name,
            since=cls.parse_optional_attribute(element, "since"),
            description=cls.parse_optional_child(element, Description, "description"),
            arg=cls.parse_repeated_child(element, Argument, "arg"),
            type=cls.parse_optional_attribute(element, "type"),
        )

    @property
    def new_id(self) -> Argument | None:
        for arg in self.arg:
            if arg.type == ArgumentType.NewId:
                return arg
        return None

    @property
    def method_args(self) -> Iterable[str]:
        """Generator of the arguments to the method

        The `new_id` args are generated in marshaling the args, they do not
        appear in the args of the method.
        """
        for arg in self.arg:
            if arg.type == ArgumentType.NewId:
                # An interface of known type is created for us
                if arg.interface:
                    continue
                # A `new_id` with no interface, c.f. wl_registry_bind
                # Need a string (interface name) and int (interface version)
                yield f"{NO_IFACE}: Type[T]"
                yield f"{NO_IFACE_VERSION}: int"
            else:
                yield arg.signature

    @property
    def marshal_args(self) -> Iterable[str]:
        """Arguments sent to `._marshal`"""
        for arg in self.arg:
            if arg.type == ArgumentType.NewId:
                if not arg.interface:
                    yield "{}.name".format(NO_IFACE)
                    yield NO_IFACE_VERSION
            else:
                yield arg.name

    def output_doc_params(self, printer: Printer) -> None:
        """Aguments documented as parameters

        Anything that is not a `new_id` is
        """
        ret = None
        for arg in self.arg:
            if arg.type == ArgumentType.NewId:
                ret = arg
                if arg.interface:
                    continue
                printer(f":param {NO_IFACE}:")
                printer("    Interface name")
                printer(f":type {NO_IFACE}:")
                printer("    `string`")
                printer(f":param {NO_IFACE_VERSION}:")
                printer("    Interface version")
                printer(f":type {NO_IFACE_VERSION}:")
                printer("    `int`")
            else:
                arg.output_doc_param(printer)
        if ret is not None:
            ret.output_doc_ret(printer)

    def output_doc_ret(self, printer: Printer) -> None:
        """Aguments documented as return values

        Arguments of type `new_id` are returned from requests.
        """
        for arg in self.arg:
            if arg.type == ArgumentType.NewId:
                arg.output_doc_ret(printer)

    def output_body(self, printer: Printer, opcode: int) -> None:
        """Output the body of the request to the printer"""
        if self.new_id:
            if self.new_id.interface:
                id_class = self.new_id.interface_class
            else:
                id_class = NO_IFACE
            args = ", ".join([str(opcode), id_class] + list(self.marshal_args))
            printer("{} = self._marshal_constructor({})".format(self.new_id.name, args))
            printer("return {}".format(self.new_id.name))
        else:
            args = ", ".join([str(opcode)] + list(self.marshal_args))
            printer("self._marshal({})".format(args))
            if self.type == "destructor":
                printer("self._destroy()")

    @property
    def return_type(self) -> str:
        """The return type for the request."""
        if self.new_id:
            if self.new_id.interface:
                return f"Proxy[{self.new_id.interface_class}]"
            else:
                return "Proxy[T]"
        return "None"

    @property
    def needs_any(self) -> bool:
        for arg in self.arg:
            if arg.type == ArgumentType.Object and not arg.interface:
                return True
        return False


text:
package sample;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Integration tests for {@link OAuth2ResourceServerApplication}
 *
 * @author Josh Cummings
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class OAuth2ResourceServerApplicationITests {

	String noScopesToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWJqZWN0IiwiZXhwIjoyMTY0MjQ1ODgwLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiMDFkOThlZWEtNjc0MC00OGRlLTk4ODAtYzM5ZjgyMGZiNzVlIiwiY2xpZW50X2lkIjoibm9zY29wZXMiLCJzY29wZSI6WyJub25lIl19.VOzgGLOUuQ_R2Ur1Ke41VaobddhKgUZgto7Y3AGxst7SuxLQ4LgWwdSSDRx-jRvypjsCgYPbjAYLhn9nCbfwtCitkymUKUNKdebvVAI0y8YvliWTL5S-GiJD9dN8SSsXUla9A4xB_9Mt5JAlRpQotQSCLojVSKQmjhMpQWmYAlKVjnlImoRwQFPI4w3Ijn4G4EMTKWUYRfrD0-WNT9ZYWBeza6QgV6sraP7ToRB3eQLy2p04cU40X-RHLeYCsMBfxsMMh89CJff-9tn7VDKi1hAGc_Lp9yS9ZaItJuFJTjf8S_vsjVB1nBhvdS_6IED_m_fOU52KiGSO2qL6shxHvg";
	String messageReadToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWJqZWN0IiwiZXhwIjoyMTY0MjQ1NjQ4LCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiY2I1ZGMwNDYtMDkyMi00ZGJmLWE5MzAtOGI2M2FhZTYzZjk2IiwiY2xpZW50X2lkIjoicmVhZGVyIiwic2NvcGUiOlsibWVzc2FnZTpyZWFkIl19.Pre2ksnMiOGYWQtuIgHB0i3uTnNzD0SMFM34iyQJHK5RLlSjge08s9qHdx6uv5cZ4gZm_cB1D6f4-fLx76bCblK6mVcabbR74w_eCdSBXNXuqG-HNrOYYmmx5iJtdwx5fXPmF8TyVzsq_LvRm_LN4lWNYquT4y36Tox6ZD3feYxXvHQ3XyZn9mVKnlzv-GCwkBohCR3yPow5uVmr04qh_al52VIwKMrvJBr44igr4fTZmzwRAZmQw5rZeyep0b4nsCjadNcndHtMtYKNVuG5zbDLsB7GGvilcI9TDDnUXtwthB_3iq32DAd9x8wJmJ5K8gmX6GjZFtYzKk_zEboXoQ";
	String messageWriteToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWJqZWN0IiwiZXhwIjoyMTY0MjQzOTA0LCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiZGI4ZjgwMzQtM2VlNy00NjBjLTk3NTEtMDJiMDA1OWI5NzA4IiwiY2xpZW50X2lkIjoid3JpdGVyIiwic2NvcGUiOlsibWVzc2FnZTp3cml0ZSJdfQ.USvpx_ntKXtchLmc93auJq0qSav6vLm4B7ItPzhrDH2xmogBP35eKeklwXK5GCb7ck1aKJV5SpguBlTCz0bZC1zAWKB6gyFIqedALPAran5QR-8WpGfl0wFqds7d8Jw3xmpUUBduRLab9hkeAhgoVgxevc8d6ITM7kRnHo5wT3VzvBU8DquedVXm5fbBnRPgG4_jOWJKbqYpqaR2z2TnZRWh3CqL82Orh1Ww1dJYF_fae1dTVV4tvN5iSndYcGxMoBaiw3kRRi6EyNxnXnt1pFtZqc1f6D9x4AHiri8_vpBp2vwG5OfQD5-rrleP_XlIB3rNQT7tu3fiqu4vUzQaEg";

	@Autowired
	MockMvc mvc;

	@Test
	public void performWhenValidBearerTokenThenAllows()
		throws Exception {

		this.mvc.perform(get("/").with(bearerToken(this.noScopesToken)))
				.andExpect(status().isOk())
				.andExpect(content().string(containsString("Hello, subject!")));
	}

	// -- tests with scopes

	@Test
	public void performWhenValidBearerTokenThenScopedRequestsAlsoWork()
			throws Exception {

		this.mvc.perform(get("/message").with(bearerToken(this.messageReadToken)))
				.andExpect(status().isOk())
				.andExpect(content().string(containsString("secret message")));
	}

	@Test
	public void performWhenInsufficientlyScopedBearerTokenThenDeniesScopedMethodAccess()
			throws Exception {

		this.mvc.perform(get("/message").with(bearerToken(this.noScopesToken)))
				.andExpect(status().isForbidden())
				.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
						containsString("Bearer error=\"insufficient_scope\"")));
	}

	@Test
	public void performPostWhenValidBearerTokenThenScopedRequestsAlsoWork()
		throws Exception {

		this.mvc.perform(post("/message").content("example message")
				.with(bearerToken(this.messageWriteToken)))
				.andExpect(status().isOk())
				.andExpect(content().string(containsString("Message was created")));
	}

	@Test
	public void performPostWhenInsufficientlyScopedBearerTokenThenDeniesScopedMethodAccess()
		throws Exception {

		this.mvc.perform(post("/message").content("Example message")
				.with(bearerToken(this.messageReadToken)))
				.andExpect(status().isForbidden())
				.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
						containsString("Bearer error=\"insufficient_scope\"")));
	}

	private static class BearerTokenRequestPostProcessor implements RequestPostProcessor {
		private String token;

		BearerTokenRequestPostProcessor(String token) {
			this.token = token;
		}

		@Override
		public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
			request.addHeader("Authorization", "Bearer " + this.token);
			return request;
		}
	}

	private static BearerTokenRequestPostProcessor bearerToken(String token) {
		return new BearerTokenRequestPostProcessor(token);
	}
}