text:
// javascript:
(function() {
    if (typeof Storage === 'undefined') {
        alert('You must use a modern web browser to use this bookmarklet. Try Chrome, Firefox or Safari.');
        return;
    }

    var data = {};

    // set defaults
    data.new = 0;
    data.search = 0;

    // set initial page
    data.page = 0;

    // get current category
    data.category = window.location.pathname.split('/')[1];
    if (data.category === 'search') {
        data.search = 1;
        data.category = window.location.pathname.split('/')[2];
        console.log(data.category);
    }

    // check to see what last highest pid was
    data.lastHighest = localStorage['sjM' + data.category] || 0;

    // check for hidden items
    data.hiddenItems = localStorage['sjMHidden'].split(',') || [];
    removeHidden();

    // give initial .content div an id
    $('.content').attr('id', 'seanslist');

    // repurpose paginator //                               <<<< need to have logic for search pages, which have different urls
    $('body').on('click', '.paginator a', function(e) {
        e.preventDefault();
        var $this = $(this);

        data.page++; // increment page
        $('.pagenum').text('1 - ' + (data.page + 1) + '00');

        // ajax call
        var $content = $('

'),
            href;

        if (data.search) {
            href = '/search/' + data.category + window.location.search + '&s=' + data.page + '00 .content'; // e.g. /search/fuo?query=dining&zoomToPosting=&minAsk=&maxAsk=300
        } else {
            href = '/' + data.category + '/index' + data.page + '00.html .content'; // e.g. /fuo/index100.html
        }

        $content.appendTo('body').load(href, function() {
            // have CL help us lazy load images
            removeHidden();
            var $view = $('#toc_rows').find('.tocview').eq(0).find('a.sel');
            $view.removeClass('sel').trigger('click').addClass('sel');
        });
        $content = $('#page--' + data.page).detach();
        $('#seanslist').append($content);
    });

    // manipulate item links //
    $('#seanslist').on('click', '.row a', function(e) {
        var $this = $(this),
            $row = $this.closest('.row');
        if ($this.hasClass('i')) { // on img click, destroy
            hideForever($row.data('pid'));
            $row.remove();
            e.preventDefault();
        } else { // on text click, open in new tab
            $this.attr('target', '_blank');
        }
    });

    // click image to remove //

    // look for new posts //

    var pids = [],
        i,
        $rows = $('#toc_rows').find('.row');

    // do something with lastHighest for now
    if (data.lastHighest) {
        //alert('The last highest listing you saw in this category was: ' + data.lastHighest);
    } else { // never been here before
        //alert('You have never viewed this category before.');
        data.new = 1;
    }

    // we want more padding for highlighting, so let's just switch margin for padding
    $rows.css({'margin': 0, 'padding': '0.5em 0'});
/*
    // populate array of pids on page
    for (i = 0; i < 100; i++) {
        var pid = $rows.eq(i).data('pid');
        if (pid > data.lastHighest) {
            pids.push(pid);
        }
    }

    if (pids.length) { // only if we have some
        pids.sort().reverse(); // sort desc
        data.newest = pids[0];

        if (!data.new) { // only if user has been here before
            for (i = 0; i < pids.length; i++) {
                $rows.filter('[data-pid="' + pids[i] + '"]').css({'background': '#ffa'}); // newest one highlighted yellow, just to see if it works
            }
        }

        // save newest in this category for next time
        //localStorage['sjM' + data.category] = data.newest;
    }
*/
    function hideForever(pid) {
        data.hiddenItems.push(pid.toString());
        localStorage['sjMHidden'] = data.hiddenItems;
    }

    function removeHidden() {
        for (var i = 0; i < data.hiddenItems.length; i++) {
            $('.row[data-pid="' + data.hiddenItems[i] + '"]').css({'display': 'none'});
        }
    }

})();

redpajama_set_name: RedPajamaGithub


text:
package org.apache.commons.math3.optimization.univariate;

import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.optimization.BaseOptimizer;
import org.apache.commons.math3.optimization.GoalType;

/**
 * This interface is mainly intended to enforce the internal coherence of
 * Commons-Math. Users of the API are advised to base their code on
 * the following interfaces:
 *

 *
{@link org.apache.commons.math3.optimization.univariate.UnivariateOptimizer}

 *

 *
 * @param <FUNC> Type of the objective function to be optimized.
 *
 * @version $Id: BaseUnivariateOptimizer.java 1422230 2012-12-15 12:11:13Z erans $
 * @deprecated As of 3.1 (to be removed in 4.0).
 * @since 3.0
 */
@Deprecated
public interface BaseUnivariateOptimizer<FUNC extends UnivariateFunction>
    extends BaseOptimizer<UnivariatePointValuePair> {
    /**
     * Find an optimum in the given interval.
     *
     * An optimizer may require that the interval brackets a single optimum.
     *
     * @param f Function to optimize.
     * @param goalType Type of optimization goal: either
     * {@link GoalType#MAXIMIZE} or {@link GoalType#MINIMIZE}.
     * @param min Lower bound for the interval.
     * @param max Upper bound for the interval.
     * @param maxEval Maximum number of function evaluations.
     * @return a (point, value) pair where the function is optimum.
     * @throws org.apache.commons.math3.exception.TooManyEvaluationsException
     * if the maximum evaluation count is exceeded.
     * @throws org.apache.commons.math3.exception.ConvergenceException
     * if the optimizer detects a convergence problem.
     * @throws IllegalArgumentException if {@code min > max} or the endpoints
     * do not satisfy the requirements specified by the optimizer.
     */
    UnivariatePointValuePair optimize(int maxEval, FUNC f, GoalType goalType,
                                          double min, double max);

    /**
     * Find an optimum in the given interval, start at startValue.
     * An optimizer may require that the interval brackets a single optimum.
     *
     * @param f Function to optimize.
     * @param goalType Type of optimization goal: either
     * {@link GoalType#MAXIMIZE} or {@link GoalType#MINIMIZE}.
     * @param min Lower bound for the interval.
     * @param max Upper bound for the interval.
     * @param startValue Start value to use.
     * @param maxEval Maximum number of function evaluations.
     * @return a (point, value) pair where the function is optimum.
     * @throws org.apache.commons.math3.exception.TooManyEvaluationsException
     * if the maximum evaluation count is exceeded.
     * @throws org.apache.commons.math3.exception.ConvergenceException if the
     * optimizer detects a convergence problem.
     * @throws IllegalArgumentException if {@code min > max} or the endpoints
     * do not satisfy the requirements specified by the optimizer.
     * @throws org.apache.commons.math3.exception.NullArgumentException if any
     * argument is {@code null}.
     */
    UnivariatePointValuePair optimize(int maxEval, FUNC f, GoalType goalType,
                                          double min, double max,
                                          double startValue);
}


text:
<?php
/**
 */
class PluginmmMediaFolderMetadataTable extends Doctrine_Table
{

}


text:
package com.marshalchen.common.uimodule.androidanimations.attention;

import android.view.View;

import com.marshalchen.common.uimodule.androidanimations.BaseViewAnimator;
import com.marshalchen.common.uimodule.nineoldandroids.animation.ObjectAnimator;

public class StandUpAnimator extends BaseViewAnimator{
    @Override
    public void prepare(View target) {
        float x = (target.getWidth() - target.getPaddingLeft() - target.getPaddingRight())/2
                + target.getPaddingLeft();
        float y = target.getHeight() - target.getPaddingBottom();
        getAnimatorAgent().playTogether(
                ObjectAnimator.ofFloat(target,"pivotX",x,x,x,x,x),
                ObjectAnimator.ofFloat(target,"pivotY",y,y,y,y,y),
                ObjectAnimator.ofFloat(target,"rotationX",55,-30,15,-15,0)
        );
    }
}


text:
package org.apache.james.jspf.core;

/**
 * Components that need to log can implement this interface so that
 * the container will provide the SPFChecker
 */
public interface SPFCheckEnabled {
    /**
     * Provide component with an SPF Checker.
     *
     * @param checker
     *            the checker. Must not be null.
     */
    void enableSPFChecking(SPFChecker checker);
}


text:
using System;
using System.Windows.Forms;

namespace MsAglWinFormsEditor
{
    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}


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

#include "components/policy/core/browser/url_blacklist_manager.h"

#include <stdint.h>
#include <ostream>
#include <utility>

#include "base/bind.h"
#include "base/callback.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "components/url_formatter/url_fixer.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

namespace policy {

namespace {

// Helper to get the disambiguated SegmentURL() function.
URLBlacklist::SegmentURLCallback GetSegmentURLCallback() {
  return url_formatter::SegmentURL;
}

bool OverrideBlacklistForURL(const GURL& url, bool* block, int* reason) {
  return false;
}

class TestingURLBlacklistManager : public URLBlacklistManager {
 public:
  explicit TestingURLBlacklistManager(PrefService* pref_service)
      : URLBlacklistManager(pref_service,
                            base::ThreadTaskRunnerHandle::Get(),
                            base::ThreadTaskRunnerHandle::Get(),
                            GetSegmentURLCallback(),
                            base::Bind(OverrideBlacklistForURL)),
        update_called_(0),
        set_blacklist_called_(false) {}

  ~TestingURLBlacklistManager() override {}

  // Make this method public for testing.
  using URLBlacklistManager::ScheduleUpdate;

  // Makes a direct call to UpdateOnIO during tests.
  void UpdateOnIOForTesting() {
    std::unique_ptr<base::ListValue> block(new base::ListValue);
    block->Append(new base::StringValue("example.com"));
    std::unique_ptr<base::ListValue> allow(new base::ListValue);
    URLBlacklistManager::UpdateOnIO(std::move(block), std::move(allow));
  }

  // URLBlacklistManager overrides:
  void SetBlacklist(std::unique_ptr<URLBlacklist> blacklist) override {
    set_blacklist_called_ = true;
    URLBlacklistManager::SetBlacklist(std::move(blacklist));
  }

  void Update() override {
    update_called_++;
    URLBlacklistManager::Update();
  }

  int update_called() const { return update_called_; }
  bool set_blacklist_called() const { return set_blacklist_called_; }

 private:
  int update_called_;
  bool set_blacklist_called_;

  DISALLOW_COPY_AND_ASSIGN(TestingURLBlacklistManager);
};

class URLBlacklistManagerTest : public testing::Test {
 protected:
  URLBlacklistManagerTest() {}

  void SetUp() override {
    pref_service_.registry()->RegisterListPref(policy_prefs::kUrlBlacklist);
    pref_service_.registry()->RegisterListPref(policy_prefs::kUrlWhitelist);
    blacklist_manager_.reset(new TestingURLBlacklistManager(&pref_service_));
    loop_.RunUntilIdle();
  }

  void TearDown() override {
    if (blacklist_manager_.get())
      blacklist_manager_->ShutdownOnUIThread();
    loop_.RunUntilIdle();
    // Delete |blacklist_manager_| while |io_thread_| is mapping IO to
    // |loop_|.
    blacklist_manager_.reset();
  }

  base::MessageLoopForIO loop_;
  TestingPrefServiceSimple pref_service_;
  std::unique_ptr<TestingURLBlacklistManager> blacklist_manager_;
};

// Parameters for the FilterToComponents test.
struct FilterTestParams {
 public:
  FilterTestParams(const std::string& filter,
                   const std::string& scheme,
                   const std::string& host,
                   bool match_subdomains,
                   uint16_t port,
                   const std::string& path)
      : filter_(filter),
        scheme_(scheme),
        host_(host),
        match_subdomains_(match_subdomains),
        port_(port),
        path_(path) {}

  FilterTestParams(const FilterTestParams& params)
      : filter_(params.filter_), scheme_(params.scheme_), host_(params.host_),
        match_subdomains_(params.match_subdomains_), port_(params.port_),
        path_(params.path_) {}

  const FilterTestParams& operator=(const FilterTestParams& params) {
    filter_ = params.filter_;
    scheme_ = params.scheme_;
    host_ = params.host_;
    match_subdomains_ = params.match_subdomains_;
    port_ = params.port_;
    path_ = params.path_;
    return *this;
  }

  const std::string& filter() const { return filter_; }
  const std::string& scheme() const { return scheme_; }
  const std::string& host() const { return host_; }
  bool match_subdomains() const { return match_subdomains_; }
  uint16_t port() const { return port_; }
  const std::string& path() const { return path_; }

 private:
  std::string filter_;
  std::string scheme_;
  std::string host_;
  bool match_subdomains_;
  uint16_t port_;
  std::string path_;
};

// Make Valgrind happy. Without this function, a generic one will print the
// raw bytes in FilterTestParams, which due to some likely padding will access
// uninitialized memory.
void PrintTo(const FilterTestParams& params, std::ostream* os) {
  *os << params.filter();
}

class URLBlacklistFilterToComponentsTest
    : public testing::TestWithParam<FilterTestParams> {
 public:
  URLBlacklistFilterToComponentsTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(URLBlacklistFilterToComponentsTest);
};

}  // namespace

TEST_P(URLBlacklistFilterToComponentsTest, FilterToComponents) {
  std::string scheme;
  std::string host;
  bool match_subdomains = true;
  uint16_t port = 42;
  std::string path;

  URLBlacklist::FilterToComponents(GetSegmentURLCallback(),
                                   GetParam().filter(),
                                   &scheme,
                                   &host,
                                   &match_subdomains,
                                   &port,
                                   &path,
                                   NULL);
  EXPECT_EQ(GetParam().scheme(), scheme);
  EXPECT_EQ(GetParam().host(), host);
  EXPECT_EQ(GetParam().match_subdomains(), match_subdomains);
  EXPECT_EQ(GetParam().port(), port);
  EXPECT_EQ(GetParam().path(), path);
}

TEST_F(URLBlacklistManagerTest, SingleUpdateForTwoPrefChanges) {
  base::ListValue* blacklist = new base::ListValue;
  blacklist->Append(new base::StringValue("*.google.com"));
  base::ListValue* whitelist = new base::ListValue;
  whitelist->Append(new base::StringValue("mail.google.com"));
  pref_service_.SetManagedPref(policy_prefs::kUrlBlacklist, blacklist);
  pref_service_.SetManagedPref(policy_prefs::kUrlBlacklist, whitelist);
  loop_.RunUntilIdle();

  EXPECT_EQ(1, blacklist_manager_->update_called());
}

TEST_F(URLBlacklistManagerTest, ShutdownWithPendingTask0) {
  // Post an update task to the UI thread.
  blacklist_manager_->ScheduleUpdate();
  // Shutdown comes before the task is executed.
  blacklist_manager_->ShutdownOnUIThread();
  blacklist_manager_.reset();
  // Run the task after shutdown and deletion.
  loop_.RunUntilIdle();
}

TEST_F(URLBlacklistManagerTest, ShutdownWithPendingTask1) {
  // Post an update task.
  blacklist_manager_->ScheduleUpdate();
  // Shutdown comes before the task is executed.
  blacklist_manager_->ShutdownOnUIThread();
  // Run the task after shutdown, but before deletion.
  loop_.RunUntilIdle();

  EXPECT_EQ(0, blacklist_manager_->update_called());
  blacklist_manager_.reset();
  loop_.RunUntilIdle();
}

TEST_F(URLBlacklistManagerTest, ShutdownWithPendingTask2) {
  // This posts a task to the FILE thread.
  blacklist_manager_->UpdateOnIOForTesting();
  // But shutdown happens before it is done.
  blacklist_manager_->ShutdownOnUIThread();

  EXPECT_FALSE(blacklist_manager_->set_blacklist_called());
  blacklist_manager_.reset();
  loop_.RunUntilIdle();
}

INSTANTIATE_TEST_CASE_P(
    URLBlacklistFilterToComponentsTestInstance,
    URLBlacklistFilterToComponentsTest,
    testing::Values(
        FilterTestParams("google.com",
                         std::string(),
                         ".google.com",
                         true,
                         0u,
                         std::string()),
        FilterTestParams(".google.com",
                         std::string(),
                         "google.com",
                         false,
                         0u,
                         std::string()),
        FilterTestParams("http://google.com",
                         "http",
                         ".google.com",
                         true,
                         0u,
                         std::string()),
        FilterTestParams("google.com/",
                         std::string(),
                         ".google.com",
                         true,
                         0u,
                         "/"),
        FilterTestParams("http://google.com:8080/whatever",
                         "http",
                         ".google.com",
                         true,
                         8080u,
                         "/whatever"),
        FilterTestParams("http://user:pass@google.com:8080/whatever",
                         "http",
                         ".google.com",
                         true,
                         8080u,
                         "/whatever"),
        FilterTestParams("123.123.123.123",
                         std::string(),
                         "123.123.123.123",
                         false,
                         0u,
                         std::string()),
        FilterTestParams("https://123.123.123.123",
                         "https",
                         "123.123.123.123",
                         false,
                         0u,
                         std::string()),
        FilterTestParams("123.123.123.123/",
                         std::string(),
                         "123.123.123.123",
                         false,
                         0u,
                         "/"),
        FilterTestParams("http://123.123.123.123:123/whatever",
                         "http",
                         "123.123.123.123",
                         false,
                         123u,
                         "/whatever"),
        FilterTestParams("*",
                         std::string(),
                         std::string(),
                         true,
                         0u,
                         std::string()),
        FilterTestParams("ftp://*",
                         "ftp",
                         std::string(),
                         true,
                         0u,
                         std::string()),
        FilterTestParams("http://*/whatever",
                         "http",
                         std::string(),
                         true,
                         0u,
                         "/whatever")));

TEST_F(URLBlacklistManagerTest, Filtering) {
  URLBlacklist blacklist(GetSegmentURLCallback());

  // Block domain and all subdomains, for any filtered scheme.
  std::unique_ptr<base::ListValue> blocked(new base::ListValue);
  blocked->Append(new base::StringValue("google.com"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/whatever")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://google.com/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("bogus://google.com/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://notgoogle.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://mail.google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://x.mail.google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://x.mail.google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://x.y.google.com/a/b")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube.com/")));

  // Filter only http, ftp and ws schemes.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("http://secure.com"));
  blocked->Append(new base::StringValue("ftp://secure.com"));
  blocked->Append(new base::StringValue("ws://secure.com"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://secure.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://secure.com/whatever")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("ftp://secure.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("ws://secure.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://secure.com/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("wss://secure.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.secure.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://www.secure.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("wss://www.secure.com")));

  // Filter only a certain path prefix.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("path.to/ruin"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://path.to/ruin")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://path.to/ruin")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://path.to/ruins")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://path.to/ruin/signup")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.path.to/ruin")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://path.to/fortune")));

  // Filter only a certain path prefix and scheme.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("https://s.aaa.com/path"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.aaa.com/path")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.aaa.com/path/bbb")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.aaa.com/path")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://aaa.com/path")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://x.aaa.com/path")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.aaa.com/bbb")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.aaa.com/")));

  // Filter only ws and wss schemes.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("ws://ws.aaa.com"));
  blocked->Append(new base::StringValue("wss://ws.aaa.com"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("ws://ws.aaa.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("wss://ws.aaa.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://ws.aaa.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://ws.aaa.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("ftp://ws.aaa.com")));

  // Test exceptions to path prefixes, and most specific matches.
  blocked.reset(new base::ListValue);
  std::unique_ptr<base::ListValue> allowed(new base::ListValue);
  blocked->Append(new base::StringValue("s.xxx.com/a"));
  allowed->Append(new base::StringValue("s.xxx.com/a/b"));
  blocked->Append(new base::StringValue("https://s.xxx.com/a/b/c"));
  allowed->Append(new base::StringValue("https://s.xxx.com/a/b/c/d"));
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/x")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/x")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/x")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/x")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.xxx.com/a/b/c/d/x")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.xxx.com/a/b/c/d/x")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://xxx.com/a")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://xxx.com/a/b")));

  // Block an ip address.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("123.123.123.123"));
  blacklist.Block(blocked.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://123.123.123.123/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://123.123.123.124/")));

  // Open an exception.
  allowed.reset(new base::ListValue);
  allowed->Append(new base::StringValue("plus.google.com"));
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://plus.google.com/")));

  // Open an exception only when using https for mail.
  allowed.reset(new base::ListValue);
  allowed->Append(new base::StringValue("https://mail.google.com"));
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://mail.google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://www.google.com/")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://mail.google.com/")));

  // Match exactly "google.com", only for http. Subdomains without exceptions
  // are still blocked.
  allowed.reset(new base::ListValue);
  allowed->Append(new base::StringValue("http://.google.com"));
  blacklist.Allow(allowed.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://google.com/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com/")));

  // A smaller path match in an exact host overrides a longer path for hosts
  // that also match subdomains.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("yyy.com/aaa"));
  blacklist.Block(blocked.get());
  allowed.reset(new base::ListValue);
  allowed->Append(new base::StringValue(".yyy.com/a"));
  blacklist.Allow(allowed.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com/aaa")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://yyy.com/aaa2")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://www.yyy.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.yyy.com/aaa")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.yyy.com/aaa2")));

  // If the exact entry is both allowed and blocked, allowing takes precedence.
  blocked.reset(new base::ListValue);
  blocked->Append(new base::StringValue("example.com"));
  blacklist.Block(blocked.get());
  allowed.reset(new base::ListValue);
  allowed->Append(new base::StringValue("example.com"));
  blacklist.Allow(allowed.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://example.com")));
}

TEST_F(URLBlacklistManagerTest, QueryParameters) {
  URLBlacklist blacklist(GetSegmentURLCallback());
  std::unique_ptr<base::ListValue> blocked(new base::ListValue);
  std::unique_ptr<base::ListValue> allowed(new base::ListValue);

  // Block domain and all subdomains, for any filtered scheme.
  blocked->AppendString("youtube.com");
  allowed->AppendString("youtube.com/watch?v=XYZ");
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());

  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=123&v=XYZ")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&v=123")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?v=XYZ&foo=bar")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar&v=XYZ")));

  allowed.reset(new base::ListValue);
  allowed->AppendString("youtube.com/watch?av=XYZ&ag=123");
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=123&ag=XYZ")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=XYZ&av=123")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?av=XYZ&ag=123")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?ag=123&av=XYZ")));
  EXPECT_TRUE(blacklist.IsURLBlocked(
      GURL("http://youtube.com/watch?av=XYZ&ag=123&av=123")));
  EXPECT_TRUE(blacklist.IsURLBlocked(
      GURL("http://youtube.com/watch?av=XYZ&ag=123&ag=1234")));

  allowed.reset(new base::ListValue);
  allowed->AppendString("youtube.com/watch?foo=bar*&vid=2*");
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube.com/watch?foo=bar")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=2&foo=bar1")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube.com/watch?vid=234&foo=bar")));
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube.com/watch?vid=234&foo=bar23")));

  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube1.com/disallow?v=44678");
  blacklist.Block(blocked.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?v=123")));
  // Path does not match
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?v=44678")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=44678")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?v=4467")));
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube1.com/disallow?v=4467&v=123")));
  EXPECT_TRUE(blacklist.IsURLBlocked(
      GURL("http://youtube1.com/disallow?v=4467&v=123&v=44678")));

  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube1.com/disallow?g=*");
  blacklist.Block(blocked.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube1.com?ag=123")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?g=123")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube1.com/disallow?ag=13&g=123")));

  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube2.com/disallow?a*");
  blacklist.Block(blocked.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube2.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(
      GURL("http://youtube2.com/disallow?b=123&a21=467")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube2.com/disallow?abba=true")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube2.com/disallow?baba=true")));

  allowed.reset(new base::ListValue);
  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube3.com");
  allowed->AppendString("youtube3.com/watch?fo*");
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube3.com")));
  EXPECT_TRUE(
      blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?b=123&a21=467")));
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube3.com/watch?b=123&a21=467&foo1")));
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube3.com/watch?b=123&a21=467&foo=bar")));
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube3.com/watch?b=123&a21=467&fo=ba")));
  EXPECT_FALSE(
      blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?foriegn=true")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube3.com/watch?fold")));

  allowed.reset(new base::ListValue);
  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube4.com");
  allowed->AppendString("youtube4.com?*");
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube4.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube4.com/?hello")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube4.com/?foo")));

  allowed.reset(new base::ListValue);
  blocked.reset(new base::ListValue);
  blocked->AppendString("youtube5.com?foo=bar");
  allowed->AppendString("youtube5.com?foo1=bar1&foo2=bar2&");
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://youtube5.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://youtube5.com/?foo=bar&a=b")));
  // More specific filter is given precedence.
  EXPECT_FALSE(blacklist.IsURLBlocked(
      GURL("http://youtube5.com/?a=b&foo=bar&foo1=bar1&foo2=bar2")));
}

TEST_F(URLBlacklistManagerTest, BlockAllWithExceptions) {
  URLBlacklist blacklist(GetSegmentURLCallback());

  std::unique_ptr<base::ListValue> blocked(new base::ListValue);
  std::unique_ptr<base::ListValue> allowed(new base::ListValue);
  blocked->Append(new base::StringValue("*"));
  allowed->Append(new base::StringValue(".www.google.com"));
  allowed->Append(new base::StringValue("plus.google.com"));
  allowed->Append(new base::StringValue("https://mail.google.com"));
  allowed->Append(new base::StringValue("https://very.safe/path"));
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://random.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://s.www.google.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://www.google.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://plus.google.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("http://s.plus.google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://mail.google.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://mail.google.com")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://s.mail.google.com")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("https://very.safe/")));
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://very.safe/path")));
  EXPECT_FALSE(blacklist.IsURLBlocked(GURL("https://very.safe/path")));
}

TEST_F(URLBlacklistManagerTest, DontBlockResources) {
  std::unique_ptr<URLBlacklist> blacklist(
      new URLBlacklist(GetSegmentURLCallback()));
  std::unique_ptr<base::ListValue> blocked(new base::ListValue);
  blocked->Append(new base::StringValue("google.com"));
  blacklist->Block(blocked.get());
  blacklist_manager_->SetBlacklist(std::move(blacklist));
  EXPECT_TRUE(blacklist_manager_->IsURLBlocked(GURL("http://google.com")));

  int reason = net::ERR_UNEXPECTED;
  EXPECT_TRUE(blacklist_manager_->ShouldBlockRequestForFrame(
      GURL("http://google.com"), &reason));
  EXPECT_EQ(net::ERR_BLOCKED_BY_ADMINISTRATOR, reason);
}

TEST_F(URLBlacklistManagerTest, DefaultBlacklistExceptions) {
  URLBlacklist blacklist(GetSegmentURLCallback());
  std::unique_ptr<base::ListValue> blocked(new base::ListValue);

  // Blacklist everything:
  blocked->Append(new base::StringValue("*"));
  blacklist.Block(blocked.get());

  // Internal NTP and extension URLs are not blocked by the "*":
  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com")));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-extension://xyz"))));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-search://local-ntp"))));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-native://ntp"))));

  // Unless they are explicitly blacklisted:
  blocked->Append(new base::StringValue("chrome-extension://*"));
  std::unique_ptr<base::ListValue> allowed(new base::ListValue);
  allowed->Append(new base::StringValue("chrome-extension://abc"));
  blacklist.Block(blocked.get());
  blacklist.Allow(allowed.get());

  EXPECT_TRUE(blacklist.IsURLBlocked(GURL("http://www.google.com")));
  EXPECT_TRUE((blacklist.IsURLBlocked(GURL("chrome-extension://xyz"))));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-extension://abc"))));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-search://local-ntp"))));
  EXPECT_FALSE((blacklist.IsURLBlocked(GURL("chrome-native://ntp"))));
}

}  // namespace policy


text:
package ca.uhn.fhir.parser;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;

import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.base.composite.BaseCodingDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.resource.Binary;
import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
import ca.uhn.fhir.model.dstu2.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu2.resource.Medication;
import ca.uhn.fhir.model.dstu2.resource.MedicationPrescription;
import ca.uhn.fhir.model.dstu2.resource.Observation;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.resource.QuestionnaireResponse;
import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;
import ca.uhn.fhir.model.dstu2.valueset.BundleTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.IdentifierUseEnum;
import ca.uhn.fhir.model.dstu2.valueset.MaritalStatusCodesEnum;
import ca.uhn.fhir.model.dstu2.valueset.ObservationStatusEnum;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.server.Constants;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

public class JsonParserDstu2Test {
	private static final FhirContext ourCtx = FhirContext.forDstu2();
	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonParserDstu2Test.class);

	@Test
	public void testEncodeAndParseExtensions() throws Exception {

		Patient patient = new Patient();
		patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135");

		ExtensionDt ext = new ExtensionDt();
		ext.setUrl("http://example.com/extensions#someext");
		ext.setValue(new DateTimeDt("2011-01-02T11:13:15"));
		patient.addUndeclaredExtension(ext);

		ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent");
		patient.addUndeclaredExtension(parent);
		ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1"));
		parent.addUndeclaredExtension(child1);
		ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value2"));
		parent.addUndeclaredExtension(child2);

		ExtensionDt modExt = new ExtensionDt();
		modExt.setUrl("http://example.com/extensions#modext");
		modExt.setValue(new DateDt("1995-01-02"));
		modExt.setModifier(true);
		patient.addUndeclaredExtension(modExt);

		HumanNameDt name = patient.addName();
		name.addFamily("Blah");
		StringDt given = name.addGiven();
		given.setValue("Joe");
		ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given"));
		given.addUndeclaredExtension(ext2);

		StringDt given2 = name.addGiven();
		given2.setValue("Shmoe");
		ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent");
		given2.addUndeclaredExtension(given2ext);
		given2ext.addUndeclaredExtension(new ExtensionDt().setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD")));

		String output = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
		ourLog.info(output);

		String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
		assertThat(enc, Matchers.stringContainsInOrder("{\"resourceType\":\"Patient\",", "\"extension\":[{\"url\":\"http://example.com/extensions#someext\",\"valueDateTime\":\"2011-01-02T11:13:15\"}",
				"{\"url\":\"http://example.com#parent\",\"extension\":[{\"url\":\"http://example.com#child\",\"valueString\":\"value1\"},{\"url\":\"http://example.com#child\",\"valueString\":\"value2\"}]}"));
		assertThat(enc, Matchers.stringContainsInOrder("\"modifierExtension\":[" + "{" + "\"url\":\"http://example.com/extensions#modext\"," + "\"valueDate\":\"1995-01-02\"" + "}" + "],"));
		assertThat(enc, containsString("\"_given\":[" + "{" + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext\"," + "\"valueString\":\"given\"" + "}" + "]" + "}," + "{" + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext_parent\"," + "\"extension\":[" + "{"
				+ "\"url\":\"http://examples.com#givenext_child\"," + "\"valueString\":\"CHILD\"" + "}" + "]" + "}" + "]" + "}"));

		/*
		 * Now parse this back
		 */

		Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, enc);
		ext = parsed.getUndeclaredExtensions().get(0);
		assertEquals("http://example.com/extensions#someext", ext.getUrl());
		assertEquals("2011-01-02T11:13:15", ((DateTimeDt) ext.getValue()).getValueAsString());

		parent = patient.getUndeclaredExtensions().get(1);
		assertEquals("http://example.com#parent", parent.getUrl());
		assertNull(parent.getValue());
		child1 = parent.getExtension().get(0);
		assertEquals("http://example.com#child", child1.getUrl());
		assertEquals("value1", ((StringDt) child1.getValue()).getValueAsString());
		child2 = parent.getExtension().get(1);
		assertEquals("http://example.com#child", child2.getUrl());
		assertEquals("value2", ((StringDt) child2.getValue()).getValueAsString());

		modExt = parsed.getUndeclaredModifierExtensions().get(0);
		assertEquals("http://example.com/extensions#modext", modExt.getUrl());
		assertEquals("1995-01-02", ((DateDt) modExt.getValue()).getValueAsString());

		name = parsed.getName().get(0);

		ext2 = name.getGiven().get(0).getUndeclaredExtensions().get(0);
		assertEquals("http://examples.com#givenext", ext2.getUrl());
		assertEquals("given", ((StringDt) ext2.getValue()).getValueAsString());

		given2ext = name.getGiven().get(1).getUndeclaredExtensions().get(0);
		assertEquals("http://examples.com#givenext_parent", given2ext.getUrl());
		assertNull(given2ext.getValue());
		ExtensionDt given2ext2 = given2ext.getExtension().get(0);
		assertEquals("http://examples.com#givenext_child", given2ext2.getUrl());
		assertEquals("CHILD", ((StringDt) given2ext2.getValue()).getValue());

	}

	@Test
	public void testEncodeAndParseMetaProfileAndTags() {
		Patient p = new Patient();
		p.addName().addFamily("FAMILY");

		List<IdDt> profiles = new ArrayList<IdDt>();
		profiles.add(new IdDt("http://foo/Profile1"));
		profiles.add(new IdDt("http://foo/Profile2"));
		ResourceMetadataKeyEnum.PROFILES.put(p, profiles);

		TagList tagList = new TagList();
		tagList.addTag("scheme1", "term1", "label1");
		tagList.addTag("scheme2", "term2", "label2");
		ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList);

		String enc = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(p);
		ourLog.info(enc);

		//@formatter:off
		assertThat(enc, stringContainsInOrder("\"meta\":{",
				"\"profile\":[",
				"\"http://foo/Profile1\",",
				"\"http://foo/Profile2\"",
				"],",
				"\"tag\":[",
				"{",
				"\"system\":\"scheme1\",",
				"\"code\":\"term1\",",
				"\"display\":\"label1\"",
				"},",
				"{",
				"\"system\":\"scheme2\",",
				"\"code\":\"term2\",",
				"\"display\":\"label2\"",
				"}",
				"]",
				"},"));
		//@formatter:on

		Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, enc);
		List<IdDt> gotLabels = ResourceMetadataKeyEnum.PROFILES.get(parsed);

		assertEquals(2, gotLabels.size());

		IdDt label = (IdDt) gotLabels.get(0);
		assertEquals("http://foo/Profile1", label.getValue());
		label = (IdDt) gotLabels.get(1);
		assertEquals("http://foo/Profile2", label.getValue());

		tagList = ResourceMetadataKeyEnum.TAG_LIST.get(parsed);
		assertEquals(2, tagList.size());

		assertEquals(new Tag("scheme1", "term1", "label1"), tagList.get(0));
		assertEquals(new Tag("scheme2", "term2", "label2"), tagList.get(1));
	}

	@Test
	public void testEncodeAndParseSecurityLabels() {
		Patient p = new Patient();
		p.addName().addFamily("FAMILY");

		List<BaseCodingDt> labels = new ArrayList<BaseCodingDt>();
		labels.add(new CodingDt().setSystem("SYSTEM1").setCode("CODE1").setDisplay("DISPLAY1").setVersion("VERSION1"));
		labels.add(new CodingDt().setSystem("SYSTEM2").setCode("CODE2").setDisplay("DISPLAY2").setVersion("VERSION2"));

		ResourceMetadataKeyEnum.SECURITY_LABELS.put(p, labels);

		String enc = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(p);
		ourLog.info(enc);

		//@formatter:off
		assertEquals("{\n" +
			"    \"resourceType\":\"Patient\",\n" +
			"    \"meta\":{\n" +
			"        \"security\":[\n" +
			"            {\n" +
			"                \"system\":\"SYSTEM1\",\n" +
			"                \"version\":\"VERSION1\",\n" +
			"                \"code\":\"CODE1\",\n" +
			"                \"display\":\"DISPLAY1\"\n" +
			"            },\n" +
			"            {\n" +
			"                \"system\":\"SYSTEM2\",\n" +
			"                \"version\":\"VERSION2\",\n" +
			"                \"code\":\"CODE2\",\n" +
			"                \"display\":\"DISPLAY2\"\n" +
			"            }\n" +
			"        ]\n" +
			"    },\n" +
			"    \"name\":[\n" +
			"        {\n" +
			"            \"family\":[\n" +
			"                \"FAMILY\"\n" +
			"            ]\n" +
			"        }\n" +
			"    ]\n" +
			"}", enc.trim());
		//@formatter:on

		Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, enc);
		List<BaseCodingDt> gotLabels = ResourceMetadataKeyEnum.SECURITY_LABELS.get(parsed);

		assertEquals(2, gotLabels.size());

		CodingDt label = (CodingDt) gotLabels.get(0);
		assertEquals("SYSTEM1", label.getSystem());
		assertEquals("CODE1", label.getCode());
		assertEquals("DISPLAY1", label.getDisplay());
		assertEquals("VERSION1", label.getVersion());

		label = (CodingDt) gotLabels.get(1);
		assertEquals("SYSTEM2", label.getSystem());
		assertEquals("CODE2", label.getCode());
		assertEquals("DISPLAY2", label.getDisplay());
		assertEquals("VERSION2", label.getVersion());
	}

	@Test
	public void testEncodeBundleNewBundleNoText() {

		ca.uhn.fhir.model.dstu2.resource.Bundle b = new ca.uhn.fhir.model.dstu2.resource.Bundle();
		b.getText().setDiv("");
		b.getText().getStatus().setValueAsString("");
		;

		Entry e = b.addEntry();
		e.setResource(new Patient());

		String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(b);
		ourLog.info(val);
		assertThat(val, not(containsString("text")));

		val = ourCtx.newXmlParser().setPrettyPrint(false).encodeResourceToString(b);
		ourLog.info(val);
		assertThat(val, not(containsString("text")));

	}

	@Test
	public void testEncodeBundleOldBundleNoText() {

		Bundle b = new Bundle();

		BundleEntry e = b.addEntry();
		e.setResource(new Patient());
		b.addCategory("scheme", "term", "label");

		String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b);
		ourLog.info(val);

		assertThat(val, not(containsString("text")));

		b = ourCtx.newJsonParser().parseBundle(val);
		assertEquals(1, b.getEntries().size());

	}

	/**
	 * Fixing #89
	 */
	@Test
	public void testEncodeBundleWithDeletedEntry() throws ConfigurationException, DataFormatException, IOException {
		Bundle b = ourCtx.newXmlParser().parseBundle(IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/xml-bundle.xml")));
		String val = ourCtx.newJsonParser().encodeBundleToString(b);

		ourLog.info(val);

		//@formatter:off
		assertThat(val, containsString("\"deleted\":{" +
				"\"type\":\"Patient\"," +
				"\"resourceId\":\"4384\"," +
				"\"instant\":\"2015-01-15T11:04:43.054-05:00\"" +
				"}"));
		//@formatter:on
	}

	/**
	 * #158
	 */
	@Test
	public void testEncodeEmptyTag() {
		TagList tagList = new TagList();
		tagList.addTag(null, null, null);
		tagList.addTag(null, null, "Label");

		Patient p = new Patient();
		ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList);

		String encoded = ourCtx.newJsonParser().encodeResourceToString(p);
		assertThat(encoded, not(containsString("tag")));
	}

	/**
	 * #158
	 */
	@Test
	public void testEncodeEmptyTag2() {
		TagList tagList = new TagList();
		tagList.addTag("scheme", "code", null);
		tagList.addTag(null, null, "Label");

		Patient p = new Patient();
		ResourceMetadataKeyEnum.TAG_LIST.put(p, tagList);

		String encoded = ourCtx.newJsonParser().encodeResourceToString(p);
		assertThat(encoded, containsString("tag"));
		assertThat(encoded, containsString("scheme"));
		assertThat(encoded, not(containsString("Label")));
	}

	@Test
	public void testEncodeNarrativeSuppressed() throws Exception {
		Patient patient = new Patient();
		patient.setId("Patient/1/_history/1");
		patient.getText().setDiv("
THE DIV
");
		patient.addName().addFamily("FAMILY");
		patient.setMaritalStatus(MaritalStatusCodesEnum.D);

		String encoded = ourCtx.newJsonParser().setPrettyPrint(true).setSuppressNarratives(true).encodeResourceToString(patient);
		ourLog.info(encoded);

		assertThat(encoded, containsString("Patient"));
		assertThat(encoded, stringContainsInOrder(Constants.TAG_SUBSETTED_SYSTEM, Constants.TAG_SUBSETTED_CODE));
		assertThat(encoded, not(containsString("text")));
		assertThat(encoded, not(containsString("THE DIV")));
		assertThat(encoded, containsString("family"));
		assertThat(encoded, containsString("maritalStatus"));
	}

	@Test
	public void testEncodeSummary() {
		Patient patient = new Patient();
		patient.setId("Patient/1/_history/1");
		patient.getText().setDiv("
THE DIV
");
		patient.addName().addFamily("FAMILY");
		patient.setMaritalStatus(MaritalStatusCodesEnum.D);

		String encoded = ourCtx.newJsonParser().setPrettyPrint(true).setSummaryMode(true).encodeResourceToString(patient);
		ourLog.info(encoded);

		assertThat(encoded, containsString("Patient"));
		assertThat(encoded, stringContainsInOrder("\"tag\"", "\"system\":\"" + Constants.TAG_SUBSETTED_SYSTEM + "\",", "\"code\":\"" + Constants.TAG_SUBSETTED_CODE + "\","));
		assertThat(encoded, not(containsString("THE DIV")));
		assertThat(encoded, containsString("family"));
		assertThat(encoded, not(containsString("maritalStatus")));
	}

	@Test
	public void testEncodeSummary2() {
		Patient patient = new Patient();
		patient.setId("Patient/1/_history/1");
		patient.getText().setDiv("
THE DIV
");
		patient.addName().addFamily("FAMILY");
		patient.setMaritalStatus(MaritalStatusCodesEnum.D);

		TagList tl = new TagList();
		tl.add(new Tag("foo", "bar"));
		ResourceMetadataKeyEnum.TAG_LIST.put(patient, tl);

		String encoded = ourCtx.newJsonParser().setPrettyPrint(true).setSummaryMode(true).encodeResourceToString(patient);
		ourLog.info(encoded);

		assertThat(encoded, containsString("Patient"));
		assertThat(encoded, stringContainsInOrder("\"tag\"", "\"system\":\"foo\",", "\"code\":\"bar\"", "\"system\":\"" + Constants.TAG_SUBSETTED_SYSTEM + "\",", "\"code\":\"" + Constants.TAG_SUBSETTED_CODE + "\","));
		assertThat(encoded, not(containsString("THE DIV")));
		assertThat(encoded, containsString("family"));
		assertThat(encoded, not(containsString("maritalStatus")));
	}

	/**
	 * See #205
	 */
	@Test
	public void testEncodeTags() {
		Patient pt = new Patient();
		pt.addIdentifier().setSystem("sys").setValue("val");

		TagList tagList = new TagList();
		tagList.addTag("scheme", "term", "display");
		ResourceMetadataKeyEnum.TAG_LIST.put(pt, tagList);

		String enc = ourCtx.newJsonParser().encodeResourceToString(pt);
		ourLog.info(enc);

		assertEquals("{\"resourceType\":\"Patient\",\"meta\":{\"tag\":[{\"system\":\"scheme\",\"code\":\"term\",\"display\":\"display\"}]},\"identifier\":[{\"system\":\"sys\",\"value\":\"val\"}]}", enc);

	}

	@Test
	public void testEncodingNullExtension() {
		Patient p = new Patient();
		ExtensionDt extension = new ExtensionDt(false, "http://foo#bar");
		p.addUndeclaredExtension(extension);
		String str = ourCtx.newJsonParser().encodeResourceToString(p);

		assertEquals("{\"resourceType\":\"Patient\"}", str);

		extension.setValue(new StringDt());

		str = ourCtx.newJsonParser().encodeResourceToString(p);
		assertEquals("{\"resourceType\":\"Patient\"}", str);

		extension.setValue(new StringDt(""));

		str = ourCtx.newJsonParser().encodeResourceToString(p);
		assertEquals("{\"resourceType\":\"Patient\"}", str);

	}

	/**
	 * #65
	 */
	@Test
	public void testJsonPrimitiveWithExtensionEncoding() {

		QuestionnaireResponse parsed = new QuestionnaireResponse();
		parsed.getGroup().setLinkId("value123");
		parsed.getGroup().getLinkIdElement().addUndeclaredExtension(false, "http://123", new StringDt("HELLO"));

		String encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(parsed);
		ourLog.info(encoded);
		assertThat(encoded, containsString("{\"linkId\":\"value123\",\"_linkId\":{\"extension\":[{\"url\":\"http://123\",\"valueString\":\"HELLO\"}]}}"));

	}

	@Test
	public void testOmitResourceId() {
		Patient p = new Patient();
		p.setId("123");
		p.addName().addFamily("ABC");

		assertThat(ourCtx.newJsonParser().encodeResourceToString(p), stringContainsInOrder("123", "ABC"));
		assertThat(ourCtx.newJsonParser().setOmitResourceId(true).encodeResourceToString(p), containsString("ABC"));
		assertThat(ourCtx.newJsonParser().setOmitResourceId(true).encodeResourceToString(p), not(containsString("123")));
	}

	@Test
	public void testParseAndEncodeBundle() throws Exception {
		String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example.json"));

		Bundle parsed = ourCtx.newJsonParser().parseBundle(content);
		assertEquals("Bundle/example/_history/1", parsed.getId().getValue());
		assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION));
		assertEquals("1", parsed.getId().getVersionIdPart());
		assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED));
		assertEquals("searchset", parsed.getType().getValue());
		assertEquals(3, parsed.getTotalResults().getValue().intValue());
		assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLinkNext().getValue());
		assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLinkSelf().getValue());

		assertEquals(2, parsed.getEntries().size());

		MedicationPrescription p = (MedicationPrescription) parsed.getEntries().get(0).getResource();
		assertEquals("Patient/347", p.getPatient().getReference().getValue());
		assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString());
		assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue());

		Medication m = (Medication) parsed.getEntries().get(1).getResource();
		assertEquals("http://example.com/base/Medication/example", m.getId().getValue());
		assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m);

		String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(parsed);
		ourLog.info(reencoded);

		JsonConfig cfg = new JsonConfig();

		JSON expected = JSONSerializer.toJSON(content.trim(), cfg);
		JSON actual = JSONSerializer.toJSON(reencoded.trim(), cfg);

		String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
		String act = actual.toString().replace("\\r\\n", "\\n");

		ourLog.info("Expected: {}", exp);
		ourLog.info("Actual  : {}", act);

		assertEquals(exp, act);

	}

	/**
	 * Test for #146
	 */
	@Test
	public void testParseAndEncodeBundleFromXmlToJson() throws Exception {
		String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example2.xml"));

		ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newXmlParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, content);

		MedicationPrescription p = (MedicationPrescription) parsed.getEntry().get(0).getResource();
		assertEquals("#med", ((ResourceReferenceDt) p.getMedication()).getReference().getValue());

		Medication m = (Medication) ((ResourceReferenceDt) p.getMedication()).getResource();
		assertNotNull(m);
		assertEquals("#med", m.getId().getValue());
		assertEquals(1, p.getContained().getContainedResources().size());
		assertSame(m, p.getContained().getContainedResources().get(0));

		String reencoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed);
		ourLog.info(reencoded);
		assertThat(reencoded, containsString("contained"));

		reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed);
		ourLog.info(reencoded);
		assertThat(reencoded, containsString("contained"));
	}

	@Test
	public void testParseAndEncodeBundleNewStyle() throws Exception {
		String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example.json"));

		ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newJsonParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, content);
		assertEquals("Bundle/example/_history/1", parsed.getId().getValue());
		assertEquals("1", parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION));
		assertEquals("1", parsed.getId().getVersionIdPart());
		assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED));
		assertEquals("searchset", parsed.getType());
		assertEquals(3, parsed.getTotal().intValue());
		assertEquals("https://example.com/base/MedicationPrescription?patient=347&searchId=ff15fd40-ff71-4b48-b366-09c706bed9d0&page=2", parsed.getLink().get(0).getUrlElement().getValueAsString());
		assertEquals("https://example.com/base/MedicationPrescription?patient=347&_include=MedicationPrescription.medication", parsed.getLink().get(1).getUrlElement().getValueAsString());

		assertEquals(2, parsed.getEntry().size());

		MedicationPrescription p = (MedicationPrescription) parsed.getEntry().get(0).getResource();
		assertEquals("Patient/347", p.getPatient().getReference().getValue());
		assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString());
		assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue());

		Medication m = (Medication) parsed.getEntry().get(1).getResource();
		assertEquals("http://example.com/base/Medication/example", m.getId().getValue());
		assertEquals("Medication/example", ((ResourceReferenceDt) p.getMedication()).getReference().getValue());
		assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m);

		String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed);
		ourLog.info(reencoded);

		JsonConfig cfg = new JsonConfig();

		JSON expected = JSONSerializer.toJSON(content.trim(), cfg);
		JSON actual = JSONSerializer.toJSON(reencoded.trim(), cfg);

		String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
		String act = actual.toString().replace("\\r\\n", "\\n");

		ourLog.info("Expected: {}", exp);
		ourLog.info("Actual  : {}", act);

		assertEquals(exp, act);

	}

	@Test
	public void testParseAndEncodeBundleOldStyle() throws Exception {
		String content = IOUtils.toString(JsonParserDstu2Test.class.getResourceAsStream("/bundle-example.json"));

		Bundle parsed = ourCtx.newJsonParser().parseBundle(content);

		assertEquals(new InstantDt("2014-08-18T01:43:30Z"), parsed.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED));
		assertEquals("searchset", parsed.getType().getValue());
		assertEquals(3, parsed.getTotalResults().getValue().intValue());

		assertEquals(2, parsed.getEntries().size());

		MedicationPrescription p = (MedicationPrescription) parsed.getEntries().get(0).getResource();
		assertEquals("Patient/347", p.getPatient().getReference().getValue());
		assertEquals("2014-08-16T05:31:17Z", ResourceMetadataKeyEnum.UPDATED.get(p).getValueAsString());
		assertEquals("http://example.com/base/MedicationPrescription/3123/_history/1", p.getId().getValue());

		Medication m = (Medication) parsed.getEntries().get(1).getResource();
		assertEquals("http://example.com/base/Medication/example", m.getId().getValue());
		assertEquals("Medication/example", ((ResourceReferenceDt) p.getMedication()).getReference().getValue());
		assertSame(((ResourceReferenceDt) p.getMedication()).getResource(), m);

		String reencoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(parsed);
		ourLog.info(reencoded);

		JsonConfig cfg = new JsonConfig();

		JSON expected = JSONSerializer.toJSON(content.trim(), cfg);
		JSON actual = JSONSerializer.toJSON(reencoded.trim(), cfg);

		String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
		String act = actual.toString().replace("\\r\\n", "\\n");

		exp = exp.replace(",\"ifNoneExist\":\"Patient?identifier=234234\"", "");

		ourLog.info("Expected: {}", exp);
		ourLog.info("Actual  : {}", act);

		assertEquals(exp, act);

	}

	@Test
	public void testParseAndEncodeBundleWithDeletedEntry() {

		Patient res = new Patient();
		res.setId(new IdDt("Patient", "111", "222"));
		ResourceMetadataKeyEnum.DELETED_AT.put(res, new InstantDt("2011-01-01T12:12:22Z"));

		Bundle bundle = new Bundle();
		bundle.addResource(res, ourCtx, "http://foo/base");

		String actual = ourCtx.newJsonParser().encodeBundleToString(bundle);
		ourLog.info(actual);

		String expected = "{\"resourceType\":\"Bundle\",\"entry\":[{\"deleted\":{\"type\":\"Patient\",\"resourceId\":\"111\",\"versionId\":\"222\",\"instant\":\"2011-01-01T12:12:22Z\"}}]}";
		assertEquals(expected, actual);

	}

	@Test
	public void testParseAndEncodeBundleWithUuidBase() {
		//@formatter:off
		String input =
				"{\n" +
				"    \"resourceType\":\"Bundle\",\n" +
				"    \"type\":\"document\",\n" +
				"    \"entry\":[\n" +
				"        {\n" +
				"            \"fullUrl\":\"urn:uuid:180f219f-97a8-486d-99d9-ed631fe4fc57\",\n" +
				"            \"resource\":{\n" +
				"                \"resourceType\":\"Composition\",\n" +
				"                \"id\":\"180f219f-97a8-486d-99d9-ed631fe4fc57\",\n" +
				"                \"meta\":{\n" +
				"                    \"lastUpdated\":\"2013-05-28T22:12:21Z\"\n" +
				"                },\n" +
				"                \"text\":{\n" +
				"                    \"status\":\"generated\",\n" +
				"                    \"div\":\"

Generated Narrative with Details

id: 180f219f-97a8-486d-99d9-ed631fe4fc57

meta:

date: Feb 1, 2013 12:30:02 PM

type: Discharge Summary from Responsible Clinician (Details : {LOINC code '28655-9' = 'Physician attending Discharge summary)

status: final

confidentiality: N

author: Doctor Dave. Generated Summary: 23; Adam Careful

encounter: http://fhir.healthintersections.com.au/open/Encounter/doc-example

\"\n" +
				"                },\n" +
				"                \"date\":\"2013-02-01T12:30:02Z\",\n" +
				"                \"type\":{\n" +
				"                    \"coding\":[\n" +
				"                        {\n" +
				"                            \"system\":\"http://loinc.org\",\n" +
				"                            \"code\":\"28655-9\"\n" +
				"                        }\n" +
				"                    ],\n" +
				"                    \"text\":\"Discharge Summary from Responsible Clinician\"\n" +
				"                },\n" +
				"                \"status\":\"final\",\n" +
				"                \"confidentiality\":\"N\",\n" +
				"                \"subject\":{\n" +
				"                    \"reference\":\"http://fhir.healthintersections.com.au/open/Patient/d1\",\n" +
				"                    \"display\":\"Eve Everywoman\"\n" +
				"                },\n" +
				"                \"author\":[\n" +
				"                    {\n" +
				"                        \"reference\":\"Practitioner/example\",\n" +
				"                        \"display\":\"Doctor Dave\"\n" +
				"                    }\n" +
				"                ],\n" +
				"                \"encounter\":{\n" +
				"                    \"reference\":\"http://fhir.healthintersections.com.au/open/Encounter/doc-example\"\n" +
				"                },\n" +
				"                \"section\":[\n" +
				"                    {\n" +
				"                        \"title\":\"Reason for admission\",\n" +
				"                        \"content\":{\n" +
				"                            \"reference\":\"urn:uuid:d0dd51d3-3ab2-4c84-b697-a630c3e40e7a\"\n" +
				"                        }\n" +
				"                    },\n" +
				"                    {\n" +
				"                        \"title\":\"Medications on Discharge\",\n" +
				"                        \"content\":{\n" +
				"                            \"reference\":\"urn:uuid:673f8db5-0ffd-4395-9657-6da00420bbc1\"\n" +
				"                        }\n" +
				"                    },\n" +
				"                    {\n" +
				"                        \"title\":\"Known allergies\",\n" +
				"                        \"content\":{\n" +
				"                            \"reference\":\"urn:uuid:68f86194-e6e1-4f65-b64a-5314256f8d7b\"\n" +
				"                        }\n" +
				"                    }\n" +
				"                ]\n" +
				"            }\n" +
				"        }" +
				"    ]" +
				"}";
		//@formatter:on

		ca.uhn.fhir.model.dstu2.resource.Bundle parsed = ourCtx.newJsonParser().parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, input);

		String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed);
		ourLog.info(encoded);

		assertEquals("urn:uuid:180f219f-97a8-486d-99d9-ed631fe4fc57", parsed.getEntry().get(0).getResource().getId().getValue());
		assertEquals("urn:uuid:", parsed.getEntry().get(0).getResource().getId().getBaseUrl());
		assertEquals("180f219f-97a8-486d-99d9-ed631fe4fc57", parsed.getEntry().get(0).getResource().getId().getIdPart());
		assertThat(encoded, containsString("\"id\":\"180f219f-97a8-486d-99d9-ed631fe4fc57\""));
	}

	@Test
	public void testParseBundleWithBinary() {
		Binary patient = new Binary();
		patient.setId(new IdDt("http://base/Binary/11/_history/22"));
		patient.setContentType("foo");
		patient.setContent(new byte[] { 1, 2, 3, 4 });

		String val = ourCtx.newJsonParser().encodeResourceToString(patient);
		assertEquals("{\"resourceType\":\"Binary\",\"id\":\"11\",\"meta\":{\"versionId\":\"22\"},\"contentType\":\"foo\",\"content\":\"AQIDBA==\"}", val);
	}

	/**
	 * see #144 and #146
	 */
	@Test
	public void testParseContained() {

		FhirContext c = FhirContext.forDstu2();
		IParser parser = c.newJsonParser().setPrettyPrint(true);

		Observation o = new Observation();
		o.getCode().setText("obs text");

		Patient p = new Patient();
		p.addName().addFamily("patient family");
		o.getSubject().setResource(p);

		String enc = parser.encodeResourceToString(o);
		ourLog.info(enc);

		//@formatter:off
		assertThat(enc, stringContainsInOrder(
			"\"resourceType\":\"Observation\"",
			"\"contained\":[",
			"\"resourceType\":\"Patient\",",
			"\"id\":\"1\"",
			"\"reference\":\"#1\""
			));
		//@formatter:on

		o = parser.parseResource(Observation.class, enc);
		assertEquals("obs text", o.getCode().getText());

		assertNotNull(o.getSubject().getResource());
		p = (Patient) o.getSubject().getResource();
		assertEquals("patient family", p.getNameFirstRep().getFamilyAsSingleString());
	}

	@Test
	public void testParseMetadata() throws Exception {
		//@formatter:off
		String bundle = "{\n" +
			"  \"resourceType\" : \"Bundle\",\n" +
			"  \"total\" : 1,\n" +
			"   \"link\": [{\n" +
			"      \"relation\" : \"self\",\n" +
			"      \"url\" : \"http://localhost:52788/Binary?_pretty=true\"\n" +
			"   }],\n" +
			"   \"entry\" : [{\n" +
			"      \"fullUrl\" : \"http://foo/fhirBase2/Patient/1/_history/2\",\n" +
			"      \"resource\" : {\n" +
			"         \"resourceType\" : \"Patient\",\n" +
			"         \"id\" : \"1\",\n" +
			"         \"meta\" : {\n" +
			"            \"versionId\" : \"2\",\n" +
			"            \"lastUpdated\" : \"2001-02-22T11:22:33-05:00\"\n" +
			"         },\n" +
			"         \"birthDate\" : \"2012-01-02\"\n" +
			"      },\n" +
			"      \"search\" : {\n" +
			"         \"mode\" : \"match\",\n" +
			"         \"score\" : 0.123\n" +
			"      },\n" +
			"      \"request\" : {\n" +
			"         \"method\" : \"POST\",\n" +
			"         \"url\" : \"http://foo/Patient?identifier=value\"\n" +
			"      }\n" +
			"   }]\n" +
			"}";
		//@formatter:on

		Bundle b = ourCtx.newJsonParser().parseBundle(bundle);
		assertEquals(1, b.getEntries().size());

		Patient pt = (Patient) b.getEntries().get(0).getResource();
		assertEquals("http://foo/fhirBase2/Patient/1/_history/2", pt.getId().getValue());
		assertEquals("2012-01-02", pt.getBirthDateElement().getValueAsString());
		assertEquals("0.123", ResourceMetadataKeyEnum.ENTRY_SCORE.get(pt).getValueAsString());
		assertEquals("match", ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(pt).getCode());
		assertEquals("POST", ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(pt).getCode());
		assertEquals("http://foo/Patient?identifier=value", ResourceMetadataKeyEnum.LINK_SEARCH.get(pt));
		assertEquals("2001-02-22T11:22:33-05:00", ResourceMetadataKeyEnum.UPDATED.get(pt).getValueAsString());

		Bundle toBundle = new Bundle();
		toBundle.getLinkBase().setValue("http://foo/fhirBase1");
		toBundle.getTotalResults().setValue(1);
		toBundle.getLinkSelf().setValue("http://localhost:52788/Binary?_pretty=true");

		toBundle.addResource(pt, ourCtx, "http://foo/fhirBase1");
		String reEncoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(toBundle);

		JsonConfig cfg = new JsonConfig();

		JSON expected = JSONSerializer.toJSON(bundle.trim(), cfg);
		JSON actual = JSONSerializer.toJSON(reEncoded.trim(), cfg);

		String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
		String act = actual.toString().replace("\\r\\n", "\\n");

		ourLog.info("Expected: {}", exp);
		ourLog.info("Actual  : {}", act);

		assertEquals(exp, act);

	}

	@Test
	public void testParsePatientInBundle() {

		String text = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
		FhirContext ctx = FhirContext.forDstu2();
		Bundle b = ctx.newJsonParser().parseBundle(text);

		IResource patient = b.getEntries().get(0).getResource();
		assertEquals(Patient.class, patient.getClass());

		assertNull(ResourceMetadataKeyEnum.TAG_LIST.get(patient));
		assertNull(ResourceMetadataKeyEnum.PROFILES.get(patient));
	}

	/**
	 * See #163
	 */
	@Test
	public void testParseResourceType() {
		IParser jsonParser = ourCtx.newJsonParser().setPrettyPrint(true);

		// Patient
		Patient patient = new Patient();
		String patientId = UUID.randomUUID().toString();
		patient.setId(new IdDt("Patient", patientId));
		patient.addName().addGiven("John").addFamily("Smith");
		patient.setGender(AdministrativeGenderEnum.MALE);
		patient.setBirthDate(new DateDt("1987-04-16"));

		// Bundle
		ca.uhn.fhir.model.dstu2.resource.Bundle bundle = new ca.uhn.fhir.model.dstu2.resource.Bundle();
		bundle.setType(BundleTypeEnum.COLLECTION);
		bundle.addEntry().setResource(patient);

		String bundleText = jsonParser.encodeResourceToString(bundle);
		ourLog.info(bundleText);

		ca.uhn.fhir.model.dstu2.resource.Bundle reincarnatedBundle = jsonParser.parseResource(ca.uhn.fhir.model.dstu2.resource.Bundle.class, bundleText);
		Patient reincarnatedPatient = (Patient) reincarnatedBundle.getEntry().get(0).getResource();

		assertEquals("Patient", patient.getId().getResourceType());
		assertEquals("Patient", reincarnatedPatient.getId().getResourceType());
	}

	/**
	 * See #207
	 */
	@Test
	public void testParseResourceWithInvalidType() {
		String input = "{" + "\"resourceType\":\"Patient\"," + "\"contained\":[" + "    {" + "       \"rezType\":\"Organization\"" + "    }" + "  ]" + "}";

		IParser jsonParser = ourCtx.newJsonParser().setPrettyPrint(true);
		try {
			jsonParser.parseResource(input);
			fail();
		} catch (DataFormatException e) {
			assertEquals("Missing required element 'resourceType' from JSON resource object, unable to parse", e.getMessage());
		}
	}

	/**
	 * See #144 and #146
	 */
	@Test
	public void testReportSerialize() {

		ReportObservation obsv = new ReportObservation();
		obsv.getCode().addCoding().setCode("name");
		obsv.setValue(new StringDt("value test"));
		obsv.setStatus(ObservationStatusEnum.FINAL);
		obsv.addIdentifier().setSystem("System").setValue("id value");

		DiagnosticReport report = new DiagnosticReport();
		report.getContained().getContainedResources().add(obsv);
		report.addResult().setResource(obsv);

		IParser parser = ourCtx.newXmlParser().setPrettyPrint(true);
		String message = parser.encodeResourceToString(report);
		ourLog.info(message);
		Assert.assertThat(message, containsString("contained"));
	}

	/**
	 * See #144 and #146
	 */
	@Test
	public void testReportSerializeWithMatchingId() {

		ReportObservation obsv = new ReportObservation();
		obsv.getCode().addCoding().setCode("name");
		obsv.setValue(new StringDt("value test"));
		obsv.setStatus(ObservationStatusEnum.FINAL);
		obsv.addIdentifier().setSystem("System").setValue("id value");

		DiagnosticReport report = new DiagnosticReport();
		report.getContained().getContainedResources().add(obsv);

		obsv.setId("#123");
		report.addResult().setReference("#123");

		IParser parser = ourCtx.newXmlParser().setPrettyPrint(true);
		String message = parser.encodeResourceToString(report);
		ourLog.info(message);
		Assert.assertThat(message, containsString("contained"));
	}

}


text:
namespace IECore
{

/// The convert function is used to provide easy conversion
/// between simple types (like vectors) in IECore, Imath and
/// other libraries. It should be specialised appropriately in
/// support libraries.
/// \todo Could this be declared static inline?
template<typename T, typename F>
T convert( const F &from )
{
	return from;
}

} // namespace IECore

#endif // IECORE_CONVERT_H


text:
function [G, fill_ins] = mkChordal(G, order)
% Eliminate nodes in specified order, and ensure uneliminated
% neighbors are fully connected by adding edges if necessary
%
% fill_ins(i,j) = 1 iff we add a fill-in arc between i and j.
% PMTKmodified Matt Dunham

% This file is from pmtk3.googlecode.com

MG = G;
n = length(G);
eliminated = false(1, n);
for i=1:n
    G = setdiag(G, 0);
    u = order(i);
    nodes = false(1, n);
    nodes([find(G(u, :)) find(G(:, u))']) = true;
    nodes = nodes & ~eliminated;
    nodes(u) = true;
    G(nodes, nodes) = 1;
    eliminated(u) = true;

    %U = find(~eliminated); % uneliminated
    %nodes = intersectPMTK(neighbors(G, u), U); % look up neighbors in the partially filled-in graph
    %nodes = unionPMTK(nodes, u); % the clique will always contain at least u
    %G(nodes, nodes) = 1; % make them all connected to each other
    %G = setdiag(G, 0);
    %eliminated(u) = true;
end
if nargout > 1
    fill_ins = sparse(triu(max(0, G - MG), 1));
end
end


text:
import React from 'react'
import TextField from 'material-ui/TextField'
import Dialog from 'material-ui/Dialog'
import RaisedButton from 'material-ui/RaisedButton'
import LockIcon from 'material-ui/svg-icons/action/lock'
import Avatar from 'material-ui/Avatar'
import AnonymousIcon from 'material-ui/svg-icons/action/perm-identity'
import { blueA400 } from 'material-ui/styles/colors'
// import Divider from 'material-ui/Divider'
import Paper from 'material-ui/Paper'
// import ReactCSSTransitionGroup from 'react-addons-css-transition-group'
import './LoginDialog.css'

const styles = {
  loginBtn: {
    position: 'relative',
    float: 'right',
  },
  overlay: {
    backgroundImage: `url(${require('../images/kubernetes-logo.svg')})`,
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#326ce5',
    backgroundPosition: 'center center',
    backgroundSize: '150%',
  },
  icon: {
    background: 'transparent',
    width: 28,
    height: 28,
    borderRadius: 0,
  },
  backgroundRight: {
    backgroundColor: '#326ce5',
    position: 'fixed',
    top: 0,
    right: 0,
    width: '70%',
    height: '100%',
    zIndex: 2000,
  }

}

function getIcon(loginMethod) {
  if (!!loginMethod.icon) {
    return <Avatar src={loginMethod.icon} style={styles.icon}/>
  }
  switch (loginMethod.type) {
    case 'oidc':
      return <Avatar src={require('../images/oidc.png')} style={styles.icon}/>
    case 'pwfile':
      return <Avatar src={require('../images/pwfile.svg')} style={styles.icon}/>
    case 'saml':
      return <Avatar src={require('../images/saml.png')} style={styles.icon}/>
    case 'anonymous':
      return <AnonymousIcon />
    default:
      console.error(`LoginDialog::getIcon: unexpected loginMethod: ${JSON.stringify(loginMethod)}`)
  }
}

export default function LoginDialog(props) {

  let login = null
  if (props.open) {

    let credsLink = ''
    if (props.credsLink) {
      credsLink = (

        {props.loginLinks.length > 0 &&
or
}

        <Paper style={{padding: 10, marginTop: 10, overflow: 'hidden'}}>

{getIcon(props.credsLink)}Login with {props.credsLink.desc || props.credsLink.name}

          <TextField
            id={'username'}
            ref={(ref) => { props.updateInputs({username: (ref && ref.input)}); }}
            errorText={props.loginError}
            onKeyPress={(e) => (e.key === 'Enter') && props.handleLogin()}
            hintText="Username" floatingLabelText="Username" fullWidth={true} />
          <TextField
            id={'password'}
            ref={(ref) => { props.updateInputs({password: (ref && ref.input)}); }}
            errorText={props.loginError}
            onKeyPress={(e) => (e.key === 'Enter') && props.handleLogin()}
            hintText="Password" floatingLabelText="Password" fullWidth={true} type="password" />
          <RaisedButton
            label="Login"
            id={'login'}
            primary={true}
            style={styles.loginBtn}
            onTouchTap={props.handleLogin}
            />
          </Paper>

)
    }

    login = (

        <Dialog className="login" title={

Authentication Required

<LockIcon style={{
                width: 48,
                height: 48,
              }}/>

          }
          titleStyle={{
            color: 'rgba(180,180,180)',
            borderBottom: `4px solid ${blueA400}`,
            background: 'rgb(66,66,66)',
            fill: 'rgba(180,180,180)',
          }}
          modal={true}
          open={props.open}
          contentStyle={{
            maxWidth: 350,
          }}
          bodyStyle={{
            //backgroundColor: 'rgba(20, 49, 127, 0.15)',
            backgroundColor: 'rgba(0,0,0,0.2)',
            padding: 24,
          }}
          >
          <form>

            {
              props.loginLinks.map(loginMethod =>
                <RaisedButton
                  key={loginMethod.id}
                  href={loginMethod.url}
                  onTouchTap={() => console.log(`clicked ${loginMethod.id}`)}
                  primary={true}
                  fullWidth={true}
                  icon={getIcon(loginMethod)}
                  style={{marginBottom: 10}}
                  labelStyle={{
                    textTransform: 'none',
                    fontSize: 15,
                  }}
                  id={`login:${loginMethod.id}`}
                  label={`login with ${loginMethod.desc || loginMethod.name}`}
                />)
            }

            {credsLink}
          </form>
        </Dialog>

    )
  }

  return login
}


text:
import test
import os
from os.path import join, split

def IsNumber(string):
  try:
    float(string)
    return True
  except ValueError:
    return False

class BenchmarkTestCase(test.TestCase):

  def __init__(self, path, context, mode):
    super(BenchmarkTestCase, self).__init__(context, split(path), mode)
    self.root = path

  def GetLabel(self):
    return '%s benchmark %s' % (self.mode, self.GetName())

  def IsFailureOutput(self, output):
    if output.exit_code != 0:
      return True
    lines = output.stdout.splitlines()
    for line in lines:
      colon_index = line.find(':')
      if colon_index >= 0:
        if not IsNumber(line[colon_index+1:].strip()):
          return True
    return False

  def GetCommand(self):
    result = self.context.GetVmCommand(self, self.mode)
    result.append(join(self.root, 'run.js'))
    return result

  def GetName(self):
    return 'V8'

  def BeforeRun(self):
    os.chdir(self.root)

  def AfterRun(self, result):
    os.chdir(self.context.buildspace)

  def GetSource(self):
    return open(join(self.root, 'run.js')).read()

  def GetCustomFlags(self, mode):
    return []

class BenchmarkTestConfiguration(test.TestConfiguration):

  def __init__(self, context, root):
    super(BenchmarkTestConfiguration, self).__init__(context, root)

  def ListTests(self, current_path, path, mode, variant_flags):
    path = self.context.workspace
    path = join(path, 'benchmarks')
    test = BenchmarkTestCase(path, self.context, mode)
    return [test]

  def GetBuildRequirements(self):
    return ['d8']

  def GetTestStatus(self, sections, defs):
    pass

def GetConfiguration(context, root):
  return BenchmarkTestConfiguration(context, root)


text:
package com.vishnus1224.teamworkapidemo.di.component;

import com.vishnus1224.teamworkapidemo.di.module.ActivityModule;
import com.vishnus1224.teamworkapidemo.di.scope.PerActivity;
import com.vishnus1224.teamworkapidemo.ui.activity.LoginActivity;

import dagger.Subcomponent;

/**
 * Created by Vishnu on 8/14/2016.
 */
@PerActivity
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {

    void inject(LoginActivity loginActivity);
}


text:
package org.deepdive.settings

import org.deepdive.Logging
import scala.util.parsing.combinator.RegexParsers

object FactorFunctionParser extends RegexParsers with Logging {
  def relationOrField = """[\w]+""".r
  def arrayDefinition = """\[\]""".r
  def integer = """[0-9]+""".r
  // def factorFunctionName = "Imply" | "Or" | "And" | "Equal" | "IsTrue"

  def implyFactorFunction = ("Imply" | "IMPLY") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    ImplyFactorFunction(varList)
  }

  def orFactorFunction = ("Or" | "OR") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    OrFactorFunction(varList)
  }

  def xorFactorFunction = ("Xor" | "XOR") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    XorFactorFunction(varList)
  }

  def andFactorFunction = ("And" | "AND") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    AndFactorFunction(varList)
  }

  def equalFactorFunction = ("Equal" | "EQUAL") ~> "(" ~> factorVariable ~ ("," ~> factorVariable) <~ ")" ^^ {
    case v1 ~ v2 =>
    EqualFactorFunction(List(v1, v2))
  }

  def isTrueFactorFunction = ("IsTrue" | "ISTRUE") ~> "(" ~> factorVariable <~ ")" ^^ { variable =>
    IsTrueFactorFunction(List(variable))
  }

  def multinomialFactorFunction = ("Multinomial" | "MULTINOMIAL") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ {
    case (varList) =>
    MultinomialFactorFunction(varList)
  }

  // // multinomial factor with custom cupport
  // def multinomialFactorFunction = ("Multinomial" | "MULTINOMIAL") ~> ("(" ~> rep1sep(factorVariable, ",") <~ ")") ~
  //   ("(" ~> relationOrField <~ ")").? ^^ {
  //   case (varList ~ support) =>
  //     MultinomialFactorFunction(varList, support)
  // }

  // multinomial factor with custom cupport
  def multinomialFactorFunctionWithSupport = ("MultinomialWithSupport" | "MULTINOMIALWITHSUPPORT") ~> ("(" ~> rep1sep(factorVariable, ",") <~ ")") ~
    ("(" ~> relationOrField <~ ")") ^^ {
    case (varList ~ support) =>
      MultinomialFactorFunctionWithSupport(varList, support)
  }

  def treeConstraintFactorFunction = ("TreeConstraint") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    TreeConstraintFactorFunction(varList)
  }

  def parentLabelConstraintFactorFunction = ("ParentLabelConstraint") ~> "(" ~> rep1sep(factorVariable, ",") <~ ")" ^^ { varList =>
    TreeConstraintFactorFunction(varList)
  }

  def factorVariable = ("!"?) ~ rep1sep(relationOrField, ".") ~ (arrayDefinition?) ~
    (("=" ~> integer)?) ~ (("==" ~> relationOrField)?) ^^ {
    case (isNegated ~ varList ~ isArray ~ predicate ~ predicateFromData)  =>
      FactorFunctionVariable(varList.take(varList.size - 1).mkString("."), varList.last,
        isArray.isDefined, isNegated.isDefined, readPredicate(predicate), predicateFromData)
  }

  def readPredicate(predicate: Option[String]) : Option[Long] = {
    predicate match {
      case Some(number) => Some(number.toLong)
      case None => None
    }
  }

  def factorFunc = implyFactorFunction | orFactorFunction | andFactorFunction |
    equalFactorFunction | isTrueFactorFunction | xorFactorFunction |
    multinomialFactorFunction | treeConstraintFactorFunction |
    parentLabelConstraintFactorFunction | multinomialFactorFunctionWithSupport
}


text:
@interface SSWMutipleLineChart(){
    CGFloat         _totalWidth;
    CGFloat         _totalHeight;
}
@property(nonatomic)UIScrollView    *scrollView;
@property(nonatomic)UIView          *contentView;
@property(nonatomic)UILabel         *unitLab;
@property(nonatomic)NSMutableArray  *totalCirclePathArr;
@end
@implementation SSWMutipleLineChart
-(instancetype)initWithChartType:(SSWChartsType)type{
    self = [super initWithChartType:type];
    if (self) {
        [self setUp];
    }
    return self;
}
-(void)setUp{
    self.barColorArr = [@[] mutableCopy];
    self.totalCirclePathArr = [@[] mutableCopy];
    self.barWidth = 20;
    self.gapWidth = 20;
    self.yAxiasCount = 10;
    self.yAxiasValus = 50;
    [self addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];
    [self.contentView addSubview:self.unitLab];
    [self addTap];
}
-(void)addTap{
    UITapGestureRecognizer  *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.contentView addGestureRecognizer:tap];
}
-(void)tap:(UITapGestureRecognizer *)ges{
    CGPoint  point = [ges locationInView:self.contentView];
    for (int i = 0; i<self.totalCirclePathArr.count; i++) {
        for (int j = 0 ; j<[self.totalCirclePathArr[i] count]; j++) {
            UIBezierPath  *path = self.totalCirclePathArr[i][j];
            if ([path containsPoint:point]) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(SSWChartView:didSelectMutipleBarChartIndex:)]) {
                    [self.delegate SSWChartView:self didSelectMutipleBarChartIndex:@[@(i),@(j)]];
                }
            }
        }
    }

}
-(void)setUnit:(NSString *)unit{
    _unit = unit;
    self.unitLab.text = [NSString stringWithFormat:@"单位:%@",unit];
}
-(UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}
-(UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc]init];
        //        _contentView.backgroundColor = [UIColor greenColor];
    }
    return _contentView;
}
-(UILabel *)unitLab{
    if (!_unitLab) {
        _unitLab = [[UILabel alloc]init];

        _unitLab.font = AppFont(10);
        _unitLab.textColor = AppHTMLColor(@"666666");

    }
    return _unitLab;
}
-(void)layoutSubviews{
    self.scrollView.frame = self.bounds;
    _totalWidth =self.barWidth*Day +( Day+1 )*self.gapWidth;
    _totalHeight = self.bounds.size.height-20-30;
    self.scrollView.contentSize = CGSizeMake(30+_totalWidth, 0);
    self.contentView.frame = CGRectMake(30, 20, _totalWidth, _totalHeight);
    self.unitLab.frame = CGRectMake(8,0,60, 20);
    [self drawAxias];
    [self addYAxaisLabs];
    [self addXAxiasLabs];
    [self drawLines];
    [self addLegends];

}
//画坐标轴
-(void)drawAxias{
    UIBezierPath   *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(0, _totalHeight)];
    [path addLineToPoint:CGPointMake(_totalWidth, _totalHeight)];
    //画Y轴的箭头
    [path moveToPoint:CGPointMake(-5, 5)];
    [path addLineToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(5, 5)];
    //画X轴的箭头
    [path moveToPoint:CGPointMake(_totalWidth-5, _totalHeight-5)];
    [path addLineToPoint:CGPointMake(_totalWidth, _totalHeight)];
    [path addLineToPoint:CGPointMake(_totalWidth-5, _totalHeight+5)];
    //画y轴的刻度
    for (int i = (int)self.yAxiasCount; i>0; i--) {
        [path moveToPoint:CGPointMake(0, i*(_totalHeight/self.yAxiasCount))];
        [path addLineToPoint:CGPointMake(5, i*(_totalHeight/self.yAxiasCount))];
    }
    //画x轴的刻度
    for (int i = 0; i<Day; i++) {
        [path moveToPoint:CGPointMake(self.gapWidth+self.barWidth/2+(self.barWidth+self.gapWidth)*i, _totalHeight)];
        [path addLineToPoint:CGPointMake(self.gapWidth+self.barWidth/2+(self.barWidth+self.gapWidth)*i, _totalHeight-5)];
    }
    CAShapeLayer   *axiasLayer = [CAShapeLayer layer];
    axiasLayer.strokeColor = [UIColor grayColor].CGColor;
    axiasLayer.fillColor = [UIColor clearColor].CGColor;
    axiasLayer.lineWidth = 1;
    axiasLayer.path = path.CGPath;
    [self.contentView.layer addSublayer:axiasLayer];
}
//添加y轴的坐标值显示
-(void)addYAxaisLabs{
    for (int i = 0 ; i<self.yAxiasCount; i++) {
        UILabel  *lab = [[UILabel alloc]init];
        lab.text = [NSString stringWithFormat:@"%ld",self.yAxiasValus*(self.yAxiasCount-i)];
        lab.textAlignment = NSTextAlignmentRight;
        lab.font = [UIFont systemFontOfSize:10];
        lab.frame = CGRectMake(-5, i*(_totalHeight/self.yAxiasCount)-10, -25, 20);
        [self.contentView addSubview:lab];
    }
}
//添加x轴的坐标值显示
-(void)addXAxiasLabs{
    for (int i =0; i<self.xValuesArr.count; i++) {
        UILabel  *lab = [[UILabel alloc]init];
        lab.font = [UIFont systemFontOfSize:10];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.text = self.xValuesArr[i];
        lab.frame =CGRectMake(self.gapWidth+self.barWidth/2+(self.barWidth+self.gapWidth)*i-(self.barWidth+self.gapWidth/2)/2, _totalHeight,self.barWidth+self.gapWidth/2, 30);
        [self.contentView addSubview:lab];
    }
}
//计算折线的关键点,划线
-(void)drawLines{
    if (!self.yValuesArr.count) return;

    NSMutableArray  *pathArr =[@[] mutableCopy];
    NSMutableArray  *lineLayerArr = [@[] mutableCopy];
    for (int i = 0 ; i<[self.yValuesArr[0] count]; i++) {
        UIBezierPath  *linePath = [UIBezierPath bezierPath];
        [pathArr addObject:linePath];

        CAShapeLayer  *lineLayer = [CAShapeLayer layer];
        lineLayer.strokeColor = [self.barColorArr[i] CGColor];
        lineLayer.lineWidth=1;
        lineLayer.fillColor = [UIColor clearColor].CGColor;
        [self.contentView.layer addSublayer:lineLayer];
        [lineLayerArr addObject:lineLayer];
    }
    for (int i = 0 ; i<self.xValuesArr.count; i++) {
        NSMutableArray  *circlePathArr = [@[] mutableCopy];
        for (int j=0; j<[self.yValuesArr[i] count]; j++) {
            CGPoint  Point = CGPointMake(self.gapWidth+self.barWidth/2+i*(self.barWidth+self.gapWidth),_totalHeight-([self.yValuesArr[i][j] floatValue]*_totalHeight/(self.yAxiasCount*self.yAxiasValus)));
            //画点
            UIBezierPath  *circlePath = [UIBezierPath bezierPath];
            [circlePath addArcWithCenter:Point radius:3 startAngle:0 endAngle:M_PI*2 clockwise:YES];
            CAShapeLayer  *circleLayer = [CAShapeLayer layer];
            circleLayer.fillColor = [self.barColorArr[j] CGColor];
            circleLayer.lineWidth=1;
            circleLayer.strokeColor = [self.barColorArr[j] CGColor];
            circleLayer.path = circlePath.CGPath;
            [circleLayer addAnimation:[self animationWithDuration:i*0.3] forKey:nil];
            [self.contentView.layer addSublayer:circleLayer];
            [circlePathArr addObject:circlePath];

            //画折线
            UIBezierPath  *linePath = pathArr[j];
            CAShapeLayer  *lineLayer = lineLayerArr[j];
            [lineLayer addAnimation:[self animationWithDuration:(i+1)*0.3] forKey:nil];
            if (i==0) {
                [linePath moveToPoint:Point];
            }
            else{
                [linePath addLineToPoint:Point];
            }
            lineLayer.path = linePath.CGPath;

            //显示每个柱形图的值
            UILabel  *lab = [[UILabel alloc]init];
            lab.textColor = self.barColorArr[j];
            lab.font = [UIFont systemFontOfSize:10];
            lab.text = self.yValuesArr[i][j];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.bounds = CGRectMake(0, 0, self.barWidth+self.gapWidth*4/5, 20);
            lab.center = CGPointMake(Point.x, Point.y-15);
            [self.contentView addSubview:lab];

        }
        [self.totalCirclePathArr addObject:circlePathArr];
    }
}
//添加图例
-(void)addLegends{
    for (int i = 0; i<self.legendTitlesArr.count; i++) {
        UIView  *lengendView = [[UIView alloc]init];
//        lengendView.backgroundColor = [UIColor blackColor];
        lengendView.frame = CGRectMake(i*60,0, 60, -20);
        [self.contentView addSubview:lengendView];
        UILabel  *legendLab = [[UILabel alloc]init];
        legendLab.text = self.legendTitlesArr[i];
        legendLab.frame = CGRectMake(15,0,lengendView.bounds.size.width-15, lengendView.bounds.size.height);
        legendLab.font = [UIFont systemFontOfSize:10];
        [lengendView addSubview:legendLab];

        UILabel  *lengendLayer = [[UILabel alloc]init];;
        lengendLayer.backgroundColor =self.barColorArr[i] ;
        lengendLayer.frame = CGRectMake(0, lengendView.bounds.size.height/2-0.5, 10, 1);
        [lengendView addSubview:lengendLayer];
    }
}
@end


text:
@implementation AutoMappingTests

- (void)setUp
{
    [[CHObjectMapper shared] mapClass:[Team class] withOverride:^(CHObjectMapping *team) {
        [team hasMany:[Player class] propertyName:@"players"];
    }];

    [[CHObjectMapper shared] mapClass:[Player class] withOverride:^(CHObjectMapping *player) {
        [player belongsTo:[Team class] propertyName:@"team"];
    }];
}

- (void)testMapWithUnderscoreNamingConvention
{
	NSString *json = @"{ \"id\": 1, \"name\": \"Bulls\", \"head_coach_id\": 4 }";

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
        options:kNilOptions error:NULL];

    Team *team = [[Team alloc] initWithDictionary:dictionary];
    XCTAssertTrue([team.teamId isEqualToNumber:[NSNumber numberWithInt:1]]);
    XCTAssertTrue([team.name isEqualToString:@"Bulls"]);
    XCTAssertTrue([team.headCoachId isEqualToNumber:[NSNumber numberWithInt:4]]);
}

- (void)testBelongsTo
{
	NSString *json = @"{ \"id\": 1, \"team_id\": 1, "
        "\"team\": { \"id\": 1, \"name\": \"Bulls\" } }";

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
        options:kNilOptions error:NULL];

    Player *player = [[Player alloc] initWithDictionary:dictionary];
    Team *team = player.team;
    XCTAssertTrue([player.playerId isEqualToNumber:[NSNumber numberWithInt:1]]);
    XCTAssertTrue([player.teamId isEqualToNumber:[NSNumber numberWithInt:1]]);
    XCTAssertNotNil(team);
    XCTAssertTrue([team.name isEqualToString:@"Bulls"]);
}

- (void)testHasMany
{
	NSString *json = @"{ \"id\": 1, \"name\": \"Bulls\", "
    	"\"players\": ["
        "{ \"id\": 1, \"team_id\": 1 }, "
        "{ \"id\": 2, \"team_id\": 1 } ] }";

    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
        options:kNilOptions error:NULL];

    Team *team = [[Team alloc] initWithDictionary:dictionary];
    Player *player = [team.players objectAtIndex:1];
    XCTAssertTrue([player.teamId isEqualToNumber:[NSNumber numberWithInt:1]]);
}

@end


text:
qc::perms
=========

part of [Docs](../index.md)

Usage
-----
`qc::perms body`

Description
-----------
Test each line of permissions<br/>Throws an error after all tests if any fail, and sets a global ldict errorList

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"