text:
package org.mcupdater.settings;

import org.mcupdater.MCUApp;
import org.mcupdater.model.JSON;

import java.util.logging.Level;

@JSON
public class Profile {
	private String style;
	private String name;
	private String username;
	private String sessionKey;
	private String accessToken;
	private String lastInstance;
	private String uuid;
	private String userId;
	private boolean legacy;

	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUsername() {
		return username;
	}

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

	public String getSessionKey(MCUApp caller) throws Exception {
		String currentSessionKey = null;
		if (this.sessionKey == null || this.sessionKey.isEmpty()) {
			if (this.style.equals("Yggdrasil")) {
				try {
					currentSessionKey = caller.getAuthManager().getSessionKey(this);
				} catch (Exception e) {
					Profile newProfile = caller.requestLogin(this.username);
					SettingsManager.getInstance().getSettings().addOrReplaceProfile(newProfile);
					if (!SettingsManager.getInstance().isDirty()) {
						SettingsManager.getInstance().saveSettings();
					}
					currentSessionKey = newProfile.getSessionKey(caller);
					caller.baseLogger.log(Level.INFO, "A full login request occurred due to the following exception", e);
					caller.baseLogger.finer("Session key: " + currentSessionKey);
				}
			}
		} else {
			currentSessionKey = this.sessionKey;
		}
		return currentSessionKey;
	}

	public void setSessionKey(String sessionKey) {
		this.sessionKey = sessionKey;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getLastInstance() {
		return lastInstance;
	}

	public void setLastInstance(String lastInstance) {
		this.lastInstance = lastInstance;
	}

	public String getUUID() {
		return uuid;
	}

	public void setUUID(String uuid) { this.uuid = uuid; }

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public boolean isLegacy() {
		return legacy;
	}

	public void setLegacy(boolean legacy) {
		this.legacy = legacy;
	}

	@Override
	public String toString() { return this.getName(); }
}


text:
package test;

import java.io.File;
import java.util.Properties;
import java.util.jar.Manifest;

import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;

import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Jar;
import junit.framework.TestCase;

@SuppressWarnings("resource")
public class ExportAnnotationTest extends TestCase {

	public void testCalculated() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals("buzz", a.get("fizz"));
			assertEquals("fizzbuzz", a.get("foobar:"));
			assertEquals(Version.valueOf("1.2.3.qual"), Version.valueOf(a.get("viking")));
			assertEquals(Attrs.Type.VERSION, a.getType("viking"));
			assertEquals("test.export.annotation." + getName() + ".used", a.get("uses:"));
			assertEquals(Version.valueOf("1.0.0"), Version.valueOf(a.get("version")));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals(VersionRange.valueOf("[1.0.0,1.1.0)"), VersionRange.valueOf(a.get("version")));
		}
	}

	public void testProvider() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals("buzz", a.get("fizz"));
			assertEquals("fizzbuzz", a.get("foobar:"));
			assertEquals("test.export.annotation." + getName() + ".used", a.get("uses:"));
			assertEquals(Version.valueOf("1.0.0"), Version.valueOf(a.get("version")));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals(VersionRange.valueOf("[1.0.0,1.1.0)"), VersionRange.valueOf(a.get("version")));
		}
	}

	public void testConsumer() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals("buzz", a.get("fizz"));
			assertEquals("fizzbuzz", a.get("foobar:"));
			assertEquals("test.export.annotation." + getName() + ".used", a.get("uses:"));
			assertEquals(Version.valueOf("1.0.0"), Version.valueOf(a.get("version")));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals(VersionRange.valueOf("[1.0.0,2.0.0)"), VersionRange.valueOf(a.get("version")));
		}
	}

	public void testNoimport() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals("buzz", a.get("fizz"));
			assertEquals("fizzbuzz", a.get("foobar:"));
			assertEquals("test.export.annotation." + getName() + ".used", a.get("uses:"));
			assertEquals(Version.valueOf("1.0.0"), Version.valueOf(a.get("version")));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNull(a);
		}
	}

	public void testUses() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals("foo,bar", a.get("uses:"));
			assertEquals(Version.valueOf("1.0.0"), Version.valueOf(a.get("version")));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals(VersionRange.valueOf("[1.0.0,1.1.0)"), VersionRange.valueOf(a.get("version")));
		}
	}

	public void testNouses() throws Exception {
		try (Builder builder = new Builder()) {
			Jar bin = new Jar(new File("bin"));
			builder.setClasspath(new Jar[] {
				bin
			});
			Properties p = new Properties();
			p.setProperty("Private-Package", "test.export.annotation." + getName() + "*");
			builder.setProperties(p);
			Jar jar = builder.build();
			Manifest manifest = jar.getManifest();

			String exported = manifest.getMainAttributes()
				.getValue("Export-Package");
			assertNotNull(exported);
			Parameters e = OSGiHeader.parseHeader(exported);
			Attrs a = e.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertNull(a.get("uses:"));

			String imported = manifest.getMainAttributes()
				.getValue("Import-Package");
			assertNotNull(imported);
			Parameters i = OSGiHeader.parseHeader(imported);
			a = i.get("test.export.annotation." + getName());
			assertNotNull(a);
			assertEquals(VersionRange.valueOf("[1.0.0,1.1.0)"), VersionRange.valueOf(a.get("version")));
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Generates an HTML report from an PHP_CodeCoverage object.
 *
 * @category   PHP
 * @package    CodeCoverage
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2009-2011 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://github.com/sebastianbergmann/php-code-coverage
 * @since      Class available since Release 1.0.0
 */
class PHP_CodeCoverage_Report_HTML
{
    /**
     * @var string
     */
    public static $templatePath;

    /**
     * @var array
     */
    protected $options;

    /**
     * Constructor.
     *
     * @param array $options
     */
    public function __construct(array $options = array())
    {
        if (!isset($options['title'])) {
            $options['title'] = '';
        }

        if (!isset($options['charset'])) {
            $options['charset'] = 'UTF-8';
        }

        if (!isset($options['cacheTokens'])) {
            $options['cacheTokens'] = TRUE;
        }

        if (!isset($options['yui'])) {
            $options['yui'] = TRUE;
        }

        if (!isset($options['highlight'])) {
            $options['highlight'] = FALSE;
        }

        if (!isset($options['lowUpperBound'])) {
            $options['lowUpperBound'] = 35;
        }

        if (!isset($options['highLowerBound'])) {
            $options['highLowerBound'] = 70;
        }

        if (!isset($options['generator'])) {
            $options['generator'] = '';
        }

        $this->options = $options;

        self::$templatePath = sprintf(
          '%s%sHTML%sTemplate%s',

          dirname(__FILE__),
          DIRECTORY_SEPARATOR,
          DIRECTORY_SEPARATOR,
          DIRECTORY_SEPARATOR
        );
    }

    /**
     * @param PHP_CodeCoverage $coverage
     * @param string           $target
     */
    public function process(PHP_CodeCoverage $coverage, $target)
    {
        $target     = PHP_CodeCoverage_Util::getDirectory($target);
        $files      = $coverage->getData();
        $commonPath = PHP_CodeCoverage_Util::reducePaths($files);
        $items      = PHP_CodeCoverage_Util::buildDirectoryStructure($files);
        $root       = new PHP_CodeCoverage_Report_HTML_Node_Directory(
                        $commonPath, NULL
                      );

        $this->addItems($root, $items, $coverage->getTests());

        $this->renderDashboard(
          $root, $target . 'index.dashboard.html', $this->options['title']
        );

        foreach ($root as $node) {
            if ($node instanceof PHP_CodeCoverage_Report_HTML_Node_Directory) {
                $this->renderDashboard(
                  $node,
                  $target . PHP_CodeCoverage_Util::getSafeFilename(
                              $node->getId()
                            ) . '.dashboard.html',
                  $node->getName(TRUE)
                );
            }
        }

        $root->render(
          $target,
          $this->options['title'],
          $this->options['charset'],
          $this->options['lowUpperBound'],
          $this->options['highLowerBound'],
          $this->options['generator']
        );

        $this->copyFiles($target);
    }

    /**
     * @param PHP_CodeCoverage_Report_HTML_Node_Directory $root
     * @param string                                      $file
     * @param string                                      $title
     */
    protected function renderDashboard(PHP_CodeCoverage_Report_HTML_Node_Directory $root, $file, $title)
    {
        $classes  = $this->classes($root);
        $template = new Text_Template(
          PHP_CodeCoverage_Report_HTML::$templatePath . 'dashboard.html'
        );

        $template->setVar(
          array(
            'title'                  => $title,
            'charset'                => $this->options['charset'],
            'date'                   => date(
                                          'D M j G:i:s T Y',
                                          $_SERVER['REQUEST_TIME']
                                        ),
            'version'                => '@package_version@',
            'php_version'            => PHP_VERSION,
            'generator'              => $this->options['generator'],
            'least_tested_methods'   => $this->leastTestedMethods($classes),
            'top_project_risks'      => $this->topProjectRisks($classes),
            'cc_values'              => $this->classComplexity($classes),
            'ccd_values'             => $this->classCoverageDistribution($classes),
            'backlink'               => basename(str_replace('.dashboard', '', $file))
          )
        );

        $template->renderTo($file);
    }

    /**
     * @param PHP_CodeCoverage_Report_HTML_Node_Directory $root
     * @param array                                       $items
     * @param array                                       $tests
     */
    protected function addItems(PHP_CodeCoverage_Report_HTML_Node_Directory $root, array $items, array $tests)
    {
        foreach ($items as $key => $value) {
            if (substr($key, -2) == '/f') {
                try {
                    $root->addFile(
                      substr($key, 0, -2),
                      $value,
                      $tests,
                      $this->options['cacheTokens'],
                      $this->options['yui'],
                      $this->options['highlight']
                    );
                }

                catch (RuntimeException $e) {
                    continue;
                }
            } else {
                $child = $root->addDirectory($key);
                $this->addItems($child, $value, $tests);
            }
        }
    }

    /**
     * Returns the classes.
     *
     * @param  PHP_CodeCoverage_Report_HTML_Node_Directory $root
     * @return array
     */
    protected function classes(PHP_CodeCoverage_Report_HTML_Node_Directory $root)
    {
        $classes = array();

        foreach ($root as $node) {
            if ($node instanceof PHP_CodeCoverage_Report_HTML_Node_File) {
                $classes = array_merge($classes, $node->getClasses());
            }
        }

        if (isset($classes['*'])) {
            unset($classes['*']);
        }

        return $classes;
    }

    /**
     * Returns the data for the Class Complexity chart.
     *
     * @param  array $classes
     * @return string
     */
    protected function classComplexity(array $classes)
    {
        $data = array();

        foreach ($classes as $name => $class) {
            $data[] = array($class['coverage'], $class['ccn'], 'blue', $name);
        }

        return json_encode($data);
    }

    /**
     * Returns the data for the Class Coverage Distribution chart.
     *
     * @param  array $classes
     * @return string
     */
    protected function classCoverageDistribution(array $classes)
    {
        $data = array(
          '0%'      => 0,
          '0-10%'   => 0,
          '10-20%'  => 0,
          '20-30%'  => 0,
          '30-40%'  => 0,
          '40-50%'  => 0,
          '50-60%'  => 0,
          '60-70%'  => 0,
          '70-80%'  => 0,
          '80-90%'  => 0,
          '90-100%' => 0,
          '100%'    => 0
        );

        foreach ($classes as $class) {
            if ($class['coverage'] == 0) {
                $data['0%']++;
            }

            else if ($class['coverage'] == 100) {
                $data['100%']++;
            }

            else {
                $key = floor($class['coverage']/10)*10;
                $key = $key . '-' . ($key + 10) . '%';
                $data[$key]++;
            }
        }

        return json_encode(array_values($data));
    }

    /**
     * @param string $target
     */
    protected function copyFiles($target)
    {
        $files = array(
          'butter.png',
          'chameleon.png',
          'close12_1.gif',
          'container.css',
          'container-min.js',
          'directory.png',
          'excanvas.compressed.js',
          'file.png',
          'glass.png',
          'RGraph.bar.js',
          'RGraph.common.core.js',
          'RGraph.common.tooltips.js',
          'RGraph.scatter.js',
          'scarlet_red.png',
          'snow.png',
          'style.css',
          'yahoo-dom-event.js'
        );

        foreach ($files as $file) {
            copy(self::$templatePath . $file, $target . $file);
        }
    }

    /**
     * Returns the least tested methods.
     *
     * @param  array   $classes
     * @param  integer $max
     * @return string
     */
    protected function leastTestedMethods(array $classes, $max = 10)
    {
        $methods = array();

        foreach ($classes as $className => $class) {
            foreach ($class['methods'] as $methodName => $method) {
                if ($method['coverage'] < 100) {
                    if ($className != '*') {
                        $key = $className . '::' . $methodName;
                    } else {
                        $key = $methodName;
                    }

                    $methods[$key] = $method['coverage'];
                }
            }
        }

        asort($methods);

        $methods = array_slice($methods, 0, min($max, count($methods)));
        $buffer  = '';

        foreach ($methods as $name => $coverage) {
            list($class, $method) = explode('::', $name);

            $buffer .= sprintf(
              '
%s (%d%%)
' . "\n",
              $classes[$class]['methods'][$method]['file'],
              $name,
              $coverage
            );
        }

        return $buffer;
    }

    /**
     * Returns the top project risks according to the CRAP index.
     *
     * @param  array   $classes
     * @param  integer $max
     * @return string
     */
    protected function topProjectRisks(array $classes, $max = 10)
    {
        $risks = array();

        foreach ($classes as $className => $class) {
            if ($class['coverage'] < 100 &&
                $class['ccn'] > count($class['methods'])) {
                $risks[$className] = $class['crap'];
            }
        }

        asort($risks);

        $risks = array_reverse(
          array_slice($risks, 0, min($max, count($risks)))
        );

        $buffer = '';

        foreach ($risks as $name => $crap) {
            $buffer .= sprintf(
              '
%s (%d)
' . "\n",
              $classes[$name]['file'],
              $name,
              $crap
            );
        }

        return $buffer;
    }
}


text:
using System.Windows;

namespace UITest
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    // ReSharper disable once RedundantExtendsListEntry
    public partial class App : Application
    {
        public App()
        {
            Current.DispatcherUnhandledException += (sender, args) => MessageBox.Show(args.Exception.InnerException?.Message ?? args.Exception.Message);
        }
    }
}


text:
import $ from 'jquery'
import Mailcheck from 'mailcheck'

$(() => {
    $('#id_email').on('blur', (e) => {
        const removeSuggestions = (element) => $(element).parent().find('.help-block').remove()
        const emailField = e.currentTarget
        Mailcheck.run({
            email: emailField.value,
            suggested: (suggestion) => {
                removeSuggestions(emailField)
                const suggestedLink = $('').text(suggestion.full)
                suggestedLink.on('click', () => {
                    $('#id_email').val(suggestion.full)
                    removeSuggestions(emailField)
                    return false
                })
                $('')
                    .text('Did you mean ')
                    .append(suggestedLink)
                    .append('?')
                    .insertAfter(emailField)
            },
            empty: (element) => removeSuggestions(element)
        })
    })
})


text:
import { mount } from '@vue/test-utils'
import { BSpinner } from './spinner'

describe('spinner', () => {
  it('default has root element of span, and no children', async () => {
    const wrapper = mount(BSpinner)

    expect(wrapper).toBeDefined()
    expect(wrapper.element.tagName).toBe('SPAN')
    expect(wrapper.find('span.sr-only').exists()).toBe(false)

    wrapper.destroy()
  })

  it('renders custom root element when tag prop is set', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { tag: 'aside' }
      }
    })

    expect(wrapper.element.tagName).toBe('ASIDE')

    wrapper.destroy()
  })

  it('default has inner span when label is set', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          tag: 'div',
          label: 'Loading...'
        }
      }
    })

    expect(wrapper).toBeDefined()
    expect(wrapper.element.tagName).toBe('DIV')
    expect(wrapper.find('span').exists()).toBe(true)
    expect(wrapper.text()).toBe('Loading...')

    wrapper.destroy()
  })

  it('accepts custom label text via label slot', async () => {
    const wrapper = mount(BSpinner, {
      slots: { label: 'foobar' },
      context: {}
    })

    expect(wrapper.text()).toBe('foobar')

    wrapper.destroy()
  })

  it('has inner span class "sr-only" when label is set', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          tag: 'div',
          label: 'Loading...'
        }
      }
    })

    const span = wrapper.find('span')
    expect(span).toBeDefined()
    expect(span.classes().length).toBe(1)
    expect(span.classes()).toContain('sr-only')

    wrapper.destroy()
  })

  it('default has class "spinner-border"', async () => {
    const wrapper = mount(BSpinner)

    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.classes()).toContain('spinner-border')

    wrapper.destroy()
  })

  it('default has class "spinner-border-sm" when prop small=true', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { small: true }
      }
    })

    expect(wrapper.classes().length).toBe(2)
    expect(wrapper.classes()).toContain('spinner-border')
    expect(wrapper.classes()).toContain('spinner-border-sm')

    wrapper.destroy()
  })

  it('default has classes "spinner-border" and "text-danger" when prop variant="danger"', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { variant: 'danger' }
      }
    })

    expect(wrapper.classes().length).toBe(2)
    expect(wrapper.classes()).toContain('spinner-border')
    expect(wrapper.classes()).toContain('text-danger')

    wrapper.destroy()
  })

  it('default has class "text-danger" and "spinner-border-sm" when prop variant="danger" and small=true', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          variant: 'danger',
          small: true
        }
      }
    })

    expect(wrapper.classes().length).toBe(3)
    expect(wrapper.classes()).toContain('spinner-border')
    expect(wrapper.classes()).toContain('spinner-border-sm')
    expect(wrapper.classes()).toContain('text-danger')

    wrapper.destroy()
  })

  it('does not have role "status" when no label provided', async () => {
    const wrapper = mount(BSpinner)

    expect(wrapper.attributes('role')).toBeUndefined()

    wrapper.destroy()
  })

  it('has role "status" when label provided', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { label: 'Loading' }
      }
    })

    expect(wrapper.attributes('role')).toBeDefined()
    expect(wrapper.attributes('role')).toEqual('status')

    wrapper.destroy()
  })

  it('does not add custom role when role prop is set and no label', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          role: 'foobar'
        }
      }
    })

    expect(wrapper.attributes('role')).toBeUndefined()

    wrapper.destroy()
  })

  it('adds custom role when role prop is set and label provided', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          role: 'foobar',
          label: 'loading'
        }
      }
    })

    expect(wrapper.attributes('role')).toBeDefined()
    expect(wrapper.attributes('role')).toEqual('foobar')

    wrapper.destroy()
  })

  it('has attribute "aria-hidden" when no label provided', async () => {
    const wrapper = mount(BSpinner)

    expect(wrapper.attributes('aria-hidden')).toBeDefined()
    expect(wrapper.attributes('aria-hidden')).toEqual('true')

    wrapper.destroy()
  })

  it('does not have attribute "aria-hidden" when label provided', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { label: 'loading' }
      }
    })

    expect(wrapper.attributes('aria-hidden')).toBeUndefined()

    wrapper.destroy()
  })

  it('does not have attribute "aria-hidden" when label slot provided', async () => {
    const wrapper = mount(BSpinner, {
      slots: {
        label: 'loading'
      }
    })

    expect(wrapper.attributes('aria-hidden')).toBeUndefined()

    wrapper.destroy()
  })

  it('places user supplied attributes on root element', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        attrs: { id: 'foobar' }
      }
    })

    expect(wrapper.attributes('id')).toBeDefined()
    expect(wrapper.attributes('id')).toEqual('foobar')

    wrapper.destroy()
  })

  it('places user supplied class on root element', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        class: ['foo', 'bar']
      }
    })

    expect(wrapper.classes()).toContain('spinner-border')
    expect(wrapper.classes()).toContain('foo')
    expect(wrapper.classes()).toContain('bar')

    wrapper.destroy()
  })

  it('has class "spinner-grow" when prop type="grow"', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: { type: 'grow' }
      }
    })

    expect(wrapper.classes().length).toBe(1)
    expect(wrapper.classes()).toContain('spinner-grow')

    wrapper.destroy()
  })

  it('has class "spinner-grow-sm" when props small=true and type="grow"', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          small: true,
          type: 'grow'
        }
      }
    })

    expect(wrapper.classes().length).toBe(2)
    expect(wrapper.classes()).toContain('spinner-grow')
    expect(wrapper.classes()).toContain('spinner-grow-sm')

    wrapper.destroy()
  })

  it('has classes "spinner-grow" and "text-danger" when props type="grow" and variant="danger"', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          type: 'grow',
          variant: 'danger'
        }
      }
    })

    expect(wrapper.classes().length).toBe(2)
    expect(wrapper.classes()).toContain('spinner-grow')
    expect(wrapper.classes()).toContain('text-danger')

    wrapper.destroy()
  })

  it('has classes "text-info", "spinner-grow" and "spinner-grow-sm" when props type="grow", variant="info" and small=true', async () => {
    const wrapper = mount(BSpinner, {
      context: {
        props: {
          type: 'grow',
          variant: 'info',
          small: true
        }
      }
    })

    expect(wrapper.classes().length).toBe(3)
    expect(wrapper.classes()).toContain('spinner-grow')
    expect(wrapper.classes()).toContain('spinner-grow-sm')
    expect(wrapper.classes()).toContain('text-info')

    wrapper.destroy()
  })
})


text:
import React from 'react';

const VideoDetail = ({video}) => {
    //just adding this little check prevents a null error when the page is loading, because we don't get a "null" property back before the API has grabbed a video. Only add this when it's neccesarry, usually high-level components. He called it an "ajax spinner"
    if (!video) {
        return
Loading...
;
    }

    const videoId = video.id.videoId;
    //in es6, the backticks let us interpolate a javascript object like below as opposed to just concatenating a string
    const url = `https://www.youtube.com/embed/${videoId}`;

    return (

{video.snippet.title}

{video.snippet.description}

    )
};

export default VideoDetail;


text:
def user():
  try:
    interface = str(raw_input("interface to attach:"))
    port = int(raw_input("port to attach:"))
    return interface,port
  except:
    print "Bad Input"


text:
package handlers

import (
	"crypto/sha256"

	"github.com/hyperledger/fabric/bccsp"
	"github.com/pkg/errors"
)

// nymSecretKey contains the nym secret key
type nymSecretKey struct {
	// SKI of this key
	ski []byte
	// sk is the idemix reference to the nym secret
	sk Big
	// pk is the idemix reference to the nym public part
	pk Ecp
	// exportable if true, sk can be exported via the Bytes function
	exportable bool
}

func computeSKI(serialise func() ([]byte, error)) ([]byte, error) {
	raw, err := serialise()
	if err != nil {
		return nil, err
	}

	hash := sha256.New()
	hash.Write(raw)
	return hash.Sum(nil), nil
}

func NewNymSecretKey(sk Big, pk Ecp, exportable bool) (*nymSecretKey, error) {
	ski, err := computeSKI(sk.Bytes)
	if err != nil {
		return nil, err
	}

	return &nymSecretKey{ski: ski, sk: sk, pk: pk, exportable: exportable}, nil
}

func (k *nymSecretKey) Bytes() ([]byte, error) {
	if k.exportable {
		return k.sk.Bytes()
	}

	return nil, errors.New("not supported")
}

func (k *nymSecretKey) SKI() []byte {
	c := make([]byte, len(k.ski))
	copy(c, k.ski)
	return c
}

func (*nymSecretKey) Symmetric() bool {
	return false
}

func (*nymSecretKey) Private() bool {
	return true
}

func (k *nymSecretKey) PublicKey() (bccsp.Key, error) {
	ski, err := computeSKI(k.pk.Bytes)
	if err != nil {
		return nil, err
	}
	return &nymPublicKey{ski: ski, pk: k.pk}, nil
}

type nymPublicKey struct {
	// SKI of this key
	ski []byte
	// pk is the idemix reference to the nym public part
	pk Ecp
}

func NewNymPublicKey(pk Ecp) *nymPublicKey {
	return &nymPublicKey{pk: pk}
}

func (k *nymPublicKey) Bytes() ([]byte, error) {
	return k.pk.Bytes()
}

func (k *nymPublicKey) SKI() []byte {
	c := make([]byte, len(k.ski))
	copy(c, k.ski)
	return c
}

func (*nymPublicKey) Symmetric() bool {
	return false
}

func (*nymPublicKey) Private() bool {
	return false
}

func (k *nymPublicKey) PublicKey() (bccsp.Key, error) {
	return k, nil
}

// NymKeyDerivation derives nyms
type NymKeyDerivation struct {
	// Exportable is a flag to allow an issuer secret key to be marked as Exportable.
	// If a secret key is marked as Exportable, its Bytes method will return the key's byte representation.
	Exportable bool
	// User implements the underlying cryptographic algorithms
	User User
}

func (kd *NymKeyDerivation) KeyDeriv(k bccsp.Key, opts bccsp.KeyDerivOpts) (dk bccsp.Key, err error) {
	userSecretKey, ok := k.(*userSecretKey)
	if !ok {
		return nil, errors.New("invalid key, expected *userSecretKey")
	}
	nymKeyDerivationOpts, ok := opts.(*bccsp.IdemixNymKeyDerivationOpts)
	if !ok {
		return nil, errors.New("invalid options, expected *IdemixNymKeyDerivationOpts")
	}
	if nymKeyDerivationOpts.IssuerPK == nil {
		return nil, errors.New("invalid options, missing issuer public key")
	}
	issuerPK, ok := nymKeyDerivationOpts.IssuerPK.(*issuerPublicKey)
	if !ok {
		return nil, errors.New("invalid options, expected IssuerPK as *issuerPublicKey")
	}

	Nym, RandNym, err := kd.User.MakeNym(userSecretKey.sk, issuerPK.pk)
	if err != nil {
		return nil, err
	}

	return NewNymSecretKey(RandNym, Nym, kd.Exportable)
}

// NymPublicKeyImporter imports nym public keys
type NymPublicKeyImporter struct {
	// User implements the underlying cryptographic algorithms
	User User
}

func (i *NymPublicKeyImporter) KeyImport(raw interface{}, opts bccsp.KeyImportOpts) (k bccsp.Key, err error) {
	bytes, ok := raw.([]byte)
	if !ok {
		return nil, errors.New("invalid raw, expected byte array")
	}

	if len(bytes) == 0 {
		return nil, errors.New("invalid raw, it must not be nil")
	}

	pk, err := i.User.NewPublicNymFromBytes(bytes)
	if err != nil {
		return nil, err
	}

	return &nymPublicKey{pk: pk}, nil
}


text:
class CreatePoemVoters < ActiveRecord::Migration[5.0]
  def change
    create_table :poem_voters do |t|
      t.integer :poem_id
      t.integer :voter_id
      t.integer :value

      t.timestamps
    end
  end
end


text:
from mlstreaming.base import StreamingDemo

__version__ = '0.1.0'


text:
package ch.liquidmind.ripples.intf.logical.type;

import ch.liquidmind.ripples.intf.common.Element;

public interface Type extends Element
{
}


text:
layout: post
date: '2015-12-23'
title: "Bonny Bridal Bonny Unforgettable 1404 Plus Size Wedding Dress"
category: Bonny Bridal
tags: [Bonny Bridal]
---
### Bonny Bridal Bonny Unforgettable 1404 Plus Size Wedding Dress
Just **$341.99**
###

Not Available In-Store For Try On. Special Order Only.

Sequined lace offers a hint of nostalgia in this ball gown featuring an illusion modified Queen Anne neckline and elbow length sleeves. Beading wraps around the waist leading to the full A-line skirt and train. Finished with a covered illusion back, buttons and zipper closure.

Sizes Available: 16W- 32W

Buy it: [https://www.eudances.com/en/bonny-bridal/237-bonny-unforgettable-1404-plus-size-wedding-dress.html](https://www.eudances.com/en/bonny-bridal/237-bonny-unforgettable-1404-plus-size-wedding-dress.html)


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>

#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/repeating_test_future.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/viz/common/surfaces/video_capture_target.h"
#include "components/viz/service/frame_sinks/video_capture/shared_memory_video_frame_pool.h"
#include "media/base/video_frame.h"
#include "media/base/video_types.h"
#include "remoting/host/chromeos/ash_proxy.h"
#include "remoting/host/chromeos/frame_sink_desktop_capturer.h"
#include "remoting/host/chromeos/scoped_fake_ash_proxy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_region.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"

namespace remoting {
using gfx::ColorSpace;
using gfx::Point;
using gfx::Rect;
using gfx::Size;
using media::VideoCaptureFeedback;
using media::VideoFrame;
using media::VideoPixelFormat;
using testing::Eq;
using webrtc::DesktopCapturer;
using webrtc::DesktopFrame;
using webrtc::DesktopRect;
using webrtc::DesktopRegion;
using webrtc::DesktopSize;

namespace {
constexpr int kAnyWidth = 800;
constexpr int kAnyHeight = 600;
constexpr int kDesignLimitMaxFrames = 20;
constexpr int kFramePoolCapacity = kDesignLimitMaxFrames + 1;

const auto kPixelFormat = VideoPixelFormat::PIXEL_FORMAT_ARGB;
constexpr int kMaxFrameRate = 60;
constexpr auto kMinResolution = Size(320, 180);
constexpr auto kMaxResolution = Size(3840, 2160);
constexpr bool kFixedAspectRatio = false;

std::unique_ptr<viz::VideoFramePool> GetVideoFramePool(int capacity) {
  return std::make_unique<viz::SharedMemoryVideoFramePool>(capacity);
}

std::string ToString(DesktopSize desktop_size) {
  return base::StringPrintf("%dX%d", desktop_size.width(),
                            desktop_size.height());
}

struct CaptureResult {
  DesktopCapturer::Result result;
  std::unique_ptr<DesktopFrame> frame;
};

struct FrameParameters {
  FrameParameters() = default;

  FrameParameters WithSize(Size size) {
    this->size = size;
    return *this;
  }

  FrameParameters WithUpdatedRegion(Rect updated_region) {
    this->updated_region = updated_region;
    return *this;
  }

  FrameParameters WithScaleFactor(float scale_factor) {
    this->scale_factor = scale_factor;
    return *this;
  }

  Size size{kAnyWidth, kAnyHeight};
  Rect updated_region{0, 0, kAnyWidth, kAnyHeight};
  float scale_factor = 1.0;
};

class DesktopCapturerCallback : public DesktopCapturer::Callback {
 public:
  DesktopCapturerCallback() = default;
  DesktopCapturerCallback(const DesktopCapturerCallback&) = delete;
  DesktopCapturerCallback& operator=(const DesktopCapturerCallback&) = delete;
  ~DesktopCapturerCallback() override = default;

  CaptureResult WaitForResult() {
    EXPECT_TRUE(result_.Wait());
    return result_.Take();
  }

  void OnCaptureResult(DesktopCapturer::Result result,
                       std::unique_ptr<DesktopFrame> frame) override {
    result_.AddValue(CaptureResult{result, std::move(frame)});
  }

 private:
  base::test::RepeatingTestFuture<CaptureResult> result_;
};

// Helper class that keeps the ref_ptr to a video frame alive until the Done()
// callback is invoked.
class FakeFrameDeliveryCallback final
    : public viz::mojom::FrameSinkVideoConsumerFrameCallbacks {
 public:
  explicit FakeFrameDeliveryCallback(scoped_refptr<VideoFrame> frame)
      : frame_(frame) {}

  FakeFrameDeliveryCallback(const FakeFrameDeliveryCallback&) = delete;
  FakeFrameDeliveryCallback& operator=(const FakeFrameDeliveryCallback&) =
      delete;
  ~FakeFrameDeliveryCallback() override = default;

  void Done() override { frame_.reset(); }
  void ProvideFeedback(const VideoCaptureFeedback& feedback) override {}

  mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
  BindNewPipeAndPassRemote() {
    return receiver_.BindNewPipeAndPassRemote();
  }

 private:
  scoped_refptr<VideoFrame> frame_;
  mojo::Receiver<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> receiver_{
      this};
};

class MockFrameSinkVideoCapturer : public viz::mojom::FrameSinkVideoCapturer {
 public:
  explicit MockFrameSinkVideoCapturer(
      mojo::Remote<viz::mojom::FrameSinkVideoConsumer>& consumer_remote) {
    this->remote_ = std::move(consumer_remote);
    this->frame_pool_ = GetVideoFramePool(kFramePoolCapacity);

    ON_CALL(*this, Start)
        .WillByDefault(
            [this](mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumer>
                       consumer_remote,
                   viz::mojom::BufferFormatPreference) {
              this->remote_.Bind(std::move(consumer_remote));
            });
  }

  MOCK_METHOD(void, SetFormat, (VideoPixelFormat format));

  MOCK_METHOD(void, SetMinCapturePeriod, (base::TimeDelta min_period));

  MOCK_METHOD(void, SetMinSizeChangePeriod, (base::TimeDelta min_period));

  MOCK_METHOD(void, SetAutoThrottlingEnabled, (bool enabled));

  MOCK_METHOD(void,
              SetResolutionConstraints,
              (const Size& min_size,
               const Size& max_size,
               bool use_fixed_aspect_ratio));

  MOCK_METHOD(void,
              ChangeTarget,
              (const absl::optional<viz::VideoCaptureTarget>& target,
               uint32_t crop_version));

  MOCK_METHOD(void,
              Start,
              (mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumer> consumer,
               viz::mojom::BufferFormatPreference buffer_format_preference));

  MOCK_METHOD(void, Stop, ());

  MOCK_METHOD(void, RequestRefreshFrame, ());

  MOCK_METHOD(void,
              CreateOverlay,
              (int32_t stacking_index,
               mojo::PendingReceiver<viz::mojom::FrameSinkVideoCaptureOverlay>
                   receiver));

  MOCK_METHOD(void, FrameReceived, (scoped_refptr<VideoFrame> frame));

  void SendFrame(FrameParameters params = FrameParameters()) {
    scoped_refptr<VideoFrame> frame =
        frame_pool_->ReserveVideoFrame(kPixelFormat, params.size);
    frame->set_color_space(ColorSpace(ColorSpace::PrimaryID::ADOBE_RGB,
                                      ColorSpace::TransferID::LINEAR));

    auto handle = frame_pool_->CloneHandleForDelivery(*frame);
    ASSERT_TRUE(handle);
    ASSERT_TRUE(!handle->is_read_only_shmem_region() ||
                handle->get_read_only_shmem_region().IsValid());

    auto metadata = frame->metadata();
    metadata.device_scale_factor = params.scale_factor;
    metadata.capture_update_rect = params.updated_region;

    // Assemble frame layout, format, and metadata into a mojo struct to send to
    // the consumer.
    auto info = media::mojom::VideoFrameInfo::New(
        frame->timestamp(), metadata, frame->format(), frame->coded_size(),
        /*visible_rect=*/gfx::Rect(params.size),
        /*is_premapped=*/false, frame->ColorSpace(),
        /*strides=*/nullptr);

    auto done_callback = std::make_unique<FakeFrameDeliveryCallback>(frame);
    Rect content_rect{params.size.width(), params.size.height()};

    remote_->OnFrameCaptured(std::move(handle), std::move(info), content_rect,
                             done_callback->BindNewPipeAndPassRemote());

    done_callbacks_.push_back(std::move(done_callback));
  }

  std::unique_ptr<viz::VideoFramePool> frame_pool_;

  mojo::Receiver<viz::mojom::FrameSinkVideoCapturer> receiver_{this};
  mojo::Remote<viz::mojom::FrameSinkVideoConsumer> remote_;

  // Store the done callback receiver that we create for each frame we send
  // (so it can receive the Done() callback).
  std::vector<std::unique_ptr<FakeFrameDeliveryCallback>> done_callbacks_;

  base::WeakPtrFactory<MockFrameSinkVideoCapturer> fake_capturer_factory_{this};
};

class FrameSinkDesktopCapturerTest : public testing::Test {
 public:
  FrameSinkDesktopCapturerTest() = default;

  test::ScopedFakeAshProxy& ash_proxy() { return ash_proxy_; }

  DesktopCapturerCallback& desktop_capturer_callback() { return callback_; }

  void SetUp() override {
    ash_proxy().SetVideoCapturerReceiver(&video_capturer_.receiver_);
    ash_proxy().AddPrimaryDisplay();
  }

  void StartCapturerForTesting() {
    capturer_.Start(&desktop_capturer_callback());
    FlushForTesting();
  }

  CaptureResult CaptureFrame() {
    FlushForTesting();
    capturer_.CaptureFrame();

    return desktop_capturer_callback().WaitForResult();
  }

  // We really want to flush the mojom pipe, but we can't as the mojom remote is
  // hidden inside ClientFrameSinkDesktopCapturer, so we simply RunUntilIdle()
  // instead.
  void FlushForTesting() { base::RunLoop().RunUntilIdle(); }

  FrameParameters params() { return FrameParameters(); }

  void AddMultipleDisplays() {
    ash_proxy_.AddDisplayWithId(111);
    ash_proxy_.AddDisplayWithId(222);
  }

 protected:
  base::test::SingleThreadTaskEnvironment environment_;
  DesktopCapturerCallback callback_;
  test::ScopedFakeAshProxy ash_proxy_;
  FrameSinkDesktopCapturer capturer_{ash_proxy_};

  mojo::Remote<viz::mojom::FrameSinkVideoConsumer> video_consumer_remote_;

  MockFrameSinkVideoCapturer video_capturer_{video_consumer_remote_};
};

}  // namespace

TEST_F(FrameSinkDesktopCapturerTest,
       ShouldReturnTemporaryErrorIfNoFrameWasReceived) {
  StartCapturerForTesting();

  capturer_.CaptureFrame();

  CaptureResult result = desktop_capturer_callback().WaitForResult();
  EXPECT_THAT(result.result, Eq(DesktopCapturer::Result::ERROR_TEMPORARY));
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldBindVideoCapturerInStart) {
  EXPECT_CALL(video_capturer_, Start);

  StartCapturerForTesting();
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldSetParamsInStart) {
  EXPECT_CALL(video_capturer_, SetFormat(kPixelFormat));
  EXPECT_CALL(video_capturer_, SetMinCapturePeriod(base::Hertz(kMaxFrameRate)));
  EXPECT_CALL(video_capturer_, SetMinSizeChangePeriod(base::Seconds(0)));
  EXPECT_CALL(video_capturer_, SetAutoThrottlingEnabled(/*enabled=*/false));
  EXPECT_CALL(video_capturer_,
              SetResolutionConstraints(kMinResolution, kMaxResolution,
                                       kFixedAspectRatio));

  StartCapturerForTesting();
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldStartByCapturingThePrimaryDisplay) {
  AddMultipleDisplays();

  DisplayId primary_display_id = ash_proxy().GetPrimaryDisplayId();
  const auto expected_target = absl::optional<viz::VideoCaptureTarget>(
      ash_proxy().GetFrameSinkId(primary_display_id));

  EXPECT_CALL(video_capturer_, ChangeTarget(expected_target, 0));

  StartCapturerForTesting();
}
TEST_F(FrameSinkDesktopCapturerTest, ShouldReturnSuccessIfFrameWasReceived) {
  StartCapturerForTesting();

  video_capturer_.SendFrame();
  CaptureResult result = CaptureFrame();

  EXPECT_THAT(result.result, Eq(DesktopCapturer::Result::SUCCESS));
}

TEST_F(FrameSinkDesktopCapturerTest,
       ShouldReturnTheFrameSentByTheVideoCapturer) {
  StartCapturerForTesting();

  video_capturer_.SendFrame(params().WithSize({110, 220}));
  CaptureResult result = CaptureFrame();
  auto frame_size = result.frame->size();

  // Note we don't test the actual frame data but instead we just look at the
  // resolution.
  EXPECT_EQ(ToString(frame_size), "110X220");
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldReleaseMemoryOfUnusedFrames) {
  StartCapturerForTesting();

  for (int i = 0; i < 10; i++) {
    video_capturer_.SendFrame();
    CaptureFrame();
  }

  // At this point the memory of all but the last frame should have been
  // released.
  EXPECT_EQ(video_capturer_.frame_pool_->GetNumberOfReservedFrames(), 1u);
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldSetDpiOfFrame) {
  StartCapturerForTesting();
  int scale_factor = 2.0;
  int dpi = ash_proxy().ScaleFactorToDpi(scale_factor);

  video_capturer_.SendFrame(params().WithScaleFactor(scale_factor));
  CaptureResult result = CaptureFrame();

  EXPECT_THAT(result.frame->dpi().x(), Eq(dpi));
  EXPECT_THAT(result.frame->dpi().y(), Eq(dpi));
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldSetUpdatedRegionOfFrame) {
  StartCapturerForTesting();

  int left = 50, top = 50, width = 250, height = 150;

  auto updated_rect = Rect(left, top, height, width);
  video_capturer_.SendFrame(params().WithUpdatedRegion(updated_rect));
  CaptureResult result = CaptureFrame();

  auto updated_region = result.frame->updated_region();
  DesktopRegion desktop_region{
      DesktopRect::MakeLTRB(updated_rect.x(), updated_rect.y(),
                            updated_rect.right(), updated_rect.bottom())};
  // No method to get the dimensions of updated region.
  EXPECT_TRUE(updated_region.Equals(desktop_region));
}

TEST_F(FrameSinkDesktopCapturerTest, ShouldSetDisplayBounds) {
  int width = 666, height = 400;

  StartCapturerForTesting();

  video_capturer_.SendFrame(params().WithSize({width, height}));
  CaptureResult result = CaptureFrame();

  auto frame_rect = result.frame->rect();
  EXPECT_EQ(frame_rect.width(), width);
  EXPECT_EQ(frame_rect.height(), height);
}

}  // namespace remoting


text:
<?php

use Pagekit\Auth\Auth;
use Pagekit\Auth\AuthEvents;
use Pagekit\Auth\Encoder\NativePasswordEncoder;
use Pagekit\Auth\Event\AuthenticateEvent;
use Pagekit\Auth\Event\LoginEvent;
use Pagekit\Auth\Event\LogoutEvent;
use Pagekit\Auth\RememberMe;
use RandomLib\Factory;
use Symfony\Component\HttpFoundation\RedirectResponse;

return [

    'name' => 'auth',

    'main' => function ($app) {

        $app['auth'] = function ($app) {
            return new Auth($app['events'], $app['session'], $this->config('auth'));
        };

        $app['auth.password'] = function () {
            return new NativePasswordEncoder;
        };

        $app['auth.random'] = function () {
            return (new Factory)->getMediumStrengthGenerator();
        };

        $app['auth.remember'] = function ($app) {

            $config = [

                'gc_maxlifetime' => $app['session.options']['gc_maxlifetime'],
                'rememberme_lifetime' => $this->config('rememberme.timeout')

            ];

            return new RememberMe($app['session'], $config);
        };

    },

    'events' => [

        'boot' => function ($event, $app) {

            if (!$this->config('rememberme.enabled')) {
                return;
            }

            $app->on('request', function () use ($app) {

                try {

                    if (null !== $app['auth']->getUser()) {
                        return;
                    }

                    $user = $app['auth.remember']->autoLogin($app['auth']->getUserProvider());

                    $app['auth']->setUser($user);
                    $app['events']->trigger(new LoginEvent(AuthEvents::LOGIN, $user), ['auto' => true]);

                } catch (\Exception $e) {}

            }, 49);

            $app->on(AuthEvents::SUCCESS, function (AuthenticateEvent $event) use ($app) {
                $app['auth.remember']->set($app['request'], $event->getUser());
            });

            $app->on(AuthEvents::LOGOUT, function ($event, $auto = false) use ($app) {
                if (!$auto) {
                    $app['auth.remember']->remove();
                }
            });

        }

    ],

    'autoload' => [

        'Pagekit\\Auth\\' => 'src'

    ],

    'config' => [

        'auth' => [

            'timeout' => 900

        ],

        'rememberme' => [

            'enabled' => true,
            'timeout' => 31536000

        ]

    ]

];


text:
@interface CMWebViewController ()

@end

@implementation CMWebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.titleLabel.text = @"검색";

    self.webView.scalesPageToFit = YES;
	self.webView.allowsInlineMediaPlayback = YES;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    [self setWebView:nil];
    [super viewDidUnload];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	// 로딩 종료.
	[self hide];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
	// 로딩 시작.
    [self show];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	// 로딩 종료.
	[self hide];
}

@end


text:
const char kUrlDelimiter[] = "?fb=";

// Set ThumbnailService now as Profile isn't thread safe.
ThumbnailSource::ThumbnailSource(Profile* profile, bool capture_thumbnails)
    : thumbnail_service_(ThumbnailServiceFactory::GetForProfile(profile)),
      capture_thumbnails_(capture_thumbnails),
      weak_ptr_factory_(this) {
  image_fetcher_.reset(
      new suggestions::ImageFetcherImpl(profile->GetRequestContext()));
}

ThumbnailSource::~ThumbnailSource() {
}

std::string ThumbnailSource::GetSource() const {
  return capture_thumbnails_ ?
      chrome::kChromeUIThumbnailHost2 : chrome::kChromeUIThumbnailHost;
}

void ThumbnailSource::StartDataRequest(
    const std::string& path,
    int render_process_id,
    int render_frame_id,
    const content::URLDataSource::GotDataCallback& callback) {
  GURL page_url;
  GURL fallback_thumbnail_url;
  ExtractPageAndThumbnailUrls(path, &page_url, &fallback_thumbnail_url);

  scoped_refptr<base::RefCountedMemory> data;
  if (page_url.is_valid() &&
      thumbnail_service_->GetPageThumbnail(page_url, capture_thumbnails_,
                                           &data)) {
    // If a local thumbnail is available for the page's URL, provide it.
    callback.Run(data.get());
  } else if (fallback_thumbnail_url.is_valid()) {
    // Otherwise, if a fallback thumbnail URL was provided, fetch it and
    // eventually return it.
    image_fetcher_->StartOrQueueNetworkRequest(
        page_url, fallback_thumbnail_url,
        base::Bind(&ThumbnailSource::SendFetchedUrlImage,
                   weak_ptr_factory_.GetWeakPtr(), callback));
  } else {
    callback.Run(default_thumbnail_.get());
  }
  if (page_url.is_valid() && capture_thumbnails_)
    thumbnail_service_->AddForcedURL(page_url);
}

std::string ThumbnailSource::GetMimeType(const std::string&) const {
  // We need to explicitly return a mime type, otherwise if the user tries to
  // drag the image they get no extension.
  return "image/png";
}

base::MessageLoop* ThumbnailSource::MessageLoopForRequestPath(
    const std::string& path) const {
  // TopSites can be accessed from the IO thread. Otherwise, the URLs should be
  // accessed on the UI thread.
  return thumbnail_service_.get()
             ? nullptr
             : content::URLDataSource::MessageLoopForRequestPath(path);
}

bool ThumbnailSource::ShouldServiceRequest(
    const net::URLRequest* request) const {
  if (request->url().SchemeIs(chrome::kChromeSearchScheme))
    return InstantIOContext::ShouldServiceRequest(request);
  return URLDataSource::ShouldServiceRequest(request);
}

void ThumbnailSource::ExtractPageAndThumbnailUrls(
    const std::string& path,
    GURL* page_url,
    GURL* fallback_thumbnail_url) {
  std::string page_url_str(path);
  std::string fallback_thumbnail_url_str;

  size_t pos = path.find(kUrlDelimiter);
  if (pos != std::string::npos) {
    page_url_str = path.substr(0, pos);
    fallback_thumbnail_url_str = path.substr(pos + strlen(kUrlDelimiter));
  }

  *page_url = GURL(page_url_str);
  *fallback_thumbnail_url = GURL(fallback_thumbnail_url_str);
}

void ThumbnailSource::SendFetchedUrlImage(
    const content::URLDataSource::GotDataCallback& callback,
    const GURL& url,
    const gfx::Image& image) {
  // In case the image could not be retrieved an empty image is returned.
  if (image.IsEmpty()) {
    callback.Run(default_thumbnail_.get());
    return;
  }

  const SkBitmap* bitmap = image.ToSkBitmap();
  scoped_refptr<base::RefCountedBytes> encoded_data(
      new base::RefCountedBytes());
  if (!suggestions::EncodeSkBitmapToJPEG(*bitmap, &encoded_data->data())) {
    callback.Run(default_thumbnail_.get());
    return;
  }

  callback.Run(encoded_data.get());
}


text:
require_relative 'syntax_result'

module BELParser
  module Language
    module Syntax
      # SyntaxWarning defines a {SyntaxResult} that should be regarded as an
      # warning with the expression.
      class SyntaxWarning < SyntaxResult
        def initialize(expression_node, specification)
          super(expression_node, specification)
        end

        def success?
          false
        end

        def failure?
          true
        end

        def to_s
          "Warning: #{msg}"
        end
      end
    end
  end
end


text:
(function($) {
    var defaults = {};

    var methods = {
        init: function(params) {
            var options = $.extend({}, defaults, params);

            $("html").bind("click", function(e) {
                $(".jetselect .jetselectdropdown").addClass("closed");
                var js = $(e.target).closest(".jetselect");
                if (js.size() && js.find(".jetselectdropdown").hasClass("closed")) {
                    $(js).find(".jetselectdropdown").removeClass("closed");
                }
            });

            return this.each(function() {
                var c = "jetselect";
                if ($(this).attr("class") !== undefined) {
                    c += " " + $(this).attr("class");
                }
                var el = $(this).wrap("
").parent(),
                    dd = el.append("

")
                            .find(".jetselectdropdown");

                $.each(el.find("select option"), function(i, val) {
                    var html = $(val).attr("label");

                    if (html === undefined || html === "") {
                        html = $(val).text();
                    }
                    dd.append($("
").html(html));
                });
                el.closest(".jetselect").jetSelect('select', el.find("select option:selected").index());

                $(".jetselect > ul > li").bind("click", function() {
                    el.closest(".jetselect").jetSelect('select', $(this).index());
                    $(this).parent().addClass("closed");
                    return false;
                });

                el.find(".jetselectvalue").click(function() {
                    if (dd.hasClass("closed")) {
                        dd.removeClass("closed");
                    } else {
                        dd.addClass("closed");
                        return false;
                    }
                });

            });
        },
        select: function(index) {
            var el = this,
                li = el.find("li").removeClass("selected").eq(index).addClass("selected");
            el.find(".jetselectvalue").html(li.html());
            el.find("option").removeAttr("selected");
            el.find("option").eq(index).attr("selected", "selected");
            el.find("select").trigger('change');
        }
    };
    $.fn.jetSelect = function(method){
        if ( methods[method] ) {
            return methods[ method ].apply(this, Array.prototype.slice.call( arguments, 1));
        } else {
            return methods.init.apply(this, arguments);
        }
    };
})(jQuery);


text:
drop table ActivityTracker;

create table AnnouncementsDelivery (
	deliveryId number(30,0) not null primary key,
	companyId number(30,0),
	userId number(30,0),
	type_ varchar2(75) null,
	email number(1, 0),
	sms number(1, 0),
	website number(1, 0)
);

create table AnnouncementsEntry (
	uuid_ varchar2(75) null,
	entryId number(30,0) not null primary key,
	companyId number(30,0),
	userId number(30,0),
	userName varchar2(75) null,
	createDate timestamp null,
	modifiedDate timestamp null,
	classNameId number(30,0),
	classPK number(30,0),
	title varchar2(75) null,
	content varchar2(4000) null,
	url varchar2(4000) null,
	type_ varchar2(75) null,
	displayDate timestamp null,
	expirationDate timestamp null,
	priority number(30,0),
	alert number(1, 0)
);

create table AnnouncementsFlag (
	flagId number(30,0) not null primary key,
	userId number(30,0),
	createDate timestamp null,
	entryId number(30,0),
	value number(30,0)
);

create table ExpandoColumn (
	columnId number(30,0) not null primary key,
	tableId number(30,0),
	name varchar2(75) null,
	type_ number(30,0)
);

create table ExpandoRow (
	rowId_ number(30,0) not null primary key,
	tableId number(30,0),
	classPK number(30,0)
);

create table ExpandoTable (
	tableId number(30,0) not null primary key,
	classNameId number(30,0),
	name varchar2(75) null
);

create table ExpandoValue (
	valueId number(30,0) not null primary key,
	tableId number(30,0),
	columnId number(30,0),
	rowId_ number(30,0),
	classNameId number(30,0),
	classPK number(30,0),
	data_ varchar2(75) null
);

alter table IGImage add name varchar2(75) null;
alter table IGImage add custom1ImageId number(30,0) null;
alter table IGImage add custom2ImageId number(30,0) null;

update Group_ set type_ = 3 where type_ = 0;

update Image set type_ = 'jpg' where type_ = 'jpeg';

create table PortletItem (
	portletItemId number(30,0) not null primary key,
	groupId number(30,0),
	companyId number(30,0),
	userId number(30,0),
	userName varchar2(75) null,
	createDate timestamp null,
	modifiedDate timestamp null,
	name varchar2(75) null,
	portletId varchar2(75) null,
	classNameId number(30,0)
);

create table SocialActivity (
	activityId number(30,0) not null primary key,
	groupId number(30,0),
	companyId number(30,0),
	userId number(30,0),
	createDate timestamp null,
	classNameId number(30,0),
	classPK number(30,0),
	type_ varchar2(75) null,
	extraData clob null,
	receiverUserId number(30,0)
);

create table SocialRelation (
	uuid_ varchar2(75) null,
	relationId number(30,0) not null primary key,
	companyId number(30,0),
	createDate timestamp null,
	userId1 number(30,0),
	userId2 number(30,0),
	type_ number(30,0)
);

create table TasksProposal (
	proposalId number(30,0) not null primary key,
	groupId number(30,0),
	companyId number(30,0),
	userId number(30,0),
	userName varchar2(75) null,
	createDate timestamp null,
	modifiedDate timestamp null,
	classNameId number(30,0),
	classPK varchar2(75) null,
	name varchar2(75) null,
	description varchar2(4000) null,
	publishDate timestamp null,
	dueDate timestamp null
);

create table TasksReview (
	reviewId number(30,0) not null primary key,
	groupId number(30,0),
	companyId number(30,0),
	userId number(30,0),
	userName varchar2(75) null,
	createDate timestamp null,
	modifiedDate timestamp null,
	proposalId number(30,0),
	assignedByUserId number(30,0),
	assignedByUserName varchar2(75) null,
	stage number(30,0),
	completed number(1, 0),
	rejected number(1, 0)
);

alter table WikiPage add parentTitle varchar2(75) null;
alter table WikiPage add redirectTitle varchar2(75) null;


text:
require("object");

Stack = class();

Stack.defaultStack = function(self)
	size = 0;
	array = {};
	for k = 1, 50 do
		array[k] = 0;
	end
end

Stack.ctor = function(self, length)
	size = 0;
	array = {};
	for k = 1, length do
		array[k] = 0;
	end
end

Stack.isEmpty = function(self)
	return size == 0;
end

Stack.pop = function(self)
	if size == 0 then
		print(" satck is empty");
		return;
	else
		local oldSize = size;
		size = size - 1;
		return array[oldSize];
	end
end

Stack.push = function(self, item)
	if size >= #array then
		print(" stack is full");
		return;
	end
--	local oldSize = size;
	size = size + 1;
	array[size] = item;
end

Stack.size = function(self)
	return size;
end

Stack.toString = function(self)
	for k= size, 1, -1 do
		print(array[k]);
	end
end


text:
#include <OpenSim/Simulation/SimbodyEngine/SliderJoint.h>
#include <OpenSim/Simulation/SimbodyEngine/PinJoint.h>
#include <OpenSim/Simulation/SimbodyEngine/PlanarJoint.h>
#include <OpenSim/Actuators/CoordinateActuator.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Simulation/Model/PointToPointSpring.h>
//#include <OpenSim/Simulation/Model/ModelComponent.h>
#include <OpenSim/Analyses/ForceReporter.h>
#include <Moco/osimMoco.h>
#include <OpenSim/Common/Reporter.h>
#include <OpenSim/Common/Constant.h>
#include <OpenSim/Simulation/Control/PrescribedController.h>

#include <MocoSandboxShared.h>

// TODO achieve sliding friction (apply constant tangential force,
// maybe from gravity?).

// TODO add tests for contact model (energy conservation) to make sure, for
// example, ball bounces back to original height if there is no dissipation.

using namespace OpenSim;
using SimTK::Vec3;

class CustomContactForce : public Force {
    OpenSim_DECLARE_CONCRETE_OBJECT(CustomContactForce, Force);
public:
    OpenSim_DECLARE_SOCKET(station, Station, "TODO");
    void computeForce(const SimTK::State& s,
            SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
            SimTK::Vector& /*generalizedForces*/) const override {
        const auto& pt = getConnectee<Station>("station");
        const auto& pos = pt.getLocationInGround(s);
        const auto& vel = pt.getVelocityInGround(s);
        const SimTK::Real y = pos[1];
        const SimTK::Real vy = vel[1];
        SimTK::Vec3 force(0);
        const SimTK::Real depth = 0 - y;
        const SimTK::Real depthRate = 0 - vy;
        const SimTK::Real a = 5e7; // N/m^3
        const SimTK::Real b = 1.0; // s/m
        if (depth > 0) {
            //force = 1000 * depth;
            force[1] = fmax(0, a * pow(depth, 3) * (1 + b * depthRate));
        }
        const SimTK::Real voidStiffness = 1.0; // N/m
        force[1] += voidStiffness * depth;
        //applyGeneralizedForce(s, getModel().getCoordinateSet().get(0),
        //        force, generalizedForces);
        applyForceToPoint(s, pt.getParentFrame(), pt.get_location(), force,
                bodyForces);
        // TODO equal and opposite force on ground.
    }
};

Model createModel() {
    Model model;
    model.setName("point_mass");
    auto* body = new Body("body", 50.0, Vec3(0), SimTK::Inertia(0));
    model.addComponent(body);

    // Allows translation along x.
    auto* joint = new SliderJoint("slider",
            model.getGround(), Vec3(0), SimTK::Vec3(0, 0, 0.5 * SimTK::Pi),
            *body, Vec3(0), Vec3(0));
    auto& coord = joint->updCoordinate(SliderJoint::Coord::TranslationX);
    coord.setName("y");
    model.addComponent(joint);

    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*body);
    model.addComponent(station);

    auto* force = new CustomContactForce();
    force->setName("contact");
    model.addComponent(force);
    force->connectSocket_station(*station);

    return model;
}

std::unique_ptr<Model> createModel2D() {
    auto model = make_unique<Model>();
    model->setName("point_mass");
    auto* intermed = new Body("intermed", 0, Vec3(0), SimTK::Inertia(0));
    model->addComponent(intermed);
    // TODO inertia...
    auto* body = new Body("body", 50.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(body);

    // Allows translation along x.
    auto* jointX = new SliderJoint();
    jointX->setName("tx");
    jointX->connectSocket_parent_frame(model->getGround());
    jointX->connectSocket_child_frame(*intermed);
    auto& coordX = jointX->updCoordinate(SliderJoint::Coord::TranslationX);
    coordX.setName("tx");
    model->addComponent(jointX);

    // The joint's x axis must point in the global "+y" direction.
    auto* jointY = new SliderJoint("ty",
            *intermed, Vec3(0), Vec3(0, 0, 0.5 * SimTK::Pi),
            *body, Vec3(0), Vec3(0, 0, 0.5 * SimTK::Pi));
    auto& coordY = jointY->updCoordinate(SliderJoint::Coord::TranslationX);
    coordY.setName("ty");
    model->addComponent(jointY);

    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*body);
    model->addComponent(station);

    //auto* force = new CustomContactForce();
    auto* force = new AckermannVanDenBogert2010Force();
    force->setName("contact");
    model->addComponent(force);
    force->connectSocket_station(*station);

    return model;
}

void ball2d() {

    const SimTK::Real y0 = 0.5;
    const SimTK::Real vx0 = 0.7;
    const SimTK::Real finalTime = 1.0;

    auto model = createModel2D();
    auto state = model->initSystem();
    model->setStateVariableValue(state, "ty/ty/value", y0);
    model->setStateVariableValue(state, "tx/tx/speed", vx0);
    Manager manager(*model);
    // Without the next line: Simbody takes steps that are too large and NaNs
    // are generated.
    manager.setIntegratorMaximumStepSize(0.05);
    manager.initialize(state);
    state = manager.integrate(finalTime);
    const auto& statesTimeStepping = manager.getStateStorage();
    std::cout << "DEBUG " << statesTimeStepping.getSize() << std::endl;
    visualize(*model, statesTimeStepping);
    auto statesTimeSteppingTable = statesTimeStepping.exportToTable();
    STOFileAdapter::write(statesTimeSteppingTable, "ball2d_timestepping.sto");

    MocoStudy study;
    study.setName("ball2d");

    // Define the optimal control problem.
    // ===================================
    MocoProblem& mp = study.updProblem();

    // Model (dynamics).
    // -----------------
    mp.setModel(std::move(model));

    // Bounds.
    // -------
    // Initial time must be 0, final time can be within [0, 5].
    mp.setTimeBounds(0, finalTime);

    mp.setStateInfo("/tx/tx/value", {-5, 5}, 0);
    mp.setStateInfo("/ty/ty/value", {-0.5, 1}, y0);
    mp.setStateInfo("/tx/tx/speed", {-10, 10}, vx0);
    mp.setStateInfo("/ty/ty/speed", {-10, 10}, 0);

    // Configure the solver.

    MocoTropterSolver& ms = study.initSolver();
    ms.set_num_mesh_intervals(500);

    MocoTrajectory guess = ms.createGuess();

    // Setting this guess reduces the number of iterations from 90 to 6.
    // Can tweak the guess to test convergence (~50 iterations):
    //statesTimeSteppingTable.updDependentColumn("ty/ty/value") += 0.05;
    guess.setStatesTrajectory(statesTimeSteppingTable);

    ms.setGuess(guess);

    // TODO interface for setting these options:
    // TODO ms.setOption("optim.hessian-approximation", "limited-memory");
    // TODO ms.set_optimizer_algorithm("ipopt");

    // Now that we've finished setting up the tool, print it to a file.
    //moco.print("contact.omoco");

    // Solve the problem.
    // ==================
    MocoSolution solution = study.solve();

    solution.write("ball2d_solution.sto");

    std::cout << "RMS: " << solution.compareContinuousVariablesRMS(guess)
            << std::endl;

    // Visualize.
    // ==========
    study.visualize(solution);
}

std::unique_ptr<Model> createModelPendulum(double linkLength, double jointHeight,
        double dissipation, double frictionCoeff) {
    auto model = make_unique<Model>();
    model->setName("pendulum");
    auto* body = new Body("body", 50.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(body);

    // The joint's x axis must point in the global "+y" direction.
    auto* joint = new PinJoint("rz",
            model->getGround(), Vec3(0, jointHeight, 0), Vec3(0),
            *body, Vec3(-linkLength, 0, 0), Vec3(0));
    auto& rz = joint->updCoordinate(PinJoint::Coord::RotationZ);
    rz.setName("rz");
    model->addComponent(joint);

    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*body);
    model->addComponent(station);

    auto* force = new AckermannVanDenBogert2010Force();
    force->set_dissipation(dissipation);
    force->set_friction_coefficient(frictionCoeff);
    force->setName("contact");
    model->addComponent(force);
    force->connectSocket_station(*station);

    return model;
}

void pendulum() {
    const double jointHeight = 0.6;
    const double linkLength = 1.0;
    const double dissipation = 1.0;
    const double frictionCoeff = 1.0;
    const SimTK::Real finalTime = 1.0;
    auto model = createModelPendulum(linkLength, jointHeight, dissipation,
            frictionCoeff);
    auto state = model->initSystem();
    Manager manager(*model);
    // Without the next line: Simbody takes steps that are too large and NaNs
    // are generated.
    manager.setIntegratorMaximumStepSize(0.05);
    manager.initialize(state);
    state = manager.integrate(finalTime);
    const auto& statesTimeStepping = manager.getStateStorage();
    visualize(*model, statesTimeStepping);
    auto statesTimeSteppingTable = statesTimeStepping.exportToTable();
    STOFileAdapter::write(statesTimeSteppingTable, "pendulum_timestepping.sto");

    MocoStudy study;
    study.setName("ball2d");
    MocoProblem& mp = study.updProblem();
    mp.setModel(std::move(model));
    mp.setTimeBounds(0, finalTime);

    mp.setStateInfo("/rz/rz/value", {-0.5 * SimTK::Pi, 0.5 * SimTK::Pi}, 0);
    mp.setStateInfo("/rz/rz/speed", {-10, 10}, 0);

    // Configure the solver.

    MocoTropterSolver& ms = study.initSolver();
    ms.set_num_mesh_intervals(500);
    MocoTrajectory guess = ms.createGuess();
    guess.setStatesTrajectory(statesTimeSteppingTable);

    ms.setGuess(guess);
    MocoSolution solution = study.solve();

    solution.write("pendulum_solution.sto");

    std::cout << "RMS: " << solution.compareContinuousVariablesRMS(guess)
            << std::endl;

    // Visualize.
    // ==========
    study.visualize(solution);
}

std::unique_ptr<Model> createModelPendulumActivationCoordinateActuator() {
    const double jointHeight = 0.6;
    const double linkLength = 1.0;
    auto model = make_unique<Model>();
    model->setName("pendulum");
    auto* body = new Body("body", 50.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(body);

    // The joint's x axis must point in the global "+y" direction.
    auto* joint = new PinJoint("rz",
            model->getGround(), Vec3(0, jointHeight, 0), Vec3(0),
            *body, Vec3(-linkLength, 0, 0), Vec3(0));
    auto& rz = joint->updCoordinate(PinJoint::Coord::RotationZ);
    rz.setName("rz");
    model->addComponent(joint);

    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*body);
    model->addComponent(station);

    auto* force = new AckermannVanDenBogert2010Force();
    force->set_dissipation(1.0);
    force->set_friction_coefficient(1.0);
    force->setName("contact");
    model->addComponent(force);
    force->connectSocket_station(*station);

    auto* actu = new ActivationCoordinateActuator();
    actu->set_default_activation(0.1);
    actu->setName("actuator");
    actu->setCoordinate(&rz);
    actu->setOptimalForce(600);
    model->addComponent(actu);

    return model;
}

void pendulumActivationCoordinateActuator() {
    const SimTK::Real finalTime = 1.0;
    auto model = createModelPendulumActivationCoordinateActuator();
    PrescribedController* contr = new PrescribedController();
    contr->addActuator(model->getComponent<ActivationCoordinateActuator>
            ("actuator"));
    contr->prescribeControlForActuator("actuator", new Constant(1.0));
    model->addComponent(contr);
    auto state = model->initSystem();
    Manager manager(*model);
    // Without the next line: Simbody takes steps that are too large and NaNs
    // are generated.
    manager.setIntegratorMaximumStepSize(0.05);
    manager.initialize(state);
    state = manager.integrate(finalTime);
    const auto& statesTimeStepping = manager.getStateStorage();
    visualize(*model, statesTimeStepping);
    auto statesTimeSteppingTable = statesTimeStepping.exportToTable();
    STOFileAdapter::write(statesTimeSteppingTable,
            "pendulumaca_timestepping.sto");

    /*

    MocoStudy study;
    study.setName("pendulumaca");
    MocoProblem& mp = study.updProblem();
    mp.setModel(model);
    mp.setTimeBounds(0, finalTime);

    mp.setStateInfo("/rz/rz/value", {-0.5 * SimTK::Pi, 0.5 * SimTK::Pi}, 0);
    mp.setStateInfo("/rz/rz/speed", {-10, 10}, 0);

    // Configure the solver.

    MocoTropterSolver& ms = study.initSolver();
    ms.set_num_mesh_intervals(500);
    MocoTrajectory guess = ms.createGuess();
    guess.setStatesTrajectory(statesTimeSteppingTable);

    ms.setGuess(guess);
    MocoSolution solution = study.solve();

    solution.write("pendulumaca_solution.sto");

    std::cout << "RMS: " << solution.compareStatesControlsRMS(guess)
     << std::endl;

    // Visualize.
    // ==========
    study.visualize(solution);
     */
}

void addResidualActivationCoordinateActuators(Model& model) {

    auto& coordSet = model.updCoordinateSet();

    auto* res_rz = new ActivationCoordinateActuator();
    res_rz->setCoordinate(&coordSet.get("rz"));
    res_rz->setName("res_rz");
    res_rz->setOptimalForce(100);
    model.addComponent(res_rz);

    auto* res_tx = new ActivationCoordinateActuator();
    res_tx->setCoordinate(&coordSet.get("tx"));
    res_tx->setName("res_tx");
    res_tx->setOptimalForce(2500);
    model.addComponent(res_tx);

    auto* res_ty = new ActivationCoordinateActuator();
    res_ty->setCoordinate(&coordSet.get("ty"));
    res_ty->setName("res_ty");
    res_ty->setOptimalForce(2500);
    model.addComponent(res_ty);

}

void addResidualCoordinateActuators(Model& model) {

    auto& coordSet = model.updCoordinateSet();

    auto* res_rz = new CoordinateActuator();
    res_rz->setCoordinate(&coordSet.get("rz"));
    res_rz->setName("res_rz");
    res_rz->setOptimalForce(100);
    model.addComponent(res_rz);

    auto* res_tx = new CoordinateActuator();
    res_tx->setCoordinate(&coordSet.get("tx"));
    res_tx->setName("res_tx");
    res_tx->setOptimalForce(2500);
    model.addComponent(res_tx);

    auto* res_ty = new CoordinateActuator();
    res_ty->setCoordinate(&coordSet.get("ty"));
    res_ty->setName("res_ty");
    res_ty->setOptimalForce(2500);
    model.addComponent(res_ty);

}

std::unique_ptr<Model> createModelSLIP() {
    auto model = make_unique<Model>();
    model->setName("SLIP");
    auto* foot = new Body("foot", 15.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(foot);
    auto* pelvis = new Body("pelvis", 35.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(pelvis);

    Sphere bodyGeom(0.05);
    bodyGeom.setColor(SimTK::Red);
    foot->attachGeometry(bodyGeom.clone());
    bodyGeom.setColor(SimTK::Blue);
    pelvis->attachGeometry(bodyGeom.clone());

    auto* planar = new PlanarJoint("planar", model->getGround(), *foot);
    planar->updCoordinate(PlanarJoint::Coord::TranslationX).setName("tx");
    auto& ty = planar->updCoordinate(PlanarJoint::Coord::TranslationY);
    ty.setName("ty");
    ty.setDefaultValue(0.1);
    planar->updCoordinate(PlanarJoint::Coord::RotationZ).setName("rz");
    model->addComponent(planar);

    const Vec3 rz90 = SimTK::Vec3(0, 0, 0.5 * SimTK::Pi);
    auto* leg = new SliderJoint("leg", *foot, Vec3(0), rz90,
            *pelvis, Vec3(0), rz90);
    auto& length = leg->updCoordinate(SliderJoint::Coord::TranslationX);
    length.setName("length");
    length.setDefaultValue(1.0);
    model->addComponent(leg);

    // Foot-ground contact.
    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*foot);
    model->addComponent(station);

    auto* force = new AckermannVanDenBogert2010Force();
    force->set_dissipation(1.0);
    force->set_stiffness(5e5);
    force->set_friction_coefficient(1.0);
    force->setName("contact");
    model->addComponent(force);
    force->connectSocket_station(*station);

    // auto* force = new MeyerFregly2016Force();
    // // force->set_dissipation(1.0);
    // // force->set_stiffness(1e4);
    // force->setName("contact");
    // model->addComponent(force);
    // force->connectSocket_station(*station);

    // auto* force = new EspositoMiller2018Force();
    // force->set_stiffness(1e5);
    // force->setName("contact");
    // model->addComponent(force);
    // force->connectSocket_station(*station);

    // Leg muscles.
    // TODO spring force should be felt all the time; similar to contact.
    // TODO disallow PathSpring?
    auto* spring = new PointToPointSpring();
    model->addComponent(spring);
    spring->set_stiffness(5e3);
    spring->set_rest_length(1.0);
    spring->connectSocket_body1(*foot);
    spring->connectSocket_body2(*pelvis);

    auto* foot_marker = new Marker("foot_COM", *foot, Vec3(0));
    model->addComponent(foot_marker);
    auto* pelvis_marker = new Marker("pelvis_COM", *pelvis, Vec3(0));
    model->addComponent(pelvis_marker);

    return model;
}

std::unique_ptr<Model>createModelSLIPActuated() {
    auto model = make_unique<Model>();
    model->setName("SLIP");
    auto* foot = new Body("foot", 15.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(foot);
    auto* pelvis = new Body("pelvis", 35.0, Vec3(0), SimTK::Inertia(1));
    model->addComponent(pelvis);

    Sphere bodyGeom(0.05);
    bodyGeom.setColor(SimTK::Red);
    foot->attachGeometry(bodyGeom.clone());
    bodyGeom.setColor(SimTK::Blue);
    pelvis->attachGeometry(bodyGeom.clone());

    auto* planar = new PlanarJoint("planar", model->getGround(), *foot);
    planar->updCoordinate(PlanarJoint::Coord::TranslationX).setName("tx");
    auto& ty = planar->updCoordinate(PlanarJoint::Coord::TranslationY);
    ty.setName("ty");
    ty.setDefaultValue(0.1);
    planar->updCoordinate(PlanarJoint::Coord::RotationZ).setName("rz");
    model->addComponent(planar);

    const Vec3 rz90 = SimTK::Vec3(0, 0, 0.5 * SimTK::Pi);
    auto* leg = new SliderJoint("leg", *foot, Vec3(0), rz90,
            *pelvis, Vec3(0), rz90);
    auto& length = leg->updCoordinate(SliderJoint::Coord::TranslationX);
    length.setName("length");
    length.setDefaultValue(1.0);
    model->addComponent(leg);

    // Foot-ground contact.
    auto* station = new Station();
    station->setName("contact_point");
    station->connectSocket_parent_frame(*foot);
    model->addComponent(station);

    auto* force = new AckermannVanDenBogert2010Force();
    force->set_dissipation(1.0);
    force->set_stiffness(5e5);
    force->set_friction_coefficient(1.0);
    force->setName("contact");
    model->addComponent(force);
    force->connectSocket_station(*station);

    // auto* force = new MeyerFregly2016Force();
    // force->set_dissipation(1.0);
    // force->set_stiffness(1e4);
    // force->setName("contact");
    // model->addComponent(force);
    // force->connectSocket_station(*station);

    // auto* force = new EspositoMiller2018Force();
    // force->set_stiffness(1e5);
    // force->setName("contact");
    // model->addComponent(force);
    // force->connectSocket_station(*station);

    auto* actuator = new CoordinateActuator();
    actuator->setCoordinate(&length);
    actuator->setName("actuator");
    actuator->setOptimalForce(2500);
    //actuator->set_activation_time_constant(0.025);
    model->addComponent(actuator);

    //addResidualActivationCoordinateActuators(*model);
    addResidualCoordinateActuators(*model);

    auto* foot_marker = new Marker("foot_COM", *foot, Vec3(0));
    model->addComponent(foot_marker);
    auto* pelvis_marker = new Marker("pelvis_COM", *pelvis, Vec3(0));
    model->addComponent(pelvis_marker);

    return model;
}

void slip(double rzvalue0 = 0, double rzspeed0 = 0) {
    const SimTK::Real finalTime = 1.0;
    auto model = createModelSLIP();
    auto state = model->initSystem();
    model->setStateVariableValue(state, "planar/rz/value", rzvalue0);
    model->setStateVariableValue(state, "planar/rz/speed", rzspeed0);
    Manager manager(*model);
    manager.setIntegratorAccuracy(1e-5);
    manager.setIntegratorMaximumStepSize(0.05);
    manager.initialize(state);
    state = manager.integrate(finalTime);
    const auto& statesTimeStepping = manager.getStateStorage();
    visualize(*model, statesTimeStepping);
    auto statesTimeSteppingTable = statesTimeStepping.exportToTable();
    STOFileAdapter::write(statesTimeSteppingTable, "slip_timestepping.sto");

    MocoStudy study;
    study.setName("slip");
    MocoProblem& mp = study.updProblem();
    mp.setModel(std::move(model));
    mp.setTimeBounds(0, finalTime);
    using SimTK::Pi;
    mp.setStateInfo("/planar/tx/value", {-5, 5}, 0);
    mp.setStateInfo("/planar/ty/value", {-0.5, 2}, 0.1);
    mp.setStateInfo("/planar/rz/value", {-0.5*Pi, 0.5*Pi}, rzvalue0);
    mp.setStateInfo("/leg/length/value", {0.1, 1.9}, 1.0);
    mp.setStateInfo("/planar/tx/speed", {-10, 10}, 0);
    mp.setStateInfo("/planar/ty/speed", {-10, 10}, 0);
    mp.setStateInfo("/planar/rz/speed", {-10, 10}, rzspeed0);
    mp.setStateInfo("/leg/length/speed", {-10, 10}, 0);

    MocoTropterSolver& ms = study.initSolver();
    ms.set_num_mesh_intervals(500);
    //ms.set_optim_max_iterations(2);
    MocoTrajectory guess = ms.createGuess();
    //statesTimeSteppingTable.updMatrix() +=
    //        0.1 * SimTK::Test::randMatrix(guess.getNumTimes(), 6);
    //statesTimeSteppingTable.updDependentColumn("planar/ty/value") +=
    //        0.05 * SimTK::Test::randVector(guess.getNumTimes());
    guess.setStatesTrajectory(statesTimeSteppingTable);
    ms.setGuess(guess);

    MocoSolution solution = study.solve().unseal();
    solution.write("slip_solution.sto");
    std::cout << "RMS: " << solution.compareContinuousVariablesRMS(guess)
            << std::endl;
    study.visualize(solution);
}

void slipSolveForForce(double rzvalue0 = 0, double rzspeed0 = 0) {
    const SimTK::Real finalTime = 0.68;
    auto modelTS = createModelSLIP();
    auto reporter = new TableReporterVec3();
    reporter->setName("contact_rep");
    reporter->set_report_time_interval(0.01);
    reporter->addToReport(
            modelTS->getComponent("contact").getOutput("force_on_station"));
    modelTS->addComponent(reporter);
    auto markersReporter = new TableReporterVec3();
    markersReporter->setName("marker_rep");
    markersReporter->set_report_time_interval(0.01);
    markersReporter->addToReport(
            modelTS->getComponent("foot_COM").getOutput("location"),
            "foot_COM");
    markersReporter->addToReport(
            modelTS->getComponent("pelvis_COM").getOutput("location"),
            "pelvis_COM");
    modelTS->addComponent(markersReporter);
    auto state = modelTS->initSystem();
    modelTS->setStateVariableValue(state, "planar/rz/value", rzvalue0);
    modelTS->setStateVariableValue(state, "planar/rz/speed", rzspeed0);
    auto* forceRep = new ForceReporter(modelTS.get());
    modelTS->addAnalysis(forceRep);
    Manager manager(*modelTS);
    manager.setIntegratorAccuracy(1e-5);
    manager.setIntegratorMaximumStepSize(0.05);
    manager.initialize(state);
    state = manager.integrate(finalTime);
    const auto& statesTimeStepping = manager.getStateStorage();

    // Calculate the signed magnitude of the spring force.
    // forceRep->getForceStorage().print("DEBUG_slipSolveForForce_forces.sto");
    SimTK::Vector springForceActual;
    SimTK::Vector springForceActualTime;
    {
        auto forceRepTable = forceRep->getForcesTable();
        std::string prefix = "pointtopointspring.";
        auto X = forceRepTable.getDependentColumn(prefix + "foot.force.X");
        auto Y = forceRepTable.getDependentColumn(prefix + "foot.force.Y");
        auto Z = forceRepTable.getDependentColumn(prefix + "foot.force.Z");
        auto pX = forceRepTable.getDependentColumn(prefix + "pelvis.point.X") -
                forceRepTable.getDependentColumn(prefix + "foot.point.X");
        auto pY = forceRepTable.getDependentColumn(prefix + "pelvis.point.Y") -
                forceRepTable.getDependentColumn(prefix + "foot.point.Y");
        auto pZ = forceRepTable.getDependentColumn(prefix + "pelvis.point.Z") -
                forceRepTable.getDependentColumn(prefix + "foot.point.Z");
        const auto& stdTime = forceRepTable.getIndependentColumn();
        springForceActualTime =
                SimTK::Vector((int)stdTime.size(), stdTime.data());
        springForceActual.resize(X.size());
        assert(X.size() > 0);
        for (int i = 0; i < X.size(); ++i) {
            SimTK::Vec3 forceVec(X[i], Y[i], Z[i]);
            SimTK::Vec3 lineOfAction(pX[i], pY[i], pZ[i]);
            springForceActual[i] = forceVec.norm();
            if (~lineOfAction * forceVec < 0) {
                springForceActual[i] *= -1;
            }
        }
        forceRepTable.appendColumn("spring_force_mag", springForceActual);
        STOFileAdapter::write(forceRepTable,
                "DEBUG_slipSolveForForce_springforce.sto");
    }

    auto forcesFlattened = reporter->getTable().flatten({"x", "y", "z"});
    //TimeSeriesTable forcesFilt = filterLowpass(forcesFlattened, 18.0, true);
    STOFileAdapter::write(forcesFlattened,
        "slipSolveForForce_contact_force.sto");
    auto statesTimeSteppingTable = statesTimeStepping.exportToTable();
    STOFileAdapter::write(statesTimeSteppingTable,
            "slipSolveForForce_timestepping.sto");
    auto markers = markersReporter->getTable();
    TimeSeriesTable markersFilt = filterLowpass(markers.flatten(), 6.0, true);
    auto markersPacked = markersFilt.pack<double>();
    TimeSeriesTableVec3 markersToUse(markersPacked);
    markersToUse.setColumnLabels({"foot_COM", "pelvis_COM"});
    visualize(*modelTS, statesTimeStepping);

    MocoStudy study;
    study.setName("slipSolveForForce");
    MocoProblem& mp = study.updProblem();
    //mp.setModel(modelTS);
    mp.setModel(createModelSLIPActuated());
    mp.setTimeBounds(0, finalTime);
    using SimTK::Pi;
    mp.setStateInfo("/planar/tx/value", {-5, 5}, 0);
    mp.setStateInfo("/planar/ty/value", {-0.5, 2}, 0.1);
    mp.setStateInfo("/planar/rz/value", {-0.5*Pi, 0.5*Pi}, rzvalue0);
    mp.setStateInfo("/leg/length/value", {0.1, 1.9}, 1.0);
    mp.setStateInfo("/planar/tx/speed", {-10, 10}, 0);
    mp.setStateInfo("/planar/ty/speed", {-10, 10}, 0);
    mp.setStateInfo("/planar/rz/speed", {-10, 10}, rzspeed0);
    mp.setStateInfo("/leg/length/speed", {-10, 10}, 0);
    //mp.setStateInfo("/actuator/activation", {-2, 2});
    //mp.setStateInfo("/res_rz/activation", { -2, 2 });
    //mp.setStateInfo("/res_tx/activation", { -2, 2 });
    //mp.setStateInfo("/res_ty/activation", { -2, 2 });
    mp.setControlInfo("/actuator", {-1, 1});
    mp.setControlInfo("/res_rz", { -1, 1 });
    mp.setControlInfo("/res_tx", { -1, 1 });
    mp.setControlInfo("/res_ty", { -1, 1 });

    Storage statesFilt = statesTimeStepping;
    statesFilt.pad(statesFilt.getSize() / 2);
    statesFilt.lowpassIIR(30);
    const auto statesToTrack = statesFilt.exportToTable();
    //const auto statesToTrack = statesTimeSteppingTable;
    STOFileAdapter::write(statesToTrack, "slipSolveForForce_ref_filtered.sto");

    // TODO filter statesTimeSteppingTable!
    // TODO only track coordinate values, not speeds.

    auto* stateTracking = mp.addGoal<MocoStateTrackingCost>("state_tracking");
    stateTracking->setReference(statesToTrack);

    mp.addGoal<MocoControlGoal>("effort");

    //MocoMarkerTrackingGoal markerTracking;
    //markerTracking.setName("marker_tracking");
    //MarkersReference markersRef(markersToUse);
    //markerTracking.setMarkersReference(markersRef);
    ////markerTracking.setFreeRadius(0.01);
    //markerTracking.set_weight(1);
    //mp.addGoal(markerTracking);

    // Solves in 3-4 minutes without contact tracking, 9 minutes with contact
    // tracking.
    auto* grfTracking = mp.addGoal<MocoForceTrackingCost>("grf_tracking");
    GCVSplineSet grfSplines(forcesFlattened);
    grfTracking->m_refspline_x = *grfSplines.getGCVSpline(0);
    grfTracking->m_refspline_y = *grfSplines.getGCVSpline(1);
    double normGRFs = 0.001;
    double weight = 1;
    grfTracking->set_weight(normGRFs * weight);
    grfTracking->append_forces("contact");

    MocoTropterSolver& ms = moco.initSolver();
    ms.set_multibody_dynamics_mode("implicit");
    ms.set_num_mesh_intervals(100);
    //ms.set_num_mesh_intervals(50);
    //ms.set_optim_max_iterations(2);
    // I tried setting convergence and constraint tolerances to 1e-3, and the
    // time to solve increased from 11 to 16 minutes (using EspositoMiller2018
    // for contact). Setting the tolerance to 1e-2 decreases the solve time from
    // 11 to 6 minutes. The error in the actuator force is definitely larger (up
    // to 50 N), but the match is still very good. This was all without contact
    // tracking. With contact tracking and AckermannVanDenBogert2010, the solve
    // time is about 5 minutes whether or not the convergence tolerance is set.
    // ms.set_optim_convergence_tolerance(1e-2);
    // ms.set_optim_constraint_tolerance(1e-2);
    MocoTrajectory guess = ms.createGuess();
    guess.setStatesTrajectory(statesToTrack, true);
    ms.setGuess(guess);

    MocoSolution solution = study.solve().unseal();
    solution.write("slipSolveForForce_solution.sto");
    std::cout << "RMS: " << solution.compareContinuousVariablesRMS(guess)
            << std::endl;

    SimTK::Vector springForceRecovered =
            interpolate(solution.getTime(),
                    -2500.0 * solution.getControl("actuator"),
                    springForceActualTime);
    std::cout << "Spring force error: " <<
            springForceRecovered - springForceActual << std::endl;

    // Compute the contact force for the direct collocation solution.
    const auto statesTraj = solution.exportToStatesTrajectory(mp);
    Model model = mp.getPhase().getModel();
    model.initSystem();
    const auto& contact =
            model.getComponent<StationPlaneContactForce>("contact");
    TimeSeriesTableVec3 contactForceHistory;
    contactForceHistory.setColumnLabels(
            {"SLIPcontactforce_on_station"});

    for (const auto& s : statesTraj) {
        model.realizeVelocity(s);
        contactForceHistory.appendRow(s.getTime(),
                {contact.calcContactForceOnStation(s)});
    }

    STOFileAdapter::write(contactForceHistory.flatten({"x", "y", "z"}),
            "slipSolveForForce_dircol_force.sto");

    //ms.set_num_mesh_intervals(50);
    //ms.setGuess(solution);
    //// Does not converge instantly... TODO
    //MocoSolution solution2 = study.solve().unseal();
    //solution2.write("slipSolveForForce_solution2.sto");

    //// 200 mesh intervals results in a *much* smoother solution than 50 but takes
    //// 7626 seconds to solve. and it's smoother but not smooth; very high
    //// frequency for most of the motion; smooth in the middle third.
    //ms.set_num_mesh_intervals(200);
    //ms.setGuess(solution2);
    //MocoSolution solution200 = study.solve().unseal();
    //solution200.write("slipSolveForForce_solution200.sto");

    // This works, but it takes a few minutes:
    //ms.set_num_mesh_intervals(100);
    //ms.setGuess(solution);
    //MocoSolution solution100 = study.solve().unseal();
    //solution100.write("slipSolveForForce_solution100.sto");

    // State and GRF tracking solution:
    // + Residual actuators at pelvis (rz, tx, ty)
    // + Implicit skeletal dynamics (no activation dynamics at coordinates)
    // + 100 mesh intervals
    // + AckermannVanDenBogert2010Force contact (defaults w/ stiffness = 5e5)

    study.visualize(solution);
}

int main() {

    if (false) {
        const SimTK::Real y0 = 0.5;
        // const SimTK::Real vx0 = 0.7;
        const SimTK::Real finalTime = 1.0;
        Model model = createModel();
        auto state = model.initSystem();
        model.setStateVariableValue(state, "/slider/y/value", y0);
        Manager manager(model, state);
        state = manager.integrate(finalTime);
        visualize(model, manager.getStateStorage());
    }

    // ball2d();

    // pendulum();

    //slip();

    // slip(0.05 * SimTK::Pi, -0.5);

    // TODO need to add an actuator that can rotate the leg.

    // TODO add two legs.

    // TODO cost to minimize effort.

    // TODO use a different model that has a CoordinateActuator and recover
    // the original spring force.

    // TODO inverse dynamics: solve for what the actuator force should be.

    // TODO use a lower stiffness.
    slipSolveForForce(0.05 * SimTK::Pi, -0.5);

    //    pendulumActivationCoordinateActuator();

}


text:
\section{src/\+Event.cpp File Reference}
\label{_event_8cpp}\index{src/\+Event.\+cpp@{src/\+Event.\+cpp}}
{\ttfamily \#include \char`\"{}Event.\+h\char`\"{}}\\*
{\ttfamily \#include $<$sstream$>$}\\*
Include dependency graph for Event.\+cpp\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=207pt]{_event_8cpp__incl}
\end{center}
\end{figure}


text:
// DATA_TEMPLATE: dom_data
oTest.fnStart( "aaSortingFixed" );

$(document).ready( function () {
	/* Check the default */
	var oTable = $('#example').dataTable();
	var oSettings = oTable.fnSettings();

	oTest.fnTest(
		"No fixed sorting by default",
		null,
		function () {
			return oSettings.aaSortingFixed == null;
		}
	);

	oTest.fnTest(
		"Fixed sorting on first column (string/asc) with user sorting on second column (string/asc)",
		function () {
			oSession.fnRestore();
			$('#example').dataTable( {
				"aaSortingFixed": [['0','asc']]
			} );
			$('#example thead th:eq(1)').click();
		},
		function () { return $('#example tbody td:eq(1)').html() == "Camino 1.0"; }
	);

	oTest.fnTest(
		"Fixed sorting on first column (string/asc) with user sorting on second column (string/desc)",
		function () {
			$('#example thead th:eq(1)').click();
		},
		function () { return $('#example tbody td:eq(1)').html() == "Seamonkey 1.1"; }
	);

	oTest.fnTest(
		"Fixed sorting on fourth column (int/asc) with user sorting on second column (string/asc)",
		function () {
			oSession.fnRestore();
			$('#example').dataTable( {
				"aaSortingFixed": [['3','asc']]
			} );
			$('#example thead th:eq(1)').click();
		},
		function () { return $('#example tbody td:eq(1)').html() == "All others"; }
	);

	oTest.fnTest(
		"Fixed sorting on fourth column (int/asc) with user sorting on second column (string/desc)",
		function () {
			$('#example thead th:eq(1)').click();
		},
		function () { return $('#example tbody td:eq(1)').html() == "PSP browser"; }
	);

	oTest.fnComplete();
} );