text:
using FluentAssertions;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
using Xunit;

namespace VkNet.Tests.Enum.SafetyEnums;

public class SafetyEnumsTest
{
	[Fact]
	public void NullTest()
	{
		var result = AppFilter.FromJsonString("");

		result.Should()
			.BeNull();
	}

	[Fact]
	public void AppFilterTest()
	{
		// get test
		AppFilter.Installed.ToString()
			.Should()
			.Be("installed");

		AppFilter.Featured.ToString()
			.Should()
			.Be("featured");

		// parse test
		AppFilter.FromJsonString("installed")
			.Should()
			.Be(AppFilter.Installed);

		AppFilter.FromJsonString("featured")
			.Should()
			.Be(AppFilter.Featured);
	}

	[Fact]
	public void AppPlatformsTest()
	{
		// get test
		AppPlatforms.Ios.ToString()
			.Should()
			.Be("ios");

		AppPlatforms.Android.ToString()
			.Should()
			.Be("android");

		AppPlatforms.WinPhone.ToString()
			.Should()
			.Be("winphone");

		AppPlatforms.Web.ToString()
			.Should()
			.Be("web");

		// parse test
		AppPlatforms.FromJsonString("ios")
			.Should()
			.Be(AppPlatforms.Ios);

		AppPlatforms.FromJsonString("android")
			.Should()
			.Be(AppPlatforms.Android);

		AppPlatforms.FromJsonString("winphone")
			.Should()
			.Be(AppPlatforms.WinPhone);

		AppPlatforms.FromJsonString("web")
			.Should()
			.Be(AppPlatforms.Web);
	}

	[Fact]
	public void AppRatingTypeTest()
	{
		// get test
		AppRatingType.Level.ToString()
			.Should()
			.Be("level");

		AppRatingType.Points.ToString()
			.Should()
			.Be("points");

		// parse test
		AppRatingType.FromJsonString("level")
			.Should()
			.Be(AppRatingType.Level);

		AppRatingType.FromJsonString("points")
			.Should()
			.Be(AppRatingType.Points);
	}

	[Fact]
	public void AppRequestTypeTest()
	{
		// get test
		AppRequestType.Invite.ToString()
			.Should()
			.Be("invite");

		AppRequestType.Request.ToString()
			.Should()
			.Be("request");

		// parse test
		AppRequestType.FromJsonString("invite")
			.Should()
			.Be(AppRequestType.Invite);

		AppRequestType.FromJsonString("request")
			.Should()
			.Be(AppRequestType.Request);
	}

	[Fact]
	public void AppSortTest()
	{
		// get test
		AppSort.PopularToday.ToString()
			.Should()
			.Be("popular_today");

		AppSort.Visitors.ToString()
			.Should()
			.Be("visitors");

		AppSort.CreateDate.ToString()
			.Should()
			.Be("create_date");

		AppSort.GrowthRate.ToString()
			.Should()
			.Be("growth_rate");

		AppSort.PopularWeek.ToString()
			.Should()
			.Be("popular_week");

		// parse test
		AppSort.FromJsonString("popular_today")
			.Should()
			.Be(AppSort.PopularToday);

		AppSort.FromJsonString("visitors")
			.Should()
			.Be(AppSort.Visitors);

		AppSort.FromJsonString("create_date")
			.Should()
			.Be(AppSort.CreateDate);

		AppSort.FromJsonString("growth_rate")
			.Should()
			.Be(AppSort.GrowthRate);

		AppSort.FromJsonString("popular_week")
			.Should()
			.Be(AppSort.PopularWeek);
	}

	[Fact]
	public void ChangeNameStatusTest()
	{
		// get test
		ChangeNameStatus.Processing.ToString()
			.Should()
			.Be("processing");

		ChangeNameStatus.Declined.ToString()
			.Should()
			.Be("declined");

		ChangeNameStatus.Success.ToString()
			.Should()
			.Be("success");

		ChangeNameStatus.WasAccepted.ToString()
			.Should()
			.Be("was_accepted");

		ChangeNameStatus.WasDeclined.ToString()
			.Should()
			.Be("was_declined");

		// parse test
		ChangeNameStatus.FromJsonString("processing")
			.Should()
			.Be(ChangeNameStatus.Processing);

		ChangeNameStatus.FromJsonString("declined")
			.Should()
			.Be(ChangeNameStatus.Declined);

		ChangeNameStatus.FromJsonString("success")
			.Should()
			.Be(ChangeNameStatus.Success);

		ChangeNameStatus.FromJsonString("was_accepted")
			.Should()
			.Be(ChangeNameStatus.WasAccepted);

		ChangeNameStatus.FromJsonString("was_declined")
			.Should()
			.Be(ChangeNameStatus.WasDeclined);
	}

	[Fact]
	public void CommentObjectTypeTest()
	{
		// get test
		CommentObjectType.Post.ToString()
			.Should()
			.Be("post");

		CommentObjectType.Photo.ToString()
			.Should()
			.Be("photo");

		CommentObjectType.Video.ToString()
			.Should()
			.Be("video");

		CommentObjectType.Topic.ToString()
			.Should()
			.Be("topic");

		CommentObjectType.Note.ToString()
			.Should()
			.Be("note");

		// parse test
		CommentObjectType.FromJsonString("post")
			.Should()
			.Be(CommentObjectType.Post);

		CommentObjectType.FromJsonString("photo")
			.Should()
			.Be(CommentObjectType.Photo);

		CommentObjectType.FromJsonString("video")
			.Should()
			.Be(CommentObjectType.Video);

		CommentObjectType.FromJsonString("topic")
			.Should()
			.Be(CommentObjectType.Topic);

		CommentObjectType.FromJsonString("note")
			.Should()
			.Be(CommentObjectType.Note);
	}

	[Fact]
	public void CommentsSortTest()
	{
		// get test
		CommentsSort.Asc.ToString()
			.Should()
			.Be("asc");

		CommentsSort.Desc.ToString()
			.Should()
			.Be("desc");

		// parse test
		CommentsSort.FromJsonString("asc")
			.Should()
			.Be(CommentsSort.Asc);

		CommentsSort.FromJsonString("desc")
			.Should()
			.Be(CommentsSort.Desc);
	}

	[Fact]
	public void DeactivatedTest()
	{
		// get test
		Deactivated.Deleted.ToString()
			.Should()
			.Be("deleted");

		Deactivated.Banned.ToString()
			.Should()
			.Be("banned");

		Deactivated.Activated.ToString()
			.Should()
			.Be("activated");

		// parse test
		Deactivated.FromJsonString("deleted")
			.Should()
			.Be(Deactivated.Deleted);

		Deactivated.FromJsonString("banned")
			.Should()
			.Be(Deactivated.Banned);

		Deactivated.FromJsonString("activated")
			.Should()
			.Be(Deactivated.Activated);
	}

	[Fact]
	public void DisplayTest()
	{
		// get test
		Display.Page.ToString()
			.Should()
			.Be("page");

		Display.Popup.ToString()
			.Should()
			.Be("popup");

		Display.Mobile.ToString()
			.Should()
			.Be("mobile");

		// parse test
		Display.FromJsonString("page")
			.Should()
			.Be(Display.Page);

		Display.FromJsonString("popup")
			.Should()
			.Be(Display.Popup);

		Display.FromJsonString("mobile")
			.Should()
			.Be(Display.Mobile);
	}

	[Fact]
	public void FeedTypeTest()
	{
		// get test
		FeedType.Photo.ToString()
			.Should()
			.Be("photo");

		FeedType.PhotoTag.ToString()
			.Should()
			.Be("photo_tag");

		// parse test
		FeedType.FromJsonString("photo")
			.Should()
			.Be(FeedType.Photo);

		FeedType.FromJsonString("photo_tag")
			.Should()
			.Be(FeedType.PhotoTag);
	}

	[Fact]
	public void FriendsFilterTest()
	{
		// get test
		FriendsFilter.Mutual.ToString()
			.Should()
			.Be("mutual");

		FriendsFilter.Contacts.ToString()
			.Should()
			.Be("contacts");

		FriendsFilter.MutualContacts.ToString()
			.Should()
			.Be("mutual_contacts");

		// parse test
		FriendsFilter.FromJsonString("mutual")
			.Should()
			.Be(FriendsFilter.Mutual);

		FriendsFilter.FromJsonString("contacts")
			.Should()
			.Be(FriendsFilter.Contacts);

		FriendsFilter.FromJsonString("mutual_contacts")
			.Should()
			.Be(FriendsFilter.MutualContacts);
	}

	[Fact]
	public void FriendsOrderTest()
	{
		// get test
		FriendsOrder.Name.ToString()
			.Should()
			.Be("name");

		FriendsOrder.Hints.ToString()
			.Should()
			.Be("hints");

		FriendsOrder.Random.ToString()
			.Should()
			.Be("random");

		// parse test
		FriendsOrder.FromJsonString("name")
			.Should()
			.Be(FriendsOrder.Name);

		FriendsOrder.FromJsonString("hints")
			.Should()
			.Be(FriendsOrder.Hints);

		FriendsOrder.FromJsonString("random")
			.Should()
			.Be(FriendsOrder.Random);
	}

	[Fact]
	public void GroupsSortTest()
	{
		// get test
		GroupsSort.IdAsc.ToString()
			.Should()
			.Be("id_asc");

		GroupsSort.IdDesc.ToString()
			.Should()
			.Be("id_desc");

		GroupsSort.TimeAsc.ToString()
			.Should()
			.Be("time_asc");

		GroupsSort.TimeDesc.ToString()
			.Should()
			.Be("time_desc");

		// parse test
		GroupsSort.FromJsonString("id_asc")
			.Should()
			.Be(GroupsSort.IdAsc);

		GroupsSort.FromJsonString("id_desc")
			.Should()
			.Be(GroupsSort.IdDesc);

		GroupsSort.FromJsonString("time_asc")
			.Should()
			.Be(GroupsSort.TimeAsc);

		GroupsSort.FromJsonString("time_desc")
			.Should()
			.Be(GroupsSort.TimeDesc);
	}

	[Fact]
	public void GroupTypeTest()
	{
		// get test
		GroupType.Page.ToString()
			.Should()
			.Be("page");

		GroupType.Group.ToString()
			.Should()
			.Be("group");

		GroupType.Event.ToString()
			.Should()
			.Be("event");

		GroupType.Undefined.ToString()
			.Should()
			.Be("undefined");

		// parse test
		GroupType.FromJsonString("page")
			.Should()
			.Be(GroupType.Page);

		GroupType.FromJsonString("group")
			.Should()
			.Be(GroupType.Group);

		GroupType.FromJsonString("event")
			.Should()
			.Be(GroupType.Event);

		GroupType.FromJsonString("undefined")
			.Should()
			.Be(GroupType.Undefined);
	}

	[Fact]
	public void LikeObjectTypeTest()
	{
		// get test
		LikeObjectType.Post.ToString()
			.Should()
			.Be("post");

		LikeObjectType.Comment.ToString()
			.Should()
			.Be("comment");

		LikeObjectType.Photo.ToString()
			.Should()
			.Be("photo");

		LikeObjectType.Audio.ToString()
			.Should()
			.Be("audio");

		LikeObjectType.Video.ToString()
			.Should()
			.Be("video");

		LikeObjectType.Note.ToString()
			.Should()
			.Be("note");

		LikeObjectType.PhotoComment.ToString()
			.Should()
			.Be("photo_comment");

		LikeObjectType.VideoComment.ToString()
			.Should()
			.Be("video_comment");

		LikeObjectType.TopicComment.ToString()
			.Should()
			.Be("topic_comment");

		LikeObjectType.SitePage.ToString()
			.Should()
			.Be("sitepage");

		LikeObjectType.Market.ToString()
			.Should()
			.Be("market");

		LikeObjectType.MarketComment.ToString()
			.Should()
			.Be("market_comment");

		// parse test
		LikeObjectType.FromJsonString("post")
			.Should()
			.Be(LikeObjectType.Post);

		LikeObjectType.FromJsonString("comment")
			.Should()
			.Be(LikeObjectType.Comment);

		LikeObjectType.FromJsonString("photo")
			.Should()
			.Be(LikeObjectType.Photo);

		LikeObjectType.FromJsonString("audio")
			.Should()
			.Be(LikeObjectType.Audio);

		LikeObjectType.FromJsonString("video")
			.Should()
			.Be(LikeObjectType.Video);

		LikeObjectType.FromJsonString("note")
			.Should()
			.Be(LikeObjectType.Note);

		LikeObjectType.FromJsonString("photo_comment")
			.Should()
			.Be(LikeObjectType.PhotoComment);

		LikeObjectType.FromJsonString("video_comment")
			.Should()
			.Be(LikeObjectType.VideoComment);

		LikeObjectType.FromJsonString("topic_comment")
			.Should()
			.Be(LikeObjectType.TopicComment);

		LikeObjectType.FromJsonString("sitepage")
			.Should()
			.Be(LikeObjectType.SitePage);

		LikeObjectType.FromJsonString("market")
			.Should()
			.Be(LikeObjectType.Market);

		LikeObjectType.FromJsonString("market_comment")
			.Should()
			.Be(LikeObjectType.MarketComment);
	}

	[Fact]
	public void LikesFilterTest()
	{
		// get test
		LikesFilter.Likes.ToString()
			.Should()
			.Be("likes");

		LikesFilter.Copies.ToString()
			.Should()
			.Be("copies");

		// parse test
		LikesFilter.FromJsonString("likes")
			.Should()
			.Be(LikesFilter.Likes);

		LikesFilter.FromJsonString("copies")
			.Should()
			.Be(LikesFilter.Copies);
	}

	[Fact]
	public void LinkAccessTypeTest()
	{
		// get test
		LinkAccessType.NotBanned.ToString()
			.Should()
			.Be("not_banned");

		LinkAccessType.Banned.ToString()
			.Should()
			.Be("banned");

		LinkAccessType.Processing.ToString()
			.Should()
			.Be("processing");

		// parse test
		LinkAccessType.FromJsonString("not_banned")
			.Should()
			.Be(LinkAccessType.NotBanned);

		LinkAccessType.FromJsonString("banned")
			.Should()
			.Be(LinkAccessType.Banned);

		LinkAccessType.FromJsonString("processing")
			.Should()
			.Be(LinkAccessType.Processing);
	}

	[Fact]
	public void MediaTypeTest()
	{
		// get test
		MediaType.Photo.ToString()
			.Should()
			.Be("photo");

		MediaType.Video.ToString()
			.Should()
			.Be("video");

		MediaType.Audio.ToString()
			.Should()
			.Be("audio");

		MediaType.Doc.ToString()
			.Should()
			.Be("doc");

		MediaType.Link.ToString()
			.Should()
			.Be("link");

		MediaType.Market.ToString()
			.Should()
			.Be("market");

		MediaType.Wall.ToString()
			.Should()
			.Be("wall");

		MediaType.Share.ToString()
			.Should()
			.Be("share");

		MediaType.Graffiti.ToString()
			.Should()
			.Be("graffiti");

		// parse test
		MediaType.FromJsonString("photo")
			.Should()
			.Be(MediaType.Photo);

		MediaType.FromJsonString("video")
			.Should()
			.Be(MediaType.Video);

		MediaType.FromJsonString("audio")
			.Should()
			.Be(MediaType.Audio);

		MediaType.FromJsonString("doc")
			.Should()
			.Be(MediaType.Doc);

		MediaType.FromJsonString("link")
			.Should()
			.Be(MediaType.Link);

		MediaType.FromJsonString("market")
			.Should()
			.Be(MediaType.Market);

		MediaType.FromJsonString("wall")
			.Should()
			.Be(MediaType.Wall);

		MediaType.FromJsonString("share")
			.Should()
			.Be(MediaType.Share);

		MediaType.FromJsonString("graffiti")
			.Should()
			.Be(MediaType.Graffiti);
	}

	[Fact]
	public void NameCaseTest()
	{
		// get test
		NameCase.Nom.ToString()
			.Should()
			.Be("nom");

		NameCase.Gen.ToString()
			.Should()
			.Be("gen");

		NameCase.Dat.ToString()
			.Should()
			.Be("dat");

		NameCase.Acc.ToString()
			.Should()
			.Be("acc");

		NameCase.Ins.ToString()
			.Should()
			.Be("ins");

		NameCase.Abl.ToString()
			.Should()
			.Be("abl");

		// parse test
		NameCase.FromJsonString("nom")
			.Should()
			.Be(NameCase.Nom);

		NameCase.FromJsonString("gen")
			.Should()
			.Be(NameCase.Gen);

		NameCase.FromJsonString("dat")
			.Should()
			.Be(NameCase.Dat);

		NameCase.FromJsonString("acc")
			.Should()
			.Be(NameCase.Acc);

		NameCase.FromJsonString("ins")
			.Should()
			.Be(NameCase.Ins);

		NameCase.FromJsonString("abl")
			.Should()
			.Be(NameCase.Abl);
	}

	[Fact]
	public void NewsObjectTypesTest()
	{
		// get test
		NewsObjectTypes.Wall.ToString()
			.Should()
			.Be("wall");

		NewsObjectTypes.Tag.ToString()
			.Should()
			.Be("tag");

		NewsObjectTypes.ProfilePhoto.ToString()
			.Should()
			.Be("profilephoto");

		NewsObjectTypes.Video.ToString()
			.Should()
			.Be("video");

		NewsObjectTypes.Photo.ToString()
			.Should()
			.Be("photo");

		NewsObjectTypes.Audio.ToString()
			.Should()
			.Be("audio");

		// parse test
		NewsObjectTypes.FromJsonString("wall")
			.Should()
			.Be(NewsObjectTypes.Wall);

		NewsObjectTypes.FromJsonString("tag")
			.Should()
			.Be(NewsObjectTypes.Tag);

		NewsObjectTypes.FromJsonString("profilephoto")
			.Should()
			.Be(NewsObjectTypes.ProfilePhoto);

		NewsObjectTypes.FromJsonString("video")
			.Should()
			.Be(NewsObjectTypes.Video);

		NewsObjectTypes.FromJsonString("photo")
			.Should()
			.Be(NewsObjectTypes.Photo);

		NewsObjectTypes.FromJsonString("audio")
			.Should()
			.Be(NewsObjectTypes.Audio);
	}

	[Fact]
	public void NewsTypesTest()
	{
		// get test
		NewsTypes.Post.ToString()
			.Should()
			.Be("post");

		NewsTypes.Photo.ToString()
			.Should()
			.Be("photo");

		NewsTypes.PhotoTag.ToString()
			.Should()
			.Be("photo_tag");

		NewsTypes.WallPhoto.ToString()
			.Should()
			.Be("wall_photo");

		NewsTypes.Friend.ToString()
			.Should()
			.Be("friend");

		NewsTypes.Note.ToString()
			.Should()
			.Be("note");

		// parse test
		NewsTypes.FromJsonString("post")
			.Should()
			.Be(NewsTypes.Post);

		NewsTypes.FromJsonString("photo")
			.Should()
			.Be(NewsTypes.Photo);

		NewsTypes.FromJsonString("photo_tag")
			.Should()
			.Be(NewsTypes.PhotoTag);

		NewsTypes.FromJsonString("wall_photo")
			.Should()
			.Be(NewsTypes.WallPhoto);

		NewsTypes.FromJsonString("friend")
			.Should()
			.Be(NewsTypes.Friend);

		NewsTypes.FromJsonString("note")
			.Should()
			.Be(NewsTypes.Note);
	}

	[Fact]
	public void OccupationTypeTest()
	{
		// get test
		OccupationType.Work.ToString()
			.Should()
			.Be("work");

		OccupationType.School.ToString()
			.Should()
			.Be("school");

		OccupationType.University.ToString()
			.Should()
			.Be("university");

		// parse test
		OccupationType.FromJsonString("work")
			.Should()
			.Be(OccupationType.Work);

		OccupationType.FromJsonString("school")
			.Should()
			.Be(OccupationType.School);

		OccupationType.FromJsonString("university")
			.Should()
			.Be(OccupationType.University);
	}

	[Fact]
	public void PhotoAlbumTypeTest()
	{
		// get test
		PhotoAlbumType.Wall.ToString()
			.Should()
			.Be("wall");

		PhotoAlbumType.Profile.ToString()
			.Should()
			.Be("profile");

		PhotoAlbumType.Saved.ToString()
			.Should()
			.Be("saved");

		// parse test
		PhotoAlbumType.FromJsonString("wall")
			.Should()
			.Be(PhotoAlbumType.Wall);

		PhotoAlbumType.FromJsonString("profile")
			.Should()
			.Be(PhotoAlbumType.Profile);

		PhotoAlbumType.FromJsonString("saved")
			.Should()
			.Be(PhotoAlbumType.Saved);
	}

	[Fact]
	public void PhotoFeedTypeTest()
	{
		// get test
		PhotoFeedType.Photo.ToString()
			.Should()
			.Be("photo");

		PhotoFeedType.PhotoTag.ToString()
			.Should()
			.Be("photo_tag");

		// parse test
		PhotoFeedType.FromJsonString("photo")
			.Should()
			.Be(PhotoFeedType.Photo);

		PhotoFeedType.FromJsonString("photo_tag")
			.Should()
			.Be(PhotoFeedType.PhotoTag);
	}

	[Fact]
	public void PhotoSearchRadiusTest()
	{
		// get test
		PhotoSearchRadius.Ten.ToString()
			.Should()
			.Be("10");

		PhotoSearchRadius.OneHundred.ToString()
			.Should()
			.Be("100");

		PhotoSearchRadius.Eighty.ToString()
			.Should()
			.Be("800");

		PhotoSearchRadius.SixThousand.ToString()
			.Should()
			.Be("6000");

		PhotoSearchRadius.FiftyThousand.ToString()
			.Should()
			.Be("50000");

		// parse test
		PhotoSearchRadius.FromJsonString("10")
			.Should()
			.Be(PhotoSearchRadius.Ten);

		PhotoSearchRadius.FromJsonString("100")
			.Should()
			.Be(PhotoSearchRadius.OneHundred);

		PhotoSearchRadius.FromJsonString("800")
			.Should()
			.Be(PhotoSearchRadius.Eighty);

		PhotoSearchRadius.FromJsonString("6000")
			.Should()
			.Be(PhotoSearchRadius.SixThousand);

		PhotoSearchRadius.FromJsonString("50000")
			.Should()
			.Be(PhotoSearchRadius.FiftyThousand);
	}

	[Fact]
	public void PhotoSizeTypeTest()
	{
		// get test
		PhotoSizeType.S.ToString()
			.Should()
			.Be("s");

		PhotoSizeType.M.ToString()
			.Should()
			.Be("m");

		PhotoSizeType.X.ToString()
			.Should()
			.Be("x");

		PhotoSizeType.O.ToString()
			.Should()
			.Be("o");

		PhotoSizeType.P.ToString()
			.Should()
			.Be("p");

		PhotoSizeType.Q.ToString()
			.Should()
			.Be("q");

		PhotoSizeType.R.ToString()
			.Should()
			.Be("r");

		PhotoSizeType.Y.ToString()
			.Should()
			.Be("y");

		PhotoSizeType.Z.ToString()
			.Should()
			.Be("z");

		PhotoSizeType.W.ToString()
			.Should()
			.Be("w");

		// parse test
		PhotoSizeType.FromJsonString("s")
			.Should()
			.Be(PhotoSizeType.S);

		PhotoSizeType.FromJsonString("m")
			.Should()
			.Be(PhotoSizeType.M);

		PhotoSizeType.FromJsonString("x")
			.Should()
			.Be(PhotoSizeType.X);

		PhotoSizeType.FromJsonString("o")
			.Should()
			.Be(PhotoSizeType.O);

		PhotoSizeType.FromJsonString("p")
			.Should()
			.Be(PhotoSizeType.P);

		PhotoSizeType.FromJsonString("q")
			.Should()
			.Be(PhotoSizeType.Q);

		PhotoSizeType.FromJsonString("r")
			.Should()
			.Be(PhotoSizeType.R);

		PhotoSizeType.FromJsonString("y")
			.Should()
			.Be(PhotoSizeType.Y);

		PhotoSizeType.FromJsonString("z")
			.Should()
			.Be(PhotoSizeType.Z);

		PhotoSizeType.FromJsonString("w")
			.Should()
			.Be(PhotoSizeType.W);
	}

	[Fact]
	public void PlatformTest()
	{
		// get test
		Platform.Android.ToString()
			.Should()
			.Be("android");

		Platform.IPhone.ToString()
			.Should()
			.Be("iphone");

		Platform.WindowsPhone.ToString()
			.Should()
			.Be("wphone");

		// parse test
		Platform.FromJsonString("android")
			.Should()
			.Be(Platform.Android);

		Platform.FromJsonString("iphone")
			.Should()
			.Be(Platform.IPhone);

		Platform.FromJsonString("wphone")
			.Should()
			.Be(Platform.WindowsPhone);
	}

	[Fact]
	public void PostSourceTypeTest()
	{
		// get test
		PostSourceType.Vk.ToString()
			.Should()
			.Be("vk");

		PostSourceType.Widget.ToString()
			.Should()
			.Be("widget");

		PostSourceType.Api.ToString()
			.Should()
			.Be("api");

		PostSourceType.Rss.ToString()
			.Should()
			.Be("rss");

		PostSourceType.Sms.ToString()
			.Should()
			.Be("sms");

		// parse test
		PostSourceType.FromJsonString("vk")
			.Should()
			.Be(PostSourceType.Vk);

		PostSourceType.FromJsonString("widget")
			.Should()
			.Be(PostSourceType.Widget);

		PostSourceType.FromJsonString("api")
			.Should()
			.Be(PostSourceType.Api);

		PostSourceType.FromJsonString("rss")
			.Should()
			.Be(PostSourceType.Rss);

		PostSourceType.FromJsonString("sms")
			.Should()
			.Be(PostSourceType.Sms);
	}

	[Fact]
	public void PostTypeOrderTest()
	{
		// get test
		PostTypeOrder.Post.ToString()
			.Should()
			.Be("post");

		PostTypeOrder.Copy.ToString()
			.Should()
			.Be("copy");

		// parse test
		PostTypeOrder.FromJsonString("post")
			.Should()
			.Be(PostTypeOrder.Post);

		PostTypeOrder.FromJsonString("copy")
			.Should()
			.Be(PostTypeOrder.Copy);
	}

	[Fact]
	public void PostTypeTest()
	{
		// get test
		PostType.Post.ToString()
			.Should()
			.Be("post");

		PostType.Copy.ToString()
			.Should()
			.Be("copy");

		PostType.Reply.ToString()
			.Should()
			.Be("reply");

		PostType.Postpone.ToString()
			.Should()
			.Be("postpone");

		PostType.Suggest.ToString()
			.Should()
			.Be("suggest");

		// parse test
		PostType.FromJsonString("post")
			.Should()
			.Be(PostType.Post);

		PostType.FromJsonString("copy")
			.Should()
			.Be(PostType.Copy);

		PostType.FromJsonString("reply")
			.Should()
			.Be(PostType.Reply);

		PostType.FromJsonString("postpone")
			.Should()
			.Be(PostType.Postpone);

		PostType.FromJsonString("suggest")
			.Should()
			.Be(PostType.Suggest);
	}

	[Fact]
	public void PrivacyTest()
	{
		// get test
		Privacy.All.ToString()
			.Should()
			.Be("all");

		Privacy.Friends.ToString()
			.Should()
			.Be("friends");

		Privacy.FriendsOfFriends.ToString()
			.Should()
			.Be("friends_of_friends");

		Privacy.FriendsOfFriendsOnly.ToString()
			.Should()
			.Be("friends_of_friends_only");

		Privacy.Nobody.ToString()
			.Should()
			.Be("nobody");

		Privacy.OnlyMe.ToString()
			.Should()
			.Be("only_me");

		// parse test
		Privacy.FromJsonString("all")
			.Should()
			.Be(Privacy.All);

		Privacy.FromJsonString("friends")
			.Should()
			.Be(Privacy.Friends);

		Privacy.FromJsonString("friends_of_friends")
			.Should()
			.Be(Privacy.FriendsOfFriends);

		Privacy.FromJsonString("friends_of_friends_only")
			.Should()
			.Be(Privacy.FriendsOfFriendsOnly);

		Privacy.FromJsonString("nobody")
			.Should()
			.Be(Privacy.Nobody);

		Privacy.FromJsonString("only_me")
			.Should()
			.Be(Privacy.OnlyMe);
	}

	[Fact]
	public void RelativeTypeTest()
	{
		// get test
		RelativeType.Sibling.ToString()
			.Should()
			.Be("sibling");

		RelativeType.Parent.ToString()
			.Should()
			.Be("parent");

		RelativeType.Child.ToString()
			.Should()
			.Be("child");

		RelativeType.Grandparent.ToString()
			.Should()
			.Be("grandparent");

		RelativeType.Grandchild.ToString()
			.Should()
			.Be("grandchild");

		// parse test
		RelativeType.FromJsonString("sibling")
			.Should()
			.Be(RelativeType.Sibling);

		RelativeType.FromJsonString("parent")
			.Should()
			.Be(RelativeType.Parent);

		RelativeType.FromJsonString("child")
			.Should()
			.Be(RelativeType.Child);

		RelativeType.FromJsonString("grandparent")
			.Should()
			.Be(RelativeType.Grandparent);

		RelativeType.FromJsonString("grandchild")
			.Should()
			.Be(RelativeType.Grandchild);
	}

	[Fact]
	public void ReportTypeTest()
	{
		// get test
		ReportType.Porn.ToString()
			.Should()
			.Be("porn");

		ReportType.Spam.ToString()
			.Should()
			.Be("spam");

		ReportType.Insult.ToString()
			.Should()
			.Be("insult");

		ReportType.Advertisment.ToString()
			.Should()
			.Be("advertisment");

		// parse test
		ReportType.FromJsonString("porn")
			.Should()
			.Be(ReportType.Porn);

		ReportType.FromJsonString("spam")
			.Should()
			.Be(ReportType.Spam);

		ReportType.FromJsonString("insult")
			.Should()
			.Be(ReportType.Insult);

		ReportType.FromJsonString("advertisment")
			.Should()
			.Be(ReportType.Advertisment);
	}

	[Fact]
	public void ServicesTest()
	{
		// get test
		Services.Email.ToString()
			.Should()
			.Be("email");

		Services.Phone.ToString()
			.Should()
			.Be("phone");

		Services.Twitter.ToString()
			.Should()
			.Be("twitter");

		Services.Facebook.ToString()
			.Should()
			.Be("facebook");

		Services.Odnoklassniki.ToString()
			.Should()
			.Be("odnoklassniki");

		Services.Instagram.ToString()
			.Should()
			.Be("instagram");

		Services.Google.ToString()
			.Should()
			.Be("google");

		// parse test
		Services.FromJsonString("email")
			.Should()
			.Be(Services.Email);

		Services.FromJsonString("phone")
			.Should()
			.Be(Services.Phone);

		Services.FromJsonString("twitter")
			.Should()
			.Be(Services.Twitter);

		Services.FromJsonString("facebook")
			.Should()
			.Be(Services.Facebook);

		Services.FromJsonString("odnoklassniki")
			.Should()
			.Be(Services.Odnoklassniki);

		Services.FromJsonString("instagram")
			.Should()
			.Be(Services.Instagram);

		Services.FromJsonString("google")
			.Should()
			.Be(Services.Google);
	}

	[Fact]
	public void UserSectionTest()
	{
		// get test
		UserSection.Friends.ToString()
			.Should()
			.Be("friends");

		UserSection.Subscriptions.ToString()
			.Should()
			.Be("subscriptions");

		// parse test
		UserSection.FromJsonString("friends")
			.Should()
			.Be(UserSection.Friends);

		UserSection.FromJsonString("subscriptions")
			.Should()
			.Be(UserSection.Subscriptions);
	}

	[Fact]
	public void VideoCatalogItemTypeTest()
	{
		// get test
		VideoCatalogItemType.Video.ToString()
			.Should()
			.Be("video");

		VideoCatalogItemType.Album.ToString()
			.Should()
			.Be("album");

		// parse test
		VideoCatalogItemType.FromJsonString("video")
			.Should()
			.Be(VideoCatalogItemType.Video);

		VideoCatalogItemType.FromJsonString("album")
			.Should()
			.Be(VideoCatalogItemType.Album);
	}

	[Fact]
	public void VideoCatalogTypeTest()
	{
		// get test
		VideoCatalogType.Channel.ToString()
			.Should()
			.Be("channel");

		VideoCatalogType.Category.ToString()
			.Should()
			.Be("category");

		// parse test
		VideoCatalogType.FromJsonString("channel")
			.Should()
			.Be(VideoCatalogType.Channel);

		VideoCatalogType.FromJsonString("category")
			.Should()
			.Be(VideoCatalogType.Category);
	}

	[Fact]
	public void WallFilterTest()
	{
		// get test
		WallFilter.Owner.ToString()
			.Should()
			.Be("owner");

		WallFilter.Others.ToString()
			.Should()
			.Be("others");

		WallFilter.All.ToString()
			.Should()
			.Be("all");

		WallFilter.Suggests.ToString()
			.Should()
			.Be("suggests");

		WallFilter.Postponed.ToString()
			.Should()
			.Be("postponed");

		// parse test
		WallFilter.FromJsonString("owner")
			.Should()
			.Be(WallFilter.Owner);

		WallFilter.FromJsonString("others")
			.Should()
			.Be(WallFilter.Others);

		WallFilter.FromJsonString("all")
			.Should()
			.Be(WallFilter.All);

		WallFilter.FromJsonString("suggests")
			.Should()
			.Be(WallFilter.Suggests);

		WallFilter.FromJsonString("postponed")
			.Should()
			.Be(WallFilter.Postponed);
	}

	[Fact]
	public void KeyboardButtonColorTest()
	{
		// get test
		KeyboardButtonColor.Default.ToString()
			.Should()
			.Be("default");

		KeyboardButtonColor.Negative.ToString()
			.Should()
			.Be("negative");

		KeyboardButtonColor.Positive.ToString()
			.Should()
			.Be("positive");

		KeyboardButtonColor.Primary.ToString()
			.Should()
			.Be("primary");

		// parse test
		KeyboardButtonColor.FromJsonString("default")
			.Should()
			.Be(KeyboardButtonColor.Default);

		KeyboardButtonColor.FromJsonString("negative")
			.Should()
			.Be(KeyboardButtonColor.Negative);

		KeyboardButtonColor.FromJsonString("positive")
			.Should()
			.Be(KeyboardButtonColor.Positive);

		KeyboardButtonColor.FromJsonString("primary")
			.Should()
			.Be(KeyboardButtonColor.Primary);
	}

	[Fact]
	public void KeyboardButtonActionTypeTest()
	{
		// get test
		KeyboardButtonActionType.Text.ToString()
			.Should()
			.Be("text");

		KeyboardButtonActionType.Location.ToString()
			.Should()
			.Be("location");

		KeyboardButtonActionType.OpenLink.ToString()
			.Should()
			.Be("open_link");

		KeyboardButtonActionType.VkApp.ToString()
			.Should()
			.Be("open_app");

		KeyboardButtonActionType.VkPay.ToString()
			.Should()
			.Be("vkpay");

		KeyboardButtonActionType.Callback.ToString()
			.Should()
			.Be("callback");

		// parse test
		KeyboardButtonActionType.FromJsonString("text")
			.Should()
			.Be(KeyboardButtonActionType.Text);

		KeyboardButtonActionType.FromJsonString("location")
			.Should()
			.Be(KeyboardButtonActionType.Location);

		KeyboardButtonActionType.FromJsonString("open_link")
			.Should()
			.Be(KeyboardButtonActionType.OpenLink);

		KeyboardButtonActionType.FromJsonString("open_app")
			.Should()
			.Be(KeyboardButtonActionType.VkApp);

		KeyboardButtonActionType.FromJsonString("vkpay")
			.Should()
			.Be(KeyboardButtonActionType.VkPay);

		KeyboardButtonActionType.FromJsonString("callback")
			.Should()
			.Be(KeyboardButtonActionType.Callback);
	}

	[Fact]
	public void StoryObjectStateTest()
	{
		// get test
		StoryObjectState.Hidden.ToString()
			.Should()
			.Be("hidden");

		StoryObjectState.On.ToString()
			.Should()
			.Be("on");

		StoryObjectState.Off.ToString()
			.Should()
			.Be("off");

		// parse test
		StoryObjectState.FromJsonString("hidden")
			.Should()
			.Be(StoryObjectState.Hidden);

		StoryObjectState.FromJsonString("on")
			.Should()
			.Be(StoryObjectState.On);

		StoryObjectState.FromJsonString("off")
			.Should()
			.Be(StoryObjectState.Off);
	}

	[Fact]
	public void StoryLinkTextTest()
	{
		// get test
		StoryLinkText.Book.ToString()
			.Should()
			.Be("book");

		StoryLinkText.Buy.ToString()
			.Should()
			.Be("buy");

		StoryLinkText.Contact.ToString()
			.Should()
			.Be("contact");

		StoryLinkText.Enroll.ToString()
			.Should()
			.Be("enroll");

		StoryLinkText.Fill.ToString()
			.Should()
			.Be("fill");

		StoryLinkText.GoTo.ToString()
			.Should()
			.Be("go_to");

		StoryLinkText.Install.ToString()
			.Should()
			.Be("install");

		StoryLinkText.LearnMore.ToString()
			.Should()
			.Be("learn_more");

		StoryLinkText.More.ToString()
			.Should()
			.Be("more");

		StoryLinkText.Open.ToString()
			.Should()
			.Be("open");

		StoryLinkText.Order.ToString()
			.Should()
			.Be("order");

		StoryLinkText.Play.ToString()
			.Should()
			.Be("play");

		StoryLinkText.Read.ToString()
			.Should()
			.Be("read");

		StoryLinkText.Signup.ToString()
			.Should()
			.Be("signup");

		StoryLinkText.View.ToString()
			.Should()
			.Be("view");

		StoryLinkText.Vote.ToString()
			.Should()
			.Be("vote");

		StoryLinkText.Watch.ToString()
			.Should()
			.Be("watch");

		StoryLinkText.Write.ToString()
			.Should()
			.Be("write");

		// parse test
		StoryLinkText.FromJsonString("book")
			.Should()
			.Be(StoryLinkText.Book);

		StoryLinkText.FromJsonString("buy")
			.Should()
			.Be(StoryLinkText.Buy);

		StoryLinkText.FromJsonString("contact")
			.Should()
			.Be(StoryLinkText.Contact);

		StoryLinkText.FromJsonString("enroll")
			.Should()
			.Be(StoryLinkText.Enroll);

		StoryLinkText.FromJsonString("fill")
			.Should()
			.Be(StoryLinkText.Fill);

		StoryLinkText.FromJsonString("go_to")
			.Should()
			.Be(StoryLinkText.GoTo);

		StoryLinkText.FromJsonString("install")
			.Should()
			.Be(StoryLinkText.Install);

		StoryLinkText.FromJsonString("learn_more")
			.Should()
			.Be(StoryLinkText.LearnMore);

		StoryLinkText.FromJsonString("more")
			.Should()
			.Be(StoryLinkText.More);

		StoryLinkText.FromJsonString("open")
			.Should()
			.Be(StoryLinkText.Open);

		StoryLinkText.FromJsonString("order")
			.Should()
			.Be(StoryLinkText.Order);

		StoryLinkText.FromJsonString("play")
			.Should()
			.Be(StoryLinkText.Play);

		StoryLinkText.FromJsonString("read")
			.Should()
			.Be(StoryLinkText.Read);

		StoryLinkText.FromJsonString("signup")
			.Should()
			.Be(StoryLinkText.Signup);

		StoryLinkText.FromJsonString("view")
			.Should()
			.Be(StoryLinkText.View);

		StoryLinkText.FromJsonString("vote")
			.Should()
			.Be(StoryLinkText.Vote);

		StoryLinkText.FromJsonString("watch")
			.Should()
			.Be(StoryLinkText.Watch);

		StoryLinkText.FromJsonString("write")
			.Should()
			.Be(StoryLinkText.Write);
	}

	[Fact]
	public void MarketItemButtonTitleTest()
	{
		// get test
		MarketItemButtonTitle.Buy.ToString()
			.Should()
			.Be("Купить");

		MarketItemButtonTitle.BuyATicket.ToString()
			.Should()
			.Be("Купить билет");

		MarketItemButtonTitle.GoToTheStore.ToString()
			.Should()
			.Be("Перейти в магазин");

		// parse test
		MarketItemButtonTitle.FromJsonString("Купить")
			.Should()
			.Be(MarketItemButtonTitle.Buy);

		MarketItemButtonTitle.FromJsonString("Купить билет")
			.Should()
			.Be(MarketItemButtonTitle.BuyATicket);

		MarketItemButtonTitle.FromJsonString("Перейти в магазин")
			.Should()
			.Be(MarketItemButtonTitle.GoToTheStore);
	}

	[Fact]
	public void AppWidgetTypeTest()
	{
		// get test
		AppWidgetType.Donation.ToString()
			.Should()
			.Be("donation");

		AppWidgetType.List.ToString()
			.Should()
			.Be("list");

		AppWidgetType.Match.ToString()
			.Should()
			.Be("match");

		AppWidgetType.Matches.ToString()
			.Should()
			.Be("matches");

		AppWidgetType.Table.ToString()
			.Should()
			.Be("table");

		AppWidgetType.Text.ToString()
			.Should()
			.Be("text");

		AppWidgetType.Tiles.ToString()
			.Should()
			.Be("tiles");

		AppWidgetType.CompactList.ToString()
			.Should()
			.Be("compact_list");

		AppWidgetType.CoverList.ToString()
			.Should()
			.Be("cover_list");

		// parse test
		AppWidgetType.FromJsonString("donation")
			.Should()
			.Be(AppWidgetType.Donation);

		AppWidgetType.FromJsonString("list")
			.Should()
			.Be(AppWidgetType.List);

		AppWidgetType.FromJsonString("match")
			.Should()
			.Be(AppWidgetType.Match);

		AppWidgetType.FromJsonString("matches")
			.Should()
			.Be(AppWidgetType.Matches);

		AppWidgetType.FromJsonString("table")
			.Should()
			.Be(AppWidgetType.Table);

		AppWidgetType.FromJsonString("text")
			.Should()
			.Be(AppWidgetType.Text);

		AppWidgetType.FromJsonString("tiles")
			.Should()
			.Be(AppWidgetType.Tiles);

		AppWidgetType.FromJsonString("compact_list")
			.Should()
			.Be(AppWidgetType.CompactList);

		AppWidgetType.FromJsonString("cover_list")
			.Should()
			.Be(AppWidgetType.CoverList);
	}

	[Fact]
	public void TranscriptStatesTest()
	{
		// get test
		TranscriptStates.Done.ToString()
			.Should()
			.Be("done");

		TranscriptStates.InProgress.ToString()
			.Should()
			.Be("in_progress");

		// parse test
		TranscriptStates.FromJsonString("done")
			.Should()
			.Be(TranscriptStates.Done);

		TranscriptStates.FromJsonString("in_progress")
			.Should()
			.Be(TranscriptStates.InProgress);
	}

	[Fact]
	public void MessageEventTypeTest()
	{
		// get test
		MessageEventType.OpenApp.ToString()
			.Should()
			.Be("open_app");

		MessageEventType.OpenLink.ToString()
			.Should()
			.Be("open_link");

		MessageEventType.SnowSnackbar.ToString()
			.Should()
			.Be("show_snackbar");

		// parse test
		MessageEventType.FromJsonString("open_app")
			.Should()
			.Be(MessageEventType.OpenApp);

		MessageEventType.FromJsonString("open_link")
			.Should()
			.Be(MessageEventType.OpenLink);

		MessageEventType.FromJsonString("show_snackbar")
			.Should()
			.Be(MessageEventType.SnowSnackbar);
	}
}


text:
namespace {

// Used for indicating that the .ico contains an icon (rather than a cursor)
// image. This value is set in the |idType| field of the ICONDIR structure.
const int kResourceTypeIcon = 1;

struct ScopedICONINFO : ICONINFO {
  ScopedICONINFO() {
    hbmColor = NULL;
    hbmMask = NULL;
  }

  ~ScopedICONINFO() {
    if (hbmColor)
      ::DeleteObject(hbmColor);
    if (hbmMask)
      ::DeleteObject(hbmMask);
  }
};

// Creates a new ImageFamily, |resized_image_family|, based on the images in
// |image_family|, but containing images of specific dimensions desirable for
// Windows icons. For each desired image dimension, it chooses the most
// appropriate image for that size, and resizes it to the desired size.
// Returns true on success, false on failure. Failure can occur if
// |image_family| is empty, all images in the family have size 0x0, or an image
// has no allocated pixel data.
// |resized_image_family| must be empty.
bool BuildResizedImageFamily(const gfx::ImageFamily& image_family,
                             gfx::ImageFamily* resized_image_family) {
  DCHECK(resized_image_family);
  DCHECK(resized_image_family->empty());

  // Determine whether there is an image bigger than 48x48 (kMediumIconSize).
  const gfx::Image* biggest =
      image_family.GetBest(IconUtil::kLargeIconSize, IconUtil::kLargeIconSize);
  if (!biggest || biggest->IsEmpty()) {
    // Either |image_family| is empty, or all images have size 0x0.
    return false;
  }

  bool has_bigger_than_medium = biggest->Width() > IconUtil::kMediumIconSize ||
                                biggest->Height() > IconUtil::kMediumIconSize;

  for (size_t i = 0; i < IconUtil::kNumIconDimensions; ++i) {
    int dimension = IconUtil::kIconDimensions[i];
    // Windows' "Large icons" view displays icons at full size only if there is
    // a 256x256 (kLargeIconSize) image in the .ico file. Otherwise, it shrinks
    // icons to 48x48 (kMediumIconSize). Therefore, if there is no source icon
    // larger than 48x48, do not create any images larger than 48x48.
    // kIconDimensions is sorted in ascending order, so it is safe to break
    // here.
    if (!has_bigger_than_medium && dimension > IconUtil::kMediumIconSize)
      break;

    gfx::Image resized = image_family.CreateExact(dimension, dimension);
    if (resized.IsEmpty()) {
      // An error occurred in CreateExact (typically because the image had the
      // wrong pixel format).
      return false;
    }

    resized_image_family->Add(resized);
  }
  return true;
}

// Creates a set of bitmaps from an image family.
// All images smaller than 256x256 are converted to SkBitmaps, and inserted into
// |bitmaps| in order of aspect ratio (thinnest to widest), and then ascending
// size order. If an image of exactly 256x256 is specified, it is converted into
// PNG format and stored in |png_bytes|. Images with width or height larger than
// 256 are ignored.
// |bitmaps| must be an empty vector, and not NULL.
// Returns true on success, false on failure. This fails if any image in
// |image_family| is not a 32-bit ARGB image, or is otherwise invalid.
bool ConvertImageFamilyToBitmaps(
    const gfx::ImageFamily& image_family,
    std::vector<SkBitmap>* bitmaps,
    scoped_refptr<base::RefCountedMemory>* png_bytes) {
  DCHECK(bitmaps != NULL);
  DCHECK(bitmaps->empty());

  for (gfx::ImageFamily::const_iterator it = image_family.begin();
       it != image_family.end(); ++it) {
    const gfx::Image& image = *it;

    // All images should have one of the kIconDimensions sizes.
    DCHECK_GT(image.Width(), 0);
    DCHECK_LE(image.Width(), IconUtil::kLargeIconSize);
    DCHECK_GT(image.Height(), 0);
    DCHECK_LE(image.Height(), IconUtil::kLargeIconSize);

    SkBitmap bitmap = image.AsBitmap();

    // Only 32 bit ARGB bitmaps are supported. We also make sure the bitmap has
    // been properly initialized.
    SkAutoLockPixels bitmap_lock(bitmap);
    if ((bitmap.colorType() != kN32_SkColorType) ||
        (bitmap.getPixels() == NULL)) {
      return false;
    }

    // Special case: Icons exactly 256x256 are stored in PNG format.
    if (image.Width() == IconUtil::kLargeIconSize &&
        image.Height() == IconUtil::kLargeIconSize) {
      *png_bytes = image.As1xPNGBytes();
    } else {
      bitmaps->push_back(bitmap);
    }
  }

  return true;
}

}  // namespace

// The icon images appear in the icon file in same order in which their
// corresponding dimensions appear in this array, so it is important to keep
// this array sorted. Also note that the maximum icon image size we can handle
// is 256 by 256. See:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa511280.aspx#size
const int IconUtil::kIconDimensions[] = {
  8,    // Recommended by the MSDN as a nice to have icon size.
  10,   // Used by the Shell (e.g. for shortcuts).
  14,   // Recommended by the MSDN as a nice to have icon size.
  16,   // Toolbar, Application and Shell icon sizes.
  22,   // Recommended by the MSDN as a nice to have icon size.
  24,   // Used by the Shell (e.g. for shortcuts).
  32,   // Toolbar, Dialog and Wizard icon size.
  40,   // Quick Launch.
  48,   // Alt+Tab icon size.
  64,   // Recommended by the MSDN as a nice to have icon size.
  96,   // Recommended by the MSDN as a nice to have icon size.
  128,  // Used by the Shell (e.g. for shortcuts).
  256   // Used by Vista onwards for large icons.
};

const size_t IconUtil::kNumIconDimensions = arraysize(kIconDimensions);
const size_t IconUtil::kNumIconDimensionsUpToMediumSize = 9;

HICON IconUtil::CreateHICONFromSkBitmap(const SkBitmap& bitmap) {
  // Only 32 bit ARGB bitmaps are supported. We also try to perform as many
  // validations as we can on the bitmap.
  SkAutoLockPixels bitmap_lock(bitmap);
  if ((bitmap.colorType() != kN32_SkColorType) ||
      (bitmap.width() <= 0) || (bitmap.height() <= 0) ||
      (bitmap.getPixels() == NULL))
    return NULL;

  // We start by creating a DIB which we'll use later on in order to create
  // the HICON. We use BITMAPV5HEADER since the bitmap we are about to convert
  // may contain an alpha channel and the V5 header allows us to specify the
  // alpha mask for the DIB.
  BITMAPV5HEADER bitmap_header;
  InitializeBitmapHeader(&bitmap_header, bitmap.width(), bitmap.height());

  void* bits = NULL;
  HBITMAP dib;

  {
    base::win::ScopedGetDC hdc(NULL);
    dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&bitmap_header),
                             DIB_RGB_COLORS, &bits, NULL, 0);
  }
  if (!dib || !bits)
    return NULL;

  memcpy(bits, bitmap.getPixels(), bitmap.width() * bitmap.height() * 4);

  // Icons are generally created using an AND and XOR masks where the AND
  // specifies boolean transparency (the pixel is either opaque or
  // transparent) and the XOR mask contains the actual image pixels. If the XOR
  // mask bitmap has an alpha channel, the AND monochrome bitmap won't
  // actually be used for computing the pixel transparency. Even though all our
  // bitmap has an alpha channel, Windows might not agree when all alpha values
  // are zero. So the monochrome bitmap is created with all pixels transparent
  // for this case. Otherwise, it is created with all pixels opaque.
  bool bitmap_has_alpha_channel = PixelsHaveAlpha(
      static_cast<const uint32*>(bitmap.getPixels()),
      bitmap.width() * bitmap.height());

  scoped_ptr<uint8[]> mask_bits;
  if (!bitmap_has_alpha_channel) {
    // Bytes per line with paddings to make it word alignment.
    size_t bytes_per_line = (bitmap.width() + 0xF) / 16 * 2;
    size_t mask_bits_size = bytes_per_line * bitmap.height();

    mask_bits.reset(new uint8[mask_bits_size]);
    DCHECK(mask_bits.get());

    // Make all pixels transparent.
    memset(mask_bits.get(), 0xFF, mask_bits_size);
  }

  HBITMAP mono_bitmap = ::CreateBitmap(bitmap.width(), bitmap.height(), 1, 1,
      reinterpret_cast<LPVOID>(mask_bits.get()));
  DCHECK(mono_bitmap);

  ICONINFO icon_info;
  icon_info.fIcon = TRUE;
  icon_info.xHotspot = 0;
  icon_info.yHotspot = 0;
  icon_info.hbmMask = mono_bitmap;
  icon_info.hbmColor = dib;
  HICON icon = ::CreateIconIndirect(&icon_info);
  ::DeleteObject(dib);
  ::DeleteObject(mono_bitmap);
  return icon;
}

SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) {
  // We start with validating parameters.
  if (!icon || s.IsEmpty())
    return NULL;
  ScopedICONINFO icon_info;
  if (!::GetIconInfo(icon, &icon_info))
    return NULL;
  if (!icon_info.fIcon)
    return NULL;
  return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, s));
}

// static
scoped_ptr<gfx::ImageFamily> IconUtil::CreateImageFamilyFromIconResource(
    HMODULE module,
    int resource_id) {
  // Read the resource directly so we can get the icon image sizes. This data
  // will also be used to directly get the PNG bytes for large images.
  void* icon_dir_data = NULL;
  size_t icon_dir_size = 0;
  if (!base::win::GetResourceFromModule(module, resource_id, RT_GROUP_ICON,
                                        &icon_dir_data, &icon_dir_size)) {
    return nullptr;
  }
  DCHECK(icon_dir_data);
  DCHECK_GE(icon_dir_size, sizeof(GRPICONDIR));

  const GRPICONDIR* icon_dir =
      reinterpret_cast<const GRPICONDIR*>(icon_dir_data);
  scoped_ptr<gfx::ImageFamily> result(new gfx::ImageFamily);
  for (size_t i = 0; i < icon_dir->idCount; ++i) {
    const GRPICONDIRENTRY* entry = &icon_dir->idEntries[i];
    if (entry->bWidth != 0 || entry->bHeight != 0) {
      // Ignore the low-bit-depth versions of the icon.
      if (entry->wBitCount != 32)
        continue;

      // For everything except the Vista+ 256x256 icons, use |LoadImage()|.
      HICON icon_handle = static_cast<HICON>(LoadImage(
          module, MAKEINTRESOURCE(resource_id), IMAGE_ICON, entry->bWidth,
          entry->bHeight, LR_DEFAULTCOLOR | LR_DEFAULTSIZE));
      scoped_ptr<SkBitmap> bitmap(
          IconUtil::CreateSkBitmapFromHICON(icon_handle));
      DestroyIcon(icon_handle);
      result->Add(gfx::Image::CreateFrom1xBitmap(*bitmap));
    } else {
      // 256x256 icons are stored with width and height set to 0.
      // See: http://en.wikipedia.org/wiki/ICO_(file_format)
      void* png_data = NULL;
      size_t png_size = 0;
      if (!base::win::GetResourceFromModule(module, entry->nID, RT_ICON,
                                            &png_data, &png_size)) {
        return nullptr;
      }
      DCHECK(png_data);
      DCHECK_EQ(png_size, entry->dwBytesInRes);

      result->Add(gfx::Image::CreateFrom1xPNGBytes(
          new base::RefCountedStaticMemory(png_data, png_size)));
    }
  }
  return result;
}

SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon) {
  // We start with validating parameters.
  if (!icon)
    return NULL;

  ScopedICONINFO icon_info;
  BITMAP bitmap_info = { 0 };

  if (!::GetIconInfo(icon, &icon_info))
    return NULL;

  if (!::GetObject(icon_info.hbmMask, sizeof(bitmap_info), &bitmap_info))
    return NULL;

  gfx::Size icon_size(bitmap_info.bmWidth, bitmap_info.bmHeight);
  return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, icon_size));
}

HICON IconUtil::CreateCursorFromDIB(const gfx::Size& icon_size,
                                    const gfx::Point& hotspot,
                                    const void* dib_bits,
                                    size_t dib_size) {
  BITMAPINFO icon_bitmap_info = {};
  gfx::CreateBitmapHeader(
      icon_size.width(),
      icon_size.height(),
      reinterpret_cast<BITMAPINFOHEADER*>(&icon_bitmap_info));

  base::win::ScopedGetDC dc(NULL);
  base::win::ScopedCreateDC working_dc(CreateCompatibleDC(dc));
  base::win::ScopedGDIObject<HBITMAP> bitmap_handle(
      CreateDIBSection(dc,
                       &icon_bitmap_info,
                       DIB_RGB_COLORS,
                       0,
                       0,
                       0));
  if (dib_size > 0) {
    SetDIBits(0,
              bitmap_handle,
              0,
              icon_size.height(),
              dib_bits,
              &icon_bitmap_info,
              DIB_RGB_COLORS);
  }

  HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(
      SelectObject(working_dc.Get(), bitmap_handle));
  SetBkMode(working_dc.Get(), TRANSPARENT);
  SelectObject(working_dc.Get(), old_bitmap);

  base::win::ScopedGDIObject<HBITMAP> mask(
      CreateBitmap(icon_size.width(),
                   icon_size.height(),
                   1,
                   1,
                   NULL));
  ICONINFO ii = {0};
  ii.fIcon = FALSE;
  ii.xHotspot = hotspot.x();
  ii.yHotspot = hotspot.y();
  ii.hbmMask = mask;
  ii.hbmColor = bitmap_handle;

  return CreateIconIndirect(&ii);
}

SkBitmap IconUtil::CreateSkBitmapFromHICONHelper(HICON icon,
                                                 const gfx::Size& s) {
  DCHECK(icon);
  DCHECK(!s.IsEmpty());

  // Allocating memory for the SkBitmap object. We are going to create an ARGB
  // bitmap so we should set the configuration appropriately.
  SkBitmap bitmap;
  bitmap.allocN32Pixels(s.width(), s.height());
  bitmap.eraseARGB(0, 0, 0, 0);
  SkAutoLockPixels bitmap_lock(bitmap);

  // Now we should create a DIB so that we can use ::DrawIconEx in order to
  // obtain the icon's image.
  BITMAPV5HEADER h;
  InitializeBitmapHeader(&h, s.width(), s.height());
  HDC hdc = ::GetDC(NULL);
  uint32* bits;
  HBITMAP dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&h),
      DIB_RGB_COLORS, reinterpret_cast<void**>(&bits), NULL, 0);
  DCHECK(dib);
  HDC dib_dc = CreateCompatibleDC(hdc);
  ::ReleaseDC(NULL, hdc);
  DCHECK(dib_dc);
  HGDIOBJ old_obj = ::SelectObject(dib_dc, dib);

  // Windows icons are defined using two different masks. The XOR mask, which
  // represents the icon image and an AND mask which is a monochrome bitmap
  // which indicates the transparency of each pixel.
  //
  // To make things more complex, the icon image itself can be an ARGB bitmap
  // and therefore contain an alpha channel which specifies the transparency
  // for each pixel. Unfortunately, there is no easy way to determine whether
  // or not a bitmap has an alpha channel and therefore constructing the bitmap
  // for the icon is nothing but straightforward.
  //
  // The idea is to read the AND mask but use it only if we know for sure that
  // the icon image does not have an alpha channel. The only way to tell if the
  // bitmap has an alpha channel is by looking through the pixels and checking
  // whether there are non-zero alpha bytes.
  //
  // We start by drawing the AND mask into our DIB.
  size_t num_pixels = s.GetArea();
  memset(bits, 0, num_pixels * 4);
  ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_MASK);

  // Capture boolean opacity. We may not use it if we find out the bitmap has
  // an alpha channel.
  scoped_ptr<bool[]> opaque(new bool[num_pixels]);
  for (size_t i = 0; i < num_pixels; ++i)
    opaque[i] = !bits[i];

  // Then draw the image itself which is really the XOR mask.
  memset(bits, 0, num_pixels * 4);
  ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_NORMAL);
  memcpy(bitmap.getPixels(), static_cast<void*>(bits), num_pixels * 4);

  // Finding out whether the bitmap has an alpha channel.
  bool bitmap_has_alpha_channel = PixelsHaveAlpha(
      static_cast<const uint32*>(bitmap.getPixels()), num_pixels);

  // If the bitmap does not have an alpha channel, we need to build it using
  // the previously captured AND mask. Otherwise, we are done.
  if (!bitmap_has_alpha_channel) {
    uint32* p = static_cast<uint32*>(bitmap.getPixels());
    for (size_t i = 0; i < num_pixels; ++p, ++i) {
      DCHECK_EQ((*p & 0xff000000), 0u);
      if (opaque[i])
        *p |= 0xff000000;
      else
        *p &= 0x00ffffff;
    }
  }

  ::SelectObject(dib_dc, old_obj);
  ::DeleteObject(dib);
  ::DeleteDC(dib_dc);

  return bitmap;
}

// static
bool IconUtil::CreateIconFileFromImageFamily(
    const gfx::ImageFamily& image_family,
    const base::FilePath& icon_path,
    WriteType write_type) {
  // Creating a set of bitmaps corresponding to the icon images we'll end up
  // storing in the icon file. Each bitmap is created by resizing the most
  // appropriate image from |image_family| to the desired size.
  gfx::ImageFamily resized_image_family;
  if (!BuildResizedImageFamily(image_family, &resized_image_family))
    return false;

  std::vector<SkBitmap> bitmaps;
  scoped_refptr<base::RefCountedMemory> png_bytes;
  if (!ConvertImageFamilyToBitmaps(resized_image_family, &bitmaps, &png_bytes))
    return false;

  // Guaranteed true because BuildResizedImageFamily will provide at least one
  // image < 256x256.
  DCHECK(!bitmaps.empty());
  size_t bitmap_count = bitmaps.size();  // Not including PNG image.
  // Including PNG image, if any.
  size_t image_count = bitmap_count + (png_bytes.get() ? 1 : 0);

  // Computing the total size of the buffer we need in order to store the
  // images in the desired icon format.
  size_t buffer_size = ComputeIconFileBufferSize(bitmaps);
  // Account for the bytes needed for the PNG entry.
  if (png_bytes.get())
    buffer_size += sizeof(ICONDIRENTRY) + png_bytes->size();

  // Setting the information in the structures residing within the buffer.
  // First, we set the information which doesn't require iterating through the
  // bitmap set and then we set the bitmap specific structures. In the latter
  // step we also copy the actual bits.
  std::vector<uint8> buffer(buffer_size);
  ICONDIR* icon_dir = reinterpret_cast<ICONDIR*>(&buffer[0]);
  icon_dir->idType = kResourceTypeIcon;
  icon_dir->idCount = static_cast<WORD>(image_count);
  // - 1 because there is already one ICONDIRENTRY in ICONDIR.
  size_t icon_dir_count = image_count - 1;

  size_t offset = sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * icon_dir_count);
  for (size_t i = 0; i < bitmap_count; i++) {
    ICONIMAGE* image = reinterpret_cast<ICONIMAGE*>(&buffer[offset]);
    DCHECK_LT(offset, buffer_size);
    size_t icon_image_size = 0;
    SetSingleIconImageInformation(bitmaps[i], i, icon_dir, image, offset,
                                  &icon_image_size);
    DCHECK_GT(icon_image_size, 0U);
    offset += icon_image_size;
  }

  // Add the PNG entry, if necessary.
  if (png_bytes.get()) {
    ICONDIRENTRY* entry = &icon_dir->idEntries[bitmap_count];
    entry->bWidth = 0;
    entry->bHeight = 0;
    entry->wPlanes = 1;
    entry->wBitCount = 32;
    entry->dwBytesInRes = static_cast<DWORD>(png_bytes->size());
    entry->dwImageOffset = static_cast<DWORD>(offset);
    memcpy(&buffer[offset], png_bytes->front(), png_bytes->size());
    offset += png_bytes->size();
  }

  DCHECK_EQ(offset, buffer_size);

  if (write_type == NORMAL_WRITE) {
    auto saved_size =
        base::WriteFile(icon_path, reinterpret_cast<const char*>(&buffer[0]),
                        static_cast<int>(buffer.size()));
    if (saved_size == static_cast<int>(buffer.size()))
      return true;
    bool delete_success = base::DeleteFile(icon_path, false);
    DCHECK(delete_success);
    return false;
  } else {
    std::string data(buffer.begin(), buffer.end());
    return base::ImportantFileWriter::WriteFileAtomically(icon_path, data);
  }
}

bool IconUtil::PixelsHaveAlpha(const uint32* pixels, size_t num_pixels) {
  for (const uint32* end = pixels + num_pixels; pixels != end; ++pixels) {
    if ((*pixels & 0xff000000) != 0)
      return true;
  }

  return false;
}

void IconUtil::InitializeBitmapHeader(BITMAPV5HEADER* header, int width,
                                      int height) {
  DCHECK(header);
  memset(header, 0, sizeof(BITMAPV5HEADER));
  header->bV5Size = sizeof(BITMAPV5HEADER);

  // Note that icons are created using top-down DIBs so we must negate the
  // value used for the icon's height.
  header->bV5Width = width;
  header->bV5Height = -height;
  header->bV5Planes = 1;
  header->bV5Compression = BI_RGB;

  // Initializing the bitmap format to 32 bit ARGB.
  header->bV5BitCount = 32;
  header->bV5RedMask = 0x00FF0000;
  header->bV5GreenMask = 0x0000FF00;
  header->bV5BlueMask = 0x000000FF;
  header->bV5AlphaMask = 0xFF000000;

  // Use the system color space.  The default value is LCS_CALIBRATED_RGB, which
  // causes us to crash if we don't specify the approprite gammas, etc.  See
  // <http://msdn.microsoft.com/en-us/library/ms536531(VS.85).aspx> and
  // <http://b/1283121>.
  header->bV5CSType = LCS_WINDOWS_COLOR_SPACE;

  // Use a valid value for bV5Intent as 0 is not a valid one.
  // <http://msdn.microsoft.com/en-us/library/dd183381(VS.85).aspx>
  header->bV5Intent = LCS_GM_IMAGES;
}

void IconUtil::SetSingleIconImageInformation(const SkBitmap& bitmap,
                                             size_t index,
                                             ICONDIR* icon_dir,
                                             ICONIMAGE* icon_image,
                                             size_t image_offset,
                                             size_t* image_byte_count) {
  DCHECK(icon_dir != NULL);
  DCHECK(icon_image != NULL);
  DCHECK_GT(image_offset, 0U);
  DCHECK(image_byte_count != NULL);
  DCHECK_LT(bitmap.width(), kLargeIconSize);
  DCHECK_LT(bitmap.height(), kLargeIconSize);

  // We start by computing certain image values we'll use later on.
  size_t xor_mask_size, bytes_in_resource;
  ComputeBitmapSizeComponents(bitmap,
                              &xor_mask_size,
                              &bytes_in_resource);

  icon_dir->idEntries[index].bWidth = static_cast<BYTE>(bitmap.width());
  icon_dir->idEntries[index].bHeight = static_cast<BYTE>(bitmap.height());
  icon_dir->idEntries[index].wPlanes = 1;
  icon_dir->idEntries[index].wBitCount = 32;
  icon_dir->idEntries[index].dwBytesInRes = bytes_in_resource;
  icon_dir->idEntries[index].dwImageOffset = image_offset;
  icon_image->icHeader.biSize = sizeof(BITMAPINFOHEADER);

  // The width field in the BITMAPINFOHEADER structure accounts for the height
  // of both the AND mask and the XOR mask so we need to multiply the bitmap's
  // height by 2. The same does NOT apply to the width field.
  icon_image->icHeader.biHeight = bitmap.height() * 2;
  icon_image->icHeader.biWidth = bitmap.width();
  icon_image->icHeader.biPlanes = 1;
  icon_image->icHeader.biBitCount = 32;

  // We use a helper function for copying to actual bits from the SkBitmap
  // object into the appropriate space in the buffer. We use a helper function
  // (rather than just copying the bits) because there is no way to specify the
  // orientation (bottom-up vs. top-down) of a bitmap residing in a .ico file.
  // Thus, if we just copy the bits, we'll end up with a bottom up bitmap in
  // the .ico file which will result in the icon being displayed upside down.
  // The helper function copies the image into the buffer one scanline at a
  // time.
  //
  // Note that we don't need to initialize the AND mask since the memory
  // allocated for the icon data buffer was initialized to zero. The icon we
  // create will therefore use an AND mask containing only zeros, which is OK
  // because the underlying image has an alpha channel. An AND mask containing
  // only zeros essentially means we'll initially treat all the pixels as
  // opaque.
  unsigned char* image_addr = reinterpret_cast<unsigned char*>(icon_image);
  unsigned char* xor_mask_addr = image_addr + sizeof(BITMAPINFOHEADER);
  CopySkBitmapBitsIntoIconBuffer(bitmap, xor_mask_addr, xor_mask_size);
  *image_byte_count = bytes_in_resource;
}

void IconUtil::CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap,
                                              unsigned char* buffer,
                                              size_t buffer_size) {
  SkAutoLockPixels bitmap_lock(bitmap);
  unsigned char* bitmap_ptr = static_cast<unsigned char*>(bitmap.getPixels());
  size_t bitmap_size = bitmap.height() * bitmap.width() * 4;
  DCHECK_EQ(buffer_size, bitmap_size);
  for (size_t i = 0; i < bitmap_size; i += bitmap.width() * 4) {
    memcpy(buffer + bitmap_size - bitmap.width() * 4 - i,
           bitmap_ptr + i,
           bitmap.width() * 4);
  }
}

size_t IconUtil::ComputeIconFileBufferSize(const std::vector<SkBitmap>& set) {
  DCHECK(!set.empty());

  // We start by counting the bytes for the structures that don't depend on the
  // number of icon images. Note that sizeof(ICONDIR) already accounts for a
  // single ICONDIRENTRY structure, which is why we subtract one from the
  // number of bitmaps.
  size_t total_buffer_size = sizeof(ICONDIR);
  size_t bitmap_count = set.size();
  total_buffer_size += sizeof(ICONDIRENTRY) * (bitmap_count - 1);
  // May not have all icon sizes, but must have at least up to medium icon size.
  DCHECK_GE(bitmap_count, kNumIconDimensionsUpToMediumSize);

  // Add the bitmap specific structure sizes.
  for (size_t i = 0; i < bitmap_count; i++) {
    size_t xor_mask_size, bytes_in_resource;
    ComputeBitmapSizeComponents(set[i],
                                &xor_mask_size,
                                &bytes_in_resource);
    total_buffer_size += bytes_in_resource;
  }
  return total_buffer_size;
}

void IconUtil::ComputeBitmapSizeComponents(const SkBitmap& bitmap,
                                           size_t* xor_mask_size,
                                           size_t* bytes_in_resource) {
  // The XOR mask size is easy to calculate since we only deal with 32bpp
  // images.
  *xor_mask_size = bitmap.width() * bitmap.height() * 4;

  // Computing the AND mask is a little trickier since it is a monochrome
  // bitmap (regardless of the number of bits per pixels used in the XOR mask).
  // There are two things we must make sure we do when computing the AND mask
  // size:
  //
  // 1. Make sure the right number of bytes is allocated for each AND mask
  //    scan line in case the number of pixels in the image is not divisible by
  //    8. For example, in a 15X15 image, 15 / 8 is one byte short of
  //    containing the number of bits we need in order to describe a single
  //    image scan line so we need to add a byte. Thus, we need 2 bytes instead
  //    of 1 for each scan line.
  //
  // 2. Make sure each scan line in the AND mask is 4 byte aligned (so that the
  //    total icon image has a 4 byte alignment). In the 15X15 image example
  //    above, we can not use 2 bytes so we increase it to the next multiple of
  //    4 which is 4.
  //
  // Once we compute the size for a singe AND mask scan line, we multiply that
  // number by the image height in order to get the total number of bytes for
  // the AND mask. Thus, for a 15X15 image, we need 15 * 4 which is 60 bytes
  // for the monochrome bitmap representing the AND mask.
  size_t and_line_length = (bitmap.width() + 7) >> 3;
  and_line_length = (and_line_length + 3) & ~3;
  size_t and_mask_size = and_line_length * bitmap.height();
  size_t masks_size = *xor_mask_size + and_mask_size;
  *bytes_in_resource = masks_size + sizeof(BITMAPINFOHEADER);
}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.securityhub.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.securityhub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * BatchImportFindingsResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchImportFindingsResultJsonUnmarshaller implements Unmarshaller<BatchImportFindingsResult, JsonUnmarshallerContext> {

    public BatchImportFindingsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        BatchImportFindingsResult batchImportFindingsResult = new BatchImportFindingsResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return batchImportFindingsResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("FailedCount", targetDepth)) {
                    context.nextToken();
                    batchImportFindingsResult.setFailedCount(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("SuccessCount", targetDepth)) {
                    context.nextToken();
                    batchImportFindingsResult.setSuccessCount(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("FailedFindings", targetDepth)) {
                    context.nextToken();
                    batchImportFindingsResult.setFailedFindings(new ListUnmarshaller<ImportFindingsError>(ImportFindingsErrorJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return batchImportFindingsResult;
    }

    private static BatchImportFindingsResultJsonUnmarshaller instance;

    public static BatchImportFindingsResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new BatchImportFindingsResultJsonUnmarshaller();
        return instance;
    }
}


text:
import wx

from odm2api.ODMconnection import dbconnection
#TODO get rid of *
from odm2api.ODM2.services.readService import *
from src.wizard.controller.frmNewSeriesDialog import NewSeriesDialog
from src.wizard.controller.frmAddNewResultsPanel import AddNewResultsPanelController
from src.wizard.controller.frmSeriesSelectPanel import SeriesSelectPanel

from src.wizard.view.clsResultPage import ResultPageView

from ObjectListView import ObjectListView, ColumnDefn

class ResultsSelectPanel(SeriesSelectPanel):
    '''
    '''
    def __init__( self, parent, label):
        super(ResultsSelectPanel, self).__init__(parent, label)
        self.list_ctrl.Show(False)
        self.new_button.Show(False)
        sizer = self.GetSizer()
        sizer.Add(ResultPageView, 0, wx.ALL, 5)

    def getSeriesData(self):
        read = self.db.getReadSession()
        return read.getResults()

    def onButtonAdd(self, event):
        event.Skip()

    def __del__( self ):
        pass


text:
using System.Data.Entity.ModelConfiguration;
using Inspire.Shared.Models;

namespace GameServer.Models.Mapping
{
    public class CharacterMap : EntityTypeConfiguration<Character>
    {
        public CharacterMap()
        {
            // Primary Key
            this.HasKey(t => t.CharacterId);

            // Properties
            this.Property(t => t.Name)
                .IsRequired()
                .HasMaxLength(45);

        }
    }
}


text:
package misc;

public class D implements A, B, C {

    @Override
    public void common() {
        System.out.println(getClass().getSuperclass().getName());
    }

    public static void main(String[] args) {
        new D().common();
    }
}


text:
'use strict';

var assert = require('assert');
var mockery = require('mockery-next');
var is = require('is');
var nodeutil = require('util');

var ServiceObject = require('../../lib/common/service-object.js');
var util = require('../../lib/common/util.js');

function FakeServiceObject() {
  this.calledWith_ = arguments;
  ServiceObject.apply(this, arguments);
}

nodeutil.inherits(FakeServiceObject, ServiceObject);

describe('BigQuery/Job', function() {
  var BIGQUERY = {
    projectId: 'my-project'
  };
  var JOB_ID = 'job_XYrk_3z';
  var Job;
  var job;

  before(function() {
    mockery.registerMock(
      '../../lib/common/service-object.js',
      FakeServiceObject
    );
    mockery.enable({
      useCleanCache: true,
      warnOnUnregistered: false
    });

    Job = require('../../lib/bigquery/job.js');
  });

  after(function() {
    mockery.deregisterAll();
    mockery.disable();
  });

  beforeEach(function() {
    job = new Job(BIGQUERY, JOB_ID);
  });

  describe('initialization', function() {
    it('should assign this.bigQuery', function() {
      assert.deepEqual(job.bigQuery, BIGQUERY);
    });

    it('should inherit from ServiceObject', function() {
      assert(job instanceof ServiceObject);

      var calledWith = job.calledWith_[0];

      assert.strictEqual(calledWith.parent, BIGQUERY);
      assert.strictEqual(calledWith.baseUrl, '/jobs');
      assert.strictEqual(calledWith.id, JOB_ID);
      assert.deepEqual(calledWith.methods, {
        exists: true,
        get: true,
        getMetadata: true
      });
    });

    describe('request interceptor', function() {
      it('should assign a request interceptor for /cancel', function() {
        var requestInterceptor = job.interceptors.pop().request;
        assert(is.fn(requestInterceptor));
      });

      it('should transform `projects` -> `project` for /cancel', function() {
        var reqOpts = {
          uri: '/bigquery/v2/projects/projectId/jobs/jobId/cancel'
        };
        var expectedReqOpts = {
          uri: '/bigquery/v2/project/projectId/jobs/jobId/cancel'
        };

        var requestInterceptor = job.interceptors.pop().request;
        assert.deepEqual(requestInterceptor(reqOpts), expectedReqOpts);
      });

      it('should not affect non-cancel requests', function() {
        var reqOpts = {
          uri: '/bigquery/v2/projects/projectId/jobs/jobId/getQueryResults'
        };
        var expectedReqOpts = {
          uri: '/bigquery/v2/projects/projectId/jobs/jobId/getQueryResults'
        };

        var requestInterceptor = job.interceptors.pop().request;
        assert.deepEqual(requestInterceptor(reqOpts), expectedReqOpts);
      });
    });

  });

  describe('cancel', function() {
    it('should make the correct API request', function(done) {
      job.request = function(reqOpts) {
        assert.strictEqual(reqOpts.method, 'POST');
        assert.strictEqual(reqOpts.uri, '/cancel');
        done();
      };

      job.cancel(assert.ifError);
    });

    it('should not require a callback', function(done) {
      job.request = function(reqOpts, callback) {
        assert.doesNotThrow(function() {
          callback();
          done();
        });
      };

      job.cancel();
    });

    it('should execute callback with only error & API resp', function(done) {
      var arg1 = {};
      var arg2 = {};
      var arg3 = {};

      job.request = function(reqOpts, callback) {
        callback(arg1, arg2, arg3);
      };

      job.cancel(function(arg1_, arg2_) {
        assert.strictEqual(arguments.length, 2);
        assert.strictEqual(arg1_, arg1);
        assert.strictEqual(arg2_, arg2);
        done();
      });
    });
  });

  describe('getQueryResults', function() {
    var options = {
      a: 'b',
      c: 'd'
    };
    var callback = util.noop;

    it('should accept an options object & callback', function(done) {
      job.bigQuery.query = function(opts, cb) {
        assert.deepEqual(opts, options);
        assert.equal(cb, callback);
        done();
      };

      job.getQueryResults(options, callback);
    });

    it('should accept an options object without a callback', function(done) {
      job.bigQuery.query = function(opts, cb) {
        assert.deepEqual(opts, options);
        assert.equal(cb, undefined);
        done();
      };

      job.getQueryResults(options);
    });

    it('should accept no arguments', function(done) {
      job.bigQuery.query = function(opts, cb) {
        assert.deepEqual(opts, { job: job });
        assert.equal(cb, undefined);
        done();
      };

      job.getQueryResults();
    });

    it('should assign job to the options object', function(done) {
      job.bigQuery.query = function(opts) {
        assert.deepEqual(opts.job, job);
        done();
      };

      job.getQueryResults();
    });

    it('should return the result of the call to bq.query', function(done) {
      job.bigQuery.query = function() {
        return {
          done: done
        };
      };

      job.getQueryResults().done();
    });
  });
});


text:
package org.rabix.bindings.protocol.draft3.bean;

import java.util.Map;

import org.rabix.bindings.protocol.draft3.Draft3JobProcessor;
import org.rabix.bindings.protocol.draft3.helper.Draft3SchemaHelper;
import org.rabix.common.json.BeanPropertyView;
import org.rabix.common.json.processor.BeanProcessorClass;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@BeanProcessorClass(name = Draft3JobProcessor.class)
public final class Draft3Job {

  @JsonProperty("id")
  private String id;

  @JsonProperty("app")
  private Draft3JobApp app;

  @JsonProperty("inputs")
  private Map<String, Object> inputs;

  @JsonProperty("outputs")
  private Map<String, Object> outputs;

  @JsonProperty("scatter")
  @JsonView(BeanPropertyView.Full.class)
  private Object scatter;

  @JsonProperty("scatterMethod")
  @JsonView(BeanPropertyView.Full.class)
  private String scatterMethod;

  @JsonProperty("allocatedResources")
  private Draft3Resources resources;

  @JsonCreator
  public Draft3Job(@JsonProperty("app") Draft3JobApp app,
      @JsonProperty("inputs") Map<String, Object> inputs,
      @JsonProperty("outputs") Map<String, Object> outputs,
      @JsonProperty("allocatedResources") Draft3Resources resources,
      @JsonProperty("id") String id, @JsonProperty("scatter") Object scatter,
      @JsonProperty("scatterMethod") String scatterMethod) {
    this.id = id;
    this.app = app;
    this.inputs = inputs;
    this.outputs = outputs;
    this.resources = resources;
    this.scatter = scatter;
    this.scatterMethod = scatterMethod;
    processPortDefaults();
  }

  private void processPortDefaults() {
    if (inputs == null) {
      return;
    }
    for (Draft3InputPort inputPort : app.getInputs()) {
      String normalizedId = Draft3SchemaHelper.normalizeId(inputPort.getId());
      if (!inputs.containsKey(normalizedId) && inputPort.getDefaultValue() != null) {
        inputs.put(normalizedId, inputPort.getDefaultValue());
      }
    }
  }

  public Draft3Job(Draft3JobApp app, Map<String, Object> inputs, Map<String, Object> outputs, Object scatter, String scatterMethod, String id) {
    this.id = id;
    this.app = app;
    this.scatter = scatter;
    this.inputs = inputs;
    this.outputs = outputs;
    this.scatterMethod = scatterMethod;
    processPortDefaults();
  }

  public Draft3Job(Draft3JobApp app, Map<String, Object> inputs) {
    this.app = app;
    this.inputs = inputs;
    processPortDefaults();
  }

  public boolean isInlineJavascriptEnabled() {
    return app.getInlineJavascriptRequirement() != null;
  }

  public boolean isShellCommandEscapeEnabled() {
    return app.getShellCommandRequirement() != null;
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public Draft3JobApp getApp() {
    return app;
  }

  public Map<String, Object> getInputs() {
    return inputs;
  }

  public Map<String, Object> getOutputs() {
    return outputs;
  }

  public void setResources(Draft3Resources resources) {
    this.resources = resources;
  }

  public Draft3Resources getResources() {
    return resources;
  }

  public Object getScatter() {
    return scatter;
  }

  public String getScatterMethod() {
    return scatterMethod;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Draft3Job other = (Draft3Job) obj;
    if (app == null) {
      if (other.app != null)
        return false;
    } else if (!app.equals(other.app))
      return false;
    if (id == null) {
      if (other.id != null)
        return false;
    } else if (!id.equals(other.id))
      return false;
    return true;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((app == null) ? 0 : app.hashCode());
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
  }

  @Override
  public String toString() {
    return "Job [id=" + id + ", app=" + app + ", inputs=" + inputs + ", outputs=" + outputs + ", scatter=" + scatter + ", resources=" + resources + "]";
  }

}


text:
require "test_helper"
require "fakefs/safe"

describe RMonitor::Commands::List do

  before :each do
    FakeFS.activate!

    RMonitor::Config.config_path = nil

    FileUtils.mkdir_p File.dirname DEFAULT_CONFIG_PATH

    File.write DEFAULT_CONFIG_PATH, <<-CONFIG
        profile "docked" do
          device "HDMI1", :mode => "1920x1080", :rate => "60.0"
          device "HDMI2", :mode => "1920x1080", :rate => "60.0"
        end

        profile "default" do
          device "eDP1", :mode => "1920x1080"
        end
    CONFIG
  end

  after :each do
    FakeFS.deactivate!
  end

  describe "#execute" do

    it "should return a list of all profiles" do
      expected = RMonitor::Config::Builder.define do
        profile "docked" do
          device "HDMI1", :mode => "1920x1080", :rate => "60.0"
          device "HDMI2", :mode => "1920x1080", :rate => "60.0"
        end

        profile "default" do
          device "eDP1", :mode => "1920x1080"
        end
      end

      actual = RMonitor::Commands::List.new.execute

      assert_equal expected, actual
    end

  end

end


text:
//
//  JXBanTangViewController.m
//  JXPlaygroundDemo
//
//  Created by mac on 17/6/1.
//  Copyright © 2017年 Mr.Gao. All rights reserved.
//

#import "JXBanTangViewController.h"
#import "UIView+Extension.h"
#import "JXBanTangHeaderView.h"
#import "JXBanTangRefreshHeader.h"
#import "JXBanTangTableViewController.h"
#import "UIButton+Size.h"

#define CATEGORY  @[@"推荐",@"原创",@"热门",@"美食",@"生活",@"设计感",@"家居",@"礼物",@"阅读",@"运动健身",@"旅行户外"]

#define NAVBARHEIGHT 64.0f

#define FONTMAX 15.0
#define FONTMIN 14.0
#define PADDING 15.0

/*! 偏移量 */
static CGFloat const kMaxOffset = 136;

@interface JXBanTangViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) JXBanTangHeaderView *jqHeaderView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;

///
//滑动事件相关
///
@property (nonatomic, strong) UIScrollView *segmentScrollView;
@property (nonatomic, strong) UIScrollView *bottomScrollView;

@property (nonatomic, strong) UIImageView *currentSelectedItemImageView;

//存放button
@property(nonatomic,strong)NSMutableArray *titleButtons;
//记录上一个button
@property (nonatomic, strong) UIButton *previousButton;
//存放控制器
@property(nonatomic,strong)NSMutableArray *controlleres;

//存放TableView
@property(nonatomic,strong)NSMutableArray *tableViews;

//记录上一个偏移量
@property (nonatomic, assign) CGFloat lastTableViewOffsetY;

@property (nonatomic, strong) UITableView *currentTableView;

@end

@implementation JXBanTangViewController

#pragma mark - lazy loading

- (UIScrollView *)bottomScrollView {

    if (!_bottomScrollView) {
        _bottomScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        _bottomScrollView.delegate = self;
        _bottomScrollView.pagingEnabled = YES;

        NSArray *colors = @[[UIColor redColor],[UIColor blueColor],[UIColor grayColor],[UIColor greenColor],[UIColor purpleColor],[UIColor orangeColor],[UIColor whiteColor],[UIColor redColor],[UIColor blueColor],[UIColor grayColor],[UIColor greenColor]];

        for (int i = 0; i<CATEGORY.count; i++) {

            JXBanTangTableViewController *jsdTableViewController = [[JXBanTangTableViewController alloc] init];
            jsdTableViewController.view.frame = CGRectMake(kScreenW * i, 0, kScreenW, kScreenH);

            jsdTableViewController.view.backgroundColor = colors[i];
            [self.bottomScrollView addSubview:jsdTableViewController.view];

            [self.controlleres addObject:jsdTableViewController];

            ///保存所有的tableView
            [self.tableViews addObject:jsdTableViewController.tableView];

            //下拉刷新动画
            JXBanTangRefreshHeader *jqRefreshHeader  = [[JXBanTangRefreshHeader alloc] initWithFrame:CGRectMake(0, BTTableHeaderViewHeight - BTRefreshHeight, kScreenW, BTRefreshHeight)];
            jqRefreshHeader.backgroundColor = [UIColor whiteColor];
            /// 赋值tableView
            jqRefreshHeader.tableView = jsdTableViewController.tableView;
            /// 监听tableView
            [jsdTableViewController.tableView.tableHeaderView addSubview:jqRefreshHeader];

            NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
            [jsdTableViewController.tableView addObserver:self forKeyPath:@"contentOffset" options:options context:nil];

        }

        self.currentTableView = self.tableViews[0];
        self.bottomScrollView.contentSize = CGSizeMake(self.controlleres.count * kScreenW, 0);

    }
    return _bottomScrollView;
}

- (UIScrollView *)segmentScrollView {

    if (!_segmentScrollView) {

        _segmentScrollView =  [[UIScrollView alloc]initWithFrame:CGRectMake(0, BTSDCycleScrollViewHeight, kScreenW, BTSegmentScrollViewHeight)];
        [_segmentScrollView addSubview:self.currentSelectedItemImageView];
        _segmentScrollView.showsHorizontalScrollIndicator = NO;
        _segmentScrollView.showsVerticalScrollIndicator = NO;
        _segmentScrollView.backgroundColor = [UIColor whiteColor];
        NSInteger btnoffset = 0;

        for (int i = 0; i<CATEGORY.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setTitle:CATEGORY[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:FONTMIN];
            CGSize size = [UIButton sizeOfLabelWithCustomMaxWidth:kScreenW systemFontSize:FONTMIN andFilledTextString:CATEGORY[i]];

            float originX =  i? PADDING*2+btnoffset:PADDING;

            btn.frame = CGRectMake(originX, 14, size.width, size.height);
            btnoffset = CGRectGetMaxX(btn.frame);

            btn.titleLabel.textAlignment = NSTextAlignmentLeft;
            [btn addTarget:self action:@selector(changeSelectedItem:) forControlEvents:UIControlEventTouchUpInside];
            [_segmentScrollView addSubview:btn];

            [self.titleButtons addObject:btn];

            //contentSize 等于按钮长度叠加
            //默认选中第一个按钮
            if (i == 0) {

                btn.selected = YES;
                _previousButton = btn;

                _currentSelectedItemImageView.frame = CGRectMake(PADDING, self.segmentScrollView.frame.size.height - 2, btn.frame.size.width, 2);
            }
        }

        _segmentScrollView.contentSize = CGSizeMake(btnoffset+PADDING, 25);
    }

    return _segmentScrollView;
}

- (UIImageView *)currentSelectedItemImageView {
    if (!_currentSelectedItemImageView) {
        _currentSelectedItemImageView = [[UIImageView alloc] init];
        _currentSelectedItemImageView.image = [UIImage imageNamed:@"nar_bgbg"];
    }
    return _currentSelectedItemImageView;
}

- (SDCycleScrollView *)cycleScrollView {

    if (!_cycleScrollView) {

        NSMutableArray *imageMutableArray = [NSMutableArray array];
        for (int i = 1; i<9; i++) {
            NSString *imageName = [NSString stringWithFormat:@"cycle_%02d.jpg",i];
            [imageMutableArray addObject:imageName];
        }

        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenW, BTSDCycleScrollViewHeight) imageNamesGroup:imageMutableArray];

    }
    return _cycleScrollView;
}

- (JXBanTangHeaderView *)jqHeaderView {

    if (!_jqHeaderView) {

        _jqHeaderView = [[JXBanTangHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 64)];
        _jqHeaderView.backgroundColor = [UIColor clearColor];

    }
    return _jqHeaderView;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        self.automaticallyAdjustsScrollViewInsets = NO;

        self.titleButtons = [[NSMutableArray alloc] initWithCapacity:CATEGORY.count];
        self.controlleres = [[NSMutableArray alloc] initWithCapacity:CATEGORY.count];
        self.tableViews = [[NSMutableArray alloc] initWithCapacity:CATEGORY.count];

        [self.view addSubview:self.bottomScrollView];
        self.jqHeaderView.tableViews = [NSMutableArray arrayWithArray:self.tableViews];

        [self.view addSubview:self.cycleScrollView];
        [self.view addSubview:self.segmentScrollView];
        [self.view addSubview:self.jqHeaderView];

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"半塘首页";
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
}

#pragma observe
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{

    UITableView *tableView = (UITableView *)object;

    if (!(self.currentTableView == tableView)) {
        return;
    }

    if (![keyPath isEqualToString:@"contentOffset"]) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        return;
    }

    CGFloat tableViewoffsetY = tableView.contentOffset.y;

    self.lastTableViewOffsetY = tableViewoffsetY;

    if ( tableViewoffsetY>=0 && tableViewoffsetY<=kMaxOffset) {

        self.segmentScrollView.frame = CGRectMake(0, BTSDCycleScrollViewHeight-tableViewoffsetY, kScreenW, BTSegmentScrollViewHeight);
        self.cycleScrollView.frame = CGRectMake(0, 0-tableViewoffsetY, kScreenW, BTSDCycleScrollViewHeight);

    }else if( tableViewoffsetY < 0){

        self.segmentScrollView.frame = CGRectMake(0, BTSDCycleScrollViewHeight, kScreenW, BTSegmentScrollViewHeight);
        self.cycleScrollView.frame = CGRectMake(0, 0, kScreenW, BTSDCycleScrollViewHeight);

    }else if (tableViewoffsetY > kMaxOffset){

        self.segmentScrollView.frame = CGRectMake(0, 64, kScreenW, BTSegmentScrollViewHeight);
        self.cycleScrollView.frame = CGRectMake(0, -kMaxOffset, kScreenW, BTSDCycleScrollViewHeight);
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView !=self.bottomScrollView) {
        return ;
    }

    int index =  scrollView.contentOffset.x/scrollView.frame.size.width;

    UIButton *currentButton = self.titleButtons[index];
    //     for (UIButton *button in self.titleButtons) {
    //         button.selected = NO;
    //     }
    _previousButton.selected = NO;
    currentButton.selected = YES;
    _previousButton = currentButton;

    self.currentTableView  = self.tableViews[index];
    for (UITableView *tableView in self.tableViews) {

        if ( self.lastTableViewOffsetY>=0 &&  self.lastTableViewOffsetY<=kMaxOffset) {

            tableView.contentOffset = CGPointMake(0,  self.lastTableViewOffsetY);

        }else if(  self.lastTableViewOffsetY < 0){

            tableView.contentOffset = CGPointMake(0, 0);

        }else if ( self.lastTableViewOffsetY > kMaxOffset){

            tableView.contentOffset = CGPointMake(0, kMaxOffset);
        }

    }

    [UIView animateWithDuration:0.3 animations:^{
        if (index == 0) {

            self.currentSelectedItemImageView.frame = CGRectMake(PADDING, self.segmentScrollView.frame.size.height - 2,currentButton.frame.size.width, 2);

        }else{

            UIButton *preButton = self.titleButtons[index - 1];

            float offsetX = CGRectGetMinX(preButton.frame)-PADDING*2;

            [self.segmentScrollView scrollRectToVisible:CGRectMake(offsetX, 0, self.segmentScrollView.frame.size.width, self.segmentScrollView.frame.size.height) animated:YES];

            self.currentSelectedItemImageView.frame = CGRectMake(CGRectGetMinX(currentButton.frame), self.segmentScrollView.frame.size.height-2, currentButton.frame.size.width, 2);
        }

    }];

}

#pragma  mark - 选项卡点击事件

-(void)changeSelectedItem:(UIButton *)currentButton{

    //     for (UIButton *button in self.titleButtons) {
    //         button.selected = NO;
    //     }

    _previousButton.selected = NO;
    currentButton.selected = YES;
    _previousButton = currentButton;

    NSInteger index = [self.titleButtons indexOfObject:currentButton];

    self.currentTableView  = self.tableViews[index];
    for (UITableView *tableView in self.tableViews) {

        if ( self.lastTableViewOffsetY>=0 &&  self.lastTableViewOffsetY<=kMaxOffset) {

            tableView.contentOffset = CGPointMake(0,  self.lastTableViewOffsetY);

        }else if(self.lastTableViewOffsetY < 0){

            tableView.contentOffset = CGPointMake(0, 0);

        }else if ( self.lastTableViewOffsetY > kMaxOffset){

            tableView.contentOffset = CGPointMake(0, kMaxOffset);
        }
    }

    [UIView animateWithDuration:0.3 animations:^{

        if (index == 0) {

            self.currentSelectedItemImageView.frame = CGRectMake(PADDING, self.segmentScrollView.frame.size.height - 2,currentButton.frame.size.width, 2);

        }else{

            UIButton *preButton = self.titleButtons[index - 1];

            float offsetX = CGRectGetMinX(preButton.frame)-PADDING*2;

            [self.segmentScrollView scrollRectToVisible:CGRectMake(offsetX, 0, self.segmentScrollView.frame.size.width, self.segmentScrollView.frame.size.height) animated:YES];

            self.currentSelectedItemImageView.frame = CGRectMake(CGRectGetMinX(currentButton.frame), self.segmentScrollView.frame.size.height-2, currentButton.frame.size.width, 2);
        }
        self.bottomScrollView.contentOffset = CGPointMake(kScreenW *index, 0);

    }];
}

@end


text:
scoped_refptr<UserStyleSheetWatcher>
UserStyleSheetWatcherFactory::GetForProfile(
    Profile* profile) {
  return static_cast<UserStyleSheetWatcher*>(
      GetInstance()->GetServiceForProfile(profile, true).get());
}

// static
UserStyleSheetWatcherFactory* UserStyleSheetWatcherFactory::GetInstance() {
  return Singleton<UserStyleSheetWatcherFactory>::get();
}

UserStyleSheetWatcherFactory::UserStyleSheetWatcherFactory()
    : RefcountedProfileKeyedServiceFactory(
          "UserStyleSheetWatcher", ProfileDependencyManager::GetInstance()) {
}

UserStyleSheetWatcherFactory::~UserStyleSheetWatcherFactory() {
}

scoped_refptr<RefcountedProfileKeyedService>
UserStyleSheetWatcherFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  Profile* profile = static_cast<Profile*>(context);
  scoped_refptr<UserStyleSheetWatcher> user_style_sheet_watcher(
      new UserStyleSheetWatcher(profile, profile->GetPath()));
  user_style_sheet_watcher->Init();
  return user_style_sheet_watcher;
}

bool UserStyleSheetWatcherFactory::ServiceRedirectedInIncognito() const {
  return true;
}

bool UserStyleSheetWatcherFactory::ServiceIsNULLWhileTesting() const {
  return true;
}


text:
$:.push File.expand_path("../../../lib", __FILE__)

require 'rails'
require 'templify'
require 'rspec/matchers'


text:
package types

// FeatureToggle type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/xpack/usage/types.ts#L40-L42
type FeatureToggle struct {
	Enabled bool `json:"enabled"`
}

// NewFeatureToggle returns a FeatureToggle.
func NewFeatureToggle() *FeatureToggle {
	r := &FeatureToggle{}

	return r
}


text:
package org.adligo.fabricate_tests.common.system;

import org.adligo.fabricate.common.en.FabricateEnConstants;
import org.adligo.fabricate.common.files.I_FabFileIO;
import org.adligo.fabricate.common.log.I_FabLog;
import org.adligo.fabricate.common.system.FabricateDefaults;
import org.adligo.fabricate.common.system.FabricateEnvironment;
import org.adligo.fabricate.common.system.I_FabSystem;
import org.adligo.tests4j.shared.asserts.common.ExpectedThrowable;
import org.adligo.tests4j.shared.asserts.common.I_Thrower;
import org.adligo.tests4j.shared.asserts.common.MatchType;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_4mockito.MockMethod;
import org.adligo.tests4j_4mockito.MockitoSourceFileTrial;

import java.io.File;

@SourceFileScope (sourceClass=FabricateEnvironment.class,minCoverage=100.0)
public class FabricateEnvironmentTrial extends MockitoSourceFileTrial {
  private I_FabSystem sysMock_;
  private I_FabLog logMock_;
  private I_FabFileIO filesMock_;

  MockMethod<Void> printlnMethod_ = new MockMethod<Void>();
  MockMethod<Void> printtraceMethod_ = new MockMethod<Void>();

  public void beforeTests() {
    sysMock_ = mock(I_FabSystem.class);
    logMock_ = mock(I_FabLog.class);
    when(sysMock_.getLog()).thenReturn(logMock_);
    when(sysMock_.lineSeparator()).thenReturn(System.lineSeparator());
    when(sysMock_.getConstants()).thenReturn(FabricateEnConstants.INSTANCE);

    printlnMethod_ = new MockMethod<Void>();
    printtraceMethod_ = new MockMethod<Void>();

    doAnswer(printlnMethod_).when(logMock_).println(any());
    doAnswer(printtraceMethod_).when(logMock_).printTrace(any());

    filesMock_ = mock(I_FabFileIO.class);
    when(sysMock_.getFileIO()).thenReturn(filesMock_);
  }

  @SuppressWarnings("boxing")
  @Test
  public void testConstants() {

    assertEquals("FABRICATE_HOME", FabricateEnvironment.FABRICATE_HOME);
    assertEquals("FABRICATE_REPOSITORY", FabricateEnvironment.FABRICATE_REPOSITORY);
    assertEquals("JAVA_HOME", FabricateEnvironment.JAVA_HOME);
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetJavaHome() {

     when(sysMock_.getenv(FabricateEnvironment.JAVA_HOME)).thenReturn("jh");

     assertEquals("jh", FabricateEnvironment.INSTANCE.getJavaHome(sysMock_));

     assertEquals(0, printlnMethod_.count());
     assertEquals(0, printtraceMethod_.count());
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetJavaHomeEmptyValue() {
    when(sysMock_.getenv(FabricateEnvironment.JAVA_HOME)).thenReturn(null);

    assertThrown(new ExpectedThrowable(new IllegalStateException(), MatchType.NULL),
        new I_Thrower() {

          @Override
          public void run() throws Throwable {
            FabricateEnvironment.INSTANCE.getJavaHome(sysMock_);
          }
        });
    assertEquals("Exception: No $JAVA_HOME environment variable set.",
        printlnMethod_.getArg(0));
    assertEquals("LASTLINE END",
        printlnMethod_.getArg(1));
    assertEquals(2, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());

    beforeTests();
    when(sysMock_.getenv(FabricateEnvironment.JAVA_HOME)).thenReturn("");

    assertThrown(new ExpectedThrowable(new IllegalStateException(), MatchType.NULL),
        new I_Thrower() {

          @Override
          public void run() throws Throwable {
            FabricateEnvironment.INSTANCE.getJavaHome(sysMock_);
          }
        });
    assertEquals("Exception: No $JAVA_HOME environment variable set.",
        printlnMethod_.getArg(0));
    assertEquals("LASTLINE END",
        printlnMethod_.getArg(1));
    assertEquals(2, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetFabricateHome() {
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_HOME)).thenReturn("fh");

    assertEquals("fh", FabricateEnvironment.INSTANCE.getFabricateHome(sysMock_));

    assertEquals(0, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetFabricateHomeEmptyValue() {
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_HOME)).thenReturn(null);

    assertThrown(new ExpectedThrowable(new IllegalStateException(), MatchType.NULL),
        new I_Thrower() {

          @Override
          public void run() throws Throwable {
            FabricateEnvironment.INSTANCE.getFabricateHome(sysMock_);
          }
        });
    assertEquals("Exception: No $FABRICATE_HOME environment variable set.",
        printlnMethod_.getArg(0));
    assertEquals("LASTLINE END",
        printlnMethod_.getArg(1));
    assertEquals(2, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());

    beforeTests();
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_HOME)).thenReturn("");

    assertThrown(new ExpectedThrowable(new IllegalStateException(), MatchType.NULL),
        new I_Thrower() {

          @Override
          public void run() throws Throwable {
            FabricateEnvironment.INSTANCE.getFabricateHome(sysMock_);
          }
        });
    assertEquals("Exception: No $FABRICATE_HOME environment variable set.",
        printlnMethod_.getArg(0));
    assertEquals("LASTLINE END",
        printlnMethod_.getArg(1));
    assertEquals(2, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetFabricateRepository() {

    when(filesMock_.getNameSeparator()).thenReturn("/");
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_REPOSITORY)).thenReturn("fr");
    assertEquals("fr/", FabricateEnvironment.INSTANCE.getFabricateRepository(sysMock_));

    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_REPOSITORY)).thenReturn("fr/");
    assertEquals("fr/", FabricateEnvironment.INSTANCE.getFabricateRepository(sysMock_));

    //windows
    when(filesMock_.getNameSeparator()).thenReturn("\\");
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_REPOSITORY)).thenReturn("C:\\fr");
    assertEquals("C:\\fr\\", FabricateEnvironment.INSTANCE.getFabricateRepository(sysMock_));

    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_REPOSITORY)).thenReturn("C:\\fr\\");
    assertEquals("C:\\fr\\", FabricateEnvironment.INSTANCE.getFabricateRepository(sysMock_));

    assertEquals(0, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());
  }

  @SuppressWarnings("boxing")
  @Test
  public void testMethodGetFabricateHomeDefaultValue() {
    when(sysMock_.getenv(FabricateEnvironment.FABRICATE_REPOSITORY)).thenReturn(null);
    when(filesMock_.getNameSeparator()).thenReturn(File.separator);

    assertEquals(FabricateDefaults.LOCAL_REPOSITORY,
        FabricateEnvironment.INSTANCE.getFabricateRepository(sysMock_));

    assertEquals(0, printlnMethod_.count());
    assertEquals(0, printtraceMethod_.count());
  }
}


text:
  Error 404.
  La Pagina especificada, no existe o no se encuentra.