text:
package com.oregonscientific.meep.home.test;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import junit.framework.Test;
import junit.framework.TestSuite;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.bitbar.recorder.extensions.ExtSolo;
import com.oregonscientific.meep.ServiceManager;
import com.oregonscientific.meep.account.Account;
import com.oregonscientific.meep.account.AccountManager;
import com.oregonscientific.meep.home.R;
import com.oregonscientific.meep.home.view.ContentLayout;
import com.oregonscientific.meep.home.view.FadingScrollView;
import com.oregonscientific.meep.home.view.MenuItem;
import com.oregonscientific.meep.home.view.MyTextView;
import com.oregonscientific.meep.home.view.UserImageView;
import com.oregonscientific.meep.junit.test.BaseSingleLaunchActivityTestCase;
import com.oregonscientific.meep.junit.test.TestData;
import com.oregonscientific.meep.permission.PermissionManager;

public class HomeActivityTest extends
		BaseSingleLaunchActivityTestCase {

	private ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps collecting better test execution data during test runs
	private boolean requireMenuToRestore = false;
	private boolean requireToExitTopActivity = false;
	private boolean requireToExitParentalSetting = false;

	@Override
	public void setUp() throws Exception {
		super.setUp();

		solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
				.getCanonicalName(), getName());
	}

	@Override
	public void tearDown() throws Exception {

		if (requireToExitParentalSetting) {
			// self exit
			solo.sleep(1000);
			solo.goBack();
			solo.sleep(1000);
			solo.clickOnScreen(solo.toScreenX(0.572f), solo.toScreenY(0.680f));
			solo.sleep(1000);
			requireToExitParentalSetting = false;
		}

		if (requireToExitTopActivity) {
			solo.sleep(1000);
			solo.goBack();
			solo.sleep(1000);
			requireToExitTopActivity = false;
		}

		if (requireMenuToRestore) {
			dragDownScrollView(true);
			dragDownScrollView(false);
			dragDownLeftMenu();
			dragDownRightMenu();
			requireMenuToRestore = false;
		}

		solo.tearDown();
		super.tearDown();
	}

	public void test0_startServer () {
		startServer(getActivity());
	}
	public void testZ_stopServer() {
		stopServer(getActivity());
	}

	public void test1_AutoSignIn() {
		assertTrue("Fail to launch Home Activity", solo.waitForActivity("HomeActivity", 3000));
		solo.sleep(5000);
		MyTextView tv = (MyTextView)solo.findViewById(R.id.header_profile_user_name);
		assertTrue("Fail to login or login wrongly", tv.getText().toString().equalsIgnoreCase(TestData.TEST_USER_NAME));

	}

	public void test2_openMenuWithClick() {

		clickLeftMenu(false);
		clickRightMenu(false);
		solo.sleep(3000);
	}

	public void test3_closeMenuWithClick() {
		clickLeftMenu(true);
		clickRightMenu(true);
		solo.sleep(3000);

	}

	public void test4_openMenuWithDrag() {
		dragUpLeftMenu();
		dragUpRightMenu();
	}

	public void test5_closeMenuWithDrag() {
		dragDownLeftMenu();
		dragDownRightMenu();
	}

	public void test6_dragUpAndDownMenusQuickly() {

		requireMenuToRestore = true;

		Date startDate = Calendar.getInstance().getTime();
		Date endDate = new Date(startDate.getTime() + 10000);
		Date iteratingDate = startDate;
		while (iteratingDate.before(endDate)) {
			boolean left = (Math.round(Math.random()*100) %2 == 1);
			if (left)
				dragLeftMenuQuickly();
			else
				dragRightMenuQuickly();

			iteratingDate = Calendar.getInstance().getTime();
		}

	}

	public void test7_dragUpAndDownScrollViewInMenuQuickly() {

		requireMenuToRestore = true;

		clickLeftMenu(false);
		clickRightMenu(false);

		Date startDate = Calendar.getInstance().getTime();
		Date endDate = new Date(startDate.getTime() + 10000);
		Date iteratingDate = startDate;
		while (iteratingDate.before(endDate)) {
			boolean left = (Math.round(Math.random()*100) %2 == 1);
			if (left)
				dragLeftScrollViewQuickly();
			else
				dragRightScrollViewQuickly();

			iteratingDate = Calendar.getInstance().getTime();
		}

	}

	public void test8_recentlyUsedAppWithCorrectName() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		launchAppWithResourceId(R.id.menu_item_notifications);
		solo.sleep(9000);
		solo.goBack();
		solo.sleep(1000);
		TextView tv = (TextView) solo.findViewById(R.id.menu_item_header_recently_used_title);
		assertTrue("Recently used app not Notifications, is " + tv.getText().toString(), tv.getText().toString().contains("Notification"));
		solo.sleep(3000);
	}

	public void test9_launchRecentlyUsedApp() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		final String NOTIFICATION_PACKAGE = getActivity().getString(R.string.package_meep_notification);
		ImageView iv = (ImageView) solo.findViewById(R.id.menu_item_header_recently_used_image);
		int location[] = {0,0};
		iv.getLocationOnScreen(location);
		solo.clickOnScreen(location[0], location[1]);
		solo.sleep(3000);
		ActivityManager am = (ActivityManager) getActivity().getSystemService(Activity.ACTIVITY_SERVICE);
	     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
	     ComponentName componentInfo = taskInfo.get(0).topActivity;
	     assertTrue("Notification fail to launch, topActivity is " + componentInfo.getPackageName(),
	    		 componentInfo.getPackageName().equalsIgnoreCase(NOTIFICATION_PACKAGE));

	}

	public void testA_launchProfileSetting() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		final String PROFILE_ACTIVITY = "com.oregonscientific.meep.home.ProfileActivity";
		UserImageView hdv = (UserImageView) solo.findViewById(R.id.header_profile_user_image);
		int location[] = {0,0};
		hdv.getLocationOnScreen(location);
		solo.clickOnScreen(location[0], location[1]);
		solo.sleep(3000);
		ActivityManager am = (ActivityManager) getActivity().getSystemService(Activity.ACTIVITY_SERVICE);
	     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
	     ComponentName componentInfo = taskInfo.get(0).topActivity;
	     assertTrue("Profile activity fail to launch, topActivity is " + componentInfo.getClassName(),
	    		 componentInfo.getClassName().equalsIgnoreCase(PROFILE_ACTIVITY));

	}

	public void testB_launchNews() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		final String NOTIFICATION_PACKAGE = getActivity().getString(R.string.package_meep_notification);
		launchAppWithResourceId(R.id.menu_item_news, NOTIFICATION_PACKAGE);
	}

	public void testC_launchBrowser() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		final String BROWSER_PACKAGE = getActivity().getString(R.string.package_meep_browser);
		launchAppWithResourceId(R.id.menu_item_browser, BROWSER_PACKAGE);
	}

	public void testD_launchCommunicator() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		final String COMMUNICATOR_PACKAGE = getActivity().getString(R.string.package_meep_communicator);
		launchAppWithResourceId(R.id.menu_item_communicator, COMMUNICATOR_PACKAGE);

	}

	public void testE_launchStore() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		final String STORE_PACKAGE = getActivity().getString(R.string.package_meep_store);
		launchAppWithResourceId(R.id.menu_item_store, STORE_PACKAGE);
	}

	public void testF_launchParentalSetting() {

		requireMenuToRestore = true;
		requireToExitParentalSetting = true;
		dragUpLeftMenu();
		dragUpLeftScrollView();
		final String TOGETHER_PACKAGE = getActivity().getString(R.string.package_meep_portal);
		launchAppWithResourceId(R.id.menu_item_portal, TOGETHER_PACKAGE);
		solo.sleep(1000);

	}

	public void testG_launchYouTube() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpLeftMenu();
		dragUpLeftScrollView();
		final String YOUTUBE_PACKAGE = getActivity().getString(R.string.package_meep_youtube);
		launchAppWithResourceId(R.id.menu_item_youtube, YOUTUBE_PACKAGE);
		solo.sleep(1000);
		// close the keyboard first
		solo.goBack();
	}

	public void testH_launchMusic() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		final String MUSIC_PACKAGE = getActivity().getString(R.string.package_meep_music);
		launchAppWithResourceId(R.id.menu_item_music, MUSIC_PACKAGE);

	}

	public void testI_launchGame() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		final String GAME_PACKAGE = getActivity().getString(R.string.package_meep_game);
		launchAppWithResourceId(R.id.menu_item_game, GAME_PACKAGE);

	}

	public void testJ_launchPicture() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		final String PHOTO_PACKAGE = getActivity().getString(R.string.package_meep_photo);
		launchAppWithResourceId(R.id.menu_item_picture, PHOTO_PACKAGE);
		solo.sleep(1000);
	}

	public void testK_launchEbooks() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		final String EBOOK_PACKAGE = getActivity().getString(R.string.package_meep_ebook);
		launchAppWithResourceId(R.id.menu_item_ebook, EBOOK_PACKAGE);
		solo.sleep(1000);
	}

	public void testL_launchVideos() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		final String MOVIE_PACKAGE = getActivity().getString(R.string.package_meep_movie);
		launchAppWithResourceId(R.id.menu_item_movie, MOVIE_PACKAGE);
		solo.sleep(1000);
	}

	public void testM_launchSafty() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		dragUpRightScrollView();
		final String SAFTY_PACKAGE = getActivity().getString(R.string.package_meep_safty);
		launchAppWithResourceId(R.id.menu_item_help, SAFTY_PACKAGE);
		solo.sleep(1000);
	}

	public void testN_launchCamera() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		dragUpRightScrollView();

		final String CAMERA_PACKAGE = getActivity().getString(R.string.package_meep_camera);

		MenuItem mi = (MenuItem) solo.findViewById(R.id.menu_item_camera);
		if (mi != null) {
			Log.d("HomeActivityTest", "Launching" + mi.getName());
			int location[] = {0,0};
			mi.getLocationOnScreen(location);
			Log.e("HomeActivityTest", location[0] + ":" + location[1]);
			solo.clickOnScreen(location[0], location[1]);
		}

		solo.sleep(5000);

		solo.clickOnScreen(solo.toScreenX(0.361f), solo.toScreenY(0.493f));
		solo.sleep(1000);
		solo.clickOnScreen(solo.toScreenX(0.356f), solo.toScreenY(0.543f));
		solo.sleep(2800);

		AccountManager accm = (AccountManager) ServiceManager.getService(getActivity(), ServiceManager.ACCOUNT_SERVICE);
		Account a = accm.getLoggedInAccount();
		PermissionManager pm = (PermissionManager) ServiceManager.getService(getActivity(), ServiceManager.PERMISSION_SERVICE);
		ComponentName  componentName = null;
		if (!CAMERA_PACKAGE.equals(getActivity().getString(R.string.package_meep_camera))) {
			Intent launchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CAMERA_PACKAGE);
			componentName = launchIntent.getComponent();
		} else {
			componentName = new ComponentName("com.android.camera", "com.android.camera.CameraEntry");
		}

		if (pm.isAccessible(a.getMeepTag(), componentName)) {

			if (CAMERA_PACKAGE != null) {

				ActivityManager am = (ActivityManager) getActivity().getSystemService(Activity.ACTIVITY_SERVICE);
				List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
				ComponentName componentInfo = taskInfo.get(0).topActivity;
				assertTrue("Activity fail to launch, topActivity is " + componentInfo.getPackageName(),
						componentInfo.getPackageName().equalsIgnoreCase(CAMERA_PACKAGE));
			}

		} else {
			assertTrue("Blocked pop up did not came up", solo.waitForFragmentByTag("dialog", 20000));
		}

		solo.sleep(1000);
	}

	public void testO_launchSetting() {

		requireMenuToRestore = true;
		requireToExitTopActivity = true;

		dragUpRightMenu();
		dragUpRightScrollView();

		final String SETTING_PACKAGE = getActivity().getString(R.string.package_meep_settins);
		launchAppWithResourceId(R.id.menu_item_setting, SETTING_PACKAGE);
		solo.sleep(1000);
	}

	private void dragLeftMenuQuickly() {

		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		int location[] = {0,0};
		leftMenu.getLocationOnScreen(location);
		int leftMenuOriginalTopPosition = location[1];

		boolean up = (leftMenuOriginalTopPosition > 200);

		if (up) {
			solo.sleep(300);
			solo.drag(solo.toScreenX(0.172f), solo.toScreenX(0.190f),
					solo.toScreenY(0.874f), solo.toScreenY(0.124f), 8);
			solo.sleep(300);
		} else {
			solo.sleep(300);
			solo.drag(solo.toScreenX(0.172f), solo.toScreenX(0.190f),
					solo.toScreenY(0.124f), solo.toScreenY(0.874f), 8);
			solo.sleep(300);
		}

		int afterlocation[] = {0,0};
		leftMenu.getLocationOnScreen(afterlocation);
		if (up)
			assertTrue("Left Menu not opened", afterlocation[1]  < leftMenuOriginalTopPosition);
		else
			assertTrue("Left Menu still opened", afterlocation[1]  > leftMenuOriginalTopPosition);
	}

	private void dragRightMenuQuickly() {

		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		int location[] = {0,0};
		rightMenu.getLocationOnScreen(location);
		int rightMenuOriginalTopPosition = location[1];

		boolean up = (rightMenuOriginalTopPosition > 200);

		if (up) {
			solo.sleep(300);
			solo.drag(solo.toScreenX(0.764f), solo.toScreenX(0.800f),
					solo.toScreenY(0.874f), solo.toScreenY(0.124f), 8);
			solo.sleep(300);
		} else {
			solo.sleep(300);
			solo.drag(solo.toScreenX(0.764f), solo.toScreenX(0.800f),
					solo.toScreenY(0.124f), solo.toScreenY(0.874f), 8);
			solo.sleep(300);
		}

		int afterlocation[] = {0,0};
		rightMenu.getLocationOnScreen(afterlocation);
		if (up)
			assertTrue("Right Menu not opened", afterlocation[1]  < rightMenuOriginalTopPosition);
		else
			assertTrue("Right Menu still opened", afterlocation[1]  > rightMenuOriginalTopPosition);
	}

	private void dragUpLeftMenu() {
		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		int location[] = {0,0};
		leftMenu.getLocationOnScreen(location);
		int leftMenuOriginalTopPosition = location[1];

		solo.sleep(5700);

		solo.drag(solo.toScreenX(0.172f), solo.toScreenX(0.190f),
		solo.toScreenY(0.874f), solo.toScreenY(0.124f), 10);
		solo.sleep(1000);

		int afterlocation[] = {0,0};
		leftMenu.getLocationOnScreen(afterlocation);

		assertTrue("Left Menu not opened", afterlocation[1]  <= leftMenuOriginalTopPosition);
	}

	private void dragDownLeftMenu() {

		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		int location[] = {0,0};
		leftMenu.getLocationOnScreen(location);
		int leftMenuOriginalTopPosition = location[1];

		solo.sleep(5700);
		solo.drag(solo.toScreenX(0.172f), solo.toScreenX(0.190f),
				solo.toScreenY(0.124f), solo.toScreenY(0.874f), 10);

		solo.sleep(1000);
		int afterlocation[] = {0,0};
		leftMenu.getLocationOnScreen(afterlocation);

		assertTrue("Left Menu still opened", afterlocation[1]  >= leftMenuOriginalTopPosition);
	}

	private void dragUpRightMenu() {
		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		int location[] = {0,0};
		rightMenu.getLocationOnScreen(location);
		int rightMenuOriginalTopPosition = location[1];

		solo.sleep(5000);
		solo.drag(solo.toScreenX(0.764f), solo.toScreenX(0.800f),
				solo.toScreenY(0.874f), solo.toScreenY(0.124f), 10);
		solo.sleep(1000);

		int afterlocation[] = {0,0};
		rightMenu.getLocationOnScreen(afterlocation);

		assertTrue("Right Menu not opened", afterlocation[1]  <= rightMenuOriginalTopPosition);
	}

	private void dragDownRightMenu() {
		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		int location[] = {0,0};
		rightMenu.getLocationOnScreen(location);
		int rightMenuOriginalTopPosition = location[1];

		solo.sleep(5000);
		solo.drag(solo.toScreenX(0.764f), solo.toScreenX(0.800f),
				solo.toScreenY(0.124f), solo.toScreenY(0.874f), 10);
		solo.sleep(1000);

		int afterlocation[] = {0,0};
		rightMenu.getLocationOnScreen(afterlocation);

		assertTrue("Right Menu still opened"  + afterlocation[1] + " orig:" + rightMenuOriginalTopPosition, afterlocation[1] >= rightMenuOriginalTopPosition);
	}

	private void clickLeftMenu(boolean opened) {

		solo.sleep(1000);
		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		int location[] = {0,0};
		leftMenu.getLocationOnScreen(location);
		int leftMenuOriginalTopPosition = location[1];

		solo.clickOnView(solo.findViewById(com.oregonscientific.meep.home.R.id.header_profile_user_tag));
		solo.sleep(2700);
		int afterlocation[] = {0,0};
		leftMenu.getLocationOnScreen(afterlocation);

		if (!opened) {
			assertTrue("Left Menu not opened" + afterlocation[1] + " orig:" + leftMenuOriginalTopPosition, afterlocation[1] < leftMenuOriginalTopPosition);
		} else {
			assertTrue("Left Menu still opened"  + afterlocation[1] + " orig:" + leftMenuOriginalTopPosition, afterlocation[1] > leftMenuOriginalTopPosition);
		}

		solo.sleep(2000);
	}

	private void clickRightMenu(boolean opened) {
		solo.sleep(1000);
		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		int location[] = {0,0};
		rightMenu.getLocationOnScreen(location);
		int rightMenuOriginalTopPosition = location[1];
		assertTrue(
				"Wait for text (id: com.oregonscientific.meep.home.R.id.menu_item_header_recently_used_title) failed.",
				solo.waitForView(
						solo.findViewById(com.oregonscientific.meep.home.R.id.menu_item_header_recently_used_title),
						20000, true));
		solo.clickOnView(solo
				.findViewById(com.oregonscientific.meep.home.R.id.menu_item_header_recently_used_title));
		solo.sleep(5500);

		int afterlocation[] = {0,0};
		rightMenu.getLocationOnScreen(afterlocation);

		Log.e("HomeActivityTest", afterlocation[1] + " orig:" + rightMenuOriginalTopPosition);
		if (!opened) {
			assertTrue("Left Menu not opened" + afterlocation[1] + " orig:" + rightMenuOriginalTopPosition, afterlocation[1] < rightMenuOriginalTopPosition);
		} else {
			assertTrue("Left Menu still opened"  + afterlocation[1] + " orig:" + rightMenuOriginalTopPosition, afterlocation[1] > rightMenuOriginalTopPosition);
		}
	}

	private void dragUpScrollView(boolean left){
		if (left) {
			solo.sleep(100);
			solo.drag(solo.toScreenX(0.226f), solo.toScreenX(0.222f),
					solo.toScreenY(0.885f), solo.toScreenY(0.327f), 8);
			solo.sleep(200);
		} else {
			solo.sleep(100);
			solo.drag(solo.toScreenX(0.783f), solo.toScreenX(0.788f),
					solo.toScreenY(0.917f), solo.toScreenY(0.315f), 5);
			solo.sleep(200);
		}
	}

	private void dragDownScrollView(boolean left){
		if (left) {
			solo.sleep(100);
			solo.drag(solo.toScreenX(0.233f), solo.toScreenX(0.216f),
					solo.toScreenY(0.320f), solo.toScreenY(0.875f), 5);
			solo.sleep(200);
		} else {
			solo.sleep(100);
			solo.drag(solo.toScreenX(0.783f), solo.toScreenX(0.779f),
					solo.toScreenY(0.365f), solo.toScreenY(1.014f), 8);
			solo.sleep(200);
		}
	}

	public void dragUpLeftScrollView () {

		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		FadingScrollView sv = (FadingScrollView) leftMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();

		dragUpScrollView(true);

		int afterOffset = sv.getScrollY();
		assertTrue("Scroll view did now scroll down", afterOffset > originalOffset);
	}

	public void dragDownLeftScrollView () {

		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		FadingScrollView sv = (FadingScrollView) leftMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();

		dragDownScrollView(true);

		int afterOffset = sv.getScrollY();
		assertTrue("Scroll view did not scroll up", afterOffset < originalOffset);
	}

	public void dragUpRightScrollView () {

		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		FadingScrollView sv = (FadingScrollView) rightMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();

		dragUpScrollView(false);

		int afterOffset = sv.getScrollY();
		assertTrue("Scroll view did not wscroll down", afterOffset > originalOffset);
	}

	public void dragDownRightScrollView () {

		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		FadingScrollView sv = (FadingScrollView) rightMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();

		dragDownScrollView(false);

		int afterOffset = sv.getScrollY();
		assertTrue("Scroll view did now scroll up", afterOffset < originalOffset);
	}

	public void dragLeftScrollViewQuickly() {

		ContentLayout leftMenu = (ContentLayout) solo.findViewById(R.id.leftPanelContent);
		FadingScrollView sv = (FadingScrollView) leftMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();
		if (originalOffset < 100)
			dragUpLeftScrollView();
		else
			dragDownLeftScrollView();

	}

	public void dragRightScrollViewQuickly() {

		ContentLayout rightMenu = (ContentLayout) solo.findViewById(R.id.rightPanelContent);
		FadingScrollView sv = (FadingScrollView) rightMenu.findViewById(R.id.menu_item_scrollview);
		int originalOffset = sv.getScrollY();
		if (originalOffset < 100)
			dragUpRightScrollView();
		else
			dragDownRightScrollView();

	}

	private void launchAppWithResourceId(int resId) {
		launchAppWithResourceId(resId, null);
	}

	private void launchAppWithResourceId(int resId, String packageName) {

		MenuItem mi = (MenuItem) solo.findViewById(resId);
		if (mi != null) {
			Log.d("HomeActivityTest", "Launching" + mi.getName());
			int location[] = {0,0};
			mi.getLocationOnScreen(location);
			Log.e("HomeActivityTest", location[0] + ":" + location[1]);
			solo.clickOnScreen(location[0], location[1]);
		}

		solo.sleep(5000);

		if (packageName == null)
			return;

		AccountManager accm = (AccountManager) ServiceManager.getService(getActivity(), ServiceManager.ACCOUNT_SERVICE);
		Account a = accm.getLoggedInAccount();
		PermissionManager pm = (PermissionManager) ServiceManager.getService(getActivity(), ServiceManager.PERMISSION_SERVICE);
		ComponentName  componentName = null;
		if (!packageName.equals(getActivity().getString(R.string.package_meep_camera))) {
			Intent launchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(packageName);
			componentName = launchIntent.getComponent();
		} else {
			componentName = new ComponentName("com.android.camera", "com.android.camera.CameraEntry");
		}

		if (pm.isAccessible(a.getMeepTag(), componentName)) {

			if (packageName != null) {

				ActivityManager am = (ActivityManager) getActivity().getSystemService(Activity.ACTIVITY_SERVICE);
				List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
				ComponentName componentInfo = taskInfo.get(0).topActivity;
				assertTrue("Activity fail to launch, topActivity is " + componentInfo.getPackageName(),
						componentInfo.getPackageName().equalsIgnoreCase(packageName));
			}

		} else {
			assertTrue("Blocked pop up did not came up", solo.waitForFragmentByTag("dialog", 20000));
		}
	}

	public static Test suite() {
		TestSuite suite = new TestSuite(
				HomeActivityTest.class);
		return suite;
	}
}


text:
using System.Collections.ObjectModel;

namespace net.openstack.Providers.Rackspace.Objects.Monitoring
{
    using System;
    using System.Collections.Generic;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    /// <summary>
    /// This class represents the detailed configuration parameters for a
    /// generic check.
    /// </summary>
    /// <threadsafety static="true" instance="false"/>
    /// <preliminary/>
    [JsonObject(MemberSerialization.OptIn)]
    public class GenericCheckDetails : CheckDetails
    {
        /// <summary>
        /// This is the backing field for the <see cref="Properties"/> property.
        /// </summary>
        [JsonExtensionData]
        private IDictionary<string, JToken> _properties;

        /// <summary>
        /// Initializes a new instance of the <see cref="GenericCheckDetails"/> class
        /// during JSON deserialization.
        /// </summary>
        [JsonConstructor]
        protected GenericCheckDetails()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GenericCheckDetails"/> class
        /// with the specified properties.
        /// </summary>
        /// <param name="properties">A collection of configuration properties for the check.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="properties"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="properties"/> contains a <see langword="null"/> or empty key.</exception>
        public GenericCheckDetails(IDictionary<string, JToken> properties)
        {
            if (properties == null)
                throw new ArgumentNullException("properties");
            if (properties.ContainsKey(string.Empty))
                throw new ArgumentException("properties cannot contain any empty keys", "properties");

            _properties = properties;
        }

        /// <summary>
        /// Gets a collection of configuration properties for the check.
        /// </summary>
        public ReadOnlyDictionary<string, JToken> Properties
        {
            get
            {
                return new ReadOnlyDictionary<string, JToken>(_properties);
            }
        }

        /// <inheritdoc/>
        /// <remarks>
        /// This class can be used for any check type. Clients using this class are responsible
        /// for adding the necessary properties for their specific check type.
        /// </remarks>
        protected internal override bool SupportsCheckType(CheckTypeId checkTypeId)
        {
            return true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**starbase_id** | **Integer** | Unique ID for this starbase (POS) |
**type_id** | **Integer** | Starbase (POS) type |
**system_id** | **Integer** | The solar system this starbase (POS) is in, unanchored POSes have this information |
**moon_id** | **Integer** | The moon this starbase (POS) is anchored on, unanchored POSes do not have this information | [optional]
**state** | **String** | state string | [optional]
**unanchor_at** | **DateTime** | When the POS started unanchoring, for starbases (POSes) in unanchoring state | [optional]
**reinforced_until** | **DateTime** | When the POS will be out of reinforcement, for starbases (POSes) in reinforced state | [optional]
**onlined_since** | **DateTime** | When the POS onlined, for starbases (POSes) in online state | [optional]


text:
package org.apache.pig.backend.hadoop.executionengine.spark.converter;

import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.apache.pig.backend.hadoop.executionengine.spark.PairFlatMapFunctionAdapter;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkShims;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkUtil;
import org.apache.spark.api.java.function.Function2;
import scala.Tuple2;
import scala.runtime.AbstractFunction1;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.backend.hadoop.executionengine.spark.operator.POSampleSortSpark;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DefaultBagFactory;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.rdd.RDD;

/*
 sort the sample data and convert the sample data to the format (all,{(sampleEle1),(sampleEle2),...})
 */
@SuppressWarnings("serial")
public class SparkSampleSortConverter implements RDDConverter<Tuple, Tuple, POSampleSortSpark> {
    private static final Log LOG = LogFactory.getLog(SparkSampleSortConverter.class);
    private static TupleFactory tf = TupleFactory.getInstance();
    private static BagFactory bf = DefaultBagFactory.getInstance();

    @Override
    public RDD<Tuple> convert(List<RDD<Tuple>> predecessors, POSampleSortSpark sortOperator)
            throws IOException {
        SparkUtil.assertPredecessorSize(predecessors, sortOperator, 1);
        RDD<Tuple> rdd = predecessors.get(0);
        RDD<Tuple2<Tuple, Object>> rddPair = rdd.map(new ToKeyValueFunction(),
                SparkUtil.<Tuple, Object> getTuple2Manifest());

        JavaPairRDD<Tuple, Object> r = new JavaPairRDD<Tuple, Object>(rddPair,
                SparkUtil.getManifest(Tuple.class),
                SparkUtil.getManifest(Object.class));
         //sort sample data
        JavaPairRDD<Tuple, Object> sorted = r.sortByKey(true);
         //convert every element in sample data from element to (all, element) format
        JavaPairRDD<String, Tuple> mapped = sorted.mapPartitionsToPair(SparkShims.getInstance().pairFlatMapFunction(new AggregateFunction()));
        //use groupByKey to aggregate all values( the format will be ((all),{(sampleEle1),(sampleEle2),...} )
        JavaRDD<Tuple> groupByKey= mapped.groupByKey().map(new ToValueFunction());
        return  groupByKey.rdd();
    }

    private static class MergeFunction implements Function2<Tuple, Tuple, Tuple>
            , Serializable {

        @Override
        public Tuple call(Tuple v1, Tuple v2) {
                Tuple res = tf.newTuple();
                res.append(v1);
                res.append(v2);
                LOG.info("MergeFunction out:"+res);
                return res;
        }
    }

    // input: Tuple2<Tuple,Object>
    // output: Tuple2("all", Tuple)
    private static class AggregateFunction implements
            PairFlatMapFunctionAdapter<Iterator<Tuple2<Tuple, Object>>, String,Tuple>, Serializable {

        private class Tuple2TransformIterable implements Iterable<Tuple2<String,Tuple>> {

            Iterator<Tuple2<Tuple, Object>> in;

            Tuple2TransformIterable(Iterator<Tuple2<Tuple, Object>> input) {
                in = input;
            }

            public Iterator<Tuple2<String,Tuple>> iterator() {
                return new IteratorTransform<Tuple2<Tuple, Object>, Tuple2<String,Tuple>>(in) {
                    @Override
                    protected Tuple2<String,Tuple> transform(Tuple2<Tuple, Object> next) {
                        LOG.info("AggregateFunction in:"+ next._1()) ;
                        return new Tuple2<String,Tuple>("all",next._1());
                    }
                };
            }
        }

        @Override
        public Iterator<Tuple2<String, Tuple>> call(Iterator<Tuple2<Tuple, Object>> input) throws Exception {
            return new Tuple2TransformIterable(input).iterator();
        }

    }

    private static class ToValueFunction implements Function<Tuple2<String, Iterable<Tuple>>, Tuple> {
        @Override
        public Tuple call(Tuple2<String, Iterable<Tuple>> next) throws Exception {
            Tuple res = tf.newTuple();
            res.append(next._1());
            Iterator<Tuple> iter = next._2().iterator();
            DataBag bag = bf.newDefaultBag();
            while(iter.hasNext()) {
                bag.add(iter.next());
            }
            res.append(bag);
            LOG.info("ToValueFunction1 out:" + res);
            return res;
        }
    }

    private static class ToKeyValueFunction extends
            AbstractFunction1<Tuple, Tuple2<Tuple, Object>> implements
            Serializable {

        @Override
        public Tuple2<Tuple, Object> apply(Tuple t) {
            if (LOG.isDebugEnabled()) {
                LOG.info("Sort ToKeyValueFunction in " + t);
            }
            Tuple key = t;
            Object value = null;
            // (key, value)
            Tuple2<Tuple, Object> out = new Tuple2<Tuple, Object>(key, value);
            if (LOG.isDebugEnabled()) {
                LOG.info("Sort ToKeyValueFunction out " + out);
            }
            return out;
        }
    }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2005-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection
package mutable

import generic._

/** This class implements mutable sets using a hashtable.
 *  The iterator and all traversal methods of this class visit elements in the order they were inserted.
 *
 *  @author  Matthias Zenger
 *  @author  Martin Odersky
 *  @author  Pavel Pavlov
 *  @version 2.0, 31/12/2006
 *  @since   1
 *
 *  @tparam A     the type of the elements contained in this set.
 *
 *  @define Coll `LinkedHashSet`
 *  @define coll linked hash set
 *  @define thatinfo the class of the returned collection. In the standard library configuration,
 *    `That` is always `LinkedHashSet[B]` because an implicit of type `CanBuildFrom[LinkedHashSet, B, LinkedHashSet[B]]`
 *    is defined in object `LinkedHashSet`.
 *  @define bfinfo an implicit value of class `CanBuildFrom` which determines the
 *    result class `That` from the current representation type `Repr`
 *    and the new element type `B`. This is usually the `canBuildFrom` value
 *    defined in object `LinkedHashSet`.
 *  @define mayNotTerminateInf
 *  @define willNotTerminateInf
 *  @define orderDependent
 *  @define orderDependentFold
 */
@SerialVersionUID(1L)
class LinkedHashSet[A] extends AbstractSet[A]
                          with Set[A]
                          with GenericSetTemplate[A, LinkedHashSet]
                          with SetLike[A, LinkedHashSet[A]]
                          with HashTable[A, LinkedHashSet.Entry[A]]
                          with Serializable
{
  override def companion: GenericCompanion[LinkedHashSet] = LinkedHashSet

  type Entry = LinkedHashSet.Entry[A]

  @transient protected var firstEntry: Entry = null
  @transient protected var lastEntry: Entry = null

  override def size: Int = tableSize

  def contains(elem: A): Boolean = findEntry(elem) ne null

  @deprecatedOverriding("+= should not be overridden so it stays consistent with add.", "2.11.0")
  def += (elem: A): this.type = { add(elem); this }

  @deprecatedOverriding("-= should not be overridden so it stays consistent with remove.", "2.11.0")
  def -= (elem: A): this.type = { remove(elem); this }

  override def add(elem: A): Boolean = findOrAddEntry(elem, null) eq null

  override def remove(elem: A): Boolean = {
    val e = removeEntry(elem)
    if (e eq null) false
    else {
      if (e.earlier eq null) firstEntry = e.later
      else e.earlier.later = e.later
      if (e.later eq null) lastEntry = e.earlier
      else e.later.earlier = e.earlier
      e.earlier = null // Null references to prevent nepotism
      e.later = null
      true
    }
  }

  def iterator: Iterator[A] = new AbstractIterator[A] {
    private var cur = firstEntry
    def hasNext = cur ne null
    def next =
      if (hasNext) { val res = cur.key; cur = cur.later; res }
      else Iterator.empty.next()
  }

  override def foreach[U](f: A => U) {
    var cur = firstEntry
    while (cur ne null) {
      f(cur.key)
      cur = cur.later
    }
  }

  protected override def foreachEntry[U](f: Entry => U) {
    var cur = firstEntry
    while (cur ne null) {
      f(cur)
      cur = cur.later
    }
  }

  protected def createNewEntry[B](key: A, dummy: B): Entry = {
    val e = new Entry(key)
    if (firstEntry eq null) firstEntry = e
    else { lastEntry.later = e; e.earlier = lastEntry }
    lastEntry = e
    e
  }

  override def clear() {
    clearTable()
    firstEntry = null
    lastEntry = null
  }

  private def writeObject(out: java.io.ObjectOutputStream) {
    serializeTo(out, { e => out.writeObject(e.key) })
  }

  private def readObject(in: java.io.ObjectInputStream) {
    firstEntry = null
    lastEntry = null
    init(in, createNewEntry(in.readObject().asInstanceOf[A], null))
  }
}

/** $factoryInfo
 *  @define Coll `LinkedHashSet`
 *  @define coll linked hash set
 */
object LinkedHashSet extends MutableSetFactory[LinkedHashSet] {
  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinkedHashSet[A]] = setCanBuildFrom[A]
  override def empty[A]: LinkedHashSet[A] = new LinkedHashSet[A]

  /** Class for the linked hash set entry, used internally.
   *  @since 2.10
   */
  private[scala] final class Entry[A](val key: A) extends HashEntry[A, Entry[A]] with Serializable {
    var earlier: Entry[A] = null
    var later: Entry[A] = null
  }
}


text:
def tags_to_dict(tags_json):
    d = {}
    if tags_json:
        for tag in tags_json:
            d[tag['Key']] = tag['Value']
    return d

def dict_to_tags(d):
    tags = list()
    for key, value in d.iteritems():
        tags.append({'Key': key, 'Value': value})
    return tags

def get_value(tags_json, key, default=None):
    return tags_to_dict(tags_json).get(key, default)

def set_value(tags_json, key, value):
    # Tag already exists.
    for t in tags_json:
        if t['Key'] == key:
            t['Value'] = value
            return

    # Set the tag for the first time.
    tags_json.append({'Key': key, 'Value': value})


text:
Audio Notes
===

Provides note frequencies for equal-tempered scale.

Available on [NPM](https://npmjs.org/package/audio-notes).

**CommonJS-ready** or standalone `window.AudioNotes`.

Usage:

With NodeJS or browserify:

```javascript
var AudioNotes = require("audio-notes");
```

With standalone script embedding:

```javascript
var AudioNotes = window.AudioNotes;
```

Conventions
===

You can access notes with two conventions:

by note name
---

You can access the note frequency with its name (English notation).

Major notes use a upper-case where minor (sharp) notes use the lower-case convention.
Then we add the octave number.

**Exemple:**

`AudioNotes.A4` is a **A** (*la* in solfège) of the 4th octave (A4 is 440 Hz).

`AudioNotes.a4` is a **A#** (*la#* in solfège) of the 4th octave (A4 is ~ 466.16 Hz).

The 12 notes of one octaves are: `C c D d E F f G g A a B`.

by MIDI value
---

You can also access a note by index:

`AudioNotes[57]` is the 57th notes of a midi keyboard, it is A4 .

Examples
===

```javascript
var melody;
with (AudioNotes) {
  melody = [ C4, C5, A4, E4, b3 ];
}
```


text:
package com.pholser.junit.quickcheck.generator.java.util.function;

import java.util.function.ToLongBiFunction;

import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.experimental.results.PrintableResult.*;
import static org.junit.experimental.results.ResultMatchers.*;

public class ToLongBiFunctionPropertyParameterTest {
    @Test public void unresolvedTypes() {
        assertThat(testResult(Unresolved.class), isSuccessful());
    }

    @RunWith(JUnitQuickcheck.class)
    public static class Unresolved<T, U> {
        @Property public void typesAreOk(
            ToLongBiFunction<? super T, ? super U> f,
            T first,
            U second) {

            long result = f.applyAsLong(first, second);
        }
    }
}


text:
When a planet orbits a star, they do so around a mutual
[center of mass](https://en.wikipedia.org/wiki/Center_of_mass). Because of this
a star will wobble, i.e. it will appear to change its apparent position.

Similar with direct observation, we could try to observe the wobble of a star
directly. This method faces the same problems, i.e. the distances of the stars
are so immense, the wobble becomes all but undetectable.

So we will quickly move on to other methods.


text:
#include "sysdep.h"
#include "bfd.h"

#ifndef TARGET_LITTLE_SYM
#define TARGET_LITTLE_SYM  arm_pei_le_vec
#define TARGET_LITTLE_NAME "pei-arm-little"
#define TARGET_BIG_SYM     arm_pei_be_vec
#define TARGET_BIG_NAME    "pei-arm-big"
#endif

#define COFF_IMAGE_WITH_PE
#define COFF_WITH_PE
#define PCRELOFFSET	   TRUE
/* Long section names not allowed in executable images, only object files.  */
#define COFF_LONG_SECTION_NAMES 0

#define COFF_SECTION_ALIGNMENT_ENTRIES \
{ COFF_SECTION_NAME_EXACT_MATCH (".bss"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".data"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".rdata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".text"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".idata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_EXACT_MATCH (".pdata"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 2 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".debug"), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 0 }, \
{ COFF_SECTION_NAME_PARTIAL_MATCH (".gnu.linkonce.wi."), \
  COFF_ALIGNMENT_FIELD_EMPTY, COFF_ALIGNMENT_FIELD_EMPTY, 0 }

#include "coff-arm.c"


text:
class Menux
{
private:
	string datum;
	double numericDatum;
	Stack<double> P1;
	Stack<double> P2;
	double Num1;
	double Num2;
	double Num3;

public:
	Menux(void);
	~Menux(void);

	void execute();
	bool isNumber(string number);
	void list();
};


text:
package curse

import (
	"log"
	"net/url"

	curse "github.com/founderio/curse-parser"
)

// This example illustrates fetching & parsing of a Curse page
func Example_curse() {
	projectURL := "https://mods.curse.com/mc-mods/minecraft/238424-taam"
	// Fetch the page content
	resp, err := curse.FetchPage(projectURL)
	if err != nil {
		log.Fatal("error fetching page:", err)
	}

	// Parse the page content
	// (URL is required for parsing some links or image URLs)
	results, err := curse.ParseCurse(projectURL, resp)
	if err != nil {
		log.Fatal("error parsing page:", err)
	}

	log.Println("The Curse project", results.Title, "was created at", results.Created)
	log.Println("Most recent update:", results.Updated)
	log.Println("View the CurseForge page at", results.CurseforgeURL.String())
	log.Println("Files:")

	for _, v := range results.Downloads {
		log.Println(v.Name, " - ", v.Date, " - for ", v.GameVersion)
	}

}

// This example illustrates fetching & parsing of a CurseForge page
func Example_curseForge() {
	// CurseForge parse expects URLs
	projectURL, err := url.Parse("https://minecraft.curseforge.com/projects/taam")
	if err != nil {
		log.Fatal("error parsing URL:", err)
	}

	log.Println("Fetching Pages...")

	// This will parse the overview page and the files page using default options.
	// That means, the file parse will parse ALL file pages! Use curse.CFOptionFilesNoPagination to prevent that.
	results, err := curse.FetchCurseForge(projectURL, curse.CFSectionOverview|curse.CFSectionFiles, curse.CFOptionNone)
	if err != nil {
		log.Fatal("error fetching CurseForge project:", err)
	}

	log.Println("The CurseForge project", results.Title, "was created at", results.Created)
	log.Println("Most recent update:", results.Updated)
	log.Println("Files:")

	for _, v := range results.Downloads {
		log.Println(v.Name, " - ", v.Date, " - for ", v.GameVersion)
	}

}


text:
package org.elasticsearch.client.ml.inference;

import org.elasticsearch.Version;
import org.elasticsearch.client.common.TimeUtil;
import org.elasticsearch.client.ml.inference.trainedmodel.InferenceConfig;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.client.ml.inference.NamedXContentObjectHelper.writeNamedObject;

public class TrainedModelConfig implements ToXContentObject {

    public static final String NAME = "trained_model_config";

    public static final ParseField MODEL_ID = new ParseField("model_id");
    public static final ParseField CREATED_BY = new ParseField("created_by");
    public static final ParseField VERSION = new ParseField("version");
    public static final ParseField DESCRIPTION = new ParseField("description");
    public static final ParseField CREATE_TIME = new ParseField("create_time");
    public static final ParseField DEFINITION = new ParseField("definition");
    public static final ParseField COMPRESSED_DEFINITION = new ParseField("compressed_definition");
    public static final ParseField TAGS = new ParseField("tags");
    public static final ParseField METADATA = new ParseField("metadata");
    public static final ParseField INPUT = new ParseField("input");
    public static final ParseField ESTIMATED_HEAP_MEMORY_USAGE_BYTES = new ParseField("estimated_heap_memory_usage_bytes");
    public static final ParseField ESTIMATED_OPERATIONS = new ParseField("estimated_operations");
    public static final ParseField LICENSE_LEVEL = new ParseField("license_level");
    public static final ParseField DEFAULT_FIELD_MAP = new ParseField("default_field_map");
    public static final ParseField INFERENCE_CONFIG = new ParseField("inference_config");

    public static final ObjectParser<Builder, Void> PARSER = new ObjectParser<>(NAME,
            true,
            TrainedModelConfig.Builder::new);
    static {
        PARSER.declareString(TrainedModelConfig.Builder::setModelId, MODEL_ID);
        PARSER.declareString(TrainedModelConfig.Builder::setCreatedBy, CREATED_BY);
        PARSER.declareString(TrainedModelConfig.Builder::setVersion, VERSION);
        PARSER.declareString(TrainedModelConfig.Builder::setDescription, DESCRIPTION);
        PARSER.declareField(TrainedModelConfig.Builder::setCreateTime,
            (p, c) -> TimeUtil.parseTimeFieldToInstant(p, CREATE_TIME.getPreferredName()),
            CREATE_TIME,
            ObjectParser.ValueType.VALUE);
        PARSER.declareObject(TrainedModelConfig.Builder::setDefinition,
            (p, c) -> TrainedModelDefinition.fromXContent(p),
            DEFINITION);
        PARSER.declareString(TrainedModelConfig.Builder::setCompressedDefinition, COMPRESSED_DEFINITION);
        PARSER.declareStringArray(TrainedModelConfig.Builder::setTags, TAGS);
        PARSER.declareObject(TrainedModelConfig.Builder::setMetadata, (p, c) -> p.map(), METADATA);
        PARSER.declareObject(TrainedModelConfig.Builder::setInput, (p, c) -> TrainedModelInput.fromXContent(p), INPUT);
        PARSER.declareLong(TrainedModelConfig.Builder::setEstimatedHeapMemory, ESTIMATED_HEAP_MEMORY_USAGE_BYTES);
        PARSER.declareLong(TrainedModelConfig.Builder::setEstimatedOperations, ESTIMATED_OPERATIONS);
        PARSER.declareString(TrainedModelConfig.Builder::setLicenseLevel, LICENSE_LEVEL);
        PARSER.declareObject(TrainedModelConfig.Builder::setDefaultFieldMap, (p, c) -> p.mapStrings(), DEFAULT_FIELD_MAP);
        PARSER.declareNamedObject(TrainedModelConfig.Builder::setInferenceConfig,
            (p, c, n) -> p.namedObject(InferenceConfig.class, n, null),
            INFERENCE_CONFIG);
    }

    public static TrainedModelConfig fromXContent(XContentParser parser) throws IOException {
        return PARSER.parse(parser, null).build();
    }

    private final String modelId;
    private final String createdBy;
    private final Version version;
    private final String description;
    private final Instant createTime;
    private final TrainedModelDefinition definition;
    private final String compressedDefinition;
    private final List<String> tags;
    private final Map<String, Object> metadata;
    private final TrainedModelInput input;
    private final Long estimatedHeapMemory;
    private final Long estimatedOperations;
    private final String licenseLevel;
    private final Map<String, String> defaultFieldMap;
    private final InferenceConfig inferenceConfig;

    TrainedModelConfig(String modelId,
                       String createdBy,
                       Version version,
                       String description,
                       Instant createTime,
                       TrainedModelDefinition definition,
                       String compressedDefinition,
                       List<String> tags,
                       Map<String, Object> metadata,
                       TrainedModelInput input,
                       Long estimatedHeapMemory,
                       Long estimatedOperations,
                       String licenseLevel,
                       Map<String, String> defaultFieldMap,
                       InferenceConfig inferenceConfig) {
        this.modelId = modelId;
        this.createdBy = createdBy;
        this.version = version;
        this.createTime = createTime == null ? null : Instant.ofEpochMilli(createTime.toEpochMilli());
        this.definition = definition;
        this.compressedDefinition = compressedDefinition;
        this.description = description;
        this.tags = tags == null ? null : Collections.unmodifiableList(tags);
        this.metadata = metadata == null ? null : Collections.unmodifiableMap(metadata);
        this.input = input;
        this.estimatedHeapMemory = estimatedHeapMemory;
        this.estimatedOperations = estimatedOperations;
        this.licenseLevel = licenseLevel;
        this.defaultFieldMap = defaultFieldMap == null ? null : Collections.unmodifiableMap(defaultFieldMap);
        this.inferenceConfig = inferenceConfig;
    }

    public String getModelId() {
        return modelId;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public Version getVersion() {
        return version;
    }

    public String getDescription() {
        return description;
    }

    public Instant getCreateTime() {
        return createTime;
    }

    public List<String> getTags() {
        return tags;
    }

    public Map<String, Object> getMetadata() {
        return metadata;
    }

    public TrainedModelDefinition getDefinition() {
        return definition;
    }

    public String getCompressedDefinition() {
        return compressedDefinition;
    }

    public TrainedModelInput getInput() {
        return input;
    }

    public ByteSizeValue getEstimatedHeapMemory() {
        return estimatedHeapMemory == null ? null : new ByteSizeValue(estimatedHeapMemory);
    }

    public Long getEstimatedHeapMemoryBytes() {
        return estimatedHeapMemory;
    }

    public Long getEstimatedOperations() {
        return estimatedOperations;
    }

    public String getLicenseLevel() {
        return licenseLevel;
    }

    public Map<String, String> getDefaultFieldMap() {
        return defaultFieldMap;
    }

    public InferenceConfig getInferenceConfig() {
        return inferenceConfig;
    }

    public static Builder builder() {
        return new Builder();
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        if (modelId != null) {
            builder.field(MODEL_ID.getPreferredName(), modelId);
        }
        if (createdBy != null) {
            builder.field(CREATED_BY.getPreferredName(), createdBy);
        }
        if (version != null) {
            builder.field(VERSION.getPreferredName(), version.toString());
        }
        if (description != null) {
            builder.field(DESCRIPTION.getPreferredName(), description);
        }
        if (createTime != null) {
            builder.timeField(CREATE_TIME.getPreferredName(), CREATE_TIME.getPreferredName() + "_string", createTime.toEpochMilli());
        }
        if (definition != null) {
            builder.field(DEFINITION.getPreferredName(), definition);
        }
        if (tags != null) {
            builder.field(TAGS.getPreferredName(), tags);
        }
        if (metadata != null) {
            builder.field(METADATA.getPreferredName(), metadata);
        }
        if (input != null) {
            builder.field(INPUT.getPreferredName(), input);
        }
        if (estimatedHeapMemory != null) {
            builder.field(ESTIMATED_HEAP_MEMORY_USAGE_BYTES.getPreferredName(), estimatedHeapMemory);
        }
        if (estimatedOperations != null) {
            builder.field(ESTIMATED_OPERATIONS.getPreferredName(), estimatedOperations);
        }
        if (compressedDefinition != null) {
            builder.field(COMPRESSED_DEFINITION.getPreferredName(), compressedDefinition);
        }
        if (licenseLevel != null) {
            builder.field(LICENSE_LEVEL.getPreferredName(), licenseLevel);
        }
        if (defaultFieldMap != null) {
            builder.field(DEFAULT_FIELD_MAP.getPreferredName(), defaultFieldMap);
        }
        if (inferenceConfig != null) {
            writeNamedObject(builder, params, INFERENCE_CONFIG.getPreferredName(), inferenceConfig);
        }
        builder.endObject();
        return builder;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TrainedModelConfig that = (TrainedModelConfig) o;
        return Objects.equals(modelId, that.modelId) &&
            Objects.equals(createdBy, that.createdBy) &&
            Objects.equals(version, that.version) &&
            Objects.equals(description, that.description) &&
            Objects.equals(createTime, that.createTime) &&
            Objects.equals(definition, that.definition) &&
            Objects.equals(compressedDefinition, that.compressedDefinition) &&
            Objects.equals(tags, that.tags) &&
            Objects.equals(input, that.input) &&
            Objects.equals(estimatedHeapMemory, that.estimatedHeapMemory) &&
            Objects.equals(estimatedOperations, that.estimatedOperations) &&
            Objects.equals(licenseLevel, that.licenseLevel) &&
            Objects.equals(defaultFieldMap, that.defaultFieldMap) &&
            Objects.equals(inferenceConfig, that.inferenceConfig) &&
            Objects.equals(metadata, that.metadata);
    }

    @Override
    public int hashCode() {
        return Objects.hash(modelId,
            createdBy,
            version,
            createTime,
            definition,
            compressedDefinition,
            description,
            tags,
            estimatedHeapMemory,
            estimatedOperations,
            metadata,
            licenseLevel,
            input,
            inferenceConfig,
            defaultFieldMap);
    }

    public static class Builder {

        private String modelId;
        private String createdBy;
        private Version version;
        private String description;
        private Instant createTime;
        private Map<String, Object> metadata;
        private List<String> tags;
        private TrainedModelDefinition definition;
        private String compressedDefinition;
        private TrainedModelInput input;
        private Long estimatedHeapMemory;
        private Long estimatedOperations;
        private String licenseLevel;
        private Map<String, String> defaultFieldMap;
        private InferenceConfig inferenceConfig;

        public Builder setModelId(String modelId) {
            this.modelId = modelId;
            return this;
        }

        private Builder setCreatedBy(String createdBy) {
            this.createdBy = createdBy;
            return this;
        }

        private Builder setVersion(Version version) {
            this.version = version;
            return this;
        }

        private Builder setVersion(String version) {
            return this.setVersion(Version.fromString(version));
        }

        public Builder setDescription(String description) {
            this.description = description;
            return this;
        }

        private Builder setCreateTime(Instant createTime) {
            this.createTime = createTime;
            return this;
        }

        public Builder setTags(List<String> tags) {
            this.tags = tags;
            return this;
        }

        public Builder setTags(String... tags) {
            return setTags(Arrays.asList(tags));
        }

        public Builder setMetadata(Map<String, Object> metadata) {
            this.metadata = metadata;
            return this;
        }

        public Builder setDefinition(TrainedModelDefinition.Builder definition) {
            this.definition = definition == null ? null : definition.build();
            return this;
        }

        public Builder setCompressedDefinition(String compressedDefinition) {
            this.compressedDefinition = compressedDefinition;
            return this;
        }

        public Builder setDefinition(TrainedModelDefinition definition) {
            this.definition = definition;
            return this;
        }

        public Builder setInput(TrainedModelInput input) {
            this.input = input;
            return this;
        }

        private Builder setEstimatedHeapMemory(Long estimatedHeapMemory) {
            this.estimatedHeapMemory = estimatedHeapMemory;
            return this;
        }

        private Builder setEstimatedOperations(Long estimatedOperations) {
            this.estimatedOperations = estimatedOperations;
            return this;
        }

        private Builder setLicenseLevel(String licenseLevel) {
            this.licenseLevel = licenseLevel;
            return this;
        }

        public Builder setDefaultFieldMap(Map<String, String> defaultFieldMap) {
            this.defaultFieldMap = defaultFieldMap;
            return this;
        }

        public Builder setInferenceConfig(InferenceConfig inferenceConfig) {
            this.inferenceConfig = inferenceConfig;
            return this;
        }

        public TrainedModelConfig build() {
            return new TrainedModelConfig(
                modelId,
                createdBy,
                version,
                description,
                createTime,
                definition,
                compressedDefinition,
                tags,
                metadata,
                input,
                estimatedHeapMemory,
                estimatedOperations,
                licenseLevel,
                defaultFieldMap,
                inferenceConfig);
        }
    }

}


text:
/**
 * @fileoverview Config file operations. This file must be usable in the browser,
 * so no Node-specific code can be here.
 * @author Nicholas C. Zakas
 */
"use strict";

//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------

const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
    RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
        map[value] = index;
        return map;
    }, {}),
    VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = {

    /**
     * Normalizes the severity value of a rule's configuration to a number
     * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
     * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
     * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
     * whose first element is one of the above values. Strings are matched case-insensitively.
     * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
     */
    getRuleSeverity(ruleConfig) {
        const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;

        if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
            return severityValue;
        }

        if (typeof severityValue === "string") {
            return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
        }

        return 0;
    },

    /**
     * Converts old-style severity settings (0, 1, 2) into new-style
     * severity settings (off, warn, error) for all rules. Assumption is that severity
     * values have already been validated as correct.
     * @param {Object} config The config object to normalize.
     * @returns {void}
     */
    normalizeToStrings(config) {

        if (config.rules) {
            Object.keys(config.rules).forEach(ruleId => {
                const ruleConfig = config.rules[ruleId];

                if (typeof ruleConfig === "number") {
                    config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
                } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
                    ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
                }
            });
        }
    },

    /**
     * Determines if the severity for the given rule configuration represents an error.
     * @param {int|string|Array} ruleConfig The configuration for an individual rule.
     * @returns {boolean} True if the rule represents an error, false if not.
     */
    isErrorSeverity(ruleConfig) {
        return module.exports.getRuleSeverity(ruleConfig) === 2;
    },

    /**
     * Checks whether a given config has valid severity or not.
     * @param {number|string|Array} ruleConfig The configuration for an individual rule.
     * @returns {boolean} `true` if the configuration has valid severity.
     */
    isValidSeverity(ruleConfig) {
        let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;

        if (typeof severity === "string") {
            severity = severity.toLowerCase();
        }
        return VALID_SEVERITIES.indexOf(severity) !== -1;
    },

    /**
     * Checks whether every rule of a given config has valid severity or not.
     * @param {Object} config The configuration for rules.
     * @returns {boolean} `true` if the configuration has valid severity.
     */
    isEverySeverityValid(config) {
        return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId]));
    },

    /**
     * Normalizes a value for a global in a config
     * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
     * a global directive comment
     * @returns {("readable"|"writeable"|"off")} The value normalized as a string
     * @throws Error if global value is invalid
     */
    normalizeConfigGlobal(configuredValue) {
        switch (configuredValue) {
            case "off":
                return "off";

            case true:
            case "true":
            case "writeable":
            case "writable":
                return "writable";

            case null:
            case false:
            case "false":
            case "readable":
            case "readonly":
                return "readonly";

            default:
                throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
        }
    }
};


text:
(function() {

	var win = Titanium.UI.createWindow({
	  title: 'Main Window'
	});

	// bottom view stuff
	var bottomView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height:Ti.UI.FILL,
		backgroundColor:'#ccc',
		layout:'vertical'
	});

	win.add(bottomView);

	// create a few list items
	function createListItem(i) {
		var listLbl = Ti.UI.createLabel({
		  color: '#292929',
		  font: { fontSize:20, fontWeight:200 },
		  text: 'List item ' + i,
		  textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT,
		  top:( i == 1 ) ? 30 : 20,
		  left: 10,
		  id:'triggerClick' // need this for click event later
		});

		return listLbl;
	}

	for(var i=1; i < 6; i++) {
		bottomView.add(createListItem(i));
	}

	// Top View Stuff
	var topView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height:Ti.UI.FILL,
		left:0,
		backgroundColor:'#999',
		open:false
	});

	win.add(topView);

	var toggleMenuBtn = Titanium.UI.createView({
	   top:26,
	   left:8,
	   width:44,
	   height:44,
	   borderRadius:4,
	   backgroundColor:'#656565'
	});

	topView.add(toggleMenuBtn);

	// animations we need
	var slideOpenAnimation = Titanium.UI.createAnimation({
		left: Ti.Platform.displayCaps.platformWidth - 58, // device width minus 60pts
		duration:300,
		curve: Titanium.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	var slideClosedAnimation = Titanium.UI.createAnimation({
		left:0,
		duration:300,
		curve: Titanium.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	// button actions
	toggleMenuBtn.addEventListener('click',function(e) {
		if (topView.open == false) {
			  topView.animate(slideOpenAnimation);
	  		  topView.open = true;
		} else {
			  topView.animate(slideClosedAnimation);
	  		  topView.open = false;
		}
	});

	// close menu on item click actions
	bottomView.addEventListener('click',function(e) {
		if (e.source.id == 'triggerClick') {
		  topView.animate(slideClosedAnimation);
		  topView.open = false;
		}
	});

	// open the window
	win.open();

})();


text:
describe('Gamepad', function() {

    it('should initialize all submodules', function() {
        // implement
    });

    it('should attach event handlers to the window', function () {

    })

    it('should not throw an error while updating', function () {

    })

});


text:
import React, { Component, PropTypes } from 'react';
import ReactTooltip from 'react-tooltip';

// components
import Input from './Input';
import CustomTextArea from './CustomTextArea';
import AsyncButton from '../components/AsyncButton';

// libs
import formatCurrency from '../lib/format_currency';

class AddFundsForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
      areFundsFromHost: true,
      amount: 0,
      fees: 0,
    }
  }

  render() {
    const { attributes, validationError, inProgress, collective, onChange, i18n, onSubmit, host } = this.props;

    const amountPlaceholder = formatCurrency(0, collective.currency);
    const userString = host.name ? `${host.name} (${host.email})` : host.email;
    const netAmount = formatCurrency(this.state.amount + this.state.fees, collective.currency);
    const amountStringInNotice = this.state.amount > 0 ? `(${netAmount})` : 'funds';

    return (

{i18n.getString('addFunds')}

As the host, you can add funds to {collective.name}. The funds will show up immediately in the collective's balance as a donation.

add funds details

            {i18n.getString('amount')}
            <Input
              customClass='js-transaction-amount'
              placeholder={amountPlaceholder}
              hasError={validationError.amount}
              value={attributes.amountText}
              handleChange={amountText => {
                onChange({amountText});
                this.onAmountChange(amountText, attributes.fundsFromHost);
              }} />
            {i18n.getString('title')}
            <Input
              customClass='js-transaction-title'
              placeholder='ex: T-shirt sales from Threadless'
              hasError={validationError.description}
              value={attributes.description}
              handleChange={description => onChange({description})} />

            {i18n.getString('notes')}
            <CustomTextArea
              rows={5}
              resize='vertical'
              customClass='js-transaction-notes'
              placeholder='Optional: amount earned by collective from June t-shirt sales'
              hasError={validationError.privateMessage}
              value={attributes.privateMessage}
              onChange={privateMessage => onChange({privateMessage})}
              />

donor's information

        {attributes.fundsFromHost &&

             {userString}  Change source

}

        {!attributes.fundsFromHost &&

            Tell us who these funds are from.  Keep { host.name || host.email } as the donor

              {i18n.getString('name')}
              <Input
                customClass='js-transaction-name'
                hasError={validationError.name}
                value={attributes.name}
                handleChange={name => onChange({name})} />

              {i18n.getString('email')}
              <Input
                customClass='js-transaction-email'
                hasError={validationError.email}
                value={attributes.email}
                handleChange={email => onChange({email})} />

}

funds breakdown (in USD)

             Funding amount:
             {formatCurrency(this.state.amount, collective.currency)}

             Host fees {collective.hostFeePercent}%: <ReactTooltip effect='solid' border={true} place='right' />
             {formatCurrency(this.state.fees, collective.currency)}

             Net amount: <ReactTooltip effect='solid' border={true} place='right' />
             {netAmount}

By clicking below, you agree to set aside { amountStringInNotice } in your bank account on behalf of the collective.

        <AsyncButton
          color='green'
          inProgress={inProgress}
          onClick={onSubmit.bind(this)}>
          {i18n.getString('addFunds')}
        </AsyncButton>

    )
  }

  switchState() {
    const updatedAreFundsFromDefaultUser = !this.props.attributes.fundsFromHost;
    this.props.onChange({fundsFromHost: updatedAreFundsFromDefaultUser});
    this.onAmountChange(null, updatedAreFundsFromDefaultUser);
  }

  onAmountChange(updatedAmountText, areFundsFromDefaultUser) {
    let amount;
    if (updatedAmountText) {
      amount = Math.round(100 * updatedAmountText);
    } else if (updatedAmountText === '') {
      amount = 0
    } else {
      amount = this.state.amount
    }
    const addFees = !areFundsFromDefaultUser;

    this.setState({
      amount: (amount === '' || isNaN(amount)) ? 0 : amount,
      fees: (addFees && !isNaN(amount)) ? -1*this.props.collective.hostFeePercent/100*amount : 0
    });
  }

}

AddFundsForm.propTypes = {
  onCancel: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired,
  i18n: PropTypes.object.isRequired,
  inProgress: PropTypes.bool.isRequired,
  collective: PropTypes.object.isRequired,
  validationError: PropTypes.object.isRequired,
  onChange: PropTypes.func.isRequired,
  attributes: PropTypes.object.isRequired,
  host: PropTypes.object
};

export default AddFundsForm;


text:
#include "stdafx.h"
#include "CrypToolApp.h"
#include "CrypToolBase.h"
#include "DlgHybridDecryptionDemo.h"

#include "DlgCertificateStoreAskForPassword.h"
#include "DlgCertificateStoreShowCertificateParametersAll.h"

#include "DialogeMessage.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

CDlgHybridDecryptionDemo::CDlgHybridDecryptionDemo(const CString &_documentFileName, const CString &_documentTitle, CWnd* pParent) :
	CDialog(CDlgHybridDecryptionDemo::IDD, pParent),
	m_documentFileName(_documentFileName),
	m_documentTitle(_documentTitle),
	m_byteLengthSessionKey(16),
	m_selectedCertificateSerial(0),
	m_selectedCertificatePassword(""),
	step(0) {

}

CDlgHybridDecryptionDemo::~CDlgHybridDecryptionDemo() {

}

BOOL CDlgHybridDecryptionDemo::OnInitDialog() {
	CDialog::OnInitDialog();
	// the first thing we want to do is parse the document specified at construction
	// for hybrid-encrypted data; if the following function returns false (which is
	// indicating the data could not be extracted), we dump and error and close the
	// dialog on the spot
	CrypTool::Cryptography::Asymmetric::AsymmetricAlgorithmType asymmetricAlgorithmType;
	CrypTool::Cryptography::Symmetric::SymmetricAlgorithmType symmetricAlgorithmType;
	if(!CrypTool::Utilities::parseHybridEncryptedFile(m_documentFileName, m_selectedCertificateSerial, asymmetricAlgorithmType, symmetricAlgorithmType, m_byteStringSymmetricKeyEncrypted, m_byteStringCipherText)) {
		Message(IDS_STRING_HYBRID_DEC_MSG9, MB_ICONSTOP);
		EndDialog(IDOK);
	}
	// initialize user interface
	m_FlushDecDataCtrl.EnableWindow(FALSE);
	m_ShowCertificate.EnableWindow(FALSE);
	LOGFONT LogFont;
	char DefaultFontName[32];
	LONG defaultFontWeight;
	CFont *defaultFont = m_ContinueButtonCtrl.GetFont();
	defaultFont->GetLogFont(&LogFont); // Default Systemschrift ermitteln
	strncpy(DefaultFontName, LogFont.lfFaceName, 32); // Default Wert sichern
	defaultFontWeight = LogFont.lfWeight; // Default Wert sichern
	LogFont.lfWeight = FW_BOLD; // Auf Fettdruck umstellen
	m_Font.CreateFontIndirect(&LogFont); // Font initialisieren
	m_TextSignStepsCtrl.SetFont(&m_Font);
	m_StepCtrl.SetFont(&m_Font);
	LogFont.lfWeight = defaultFontWeight; // Auf default Wert zurückstellen
	strncpy(LogFont.lfFaceName, "Courier", 32); // Auf Courier umstellen
	m_Font2.CreateFontIndirect(&LogFont); // Font2 initialisieren
	m_DisplayDataCtrl.SetFont(&m_Font2);
	m_TextSignSteps.LoadString(IDS_STRING_HYBRID_DEC_STEP);
	UpdateDataDisplay();
	UpdateData(FALSE);
	return TRUE;
}

void CDlgHybridDecryptionDemo::DoDataExchange(CDataExchange* pDX) {
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_SHOW_STEPS, m_DisplayDataCtrl);
	DDX_Control(pDX, IDC_EDIT4, m_StepCtrl);
	DDX_Control(pDX, IDC_EDIT3, m_TextSignStepsCtrl);
	DDX_Control(pDX, IDOK, m_FlushDecDataCtrl);
	DDX_Control(pDX, IDC_BUTTON_CONTINUE, m_ContinueButtonCtrl);
	DDX_Control(pDX, IDC_SHOW_CERTIFICATE, m_ShowCertificate);
	DDX_Text(pDX, IDC_EDIT3, m_TextSignSteps);
	DDX_Text(pDX, IDC_EDIT4, m_Step);
	DDX_Text(pDX, IDC_EDIT_SHOW_STEPS, m_DisplayData);
}

void CDlgHybridDecryptionDemo::OnOK() {
	// here we decrypt the cipher text using the symmetric key
	SHOW_HOUR_GLASS
	CrypTool::Cryptography::Symmetric::SymmetricOperation operation(CrypTool::Cryptography::Symmetric::SYMMETRIC_ALGORITHM_TYPE_AES, CrypTool::Cryptography::Symmetric::SYMMETRIC_OPERATION_TYPE_DECRYPTION);
	operation.executeOnByteStrings(m_byteStringCipherText, m_byteStringSymmetricKey, m_byteStringPlainText);
	// create a temporary file name for the plain text
	const CString documentFileName = CrypTool::Utilities::createTemporaryFile();
	// write plain text to the created file
	m_byteStringPlainText.writeToFile(documentFileName);
	// fire up new document
	CString title;
	title.Format(IDS_STRING_HYBRID_DEC_TITLE, m_documentFileName);
	theApp.ThreadOpenDocumentFileNoMRU(documentFileName, title, (char*)(LPCTSTR)(m_byteStringSymmetricKey.toString(16)));
	HIDE_HOUR_GLASS
	CDialog::OnOK();
}

void CDlgHybridDecryptionDemo::OnCancel() {
	CDialog::OnCancel();
}

void CDlgHybridDecryptionDemo::OnButtonContinue() {
	nFirstVisibleLine = m_DisplayDataCtrl.GetFirstVisibleLine();
	UpdateDataDisplay();
}

void CDlgHybridDecryptionDemo::OnButtonShowCertificate() {
	// retrieve both public and private parameters for the certificate
	CString publicParameters;
	CString privateParameters;
	CrypTool::Cryptography::Asymmetric::CertificateStore::instance().getUserCertificatePublicParameters(m_selectedCertificateSerial, publicParameters);
	CrypTool::Cryptography::Asymmetric::CertificateStore::instance().getUserCertificatePrivateParameters(m_selectedCertificateSerial, m_selectedCertificatePassword, privateParameters);
	// show all parameters to the user
	CDlgCertificateStoreShowCertificateParametersAll dlgCertificateStoreShowCertificateParametersAll;
	dlgCertificateStoreShowCertificateParametersAll.setPublicParameters(publicParameters);
	dlgCertificateStoreShowCertificateParametersAll.setPrivateParameters(privateParameters);
	dlgCertificateStoreShowCertificateParametersAll.DoModal();
}

int CDlgHybridDecryptionDemo::UpdateDataDisplay() {
	// newline string for convenience
	const CString nl = "\r\n";
	// inherent step limit
	const int maxsteps = 3;

	if (step == 0) {
		// here the user is prompted to proceed with continue
		if (m_DisplayData="") {
			CString temp;
			temp.Format(IDS_STRING_HYBRID_DEC_MSG2);
			m_DisplayData += temp + nl;
			temp.Format(IDS_STRING_HYBRID_DEC_MSG12);
			m_DisplayData += temp + nl + nl;
		}
		nFirstVisibleLine = 0;
		step++;
		UpdateData(false);
		m_DisplayDataCtrl.LineScroll( step ? m_DisplayDataCtrl.GetLineCount() : 0 /* nFirstVisibleLine */ );
		UpdateData(true);
	}
	else if (step == 1) {
		// here the user is prompted to enter the password for the private key of the receiver
		CDlgCertificateStoreAskForPassword dlgCertificateStoreAskForPassword(m_selectedCertificateSerial);
		if (dlgCertificateStoreAskForPassword.DoModal() == IDOK) {
			m_selectedCertificatePassword = dlgCertificateStoreAskForPassword.getCertificatePassword();
			// here we try to acquire the private key (d) of the specified certificate
			// using the password the user was prompted to supply
			if (CrypTool::Cryptography::Asymmetric::CertificateStore::instance().getUserCertificateStringRSAPrivateKeyD(m_selectedCertificateSerial, m_selectedCertificatePassword, 10, sKeyPrivate)) {
				// update user interface
				CString temp;
				temp.Format(IDS_STRING_HYBRID_DEC_MSG13);
				m_DisplayData += temp + nl;
				temp.Format(IDS_STRING_HYBRID_DEC_MSG12);
				m_DisplayData += temp + nl;
				temp.Format(IDS_STRING_HYBRID_STEP_BY_STEP, step, maxsteps);
				m_Step = temp;
				step++;
				UpdateData(false);
				m_DisplayDataCtrl.LineScroll(step ? m_DisplayDataCtrl.GetLineCount() : 0 /* nFirstVisibleLine */);
				UpdateData(true);
				// enable the button for showing the certificate
				m_ShowCertificate.EnableWindow(true);
			}
		}
	}
	else if (step == 2) {
		// update user interface
		CString temp;
		temp.Format(IDS_STRING_HYBRID_DEC_MSG4);
		m_DisplayData += temp + sKeyPrivate + nl + nl + nl;
		temp.Format(IDS_STRING_HYBRID_DEC_MSG5);
		m_DisplayData += temp + nl;
		temp.Format(IDS_STRING_HYBRID_DEC_MSG12);
		m_DisplayData += temp;
		temp.Format(IDS_STRING_HYBRID_STEP_BY_STEP, step, maxsteps);
		m_Step = temp;
		step++;
		UpdateData(false);
		m_DisplayDataCtrl.LineScroll( step ? m_DisplayDataCtrl.GetLineCount() : 0 /* nFirstVisibleLine */ );
		UpdateData(true);
	}
	else if (step == 3) {
		// here we try to decrypt the encrypted session key (NO PADDING!)
		SHOW_HOUR_GLASS
		const bool padding = false;
		CrypTool::Cryptography::Asymmetric::AsymmetricOperationEncryptOrDecrypt operation(CrypTool::Cryptography::Asymmetric::ASYMMETRIC_ALGORITHM_TYPE_RSA, CrypTool::Cryptography::Asymmetric::ASYMMETRIC_OPERATION_TYPE_DECRYPTION, padding);
		const bool result = operation.executeOnByteStrings(m_byteStringSymmetricKeyEncrypted, m_selectedCertificateSerial, m_selectedCertificatePassword, m_byteStringSymmetricKey);
		HIDE_HOUR_GLASS
		// truncate session key to appropriate size (depends on the padding option)
		if (padding) m_byteStringSymmetricKey.truncateRight(m_byteLengthSessionKey);
		else m_byteStringSymmetricKey.truncateLeft(m_byteLengthSessionKey);
		// update user interface
		CString temp;
		temp.Format(IDS_STRING_HYBRID_DEC_MSG6);
		m_DisplayData += temp + m_byteStringSymmetricKey.toString(16, " ") + nl + nl;
		temp.Format(IDS_STRING_HYBRID_DEC_MSG7);
		m_DisplayData += temp + nl + nl;
		temp.Format(IDS_STRING_HYBRID_STEP_BY_STEP, step, maxsteps);
		m_Step = temp;
		m_ContinueButtonCtrl.EnableWindow(FALSE);
		m_FlushDecDataCtrl.EnableWindow(TRUE);
		m_FlushDecDataCtrl.SetFocus();
		step++;
		UpdateData(false);
		m_DisplayDataCtrl.LineScroll( step ? m_DisplayDataCtrl.GetLineCount() : 0 /* nFirstVisibleLine */ );
		UpdateData(true);
	}
	return 0;
}

BEGIN_MESSAGE_MAP(CDlgHybridDecryptionDemo, CDialog)
	ON_BN_CLICKED(IDC_BUTTON_CONTINUE, OnButtonContinue)
	ON_BN_CLICKED(IDC_SHOW_CERTIFICATE, OnButtonShowCertificate)
END_MESSAGE_MAP()


text:
import * as React from 'react';

import { connect, MapStateToProps, MapDispatchToPropsFunction } from 'react-redux';
import { NotFound } from '../shared/not_found';
import { deleteSubmission } from '../../actions/index';

const dateFormat = require('dateformat');

const mapStateToProps: MapStateToProps = ({ submissions }, { params }) => {
  return { submission: submissions.rows.find(submission => submission.id === params.submissionId), formId: params.formId };
}

const mapDispatchToProps: MapDispatchToPropsFunction = (dispatch, { params }) => ({
  deleteSubmission: (id, formId) => {
    if (window.confirm("Do you really want to delete?")) {
      dispatch(deleteSubmission(id, formId));
    }
  },
});

@connect(mapStateToProps, mapDispatchToProps)
export class ShowSubmission extends React.Component<any, any> {
  render() {
    const { submission, formId, deleteSubmission } = this.props;

    if (!submission) {
      return <NotFound message="Perhaps head back to the submission list?" />;
    }

    const createdAt = new Date(submission.created_at);
    const data = JSON.parse(submission.data);

    return (

          <time>Submitted on {dateFormat(createdAt, 'dd/mm/yy')} at {dateFormat(createdAt, 'HH:MM')}</time>

            <button type="button" className="flat danger" onClick={() => deleteSubmission(submission.id, formId)}>Delete</button>

          {
            Object.keys(data).map(field =>

{field}

{data[field]}

            )
          }

    );
  }
}


text:
$packageName = 'dolphin'
$url = 'http://dl.dolphin-emu.org/builds/dolphin-master-4.0-8888-x64.7z'
$checksum = 'eb00beccc2cca369c4d27f278bc1415664ad7650'
$checksumType = 'sha1'
$url64 = $url
$checksum64 = $checksum
$checksumType64 = $checksumType
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Url64bit "$url64" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType" `
                             -Checksum64 "$checksum64" `
                             -ChecksumType64 "$checksumType64"


text:
require 'spec_helper'

describe Splunker::Models::Finders do
  let(:resource) do
    Splunker::Models::Search::Saved
  end

  let(:search_fixture) do
    Nokogiri::XML(fixture("saved_search.xml"))
  end

  before(:each) do
    object_path = "saved/searches/MyFinderTestSavedSearch"
    resource.client.stub(:get).with(object_path,{}).and_return(search_fixture)
  end

  it "should find_by_id" do
    a = resource.find_by_id("MyFinderTestSavedSearch", {})
    a.should be_a(Splunker::Models::Search::Saved)
    a.title.should eq("MySavedSearch")
  end

  it "should find by id by default" do
    a = resource.find("MyFinderTestSavedSearch", {})
    a.should be_a(Splunker::Models::Search::Saved)
    a.title.should eq("MySavedSearch")
  end
end


text:
module Config where

import Data.Text

data Config
  = Config
  { configUsername :: Text
  , configHostname :: Text
  , configTeam     :: Text
  , configPort     :: Int
  , configPassword :: Text
  }


text:
package com.spatial4j.core.shape.impl;

import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Rectangle;

/**
 * INTERNAL: A numeric range between a pair of numbers.
 * Perhaps this class could become 1st class citizen extending Shape but not now.
 * Only public so is accessible from tests in another package.
 */
public class Range {
  protected final double min, max;

  public static Range xRange(Rectangle rect, SpatialContext ctx) {
    if (ctx.isGeo())
      return new LongitudeRange(rect.getMinX(), rect.getMaxX());
    else
      return new Range(rect.getMinX(), rect.getMaxX());
  }

  public static Range yRange(Rectangle rect, SpatialContext ctx) {
    return new Range(rect.getMinY(), rect.getMaxY());
  }

  public Range(double min, double max) {
    this.min = min;
    this.max = max;
  }

  public double getMin() {
    return min;
  }

  public double getMax() {
    return max;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Range range = (Range) o;

    if (Double.compare(range.max, max) != 0) return false;
    if (Double.compare(range.min, min) != 0) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result;
    long temp;
    temp = min != +0.0d ? Double.doubleToLongBits(min) : 0L;
    result = (int) (temp ^ (temp >>> 32));
    temp = max != +0.0d ? Double.doubleToLongBits(max) : 0L;
    result = 31 * result + (int) (temp ^ (temp >>> 32));
    return result;
  }

  @Override
  public String toString() {
    return "Range{" + min + " TO " + max + '}';
  }

  public double getWidth() {
    return max - min;
  }

  public boolean contains(double v) {
    return v >= min && v <= max;
  }

  public double getCenter() {
    return min + getWidth()/2;
  }

  public Range expandTo(Range other) {
    assert this.getClass() == other.getClass();
    return new Range(Math.min(min, other.min), Math.max(max, other.max));
  }

  public double deltaLen(Range other) {
    double min3 = Math.max(min, other.min);
    double max3 = Math.min(max, other.max);
    return max3 - min3;
  }

  public static class LongitudeRange extends Range {

    public static final LongitudeRange WORLD_180E180W = new LongitudeRange(-180, 180);

    public LongitudeRange(double min, double max) {
      super(min, max);
    }

    public LongitudeRange(Rectangle r) {
      super(r.getMinX(), r.getMaxX());
    }

    @Override
    public double getWidth() {
      double w = super.getWidth();
      if (w < 0)
        w += 360;
      return w;
    }

    @Override
    public boolean contains(double v) {
      if (!crossesDateline())
        return super.contains(v);
      return v >= min || v <= max;// the OR is the distinction from non-dateline cross
    }

    public boolean crossesDateline() {
      return min > max;
    }

    public double getCenter() {
      double ctr = super.getCenter();
      if (ctr > 180)
        ctr -= 360;
      return ctr;
    }

    public double compareTo(LongitudeRange b) {
      return diff(getCenter(), b.getCenter());
    }

    /** a - b (compareTo order).  < 0 if a < b */
    private static double diff(double a, double b) {
      double diff = a - b;
      if (diff <= 180) {
        if (diff >= -180)
          return diff;
        return diff + 360;
      } else {
        return diff - 360;
      }
    }

    @Override
    public Range expandTo(Range other) {
      return expandTo((LongitudeRange) other);
    }

    public LongitudeRange expandTo(LongitudeRange other) {
      LongitudeRange a, b;// a.ctr <= b.ctr
      if (this.compareTo(other) <= 0) {
        a = this;
        b = other;
      } else {
        a = other;
        b = this;
      }
      LongitudeRange newMin = b.contains(a.min) ? b : a;//usually 'a'
      LongitudeRange newMax = a.contains(b.max) ? a : b;//usually 'b'
      if (newMin == newMax)
        return newMin;
      if (newMin == b && newMax == a)
        return WORLD_180E180W;
      return new LongitudeRange(newMin.min, newMax.max);
    }
  }
}


text:
require 'ipaddr'

Puppet::Parser::Functions::newfunction(:tinc_cidr_to_netmask, :type => :rvalue, :doc => <<-EOF
This function takes a CIDR prefix (24) and returns a dotted netmask (255.255.255.0)
EOF
) do |args|
  raise Puppet::ParseError, "Wrong number of arguments" if args.to_a.length != 1
  cidr  = args.to_a[0].to_i

  netmask = IPAddr.new('255.255.255.255').mask(cidr).to_s

  return netmask
end


text:
import * as fs from 'fs-extra';
import * as Path from 'path';
import * as voca from 'voca';
import * as jsonfile from 'jsonfile';

const uglify = require('uglify-js');
const zlib = require('zlib');
const deepcopy = require('deepcopy');

import { root, FS_REF } from './fs';
import { PackageMetadata, LocalLibConfig } from './types';
import { libConfig, currentPackage } from './state';
import { normalizeLibExtension } from './config';

export function log(msg: string): void {
  process.stdout.write(msg + '\n');
}

/**
 * Returns the package name.
 * If scope exists, it will be added.
 *
 * This can also be used as a partial path from the src root.
 * @param name optional, if not set, the current dirName property from CURRENT_PACKAGE is taken
 * @return {string}
 */
export function getPackageName(name?: string) {
  if (!name) {
    if (!currentPackage()) {
      throw new Error('Invalid operation, name not supplied and CURRENT_PACKAGE is not set.');
    }
    name = currentPackage().dirName;
  }

  // if (libConfig.packages.indexOf(name) === -1) {
  //   throw new Error(`Invalid name: ${name} is not part of "libConfig.packages" in package.json`);
  // }

  const scope = libConfig.scope ? `${libConfig.scope}/` : '';
  return scope + name;
}

export function getPackageRoot(dirName: string, ...args: string[]): string {
  return root(FS_REF.SRC_CONTAINER, getPackageName(dirName), ...args);
}

/**
 * Returns the local (partial) package.json object of a package.
 * @param dirName
 * @return {any}
 */
export function getLocalPackageJSON(dirName: string): { [index: string]: any } & { libConfig: LocalLibConfig } {
  return jsonfile.readFileSync(root(FS_REF.SRC_CONTAINER, getPackageName(dirName), 'package.json'));
}

export function saveTempTsConfig(meta: PackageMetadata): void {
  jsonfile.writeFileSync(root(FS_REF.TS_CONFIG_TMP), meta.tsConfigObj, {spaces: 2});
}

export function resolveWebpackConfig(config: string | any, ...args: any[]): any {
  if(typeof config === 'string') {
    return resolveWebpackConfig(require(config), ...args);
  } else if (typeof config === 'function') {
    return config(...args);
  } else if (config.__esModule === true && !!config.default) {
    return resolveWebpackConfig(config.default, ...args);
  } else {
    return config;
  }
}

/**
 * Minify and gzip a umd bundle.
 *
 * The output files will sit along side the umd bundle.
 *
 * NOTE: this is a sync operation.
 *
 * @param destDir the destination directory
 * @param umd the umd name (from metadata, not the while filename) of the bundle
 */
export function minifyAndGzip(destDir: string, srcNameNoExt: string) {
  const unminified = fs.readFileSync(Path.join(destDir, `${srcNameNoExt}.js`)).toString();
  const minified = uglify.minify(unminified);
  const gzipBuffer = zlib.gzipSync(Buffer.from(minified.code));

  fs.writeFileSync(Path.join(destDir, `${srcNameNoExt}.min.js`), minified.code, 'utf-8');
  const zipStream = fs.createWriteStream(Path.join(destDir, `${srcNameNoExt}.js.gz`));
  zipStream.write(gzipBuffer);
  zipStream.end();

  const pct = num => 100 * Math.round(10000 * (1-num)) / 10000;

  console.log(`
          --------------------------------------
          UMD Bundle info: ${srcNameNoExt}
          --------------------------------------
          unminified: \t${unminified.length / 1000} KB
          minified: \t${minified.code.length / 1000} KB \t(${pct(minified.code.length / unminified.length)} %)
          gzipped: \t${gzipBuffer.length / 1000} KB \t(${pct(gzipBuffer.length / unminified.length)}) %, ${pct(gzipBuffer.length / minified.code.length)} %)
          --------------------------------------
        `);
}

export function getModuleName(dirName: string): string {
  const scope = libConfig.scope ? `${libConfig.scope}/` : '';
  return (scope ? scope.substr(1, scope.length - 2) + '.' : '') + voca.camelCase(dirName);
}

/**
 * Returns an alias list for webpack's configuration resolve property based on a packages list.
 * If no list supplied the whole list from package.json is used.
 * @param packages
 */
export function webpackAlias(...packages: string[]): { [id: string]: string } {
  if (packages.length === 0) {
    packages = libConfig.packages;
  }

  const scope = libConfig.scope ? `${libConfig.scope}/` : '';

  return packages.reduce((curr, pkg) => {
    const pkgJson = getLocalPackageJSON(pkg);
    const entry = pkgJson.libConfig && pkgJson.libConfig.entry || 'index';
    curr[scope + pkg + '$'] = `${scope + pkg}/src/${entry}.ts`;

    if (pkgJson.libConfig && Array.isArray(pkgJson.libConfig.libExtensions)) {
      pkgJson.libConfig.libExtensions.forEach( ext => {
        normalizeLibExtension(ext);
        // TODO: remove object 'ext', only string... move everything to local package.json of extension
        curr[`${scope + pkg}/${ext.dir}$`] = `${scope + pkg}/${ext.dir}/src/${ext.entry}`;
      });
    }

    return curr;
  }, {})
}

export function jestAlias(...packages: string[]): { [id: string]: string } {
  if (packages.length === 0) {
    packages = libConfig.packages;
  }

  const scope = libConfig.scope ? `${libConfig.scope}/` : '';

  return packages.reduce((curr, pkg) => {
    const pkgJson = getLocalPackageJSON(pkg);
    const entry = pkgJson.libConfig && pkgJson.libConfig.entry || 'index';
    curr[`^${scope + pkg}$`] = `<rootDir>/src/${scope + pkg}/src/${entry}.ts`;
    curr[`^${scope + pkg}/src/(.*)`] = `<rootDir>/src/${scope + pkg}/src/$1`;

    if (pkgJson.libConfig && Array.isArray(pkgJson.libConfig.libExtensions)) {
      pkgJson.libConfig.libExtensions.forEach( ext => {
        normalizeLibExtension(ext);
        // TODO: remove object 'ext', only string... move everything to local package.json of extension
        curr[`^${scope + pkg}/${ext.dir}$`] = `<rootDir>/src/${scope + pkg}/${ext.dir}/src/${ext.entry}`;
        curr[`^${scope + pkg}/${ext.dir}/src/(.*)`] = `<rootDir>/src/${scope + pkg}/${ext.dir}/src/$1`;
      });
    }

    return curr;
  }, {})
}

export type Promisify<T> = { promise: Promise<T>; resolve: (value?: T) => void; reject: (err: any) => void };

export function promisify<T>(): Promisify<T> {
  let resolve, reject;
  const promise = new Promise( (rs, rj) => { resolve = rs; reject = rj; });
  return <any>{ promise, resolve, reject };
}


text:
namespace blink {

static bool DisplayItemClientIsFullyInvalidated(
    const DisplayItemClient& client) {
  return IsFullPaintInvalidationReason(client.GetPaintInvalidationReason());
}

void TableCellPaintInvalidator::InvalidateContainerForCellGeometryChange(
    const LayoutObject& container,
    const PaintInvalidatorContext& container_context) {
  // We only need to do this if the container hasn't been fully invalidated.
  DCHECK(!DisplayItemClientIsFullyInvalidated(container));

  // At this time we have already walked the container for paint invalidation,
  // so we should invalidate the container immediately here instead of setting
  // paint invalidation flags.
  container_context.painting_layer->SetNeedsRepaint();
  container.InvalidateDisplayItemClients(PaintInvalidationReason::kGeometry);
}

void TableCellPaintInvalidator::InvalidatePaint() {
  // The cell's containing row and section paint backgrounds behind the cell,
  // and the row or table paints collapsed borders. If the cell's geometry
  // changed and the containers which will paint backgrounds and/or collapsed
  // borders haven't been full invalidated, invalidate the containers.
  if (context_.old_paint_offset != context_.fragment_data->PaintOffset() ||
      cell_.Size() != cell_.PreviousSize()) {
    const auto& row = *cell_.Row();
    const auto& section = *row.Section();
    const auto& table = *section.Table();
    if (!DisplayItemClientIsFullyInvalidated(row) &&
        (row.StyleRef().HasBackground() ||
         (table.HasCollapsedBorders() &&
          LIKELY(!table.ShouldPaintAllCollapsedBorders())))) {
      InvalidateContainerForCellGeometryChange(row, *context_.ParentContext());
    }

    if (UNLIKELY(table.ShouldPaintAllCollapsedBorders()) &&
        !DisplayItemClientIsFullyInvalidated(table)) {
      DCHECK(table.HasCollapsedBorders());
      InvalidateContainerForCellGeometryChange(
          table, *context_.ParentContext()->ParentContext()->ParentContext());
    }

    if (!DisplayItemClientIsFullyInvalidated(section)) {
      bool section_paints_background = section.StyleRef().HasBackground();
      if (!section_paints_background) {
        auto col_and_colgroup = section.Table()->ColElementAtAbsoluteColumn(
            cell_.AbsoluteColumnIndex());
        if ((col_and_colgroup.col &&
             col_and_colgroup.col->StyleRef().HasBackground()) ||
            (col_and_colgroup.colgroup &&
             col_and_colgroup.colgroup->StyleRef().HasBackground()))
          section_paints_background = true;
      }
      if (section_paints_background) {
        InvalidateContainerForCellGeometryChange(
            section, *context_.ParentContext()->ParentContext());
      }
    }
  }

  BlockPaintInvalidator(cell_).InvalidatePaint(context_);
}

}  // namespace blink


text:
namespace mcomm
{

std::string TransformComponent::toString() const
{
	return "TransformComponent";
}

void TransformComponent::init(const pugi::xml_node& xml)
{
	auto node_scale = xml.child("Scale");
	if (!node_scale.empty())
	{
		float sx = node_scale.child("X").text().as_float();
		float sy = node_scale.child("Y").text().as_float();
		setScale(sx, sy);
	}

	auto node_origin = xml.child("Origin");
	if (!node_origin.empty())
	{
		float sx = node_origin.child("X").text().as_float();
		float sy = node_origin.child("Y").text().as_float();
		setOrigin(sx, sy);
	}

	auto node_position = xml.child("Position");

	if (!node_position.empty())
	{
		float sx = node_position.child("X").text().as_float();
		float sy = node_position.child("Y").text().as_float();
		setPosition(sx, sy);
	}

	// TODO: more properties, more error handling.
}

}