text:
using AutoMapper;
using Fan.Blog.Data;
using Fan.Blog.Enums;
using Fan.Blog.Events;
using Fan.Blog.Helpers;
using Fan.Blog.Models;
using Fan.Blog.Services.Interfaces;
using Fan.Blog.Validators;
using Fan.Exceptions;
using Fan.Helpers;
using Fan.Settings;
using MediatR;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

[assembly: InternalsVisibleTo("Fan.Blog.Tests")]

namespace Fan.Blog.Services
{
    public class BlogPostService : IBlogPostService
    {
        private readonly IPostRepository postRepository;
        private readonly ISettingService settingService;
        private readonly IImageService imageService;
        private readonly IDistributedCache cache;
        private readonly ILogger<BlogPostService> logger;
        private readonly IMapper mapper;
        private readonly IMediator mediator;

        public BlogPostService(
            ISettingService settingService,
            IImageService imageService,
            IPostRepository postRepository,
            IDistributedCache cache,
            ILogger<BlogPostService> logger,
            IMapper mapper,
            IMediator mediator)
        {
            this.settingService = settingService;
            this.imageService = imageService;
            this.postRepository = postRepository;
            this.cache = cache;
            this.mapper = mapper;
            this.logger = logger;
            this.mediator = mediator;
        }

        // -------------------------------------------------------------------- consts

        /// <summary>
        /// By default show 10 posts per page.
        /// </summary>
        public const int DEFAULT_PAGE_SIZE = 10;

        /// <summary>
        /// Showing post starts with page 1.
        /// </summary>
        public const int DEFAULT_PAGE_INDEX = 1;

        /// <summary>
        /// How many words to extract into excerpt from body. Default 55.
        /// </summary>
        public const int EXCERPT_WORD_LIMIT = 55;

        // -------------------------------------------------------------------- public methods

        /// <summary>
        /// Creates a <see cref="BlogPost"/>.
        /// </summary>
        /// <param name="blogPost">Contains incoming blog post data to create.</param>
        /// <returns></returns>
        /// <remarks>
        /// It creates tags, post and invalidates cache for posts on index page.
        /// </remarks>
        public async Task<BlogPost> CreateAsync(BlogPost blogPost)
        {
            // validate
            if (blogPost == null) throw new ArgumentNullException(nameof(blogPost));
            await blogPost.ValidateTitleAsync();

            // prep
            var post = await ConvertToPostAsync(blogPost, ECreateOrUpdate.Create);

            // before create
            await mediator.Publish(new BlogPostBeforeCreate
            {
                CategoryTitle = blogPost.CategoryTitle,
                TagTitles = blogPost.TagTitles
            });

            // create (post will get new id)
            await postRepository.CreateAsync(post, blogPost.CategoryTitle, blogPost.TagTitles);

            // invalidate cache only when published
            if (blogPost.Status == EPostStatus.Published)
            {
                await RemoveBlogCacheAsync();
            }

            // after create
            await mediator.Publish(new BlogPostCreated { BlogPost = blogPost });

            return await GetAsync(post.Id);
        }

        /// <summary>
        /// Updates a <see cref="BlogPost"/>.
        /// </summary>
        /// <param name="blogPost">Contains incoming blog post data to update.</param>
        public async Task<BlogPost> UpdateAsync(BlogPost blogPost)
        {
            // validate
            if (blogPost == null || blogPost.Id <= 0) throw new ArgumentException(null, nameof(blogPost));
            await blogPost.ValidateTitleAsync();

            // prep current post with blog post
            var post = await ConvertToPostAsync(blogPost, ECreateOrUpdate.Update);

            // before update
            await mediator.Publish(new BlogPostBeforeUpdate
            {
                CategoryTitle = blogPost.CategoryTitle,
                TagTitles = blogPost.TagTitles,
                PostTags = post.PostTags,
            });

            // update
            await postRepository.UpdateAsync(post, blogPost.CategoryTitle, blogPost.TagTitles);

            // invalidate cache
            await RemoveBlogCacheAsync();
            await RemoveSinglePostCacheAsync(post);

            // after update
            await mediator.Publish(new BlogPostUpdated { BlogPost = blogPost });

            return await GetAsync(post.Id);
        }

        /// <summary>
        /// Deletes a blog post and invalidates cache for posts on index page.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            var post = await GetAsync(id);
            await postRepository.DeleteAsync(id);
            await RemoveBlogCacheAsync();
            await RemoveSinglePostCacheAsync(post);
        }

        /// <summary>
        /// Returns a <see cref="BlogPost"/> by id with its <see cref="Category"/> and <see cref="Tag"/>
        /// and throws <see cref="FanException"/> if not found.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="FanException">if post is not found.</exception>
        /// <remarks>
        /// This is used when you want to get a post from db.
        /// </remarks>
        public async Task<BlogPost> GetAsync(int id)
        {
            var post = await QueryPostAsync(id);
            return ConvertToBlogPost(post);
        }

        /// <summary>
        /// Returns a <see cref="BlogPost"/> by slug and date time, throws <see cref="FanException"/> if not found.
        /// If the post is draft then it's considered not found.
        /// </summary>
        /// <param name="slug"></param>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <exception cref="FanException">if post is not found.</exception>
        /// <remarks>
        /// This is used by controller. The dates are stored as UTC time in database, thus the
        /// params year, month and day should be the UTC time.
        /// </remarks>
        public async Task<BlogPost> GetAsync(string slug, int year, int month, int day)
        {
            Post post = null;
            if (new DateTime(year, month, day).IsWithinDays(100))
            {
                var cacheKey = string.Format(BlogCache.KEY_POST, slug, year, month, day);
                post = await cache.GetAsync(cacheKey, BlogCache.Time_SingplePost, async () =>
                {
                    return await postRepository.GetAsync(slug, year, month, day);
                });
            }
            else
            {
                post = await postRepository.GetAsync(slug, year, month, day);
            }

            if (post == null) throw new FanException(EExceptionType.ResourceNotFound);
            var blogPost = ConvertToBlogPost(post);
            blogPost = await PreRenderAsync(blogPost);
            return blogPost;
        }

        /// <summary>
        /// Returns a list of blog posts.
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        /// <remarks>
        /// For the blog index page, admin post page, main rss feed.
        /// </remarks>
        public async Task<BlogPostList> GetListAsync(int pageIndex, int pageSize, bool cacheable = true)
        {
            PostListQuery query = new PostListQuery(EPostListQueryType.BlogPosts)
            {
                PageIndex = (pageIndex <= 0) ? 1 : pageIndex,
                PageSize = pageSize,
            };

            // cache only first page of the public site, not admin or rss
            if (query.PageIndex == 1 && cacheable)
            {
                return await cache.GetAsync(BlogCache.KEY_POSTS_INDEX, BlogCache.Time_Posts_Index, async () =>
                {
                    return await QueryPostsAsync(query);
                });
            }

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns a list of blog posts for a category.
        /// </summary>
        /// <param name="categorySlug"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public async Task<BlogPostList> GetListForCategoryAsync(string categorySlug, int pageIndex)
        {
            if (categorySlug.IsNullOrEmpty()) throw new FanException("Category does not exist.");

            PostListQuery query = new PostListQuery(EPostListQueryType.BlogPostsByCategory)
            {
                CategorySlug = categorySlug,
                PageIndex = (pageIndex <= 0) ? 1 : pageIndex,
                PageSize = (await settingService.GetSettingsAsync<BlogSettings>()).PostPerPage,
            };

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns a list of blog posts for a tag.
        /// </summary>
        /// <param name="tagSlug"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public async Task<BlogPostList> GetListForTagAsync(string tagSlug, int pageIndex)
        {
            if (tagSlug.IsNullOrEmpty()) throw new FanException("Tag does not exist.");

            PostListQuery query = new PostListQuery(EPostListQueryType.BlogPostsByTag)
            {
                TagSlug = tagSlug,
                PageIndex = (pageIndex <= 0) ? 1 : pageIndex,
                PageSize = (await settingService.GetSettingsAsync<BlogSettings>()).PostPerPage,
            };

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns a list of blog posts for archive.
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task<BlogPostList> GetListForArchive(int? year, int? month, int page = 1)
        {
            if (!year.HasValue) throw new FanException("Year must be provided.");
            var query = new PostListQuery(EPostListQueryType.BlogPostsArchive)
            {
                Year = year.Value,
                Month = month
            };

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns a list of blog drafts.
        /// </summary>
        /// <returns></returns>
        public async Task<BlogPostList> GetListForDraftsAsync()
        {
            PostListQuery query = new PostListQuery(EPostListQueryType.BlogDrafts);

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns specific number of <see cref="BlogPost"/> used by metaweblog.
        /// </summary>
        /// <param name="numberOfPosts">"All" is int.MaxValue</param>
        public async Task<BlogPostList> GetRecentPostsAsync(int numberOfPosts)
        {
            var query = new PostListQuery(EPostListQueryType.BlogPostsByNumber) { PageSize = numberOfPosts };

            return await QueryPostsAsync(query);
        }

        /// <summary>
        /// Returns spcific number of published <see cref="BlogPost"/>.
        /// </summary>
        /// <param name="numberOfPosts"></param>
        /// <returns></returns>
        public async Task<BlogPostList> GetRecentPublishedPostsAsync(int numberOfPosts)
        {
            return await cache.GetAsync(BlogCache.KEY_POSTS_RECENT, BlogCache.Time_Posts_Recent, async () =>
            {
                var query = new PostListQuery(EPostListQueryType.BlogPublishedPostsByNumber)
                {
                    PageSize = numberOfPosts <= 0 ? 1 : numberOfPosts
                };

                return await QueryPostsAsync(query);
            });
        }

        /// <summary>
        /// Invalidates cache for blog post service.
        /// </summary>
        public async Task RemoveBlogCacheAsync()
        {
            await cache.RemoveAsync(BlogCache.KEY_POSTS_INDEX);
            await cache.RemoveAsync(BlogCache.KEY_POSTS_RECENT);
            await cache.RemoveAsync(BlogCache.KEY_ALL_CATS);
            await cache.RemoveAsync(BlogCache.KEY_ALL_TAGS);
            await cache.RemoveAsync(BlogCache.KEY_ALL_ARCHIVES);
            await cache.RemoveAsync(BlogCache.KEY_POST_COUNT);
        }

        // -------------------------------------------------------------------- private methods

        /// <summary>
        /// Returns a <see cref="Post"/> from data source, throws <see cref="FanException"/> if not found.
        /// </summary>
        /// <param name="id">A blog post id.</param>
        /// <returns></returns>
        /// <remarks>
        /// Returned post is tracked.
        /// </remarks>
        private async Task<Post> QueryPostAsync(int id)
        {
            var post = await postRepository.GetAsync(id, EPostType.BlogPost);

            if (post == null)
            {
                throw new FanException($"Blog post with id {id} is not found.");
            }

            return post;
        }

        /// <summary>
        /// Returns a <see cref="BlogPostList"/> based on query from data source.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private async Task<BlogPostList> QueryPostsAsync(PostListQuery query)
        {
            var (posts, totalCount) = await postRepository.GetListAsync(query);

            var blogPostList = new BlogPostList
            {
                TotalPostCount = totalCount
            };
            foreach (var post in posts)
            {
                var blogPost = ConvertToBlogPost(post);
                blogPost = await PreRenderAsync(blogPost);
                blogPostList.Posts.Add(blogPost);
            }

            return blogPostList;
        }

        /// <summary>
        /// Prepares a <see cref="BlogPost"/> into Post for create or update.
        /// </summary>
        /// <param name="blogPost">The incoming post with user data.</param>
        /// <param name="createOrUpdate">User is doing either a create or update post.</param>
        /// <returns></returns>
        private async Task<Post> ConvertToPostAsync(BlogPost blogPost, ECreateOrUpdate createOrUpdate)
        {
            // Get post
            var post = (createOrUpdate == ECreateOrUpdate.Create) ? new Post() : await QueryPostAsync(blogPost.Id);

            // CreatedOn
            if (createOrUpdate == ECreateOrUpdate.Create)
            {
                // post time will be min value if user didn't set a time
                post.CreatedOn = (blogPost.CreatedOn <= DateTimeOffset.MinValue) ? DateTimeOffset.UtcNow : blogPost.CreatedOn.ToUniversalTime();
            }
            else
            {
                // TODO Add a time picker on the composer

                // get post.CreatedOn in local time
                var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
                var postCreatedOnLocal = post.CreatedOn.ToLocalTime(coreSettings.TimeZoneId);

                // user changed the post time
                if (!postCreatedOnLocal.YearMonthDayEquals(blogPost.CreatedOn))
                    post.CreatedOn = (blogPost.CreatedOn <= DateTimeOffset.MinValue) ? post.CreatedOn : blogPost.CreatedOn.ToUniversalTime();
            }

            // UpdatedOn (DraftSavedOn)
            // when saving a draft this should be utc now, when publishing it becomes null
            if (blogPost.Status == EPostStatus.Draft) post.UpdatedOn = DateTimeOffset.UtcNow;
            else post.UpdatedOn = null;

            // Slug
            if (blogPost.Status == EPostStatus.Draft && blogPost.Title.IsNullOrEmpty())
                post.Slug = null; // if user save a draft with empty title
            else
                post.Slug = await GetBlogPostSlugAsync(blogPost.Slug.IsNullOrEmpty() ? blogPost.Title : blogPost.Slug,
                                                       post.CreatedOn, createOrUpdate, blogPost.Id);

            // Title
            post.Title = blogPost.Title; // looks like OLW html encodes post title

            // Body & Excerpt, UserId
            post.Body = blogPost.Body.IsNullOrWhiteSpace() ? null : blogPost.Body;
            post.Excerpt = blogPost.Excerpt.IsNullOrWhiteSpace() ? null : blogPost.Excerpt;
            post.UserId = blogPost.UserId;

            // Status & CommentStatus
            post.Status = blogPost.Status;
            post.CommentStatus = blogPost.CommentStatus;

            // CategoryId
            post.CategoryId = blogPost.CategoryId;

            logger.LogDebug(createOrUpdate + " {@Post}", post);
            return post;
        }

        /// <summary>
        /// Gets a <see cref="BlogPost"/> for display to client from a <see cref="Post"/>.
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        /// <remarks>
        /// It readies <see cref="Post.CreatedOnDisplay"/>, Title, Excerpt, CategoryTitle, Tags and Body with shortcodes.
        /// </remarks>
        private BlogPost ConvertToBlogPost(Post post)
        {
            var blogPost = mapper.Map<Post, BlogPost>(post);

            // Title
            blogPost.Title = WebUtility.HtmlDecode(blogPost.Title); // since OLW encodes it, we decode it here

            // Excerpt
            blogPost.Excerpt = post.Excerpt.IsNullOrEmpty() ? Util.GetExcerpt(post.Body, EXCERPT_WORD_LIMIT) : post.Excerpt;

            // CategoryTitle
            blogPost.CategoryTitle = post.Category?.Title;

            // Tags and TagTitles
            foreach (var postTag in post.PostTags)
            {
                blogPost.Tags.Add(postTag.Tag);
                blogPost.TagTitles.Add(postTag.Tag.Title);
            }

            // ViewCount
            blogPost.ViewCount = post.ViewCount;

            logger.LogDebug("Show {@BlogPost}", blogPost);
            return blogPost;
        }

        /// <summary>
        /// Returns a unique and valid slug for a blog post.
        /// </summary>
        /// <param name="input">This could be a slug or post title.</param>
        /// <param name="createdOn">Used for making sure slug is unique by searching posts.</param>
        /// <param name="createOrUpdate">Whether the operation is create or update post.</param>
        /// <param name="blogPostId">Used for making sure slug is unique when updating.</param>
        /// <returns></returns>
        /// <remarks>
        /// If input is slug, either this is update or a create with user inputted slug, then <see cref="Util.Slugify(string)"/>
        /// will not alter it. This is very important for SEO as updating slug on an existing post will
        /// break links in search results. On the other hand, if user deliberately updated the slug
        /// when doing an update on post, then it will alter it accordingly. Please see the test case
        /// on this method.
        /// </remarks>
        internal async Task<string> GetBlogPostSlugAsync(string input, DateTimeOffset createdOn, ECreateOrUpdate createOrUpdate, int blogPostId)
        {
            // make slug
            var slug = Util.Slugify(input, maxlen: PostTitleValidator.TITLE_MAXLEN, randomCharCountOnEmpty: 8);

            // make sure slug is unique
            int i = 2;
            if (createOrUpdate == ECreateOrUpdate.Create) // create
            {
                while (await postRepository.GetAsync(slug, createdOn.Year, createdOn.Month, createdOn.Day) != null)
                {
                    slug = Util.UniquefySlug(slug, ref i);
                }
            }
            else // update
            {
                var p = await postRepository.GetAsync(slug, createdOn.Year, createdOn.Month, createdOn.Day);
                while (p != null && p.Id != blogPostId)
                {
                    slug = Util.UniquefySlug(slug, ref i);
                    p = await postRepository.GetAsync(slug, createdOn.Year, createdOn.Month, createdOn.Day);
                }
            }

            return slug;
        }

        private async Task RemoveSinglePostCacheAsync(Post post)
        {
            var cacheKey = string.Format(BlogCache.KEY_POST, post.Slug, post.CreatedOn.Year, post.CreatedOn.Month, post.CreatedOn.Day);
            await cache.RemoveAsync(cacheKey);
        }

        /// <summary>
        /// Pre render processing of a blog post. TODO consider refactor.
        /// </summary>
        /// <param name="blogPost"></param>
        /// <returns></returns>
        private async Task<BlogPost> PreRenderAsync(BlogPost blogPost)
        {
            if (blogPost == null) return blogPost;

            blogPost.Body = OembedParser.Parse(blogPost.Body);
            blogPost.Body = await imageService.ProcessResponsiveImageAsync(blogPost.Body);

            return blogPost;
        }
    }
}


text:
/**
 * Graph Configuration custom directive
 */
module.exports = graphConfigDirective;

// associate this directive with custom name:
require('nerl').directive('graphConfiguration', graphConfigDirective);

function graphConfigDirective() {
  return {
    scope: {
      graphData: '='
    },
    restrict: 'E',
    templateUrl: '/lib/edit/graphConfiguration.html'
  };
}

redpajama_set_name: RedPajamaGithub


text:
import plusnew from './src';

export default plusnew;
export * from './src';


text:
package de.fzi.cjunit.builders;

import java.util.Arrays;
import java.util.List;

import org.junit.internal.builders.AllDefaultPossibilitiesBuilder;
import org.junit.runner.Runner;
import org.junit.runners.model.RunnerBuilder;

public class ConcurrentDefaultPossibilitiesBuilder
		extends AllDefaultPossibilitiesBuilder {

	public ConcurrentDefaultPossibilitiesBuilder(
			boolean canUseSuiteMethod) {
		super(canUseSuiteMethod);
	}

	@Override
	public Runner runnerForClass(Class<?> testClass) throws Throwable {
		for (RunnerBuilder each : builderList()) {
			Runner runner = each.safeRunnerForClass(testClass);
			if (runner != null) {
				return runner;
			}
		}
		return null;
	}

	protected List<RunnerBuilder> builderList() {
		return Arrays.asList(
				ignoredBuilder(),
				annotatedBuilder(),
				suiteMethodBuilder(),
				junit3Builder(),
				concurrentBuilder(),
				junit4Builder()
				);
	}

	protected ConcurrentBuilder concurrentBuilder() {
		return new ConcurrentBuilder();
	}
}


text:
namespace XPump.SubForm
{
    partial class DialogNozzleSalesHistory
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
            this.dgv = new CC.XDatagrid();
            this.col_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_saldat = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_tank_name = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_section_name = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_nozzle_name = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_shift_name = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_mitbeg = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_mitend = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_salqty = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_unitpr = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_salval = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_shift_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_nozzle_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_stmas_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_pricelist_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_salessummary_id = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_price_date = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_stkcod = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_stkdes = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_saleshistory = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.col_working_express_db = new System.Windows.Forms.DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.dgv)).BeginInit();
            this.SuspendLayout();
            //
            // dgv
            //
            this.dgv.AllowSortByColumnHeaderClicked = false;
            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;
            this.dgv.AllowUserToResizeColumns = false;
            this.dgv.AllowUserToResizeRows = false;
            this.dgv.BackgroundColor = System.Drawing.Color.White;
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(231)))), ((int)(((byte)(207)))), ((int)(((byte)(179)))));
            dataGridViewCellStyle1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(222)));
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dgv.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
            this.dgv.ColumnHeadersHeight = 24;
            this.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.col_id,
            this.col_saldat,
            this.col_tank_name,
            this.col_section_name,
            this.col_nozzle_name,
            this.col_shift_name,
            this.col_mitbeg,
            this.col_mitend,
            this.col_salqty,
            this.col_unitpr,
            this.col_salval,
            this.col_shift_id,
            this.col_nozzle_id,
            this.col_stmas_id,
            this.col_pricelist_id,
            this.col_salessummary_id,
            this.col_price_date,
            this.col_stkcod,
            this.col_stkdes,
            this.col_saleshistory,
            this.col_working_express_db});
            dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle7.BackColor = System.Drawing.Color.White;
            dataGridViewCellStyle7.Font = new System.Drawing.Font("Tahoma", 9.75F);
            dataGridViewCellStyle7.ForeColor = System.Drawing.Color.Black;
            dataGridViewCellStyle7.SelectionBackColor = System.Drawing.Color.White;
            dataGridViewCellStyle7.SelectionForeColor = System.Drawing.Color.Black;
            dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
            this.dgv.DefaultCellStyle = dataGridViewCellStyle7;
            this.dgv.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dgv.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
            this.dgv.EnableHeadersVisualStyles = false;
            this.dgv.FillEmptyRow = false;
            this.dgv.FocusedRowBorderRedLine = true;
            this.dgv.Location = new System.Drawing.Point(0, 0);
            this.dgv.Margin = new System.Windows.Forms.Padding(0);
            this.dgv.MultiSelect = false;
            this.dgv.Name = "dgv";
            this.dgv.ReadOnly = true;
            this.dgv.RowHeadersVisible = false;
            dataGridViewCellStyle8.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(222)));
            this.dgv.RowsDefaultCellStyle = dataGridViewCellStyle8;
            this.dgv.RowTemplate.Height = 26;
            this.dgv.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dgv.Size = new System.Drawing.Size(714, 194);
            this.dgv.StandardTab = true;
            this.dgv.TabIndex = 0;
            //
            // col_id
            //
            this.col_id.DataPropertyName = "id";
            this.col_id.HeaderText = "ID";
            this.col_id.Name = "col_id";
            this.col_id.ReadOnly = true;
            this.col_id.Visible = false;
            //
            // col_saldat
            //
            this.col_saldat.DataPropertyName = "saldat";
            this.col_saldat.HeaderText = "วันที่";
            this.col_saldat.MinimumWidth = 80;
            this.col_saldat.Name = "col_saldat";
            this.col_saldat.ReadOnly = true;
            this.col_saldat.Visible = false;
            this.col_saldat.Width = 80;
            //
            // col_tank_name
            //
            this.col_tank_name.DataPropertyName = "tank_name";
            this.col_tank_name.HeaderText = "Tank Name";
            this.col_tank_name.Name = "col_tank_name";
            this.col_tank_name.ReadOnly = true;
            this.col_tank_name.Visible = false;
            //
            // col_section_name
            //
            this.col_section_name.DataPropertyName = "section_name";
            this.col_section_name.HeaderText = "Section Name";
            this.col_section_name.Name = "col_section_name";
            this.col_section_name.ReadOnly = true;
            this.col_section_name.Visible = false;
            //
            // col_nozzle_name
            //
            this.col_nozzle_name.DataPropertyName = "nozzle_name";
            this.col_nozzle_name.HeaderText = "เลขที่หัวจ่าย";
            this.col_nozzle_name.Name = "col_nozzle_name";
            this.col_nozzle_name.ReadOnly = true;
            this.col_nozzle_name.Visible = false;
            //
            // col_shift_name
            //
            this.col_shift_name.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.col_shift_name.DataPropertyName = "shift_name";
            this.col_shift_name.HeaderText = "ผลัด";
            this.col_shift_name.MinimumWidth = 80;
            this.col_shift_name.Name = "col_shift_name";
            this.col_shift_name.ReadOnly = true;
            //
            // col_mitbeg
            //
            this.col_mitbeg.DataPropertyName = "mitbeg";
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            dataGridViewCellStyle2.Format = "N2";
            dataGridViewCellStyle2.NullValue = null;
            this.col_mitbeg.DefaultCellStyle = dataGridViewCellStyle2;
            this.col_mitbeg.HeaderText = "มิเตอร์เริ่มต้น";
            this.col_mitbeg.MinimumWidth = 120;
            this.col_mitbeg.Name = "col_mitbeg";
            this.col_mitbeg.ReadOnly = true;
            this.col_mitbeg.Width = 120;
            //
            // col_mitend
            //
            this.col_mitend.DataPropertyName = "mitend";
            dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            dataGridViewCellStyle3.Format = "N2";
            dataGridViewCellStyle3.NullValue = null;
            this.col_mitend.DefaultCellStyle = dataGridViewCellStyle3;
            this.col_mitend.HeaderText = "มิเตอร์สิ้นสุด";
            this.col_mitend.MinimumWidth = 120;
            this.col_mitend.Name = "col_mitend";
            this.col_mitend.ReadOnly = true;
            this.col_mitend.Width = 120;
            //
            // col_salqty
            //
            this.col_salqty.DataPropertyName = "salqty";
            dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            dataGridViewCellStyle4.Format = "N2";
            dataGridViewCellStyle4.NullValue = null;
            this.col_salqty.DefaultCellStyle = dataGridViewCellStyle4;
            this.col_salqty.HeaderText = "ปริมาณขาย(ลิตร)";
            this.col_salqty.MinimumWidth = 130;
            this.col_salqty.Name = "col_salqty";
            this.col_salqty.ReadOnly = true;
            this.col_salqty.Width = 130;
            //
            // col_unitpr
            //
            this.col_unitpr.DataPropertyName = "unitpr";
            dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            dataGridViewCellStyle5.Format = "N2";
            dataGridViewCellStyle5.NullValue = null;
            this.col_unitpr.DefaultCellStyle = dataGridViewCellStyle5;
            this.col_unitpr.HeaderText = "ราคาขาย/ลิตร";
            this.col_unitpr.MinimumWidth = 120;
            this.col_unitpr.Name = "col_unitpr";
            this.col_unitpr.ReadOnly = true;
            this.col_unitpr.Width = 120;
            //
            // col_salval
            //
            this.col_salval.DataPropertyName = "salval";
            dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            dataGridViewCellStyle6.Format = "N2";
            dataGridViewCellStyle6.NullValue = null;
            this.col_salval.DefaultCellStyle = dataGridViewCellStyle6;
            this.col_salval.HeaderText = "มูลค่าขาย(บาท)";
            this.col_salval.MinimumWidth = 120;
            this.col_salval.Name = "col_salval";
            this.col_salval.ReadOnly = true;
            this.col_salval.Width = 120;
            //
            // col_shift_id
            //
            this.col_shift_id.DataPropertyName = "shift_id";
            this.col_shift_id.HeaderText = "Shift Id";
            this.col_shift_id.Name = "col_shift_id";
            this.col_shift_id.ReadOnly = true;
            this.col_shift_id.Visible = false;
            //
            // col_nozzle_id
            //
            this.col_nozzle_id.DataPropertyName = "nozzle_id";
            this.col_nozzle_id.HeaderText = "Nozzle Id";
            this.col_nozzle_id.Name = "col_nozzle_id";
            this.col_nozzle_id.ReadOnly = true;
            this.col_nozzle_id.Visible = false;
            //
            // col_stmas_id
            //
            this.col_stmas_id.DataPropertyName = "stmas_id";
            this.col_stmas_id.HeaderText = "Stmas Id";
            this.col_stmas_id.Name = "col_stmas_id";
            this.col_stmas_id.ReadOnly = true;
            this.col_stmas_id.Visible = false;
            //
            // col_pricelist_id
            //
            this.col_pricelist_id.DataPropertyName = "pricelist_id";
            this.col_pricelist_id.HeaderText = "Price List Id";
            this.col_pricelist_id.Name = "col_pricelist_id";
            this.col_pricelist_id.ReadOnly = true;
            this.col_pricelist_id.Visible = false;
            //
            // col_salessummary_id
            //
            this.col_salessummary_id.DataPropertyName = "salessummary_id";
            this.col_salessummary_id.HeaderText = "Sales Summary Id";
            this.col_salessummary_id.Name = "col_salessummary_id";
            this.col_salessummary_id.ReadOnly = true;
            this.col_salessummary_id.Visible = false;
            //
            // col_price_date
            //
            this.col_price_date.DataPropertyName = "price_date";
            this.col_price_date.HeaderText = "Price Date";
            this.col_price_date.Name = "col_price_date";
            this.col_price_date.ReadOnly = true;
            this.col_price_date.Visible = false;
            //
            // col_stkcod
            //
            this.col_stkcod.DataPropertyName = "stkcod";
            this.col_stkcod.HeaderText = "Stkcod";
            this.col_stkcod.Name = "col_stkcod";
            this.col_stkcod.ReadOnly = true;
            this.col_stkcod.Visible = false;
            //
            // col_stkdes
            //
            this.col_stkdes.DataPropertyName = "stkdes";
            this.col_stkdes.HeaderText = "Stkdes";
            this.col_stkdes.Name = "col_stkdes";
            this.col_stkdes.ReadOnly = true;
            this.col_stkdes.Visible = false;
            //
            // col_saleshistory
            //
            this.col_saleshistory.DataPropertyName = "saleshistory";
            this.col_saleshistory.HeaderText = "Sales History";
            this.col_saleshistory.Name = "col_saleshistory";
            this.col_saleshistory.ReadOnly = true;
            this.col_saleshistory.Visible = false;
            //
            // col_working_express_db
            //
            this.col_working_express_db.DataPropertyName = "working_express_db";
            this.col_working_express_db.HeaderText = "Working Express DB";
            this.col_working_express_db.Name = "col_working_express_db";
            this.col_working_express_db.ReadOnly = true;
            this.col_working_express_db.Visible = false;
            //
            // DialogNozzleSalesHistory
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.AppWorkspace;
            this.ClientSize = new System.Drawing.Size(714, 194);
            this.ControlBox = false;
            this.Controls.Add(this.dgv);
            this.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(222)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.KeyPreview = true;
            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.MaximizeBox = false;
            this.MaximumSize = new System.Drawing.Size(2000, 200);
            this.MinimizeBox = false;
            this.Name = "DialogNozzleSalesHistory";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
            this.Deactivate += new System.EventHandler(this.DialogNozzleSalesHistory_Deactivate);
            this.Load += new System.EventHandler(this.DialogNozzleSalesHistory_Load);
            this.Shown += new System.EventHandler(this.DialogNozzleSalesHistory_Shown);
            ((System.ComponentModel.ISupportInitialize)(this.dgv)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private CC.XDatagrid dgv;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_saldat;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_tank_name;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_section_name;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_nozzle_name;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_shift_name;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_mitbeg;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_mitend;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_salqty;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_unitpr;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_salval;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_shift_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_nozzle_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_stmas_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_pricelist_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_salessummary_id;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_price_date;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_stkcod;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_stkdes;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_saleshistory;
        private System.Windows.Forms.DataGridViewTextBoxColumn col_working_express_db;
    }
}


text:
layout: post
title: Caulk Til You Drop
date: 2012-10-22 18:34
author: admin
comments: true
---
I blame my friend Gord. (and myself)

You see, once upon a time there lived a skinny nerdy guy who loved to live in Condos where others would worry about silly little things like maintenance. For this, he paid a fee to have others do this for him and he thought he would live this way until the day he died.

But then in a land far away was a beautiful wife to be, and he filled out forms and more forms and  any money he had went to maintenance first, and then to saving for the big ring so he could propose to BW and become happily ever after. BW said yes, and the skinny little guy moved into the beautiful wife's castle:

in a land, far far away...where they love football too much, and the stores are always open and the streets never end.:

One fine fall day, the skinny guy, now happily married and living with the beautiful wife thought it would be nice to have friends over for dinner. Or she  did anyway.

The skinny guy - used to living alone in his spotless and maintentance-free apartment, was not used to such a strange custom. He had never heard of this thing called hosting before. How strange, he thought - you invite others into your home so that you feed them and offer them drinks. This is good money that could be used towards maintenance fees, he thought to himself. But he wanted to see what this custom in the strange land was all about

But, as the skinny guy did not want to upset the BW he honored her wishes and allowed others to enter the castle which he now shared. The guests enjoyed themselves, and thankfully the skinny guy knew how to make coffee for the guests, which the guests seemed to enjoy so the  skinny guy was quite pleased that his first hosting went so well. On the way out BW and skinny guy showered their guests with ebay purchases  gifts and as they were out the door, a guest suggested to the skinny guy that the caulking on the front windows needs to be replaced.

Skinny guy did not know what to make of this strange new custom where you do the work yourself. But the guest assured skinny guy he could rightly so do this strange and unknown task - all he had to do was go to the Castle Home Depot and ask the King of Home Depot about the correct tools needed for this great new adventure.

Skinny Guy, not being married for long at this point, made one mistake, and when he did it he knew there was a reason he never partook in this strange custom of hosting before. You see,  skinny guy made the mistake of telling the beautiful wife that the windows on the castle needed repair. BW asked skinny guy if he might be able to complete this task himself without using the 'maintenance fee' he had become so accustomed.

This, my friends is where the story takes a turn for the  worse:  skinny guy stated to BW that he thinks he just might be able to take on such a noble and dangerous task all by himself.  And BW asked him the fateful question: "When?" she asked.

And then,  my friends she did not stop asking skinny guy about this task and it's completion. Day, after day, after day she asked and asked and asked over and over again "When will you partake in this noble deed?" she asked.

and the next day she asked again.

and again

and again

Skinny Guy was not used to such demand for his talents at castle maintenance before so he was not sure what this custom was. Being  the curious sort, he called others with beautiful wives and the others confirmed that this happened at their castles too. They even had  a term for this new custom. They called it nagging.

But, they warned the skinny guy if he wanted to continue to live inside the  walls of the great castle and not on their couch that he should refrain from using that term in BW's presence.  They also advised he may want to get used to this as there are many more tasks like this and he should try to stall the work for as long as possible because that's what BW's want. Do not attempt  this task in haste, they warned me.

Skinny guy went back to the castle and waited and waited and dreaded each passing day as this task loomed over his head. Finally BW  could  not take the waiting any more and mentioned that if skinny guy did not complete this task promptly, he would be using his  friends couch as his castle. The skinny fellow did not want this to happen as he gets fed well in the BW's castle and so with great trepidation he ventured out of the warmth of the castle to  complete the task:

Skinny Guy was handed a tube and a thing with a trigger. This was apparently called a caulking gun,but skinny guy had never heard of such things. He worried about his hands , would this stuff make them rough? He worried about being outside when it was under 70 degrees but in the end it all did not matter, his worries - because despite his fears about new adventures and allowing people into the castle  and delivering drinks and food, only to have them critique your castle on the way out -  he knew he had made  the right choice for he would now be allowed back into the castle  as BW was pleased with the results and they both could rest assured that the castle will be toasty warm this winter now that the castle had been repaired.

Also, skinny guy noticed that once the task was completed, the nagging had stopped.  "At least for now" , he thought to himself

The End.


text:
using namespace std;

PiecewiseFunction::PiecewiseFunction(std::vector<double> const & segment_times) :
  segment_times(segment_times)
{
  for (int i = 1; i < getNumberOfSegments() + 1; i++) {
    if (segment_times[i] < segment_times[i - 1])
      throw std::runtime_error("times must be increasing");
  }
}

PiecewiseFunction::PiecewiseFunction() {
  // empty
}

PiecewiseFunction::~PiecewiseFunction()
{
  // empty
}

int PiecewiseFunction::getNumberOfSegments() const {
  return static_cast<int>(segment_times.size() - 1);
}

double PiecewiseFunction::getStartTime(int segment_number) const {
  segmentNumberRangeCheck(segment_number);
  return segment_times[segment_number];
}

double PiecewiseFunction::getEndTime(int segment_number) const {
  segmentNumberRangeCheck(segment_number);
  return segment_times[segment_number + 1];
}

double PiecewiseFunction::getDuration(int segment_number) const {
  return getEndTime(segment_number) - getStartTime(segment_number);
}

double PiecewiseFunction::getStartTime() const {
  return getStartTime(0);
}

double PiecewiseFunction::getEndTime() const {
  return getEndTime(getNumberOfSegments() - 1);
}

int PiecewiseFunction::getSegmentIndex(double t) const {
  // clip to min/max times
  t = std::min(std::max(t, getStartTime()), getEndTime());

  int segment_index = 0;
  // TODO: something smarter than this linear search
  while (t >= getEndTime(segment_index) && segment_index < getNumberOfSegments() - 1)
    segment_index++;

  return segment_index;
}

const std::vector<double>& PiecewiseFunction::getSegmentTimes() const {
  return segment_times;
}

void PiecewiseFunction::segmentNumberRangeCheck(int segment_number) const {
  if (segment_number < 0 || segment_number >= getNumberOfSegments()) {
    std::stringstream msg;
    msg << "Segment number " << segment_number << " out of range [" << 0 << ", " << getNumberOfSegments() << ")" << std::endl;
    throw std::runtime_error(msg.str().c_str());
  }
}

std::vector<double> PiecewiseFunction::randomSegmentTimes(int num_segments, std::default_random_engine& generator) {
  vector<double> segment_times;
  uniform_real_distribution<double> uniform;
  double t0 = uniform(generator);
  segment_times.push_back(t0);
  for (int i = 0; i < num_segments; ++i) {
    double duration = uniform(generator);
    segment_times.push_back(segment_times[i] + duration);
  }
  return segment_times;
}

bool PiecewiseFunction::segmentTimesEqual(const PiecewiseFunction& other, double tol) const {
  if (segment_times.size() != other.segment_times.size())
    return false;
  for (int i = 0; i < segment_times.size(); i++) {
    if (std::abs(segment_times[i] - other.segment_times[i]) > tol)
      return false;
  }
  return true;
}

void PiecewiseFunction::checkScalarValued() const
{
  if (rows() != 1 || cols() != 1) {
    throw std::runtime_error("Not scalar valued.");
  }
}


text:
namespace DotSpatial.Compatibility
{
    /// <summary>
    /// HJustification
    /// </summary>
    public enum HJustification
    {
        /// <summary>
        /// The item is centered
        /// </summary>
        Center,

        /// <summary>
        /// The item is justified to the left
        /// </summary>
        Left,

        /// <summary>
        /// The item is justified to the right
        /// </summary>
        Right
    }
}


text:
package io.quarkus.restclient.configuration;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class MyHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;

namespace DeviceCaps
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Mouse : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public Mouse()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string Buffer;
            Windows.Devices.Input.MouseCapabilities MouseCapabilities = new Windows.Devices.Input.MouseCapabilities();

            Buffer = string.Format("There is {0} mouse present\n", MouseCapabilities.MousePresent != 0 ? "a" : "no");
            Buffer += string.Format("There is {0} vertical mouse wheel present\n", MouseCapabilities.VerticalWheelPresent != 0 ? "a" : "no");
            Buffer += string.Format("There is {0} horizontal mouse wheel present\n", MouseCapabilities.HorizontalWheelPresent != 0 ? "a" : "no");
            Buffer += string.Format("The user has {0}opted to swap the mouse buttons\n", MouseCapabilities.SwapButtons != 0 ? "" : "not ");
            Buffer += string.Format("The mouse has {0} button(s)\n", MouseCapabilities.NumberOfButtons);

            MouseOutputTextBlock.Text = Buffer;
        }
    }
}


text:
<?php

namespace Immortal\Contracts\Filesystem;

interface Cloud extends Filesystem
{
    /**
     * Get the URL for the file at the given path.
     *
     * @param  string  $path
     * @return string
     */
    public function url($path);
}


text:
package com.androidtutorialpoint.googlemapsapp;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HomeScreenMainActivity extends AppCompatActivity {

    public Button StartGame;
    public Button Settings;
    public Button Leaderboard;

    public void init(){
        StartGame = (Button) findViewById(R.id.StartGame);
        StartGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Map = new Intent(HomeScreenMainActivity.this, MapsActivity.class);
                startActivity(Map);
            }
        });

        Settings = (Button) findViewById(R.id.Settings) ;
        Settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Set = new Intent(HomeScreenMainActivity.this, SettingsActivity.class);
                startActivity(Set);
            }
        });

        Leaderboard = (Button) findViewById(R.id.Leaderboard) ;
        Leaderboard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Lead = new Intent(HomeScreenMainActivity.this, LeaderboardActivity.class);
                startActivity(Lead);
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen_main);
        init();

    }
}


text:
function Applicant (
  firstName,
  lastName,
  fullName,
  dobDay,
  dobMonth,
  dobYear,
  hasNhsno,
  nhsno,
  postCode,
  addresslineone,
  addresslinetwo,
  town,
  hasMobile,
  hasEmail,
  mobile,
  contactPref,
  contactValue,
  email,
  address,
  age,
  renewing
  ) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = fullName;
    this.dobDay = dobDay;
    this.dobMonth = dobMonth;
    this.dobYear = dobYear;
    this.hasNhsno = hasNhsno;
    this.nhsno = nhsno;
    this.postCode = postCode;
    this.addresslineone = addresslineone;
    this.addresslinetwo = addresslinetwo;
    this.town = town;
    this.hasMobile = hasMobile;
    this.hasEmail = hasEmail;
    this.mobile = mobile;
    this.contactPref = contactPref;
    this.contactValue = contactValue;
    this.email = email;
    this.address = address;
    this.age = age;
    this.renewing = renewing;
};

Applicant.prototype.setFullName = function () {
  this.fullName = this.firstName + " " + this.lastName;
};

Applicant.prototype.checkAge = function () {
 if (this.age < 60) {
   return true;
 }
};

Applicant.prototype.check = function () {
  if (this.firstname === 'Bill' && this.lastname === 'Smith' && this.postcode === 'NE1 234') {
    return true;
  }
};

function createApplicant() {
  return new Applicant();
};

module.exports.createApplicant = createApplicant;


text:
(function() {

Dagaz.AI.PROTO         = true;
Dagaz.AI.CAPTURES_ONLY = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "chess-proto") {
      checkVersion(design, name, value);
  }
}

var checkStep = function(design, board, piece, pos, dir) {
  var p = design.navigate(piece.player, pos, dir);
  if (p === null) return;
  var target = board.getPiece(p);
  if (!Dagaz.AI.CAPTURES_ONLY || (target === null)) return;
  if ((target !== null) && (target.player == piece.player)) return;
  var move = Dagaz.Model.createMove(0);
  move.movePiece(pos, p, piece);
  board.moves.push(move);
}

var checkJump = function(design, board, piece, pos, o, d) {
  var p = design.navigate(piece.player, pos, o);
  if (p === null) return;
  p = design.navigate(piece.player, p, d);
  if (p === null) return;
  var target = board.getPiece(p);
  if (!Dagaz.AI.CAPTURES_ONLY || (target === null)) return;
  if ((target !== null) && (target.player == piece.player)) return;
  var move = Dagaz.Model.createMove(0);
  move.movePiece(pos, p, piece);
  board.moves.push(move);
}

var checkPawnShift = function(design, board, piece, pos, dir) {
  var p = design.navigate(piece.player, pos, dir);
  if (p === null) return;
  var target = board.getPiece(p);
  if (target !== null) return;
  var move = Dagaz.Model.createMove(0);
  move.movePiece(pos, p, piece);
  board.moves.push(move);
}

var checkPawnStep = function(design, board, piece, pos, dir) {
  var p = design.navigate(piece.player, pos, dir);
  if (p === null) return;
  var target = board.getPiece(p);
  if (target === null) return;
  if (target.player == piece.player) return;
  var move = Dagaz.Model.createMove(0);
  move.movePiece(pos, p, piece);
  board.moves.push(move);
}

var checkSlide = function(design, board, piece, pos, dir) {
  var p = design.navigate(piece.player, pos, dir);
  while (p !== null) {
      var target = board.getPiece(p);
      if (target !== null) {
          if (target.player == piece.player) return;
      } else {
          if (Dagaz.AI.CAPTURES_ONLY) return;
      }
      var move = Dagaz.Model.createMove(0);
      move.movePiece(pos, p, piece);
      board.moves.push(move);
      if (target !== null) return;
      p = design.navigate(piece.player, p, dir);
  }
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  var king   = design.getPieceType("King");  var pawn   = design.getPieceType("Pawn");
  var rook   = design.getPieceType("Rook");  var knight = design.getPieceType("Knight");
  var queen  = design.getPieceType("Queen"); var bishop = design.getPieceType("Bishop");
  var n  = design.getDirection("n");  var w  = design.getDirection("w");
  var s  = design.getDirection("s");  var e  = design.getDirection("e");
  var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
  var ne = design.getDirection("ne"); var se = design.getDirection("se");
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece === null) return;
      if (piece.player != board.player) return;
      if (piece.type == king) {
          checkStep(design, board, piece, pos, n); checkStep(design, board, piece, pos, nw);
          checkStep(design, board, piece, pos, e); checkStep(design, board, piece, pos, ne);
          checkStep(design, board, piece, pos, s); checkStep(design, board, piece, pos, se);
          checkStep(design, board, piece, pos, w); checkStep(design, board, piece, pos, sw);
      }
      if (piece.type == pawn) {
          if (!Dagaz.AI.CAPTURES_ONLY) checkPawnShift(design, board, piece, pos, n);
          checkPawnStep(design, board, piece, pos, nw); checkPawnStep(design, board, piece, pos, ne);
      }
      if ((piece.type == rook) || (piece.type == queen)) {
          checkSlide(design, board, piece, pos, n); checkSlide(design, board, piece, pos, e);
          checkSlide(design, board, piece, pos, w); checkSlide(design, board, piece, pos, s);
      }
      if ((piece.type == bishop) || (piece.type == queen)) {
          checkSlide(design, board, piece, pos, nw); checkSlide(design, board, piece, pos, ne);
          checkSlide(design, board, piece, pos, se); checkSlide(design, board, piece, pos, sw);
      }
      if (piece.type == knight) {
          checkJump(design, board, piece, pos, n, nw); checkJump(design, board, piece, pos, n, ne);
          checkJump(design, board, piece, pos, s, sw); checkJump(design, board, piece, pos, s, se);
          checkJump(design, board, piece, pos, w, sw); checkJump(design, board, piece, pos, w, nw);
          checkJump(design, board, piece, pos, e, se); checkJump(design, board, piece, pos, e, ne);
      }
  });
  CheckInvariants(board);
}

})();


text:
export declare const GPSHelper: {
    degToDmsRational: (degFloat: number) => number[][];
    dmsRationalToDeg: (dmsArray: number[][], ref: string) => number;
};


text:
TEUCHOS_UNIT_TEST( AceLaw9NuclearScatteringEnergyDistribution,
		   sampleEnergy_lower_bound )
{
   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution::EnergyDistribution
     energy_distribution;

   energy_distribution.resize(2);

   energy_distribution[0].first = 1.0;
   energy_distribution[0].second = 1.0;

   energy_distribution[1].first = 2.0;
   energy_distribution[1].second = 2.0;

   double restriction_energy = 1.5;

   // Create the fake stream
   std::vector<double> fake_stream( 1 );
   fake_stream[0] = 0.5;

   Utility::RandomNumberGenerator::setFakeStream( fake_stream );

   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution distribution( energy_distribution, restriction_energy );

   TEST_COMPARE(distribution.sampleEnergy(0.5) ,==,
     Utility::EvaporationDistribution::sample( 0.5,
                                               energy_distribution[0].second,
                                               restriction_energy ));
}

//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw9NuclearScatteringEnergyDistribution,
		   sampleEnergy_upper_bound )
{
   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution::EnergyDistribution
     energy_distribution;

   energy_distribution.resize(2);

   energy_distribution[0].first = 1.0;
   energy_distribution[0].second = 1.0;

   energy_distribution[1].first = 2.0;
   energy_distribution[1].second = 2.0;

   double restriction_energy = 1.5;

   // Create the fake stream
   std::vector<double> fake_stream( 1 );
   fake_stream[0] = 0.5;

   Utility::RandomNumberGenerator::setFakeStream( fake_stream );

   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution distribution( energy_distribution, restriction_energy );

   TEST_COMPARE(distribution.sampleEnergy(3.0) ,==,
     Utility::EvaporationDistribution::sample( 3.0,
                                               energy_distribution[1].second,
                                               restriction_energy ));
}

//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw9NuclearScatteringEnergyDistribution,
		   sampleEnergy )
{
   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution::EnergyDistribution
     energy_distribution;

   energy_distribution.resize(2);

   energy_distribution[0].first = 1.0;
   energy_distribution[0].second = 1.0;

   energy_distribution[1].first = 2.0;
   energy_distribution[1].second = 2.0;

   double restriction_energy = 1.5;

   // Create the fake stream
   std::vector<double> fake_stream( 1 );
   fake_stream[0] = 0.5;

   Utility::RandomNumberGenerator::setFakeStream( fake_stream );

   MonteCarlo::AceLaw9NuclearScatteringEnergyDistribution distribution( energy_distribution, restriction_energy );

   TEST_COMPARE(distribution.sampleEnergy(1.5) ,==,
     Utility::EvaporationDistribution::sample( 1.5,
                                               1.5,
                                               restriction_energy ));
}

//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
  Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();

  // Initialize the random number generator
  Utility::RandomNumberGenerator::createStreams();

  Teuchos::GlobalMPISession mpiSession( &argc, &argv );
  return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv );
}

//---------------------------------------------------------------------------//
// tstAceLaw9NuclearScatteringDistribution.cpp
//---------------------------------------------------------------------------//


text:
package org.jboss.elasticsearch.river.sysinfo.mgm;

import java.io.IOException;

import org.elasticsearch.action.support.nodes.NodesOperationResponse;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

/**
 * Base for action responses from to the Sysinfo River. All node responses are aggregated here.
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public abstract class JRMgmBaseResponse<T extends NodeJRMgmBaseResponse> extends NodesOperationResponse<T> {

  public JRMgmBaseResponse() {

  }

  public JRMgmBaseResponse(ClusterName clusterName, T[] nodes) {
    super(clusterName, nodes);
  }

  @Override
  public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    nodes = newNodeResponsesArray(in.readVInt());
    for (int i = 0; i < nodes.length; i++) {
      T node = newNodeResponse();
      node.readFrom(in);
      nodes[i] = node;
    }
  }

  protected abstract T[] newNodeResponsesArray(int len);

  protected abstract T newNodeResponse();

  @Override
  public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeVInt(nodes.length);
    for (T node : nodes) {
      node.writeTo(out);
    }
  }

  /**
   * Get response from node where running Sysinfo river instance was found.
   *
   * @return response from node with river or null if no river with given name was found in any node.
   */
  public T getSuccessNodeResponse() {
    if (nodes == null || nodes.length == 0)
      return null;

    for (T resp : nodes) {
      if (resp.riverFound) {
        return resp;
      }
    }
    return null;
  }

}


text:
using NForum.Core.Dtos;
using System;
using System.Collections.Generic;

namespace NForum.Datastores.EF.Dtos {

	public class Category : ICategoryDto {
		public IDictionary<String, Object> CustomProperties { get; set; }

		public String Description { get; set; }

		public String Id { get; set; }

		public String Name { get; set; }

		public Int32 SortOrder { get; set; }
	}
}


text:
var NoInternetConnect = function() {

	//UI STUFF
	var self = Ti.UI.createWindow({
		backgroundColor:'#000',
		backgroundImage:'images/admin/no_internet.png',
		opacity: 1.0,
		title: "No Internet Connection",
		layout: 'vertical',
		tabBarHidden: true,
		navBarHidden: true
	});

	return self;
};

module.exports = NoInternetConnect;


text:
package woko.ioc;

import net.sourceforge.jfacets.IFacetDescriptorManager;
import woko.persistence.ObjectStore;
import woko.users.UserManager;
import woko.users.UsernameResolutionStrategy;

import java.util.Map;

/**
 * Interface for the Woko IOC container. The Woko instance references an IOC container
 * for accessing the various mandatory components (ObjectStore, UserManager etc.).
 * The IOC container can also be used for optional, application-specific components.
 */
public interface WokoIocContainer<
        OsType extends ObjectStore,
        UmType extends UserManager,
        UnsType extends UsernameResolutionStrategy,
        FdmType extends IFacetDescriptorManager
        > {

    static final String ObjectStore = "ObjectStore";
    static final String UserManager = "UserManager";
    static final String FacetDescriptorManager = "FacetDescriptorManager";
    static final String UsernameResolutionStrategy = "UsernameResolutionStrategy";

    /**
     * Return the component for passed key if any (null if no such component)
     * @param key the component key
     * @param <T> the component type
     * @return the component for passed key
     */
    <T> T getComponent(Object key);

    /**
     * Return the ObjectStore for the app
     * @return the ObjectStore for the app
     */
    OsType getObjectStore();

    /**
     * Return the UserManager for the app
     * @return the UserManager for the app
     */
    UmType getUserManager();

    /**
     * Return the UsernameResolutionStrategy for the app
     * @return the UsernameResolutionStrategy for the app
     */
    UnsType getUsernameResolutionStrategy();

    /**
     * Return the IFacetDescriptorManager for the app
     * @return the IFacetDescriptorManager for the app
     */
    FdmType getFacetDescriptorManager();

    /**
     * Return a map of all keys/components in the ioc. This map
     * should be immutable, and should never be modified. It is
     * meant to be used read-only.
     * @return a map of all keys/components
     */
    Map<?,?> getComponents();

}


text:
#pragma once

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <vector>

#include <opencv2/opencv.hpp>
#include "Eigen/Core"

#include "modules/perception/lidar/lib/segmentation/ncut/common/flood_fill.h"
#include "modules/perception/lidar/lib/segmentation/ncut/common/lr_classifier.h"
#include "modules/perception/lidar/lib/segmentation/ncut/proto/ncut_config.pb.h"
#include "modules/perception/lidar/lib/segmentation/ncut/proto/ncut_param.pb.h"

namespace apollo {
namespace perception {
namespace lidar {

class NCut {
 public:
  NCut();
  ~NCut();
  bool Init(const NCutParam& param);

  int NumSegments() const { return static_cast<int>(_segment_pids.size()); }
  std::string GetSegmentLabel(int sid) const { return _segment_labels[sid]; }

  void GetSegmentSize(int sid, float* length, float* width,
                      float* height) const {
    NcutBoundingBox box = _segment_bbox[sid];
    *length = std::get<1>(box) - std::get<0>(box);
    *width = std::get<3>(box) - std::get<2>(box);
    *height = std::get<5>(box) - std::get<4>(box);
  }

  base::PointFCloudPtr GetSegmentPointCloud(int sid) const {
    base::PointFCloudPtr pc = base::PointFCloudPtr(
        new base::PointFCloud(*_cloud_obstacles, _segment_pids[sid]));
    return pc;
  }

  void Segment(base::PointFCloudConstPtr cloud);

  std::string GetPcRoughLabel(const base::PointFCloudPtr& cloud,
                              bool only_check_pedestrian);

  void GetSegmentRoughSize(const base::PointFCloudPtr& cloud, float* length,
                           float* width, float* height);

 private:
  struct gridIndex {
    int irow;
    int jcol;
  };

  // x_min, x_max, y_min, y_max, z_min, z_max;
  typedef std::tuple<float, float, float, float, float, float> NcutBoundingBox;
  base::PointFCloudPtr _cloud_obstacles;
  // super pixels related
  float _grid_radius;
  float _super_pixel_cell_size;
  std::unique_ptr<LRClassifier> _classifier;
  // felzenszwalb
  double _felzenszwalb_sigma;
  double _felzenszwalb_k;
  int _felzenszwalb_min_size;
  // graph cut related
  double _sigma_feature;
  double _sigma_space;
  double _connect_radius;
  int _num_cuts;
  float _ncuts_stop_threshold;
  double _ncuts_enable_classifier_threshold;
  // component (cluster) information
  std::vector<std::vector<int>> _cluster_points;
  // x_min, x_max, y_min, y_max, z_min, z_max;
  std::vector<NcutBoundingBox> _cluster_bounding_box;
  std::vector<std::string> _cluster_labels;
  // skeleton related
  float _skeleton_cell_size;  // skeleton sample size
  int _patch_size;
  cv::Mat _cv_feature_map;
  FloodFill _ff_feature_grid;
  std::vector<Eigen::MatrixXf> _cluster_skeleton_points;
  std::vector<Eigen::MatrixXf> _cluster_skeleton_features;
  // merge overlap
  double _overlap_factor;
  // final segments, each vector contains
  std::vector<std::vector<int>> _segment_pids;
  std::vector<std::string> _segment_labels;
  std::vector<NcutBoundingBox> _segment_bbox;
  std::vector<std::vector<int>> _outlier_pids;

  void SampleByGrid(const std::vector<int>& point_gids,
                    Eigen::MatrixXf* skeleton_coords,
                    Eigen::MatrixXf* skeleton_feature);

  void PrecomputeAllSkeletonAndBbox();

  bool Configure(const NCutParam& ncut_param_);

  void SuperPixelsFloodFill(base::PointFCloudConstPtr cloud, float radius,
                            float cell_size,
                            std::vector<std::vector<int>>* super_pixels);

  // super pixels
  void BuildAverageHeightMap(base::PointFCloudConstPtr cloud,
                             const FloodFill& ff_map, cv::Mat* cv_height_map,
                             std::vector<gridIndex>* point_pixel_indices);

  // skeleton
  void GetPatchFeature(const Eigen::MatrixXf& points,
                       Eigen::MatrixXf* features);

  // bounding box
  NcutBoundingBox ComputeClusterBoundingBox(const std::vector<int>& point_gids);

  std::string GetPcLabel(const base::PointFCloudPtr& cloud);

  void NormalizedCut(float ncuts_threshold, bool use_classifier,
                     std::vector<std::vector<int>>* segment_clusters,
                     std::vector<std::string>* segment_labels);

  void ComputeSkeletonWeights(Eigen::MatrixXf* weights);

  float GetMinNcuts(const Eigen::MatrixXf& in_weights,
                    const std::vector<int>* in_clusters, std::vector<int>* seg1,
                    std::vector<int>* seg2);

  void LaplacianDecomposition(const Eigen::MatrixXf& weights,
                              Eigen::MatrixXf* eigenvectors);

  bool ComputeSquaredSkeletonDistance(const Eigen::MatrixXf& in1_points,
                                      const Eigen::MatrixXf& in1_features,
                                      const Eigen::MatrixXf& in2_points,
                                      const Eigen::MatrixXf& in2_features,
                                      float* dist_point, float* dist_feature);

  bool IsMovableObstacle(const std::vector<int>& cluster_ids,
                         std::string* label);

  inline bool IsPotentialPedestrianSize(float length, float width) {
    return ((length > 0.5 && length < 1.5) && (width > 0.3 && width < 1));
  }

  inline bool IsPotentialBicyclistSize(float length, float width) {
    return ((length > 1 && length < 2.5) && (width > 0.3 && width < 1.5));
  }

  inline bool IsPotentialCarSize(float length, float width) {
    // return ( (length > 1.0 && length < 20.0) && (width > 1.0 && width < 3.5)
    // );
    return ((length > 1.0 && length < 8.0) && (width > 1.0 && width < 3.5));
  }

  int GetComponentBoundingBox(const std::vector<int>& cluster_ids,
                              NcutBoundingBox* box);

  inline float GetBboxLength(const NcutBoundingBox& box) {
    return (std::get<1>(box) - std::get<0>(box));
  }

  inline float GetBboxWidth(const NcutBoundingBox& box) {
    return (std::get<3>(box) - std::get<2>(box));
  }

  inline float GetBboxHeight(const NcutBoundingBox& box) {
    return (std::get<5>(box) - std::get<4>(box));
  }

  std::string GetClustersLabel(const std::vector<int>& cluster_ids);

  void GetClustersPids(const std::vector<int>& cids, std::vector<int>* pids);
};

}  // namespace lidar
}  // namespace perception
}  // namespace apollo


text:
import React, { Component} from 'react'
import PropTypes from 'prop-types'

export default class Todo extends Component {
    render() {
        return (
            <li
                onClick={this.props.onClick}
                style={{
                    textDecoration: this.props.completed ? 'line-through' : 'none',
                    cursor: this.props.completed ? 'default' : 'pointer'
                }}>
                {this.props.text}
            </li>
        )
    }
}

Todo.propTypes = {
    onClick: PropTypes.func.isRequired,
    text: PropTypes.string.isRequired,
    completed: PropTypes.bool.isRequired
};


text:
package org.freedesktop.nativecamera2;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

public class NativeCamera2 extends Activity {

    static final String TAG = "NativeCamera2";

    private static final int PERMISSION_REQUEST_CAMERA = 1;

    public static native void startPreview(Surface surface);

    public static native void stopPreview();

    public static native void startExtraView(Surface surface);

    public static native void stopExtraView();

    LayoutInflater extraViewLayoutInflater = null;

    boolean isBurstModeOn = false;

    static {
        System.loadLibrary("native-camera2-jni");
    }

    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;

    SurfaceView extraView;
    SurfaceHolder extraViewHolder;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(
                    this,
                    new String[] { Manifest.permission.CAMERA },
                    PERMISSION_REQUEST_CAMERA);
            return;
        }

        surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        surfaceHolder = surfaceView.getHolder();

        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {

                Log.v(TAG, "surface created.");
                startPreview(holder.getSurface());
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                stopPreview();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.v(TAG, "format=" + format + " w/h : (" + width + ", " + height + ")");
            }
        });

        extraViewLayoutInflater = LayoutInflater.from(getBaseContext());

        View view = extraViewLayoutInflater.inflate(R.layout.extraviewlayout, null);
        ViewGroup.LayoutParams layoutParamsControl
                = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        this.addContentView(view, layoutParamsControl);

        extraView = (SurfaceView) findViewById(R.id.extraview);
        extraView.setVisibility(View.INVISIBLE);

        extraViewHolder = extraView.getHolder();
        extraViewHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                startExtraView(extraViewHolder.getSurface());

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                stopExtraView();
            }
        });

        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isBurstModeOn = !isBurstModeOn;

                if (isBurstModeOn) {
                    extraView.setVisibility(View.VISIBLE);
                } else {
                    extraView.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        stopPreview();
        super.onDestroy();
    }

}


text:
package org.uct.cs.simplify.model;

import org.uct.cs.simplify.ply.header.PLYElement;
import org.uct.cs.simplify.ply.reader.PLYReader;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

public class SkippableVertexReader extends StreamingVertexReader implements AutoCloseable
{
    protected final PLYReader reader;
    protected final PLYElement vertexElement;
    protected final VertexAttrMap vam;
    protected final long start;
    protected final int blockSize;
    protected final ByteBuffer blockBuffer;
    protected long index;
    protected long count;
    protected FileInputStream istream;
    protected FileChannel inputChannel;

    public SkippableVertexReader(PLYReader r) throws IOException
    {
        reader = r;
        vertexElement = reader.getHeader().getElement("vertex");
        count = vertexElement.getCount();
        vam = new VertexAttrMap(this.vertexElement);

        start = reader.getElementDimension("vertex").getOffset();

        istream = new FileInputStream(reader.getFile());
        inputChannel = istream.getChannel();
        inputChannel.position(start);
        blockSize = vertexElement.getItemSize();
        blockBuffer = ByteBuffer.allocateDirect(blockSize);
        blockBuffer.order(ByteOrder.LITTLE_ENDIAN);
    }

    @Override
    public boolean hasNext()
    {
        return index < count;
    }

    @Override
    public Vertex next() throws IOException
    {
        Vertex v = new Vertex(0, 0, 0);
        next(v);
        return v;
    }

    @Override
    public void next(Vertex v) throws IOException
    {
        inputChannel.read(blockBuffer);
        blockBuffer.flip();
        v.read(blockBuffer, vam);
        index++;
        blockBuffer.clear();
    }

    @Override
    public long getCount()
    {
        return this.count;
    }

    @Override
    public void close() throws IOException
    {
        this.istream.close();
    }

    @Override
    public VertexAttrMap getVam()
    {
        return vam;
    }

    public void skipTo(long i) throws IOException
    {
        if (index == i) return;
        this.index = i;
        this.inputChannel.position(start + i * blockSize);
    }

    public long getIndex()
    {
        return index;
    }
}