text:
//
//  NYXMovie.m
//  qlMoviePreview
//
//  Created by @Nyx0uf on 24/12/14.
//  Copyright (c) 2014 Nyx0uf. All rights reserved.
//  www.cocoaintheshell.com
//

#import "NYXMovie.h"
#import <libavformat/avformat.h>
#import <libswscale/swscale.h>
#import <libavutil/imgutils.h>
#import <libavutil/samplefmt.h>
#import <sys/stat.h>
#import <time.h>

@implementation NYXMovie
{
	// Movie path
	NSString* _filepath;
	/// Format context
	AVFormatContext* _fmt_ctx;
	/// Codec context
	AVCodecContext* _dec_ctx;
	/// Current stream
	AVStream* _stream;
	/// Single frame for thumbnail
	AVFrame* _frame;
	/// Current stream ID
	int _stream_idx;
}

#pragma mark - Allocations / Deallocations
-(instancetype)initWithFilepath:(NSString*)filepath
{
	if ((self = [super init]))
	{
		if (nil == filepath)
			return nil;

		_filepath = [filepath copy];
		_fmt_ctx = NULL;
		_dec_ctx = NULL;
		_stream = NULL;
		_frame = NULL;
		_stream_idx = 0;

		if (avformat_open_input(&_fmt_ctx, [filepath UTF8String], NULL, NULL) != 0)
		{
			return nil;
		}

		if (avformat_find_stream_info(_fmt_ctx, NULL))
		{
			avformat_close_input(&_fmt_ctx);
			return nil;
		}

		// Find video stream
		AVCodec* codec = NULL;
		_stream_idx = av_find_best_stream(_fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
		if (_stream_idx >= 0)
		{
			_stream = _fmt_ctx->streams[_stream_idx];

			AVCodecParameters* codecpar = _stream->codecpar;
			if (codecpar != NULL && codecpar->height > 0)
			{
				codec = avcodec_find_decoder(codecpar->codec_id);
				if (!codec)
				{
					avformat_close_input(&_fmt_ctx);
					return nil;
				}

				_dec_ctx = avcodec_alloc_context3(NULL);
				if (!_dec_ctx)
				{
					avformat_close_input(&_fmt_ctx);
					return nil;
				}

				if (avcodec_parameters_to_context(_dec_ctx, codecpar) != 0)
				{
					avcodec_free_context(&_dec_ctx);
					avformat_close_input(&_fmt_ctx);
					return nil;
				}

				// Open codec
				if (avcodec_open2(_dec_ctx, codec, NULL) != 0)
				{
					avcodec_free_context(&_dec_ctx);
					avformat_close_input(&_fmt_ctx);
					return nil;
				}

				// Allocate frame
				_frame = av_frame_alloc();
				if (!_frame)
				{
					avcodec_close(_dec_ctx);
					avcodec_free_context(&_dec_ctx);
					avformat_close_input(&_fmt_ctx);
					return nil;
				}
			}
		}
	}
	return self;
}

-(void)dealloc
{
	if (_frame != NULL)
	{
		av_frame_free(&_frame);
	}
	if (_dec_ctx != NULL)
	{
		avcodec_close(_dec_ctx);
		avcodec_free_context(&_dec_ctx);
	}
	if (_fmt_ctx != NULL)
	{
		avformat_close_input(&_fmt_ctx);
	}
}

#pragma mark - Public
-(bool)createThumbnailAtPath:(NSString*)path ofSize:(NYXSize)size atPosition:(int64_t)position
{
	// Thumbnail only once
	NSFileManager* file_manager = [[NSFileManager alloc] init];
	if ([file_manager fileExistsAtPath:path])
		return true;

	// Set thumbnail offset
	// If duration is unknown or less than 2 seconds, use the first frame
	if (_fmt_ctx->duration > (2 * AV_TIME_BASE))
	{
		int64_t timestamp = (_fmt_ctx->duration > (position * 2 * AV_TIME_BASE) ? av_rescale(position, _stream->time_base.den, _stream->time_base.num) : av_rescale(_fmt_ctx->duration, _stream->time_base.den, 2 * AV_TIME_BASE * _stream->time_base.num));
		if (_stream->start_time > 0)
			timestamp += _stream->start_time;
		if (av_seek_frame(_fmt_ctx, _stream_idx, timestamp, AVSEEK_FLAG_BACKWARD) < 0)
			av_seek_frame(_fmt_ctx, _stream_idx, 0, AVSEEK_FLAG_BYTE); // Fail, rewind
	}

	AVPacket packet;
	av_init_packet(&packet);
	packet.data = NULL;
	packet.size = 0;
	int got_frame = 0;
	while (av_read_frame(_fmt_ctx, &packet) >= 0 && !got_frame)
	{
		if (packet.stream_index == _stream_idx)
		{
			avcodec_send_packet(_dec_ctx, &packet);
			got_frame = avcodec_receive_frame(_dec_ctx, _frame) >= 0;
		}
		av_packet_unref(&packet);
	}
	if (!got_frame) // No frame :<
	{
		return false;
	}

	// Keep aspect ratio
	size.w = (size_t)av_rescale(_dec_ctx->width, (int64_t)size.h, _dec_ctx->height);
	const AVRational sar = av_guess_sample_aspect_ratio(_fmt_ctx, _stream, NULL);
	if (sar.num && sar.den)
		size.w = (size_t)av_rescale((int64_t)size.w, sar.num, sar.den);

	// Convert frame and scale if needed
	struct SwsContext* sws_ctx = sws_getContext(_dec_ctx->width, _dec_ctx->height, _dec_ctx->pix_fmt, (int)size.w, (int)size.h, AV_PIX_FMT_RGB24, SWS_SPLINE, NULL, NULL, NULL);
	if (!sws_ctx)
	{
		return false;
	}

	const size_t linesize = ((3 * size.w + 15) / 16) * 16; // align
	uint8_t* buffer = (uint8_t*)malloc(linesize * size.h);
	if (!buffer)
	{
		return false;
	}

	uint8_t* const pixels[4] = { buffer };
	const int stride[4] = { (int)linesize };
	sws_scale(sws_ctx, (const uint8_t* const*)_frame->data, _frame->linesize, 0, _dec_ctx->height, pixels, stride);
	sws_freeContext(sws_ctx);

	// Create CGImageRef
	CGDataProviderRef data_provider = CGDataProviderCreateWithData(NULL, buffer, linesize * size.h, NULL);
	if (!data_provider)
	{
		free(buffer);
		return false;
	}
	CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
	CGImageRef img_ref = CGImageCreate(size.w, size.h, 8, 24, (size_t)linesize, color_space, kCGBitmapByteOrderDefault, data_provider, NULL, false, kCGRenderingIntentDefault);
	CGColorSpaceRelease(color_space);
	CGDataProviderRelease(data_provider);

	free(buffer);

	if (!img_ref)
	{
		return false;
	}

	// Save
	CGImageDestinationRef dst = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], kUTTypePNG, 1, NULL);
	if (!dst)
	{
		CGImageRelease(img_ref);
		return false;
	}
	CGImageDestinationAddImage(dst, img_ref, NULL);
	const bool ret = CGImageDestinationFinalize(dst);
	CFRelease(dst);
	CGImageRelease(img_ref);

	return ret;
}

-(void)fillDictionary:(NSMutableDictionary*)attrs
{
	// Duration
	if (_fmt_ctx->duration > 0)
		attrs[(__bridge NSString*)kMDItemDurationSeconds] = @((double)((double)_fmt_ctx->duration / AV_TIME_BASE));
	// Bit rate
	if (_fmt_ctx->bit_rate > 0)
		attrs[(__bridge NSString*)kMDItemTotalBitRate] = @(_fmt_ctx->bit_rate);
	// Title
	AVDictionaryEntry* tag = av_dict_get(_fmt_ctx->metadata, "title", NULL, 0);
	if (tag != NULL)
		attrs[(__bridge NSString*)kMDItemTitle] = [NSString stringWithUTF8String:tag->value];

	NSMutableArray* codecs = [[NSMutableArray alloc] init];
	NSMutableArray* langs = [[NSMutableArray alloc] init];
	NSMutableArray* types = [[NSMutableArray alloc] init];
	for (unsigned int stream_idx = 0; stream_idx < _fmt_ctx->nb_streams; stream_idx++)
	{
		AVStream* stream = _fmt_ctx->streams[stream_idx];
		AVCodecParameters* codecpar = stream->codecpar;
		const BOOL forced = (stream->disposition & AV_DISPOSITION_FORCED);

		if (AVMEDIA_TYPE_VIDEO == codecpar->codec_type)
		{
			if ((codecpar->bit_rate > 0) && (nil == attrs[(__bridge NSString*)kMDItemVideoBitRate]))
				attrs[(__bridge NSString*)kMDItemVideoBitRate] = @(codecpar->bit_rate);
			if ((codecpar->height > 0) && (nil == attrs[(__bridge NSString*)kMDItemPixelHeight]))
			{
				attrs[(__bridge NSString*)kMDItemPixelHeight] = @(codecpar->height);
				AVRational sar = av_guess_sample_aspect_ratio(_fmt_ctx, stream, NULL);
				if ((sar.num) && (sar.den))
					attrs[(__bridge NSString*)kMDItemPixelWidth] = @(av_rescale(codecpar->width, sar.num, sar.den));
				else
					attrs[(__bridge NSString*)kMDItemPixelWidth] = @(codecpar->width);
			}
			[types addObject:@"Video"];
		}
		else if (AVMEDIA_TYPE_AUDIO == codecpar->codec_type)
		{
			if ((codecpar->bit_rate > 0) && (nil == attrs[(__bridge NSString*)kMDItemAudioBitRate]))
				attrs[(__bridge NSString*)kMDItemAudioBitRate] = @(codecpar->bit_rate);
			if ((codecpar->channels > 0) && (nil == attrs[(__bridge NSString*)kMDItemAudioChannelCount]))
			{
				NSNumber* channels;
				switch (codecpar->channels)
				{
					case 3:
						channels = @2.1f;
						break;
					case 6:
						channels = @5.1f;
						break;
					case 7:
						channels = @6.1f;
						break;
					case 8:
						channels = @7.1f;
						break;
					default:
						channels = @(codecpar->channels);
				}
				attrs[(__bridge NSString*)kMDItemAudioChannelCount] = channels;
			}
			if ((codecpar->sample_rate > 0) && (nil == attrs[(__bridge NSString*)kMDItemAudioSampleRate]))
				attrs[(__bridge NSString*)kMDItemAudioSampleRate] = @(codecpar->sample_rate);

			// Lang
			tag = av_dict_get(stream->metadata, "language", NULL, 0);
			if (tag != NULL)
				[langs addObject:@(tag->value)];

			[types addObject:@"Audio"];
		}
		else if (AVMEDIA_TYPE_SUBTITLE == codecpar->codec_type)
		{
			if (forced)
				continue;

			[types addObject:@"Text"];
		}
		else
			continue;

		AVCodec* codec = avcodec_find_decoder(codecpar->codec_id);
		if (codec != NULL)
		{
			const char* cname = NULL;
			switch (codec->id)
			{
				case AV_CODEC_ID_H263:
					cname = "H.263";
					break;
				case AV_CODEC_ID_H263P:
					cname = "H.263+";
					break;
				case AV_CODEC_ID_H264:
					cname = "H.264 (AVC)";
					break;
				case AV_CODEC_ID_HEVC:
					cname = "H.265 (HEVC)";
					break;
				case AV_CODEC_ID_MPEG2VIDEO:
					cname = "MPEG-2";
					break;
				case AV_CODEC_ID_AAC:
					cname = "AAC";
					break;
				case AV_CODEC_ID_AC3:
					cname = "AC3";
					break;
				case AV_CODEC_ID_DTS:
					cname = "DTS";
					break;
				case AV_CODEC_ID_FLAC:
					cname = "FLAC";
					break;
				case AV_CODEC_ID_MP3:
					cname = "MP3";
					break;
				case AV_CODEC_ID_OPUS:
					cname = "Opus";
					break;
				case AV_CODEC_ID_TRUEHD:
					cname = "TrueHD";
					break;
				case AV_CODEC_ID_VORBIS:
					cname = "Vorbis";
					break;
				case AV_CODEC_ID_ASS:
					cname = "ASS";
					break;
				case AV_CODEC_ID_SSA:
					cname = "SSA";
					break;
				case AV_CODEC_ID_HDMV_PGS_SUBTITLE:
					cname = "PGS";
					break;
				case AV_CODEC_ID_SRT:
				case AV_CODEC_ID_SUBRIP:
					cname = "SRT";
					break;
				case AV_CODEC_ID_DVD_SUBTITLE:
					cname = "VobSub";
					break;
				case AV_CODEC_ID_MICRODVD:
					cname = "SUB";
					break;
				case AV_CODEC_ID_SAMI:
					cname = "SMI";
					break;
				default:
					cname = codec->long_name ? codec->long_name : codec->name;
			}

			if (cname)
			{
				const char* profile = av_get_profile_name(codec, codecpar->profile);
				NSString* s = (profile != NULL) ? [NSString stringWithFormat:@"%s [%s]", cname, profile] : [NSString stringWithUTF8String:cname];
				if (![codecs containsObject:s])
					[codecs addObject:s];
			}
		}
	}

	if ([types count])
		attrs[(__bridge NSString*)kMDItemMediaTypes] = types;

	if ([codecs count])
		attrs[(__bridge NSString*)kMDItemCodecs] = codecs;

	if ([langs count])
		attrs[(__bridge NSString*)kMDItemLanguages] = langs;
}

-(NSDictionary*)informations
{
	/* General file info */
	NSMutableDictionary* out_dict = [[NSMutableDictionary alloc] init];
	NSMutableString* str_general = [[NSMutableString alloc] initWithString:@"
📌 General

"];

	// Movie name
	AVDictionaryEntry* tag = av_dict_get(_fmt_ctx->metadata, "title", NULL, 0);
	if (tag != NULL)
		[str_general appendFormat:@"
Title: %@
", [NSString stringWithUTF8String:tag->value]];
	else
		[str_general appendString:@"
Title: Undefined
"];

	// Duration
	time_t timestamp = (time_t)((double)_fmt_ctx->duration / AV_TIME_BASE);
	struct tm* ptm = gmtime(&timestamp);
	const size_t hour = (size_t)ptm->tm_hour;
	if (0 == hour)
		[str_general appendFormat:@"
Duration: %dmn %ds
", ptm->tm_min, ptm->tm_sec];
	else
		[str_general appendFormat:@"
Duration: %zuh %dmn %ds
", hour, ptm->tm_min, ptm->tm_sec];

	// Filesize
	struct stat st;
	stat([_filepath UTF8String], &st);
	NSString* fmt = nil;
	if (st.st_size > 1073741824) // More than 1Gib
		fmt = [[NSString alloc] initWithFormat:@"%.1fGiB", (float)((float)st.st_size / 1073741824.0f)];
	else if ((st.st_size < 1073741824) && (st.st_size > 1048576)) // More than 1Mib
		fmt = [[NSString alloc] initWithFormat:@"%.1fMiB", (float)((float)st.st_size / 1048576.0f)];
	else if ((st.st_size < 1048576) && (st.st_size > 1024)) // 1Kib - 1Mib
		fmt = [[NSString alloc] initWithFormat:@"%.2fKiB", (float)((float)st.st_size / 1024.0f)];
	else // Less than 1Kib
		fmt = [[NSString alloc] initWithFormat:@"%lldB", st.st_size];
	[str_general appendFormat:@"
Size: %@

", fmt];
	out_dict[@"general"] = str_general;

	/* Look at each stream */
	NSMutableString* str_video = [[NSMutableString alloc] init];
	NSMutableString* str_audio = [[NSMutableString alloc] init];
	NSMutableString* str_subs = [[NSMutableString alloc] init];
	size_t nb_video_tracks = 0, nb_audio_tracks = 0, nb_subs_tracks = 0;
	for (unsigned int stream_idx = 0; stream_idx < _fmt_ctx->nb_streams; stream_idx++)
	{
		AVStream* stream = _fmt_ctx->streams[stream_idx];
		AVCodecParameters* codecpar = stream->codecpar;

		const BOOL def = (stream->disposition & AV_DISPOSITION_DEFAULT);
		const BOOL forced = (stream->disposition & AV_DISPOSITION_FORCED);
		if (AVMEDIA_TYPE_VIDEO == codecpar->codec_type) /* Video stream(s) */
		{
			// Separator if multiple streams
			if (nb_video_tracks > 0)
				[str_video appendString:@"
----
"];

			// show FAR
			[str_video appendFormat:@"
Resolution: %dx%d", codecpar->width, codecpar->height];
			const AVRational sar = av_guess_sample_aspect_ratio(_fmt_ctx, stream, NULL);
			// show DAR if not equal to FAR
			if ((sar.num) && (sar.den) && (sar.num != sar.den))
			{
				const int height = codecpar->height;
				const int width = (int)av_rescale(codecpar->width, sar.num, sar.den);
				[str_video appendFormat:@" => %dx%d (SAR %d:%d)", width, height, sar.num, sar.den];
			}
			const AVRational dar = stream->display_aspect_ratio;
			if ((dar.num) && (dar.den))
				[str_video appendFormat:@" (%d:%d)
", dar.num, dar.den];
			[str_video appendString:@"
"];

			// Format, profile, bitrate, reframe
			AVCodec* codec = avcodec_find_decoder(codecpar->codec_id);
			if (codec != NULL)
			{
				const char* cname = NULL;
				switch (codec->id)
				{
					case AV_CODEC_ID_H263:
						cname = "H.263";
						break;
					case AV_CODEC_ID_H263P:
						cname = "H.263+";
						break;
					case AV_CODEC_ID_H264:
						cname = "H.264 (AVC)";
						break;
					case AV_CODEC_ID_HEVC:
						cname = "H.265 (HEVC)";
						break;
					case AV_CODEC_ID_MPEG2VIDEO:
						cname = "MPEG-2";
						break;
					default:
						cname = codec->long_name ? codec->long_name : codec->name;
				}
				[str_video appendFormat:@"
Format: %s", cname];
				const char* profile = av_get_profile_name(codec, codecpar->profile);
				if (profile != NULL)
				{
					NSString* level = @"";
					switch (codecpar->level)
					{
						case 30:
							level = @"3.0";
							break;
						case 31:
							level = @"3.1";
							break;
						case 32:
							level = @"3.2";
							break;
						case 40:
							level = @"4.0";
							break;
						case 41:
							level = @"4.1";
							break;
						case 42:
							level = @"4.2";
							break;
						case 50:
							level = @"5.0";
							break;
						case 51:
							level = @"5.1";
							break;
						case 52:
							level = @"5.2";
							break;
						default:
							level = [@(codecpar->level) stringValue];
					}
					[str_video appendFormat:@" [%s@L%@]", profile, level];
				}
				if (codecpar->bit_rate > 0)
					[str_video appendFormat:@" / %d Kbps", (int)((float)codecpar->bit_rate / 1000.0f)];
				AVCodecContext* dec_ctx = avcodec_alloc_context3(NULL);
				if (dec_ctx != NULL)
				{
					if (avcodec_parameters_to_context(dec_ctx, codecpar) == 0)
					{
						if (dec_ctx->refs > 0)
							[str_video appendFormat:@" / %d ReF", dec_ctx->refs];
					}
					avcodec_free_context(&dec_ctx);
				}

				[str_video appendString:@"
"];

				const char* pix_fmt = av_get_pix_fmt_name(codecpar->format);
				if (pix_fmt != NULL)
				{
					if (strstr(pix_fmt, "p16"))
						[str_video appendString:@"
Bit depth: 16 bits
"];
					else if (strstr(pix_fmt, "p10"))
						[str_video appendString:@"
Bit depth: 10 bits
"];
					else // Assume 8 bits
						[str_video appendString:@"
Bit depth: 8 bits
"];
				}
			}

			// Framerate
			const AVRational rate = av_stream_get_r_frame_rate(stream);
			if ((rate.den) && (rate.num))
				[str_video appendFormat:@"
Framerate: %.3f
", ((double)rate.num * 100.0) / (double)rate.den / 100.0];
			else if ((stream->avg_frame_rate.den) && (stream->avg_frame_rate.num))
				[str_video appendFormat:@"
Framerate: %.3f
", ((double)stream->avg_frame_rate.num * 100.0) / (double)stream->avg_frame_rate.den / 100.0];
			else
				[str_video appendString:@"
Framerate: Undefined
"];

			// Title
			tag = av_dict_get(stream->metadata, "title", NULL, 0);
			if (tag != NULL)
				[str_video appendFormat:@"
Title: %@
", [NSString stringWithUTF8String:tag->value]];

			nb_video_tracks++;
		}
		else if (AVMEDIA_TYPE_AUDIO == codecpar->codec_type) /* Audio stream(s) */
		{
			// Separator if multiple streams
			if (nb_audio_tracks > 0)
				[str_audio appendString:@"
----
"];

			// Language
			tag = av_dict_get(stream->metadata, "language", NULL, 0);
			if (tag != NULL)
				[str_audio appendFormat:@"
Language: %@%s", def ? @"" : @"", tag->value];
			else
				[str_audio appendFormat:@"
Language: %@Undefined", def ? @"" : @""];
			[str_audio appendFormat:@" %@%@
", forced ? @"[Forced]" : @"", def ? @"" : @""];

			// Format, profile, bit depth, bitrate, sampling rate
			AVCodec* codec = avcodec_find_decoder(codecpar->codec_id);
			if (codec != NULL)
			{
				const char* cname = NULL;
				switch (codec->id)
				{
					case AV_CODEC_ID_AAC:
						cname = "AAC";
						break;
					case AV_CODEC_ID_AC3:
						cname = "AC3";
						break;
					case AV_CODEC_ID_DTS:
						cname = "DTS";
						break;
					case AV_CODEC_ID_FLAC:
						cname = "FLAC";
						break;
					case AV_CODEC_ID_MP3:
						cname = "MP3";
						break;
					case AV_CODEC_ID_OPUS:
						cname = "Opus";
						break;
					case AV_CODEC_ID_TRUEHD:
						cname = "TrueHD";
						break;
					case AV_CODEC_ID_VORBIS:
						cname = "Vorbis";
						break;
					default:
						cname = codec->long_name ? codec->long_name : codec->name;
				}
				[str_audio appendFormat:@"
Format: %s", cname];
				const char* profile = av_get_profile_name(codec, codecpar->profile);
				if (profile != NULL)
					[str_audio appendFormat:@" [%s]", profile];
				// TODO: find audio bit depth
				//[str_audio appendFormat:@" / %d", (av_get_bytes_per_sample(codecpar->format) << 3)];
				if (codecpar->sample_rate > 0)
					[str_audio appendFormat:@" / %.1f KHz", (float)((float)codecpar->sample_rate / 1000.0f)];
				if (codecpar->bit_rate > 0)
					[str_audio appendFormat:@" / %d Kbps", (int)((float)codecpar->bit_rate / 1000.0f)];
				[str_audio appendString:@"
"];
			}

			// Channels
			NSString* tmp = nil;
			switch (codecpar->channels)
			{
				case 1:
					tmp = @"Mono 1.0";
					break;
				case 2:
					tmp = @"Stereo 2.0";
					break;
				case 3:
					tmp = @"Surround 2.1";
					break;
				case 6:
					tmp = @"Surround 5.1";
					break;
				case 7:
					tmp = @"Surround 6.1";
					break;
				case 8:
					tmp = @"Surround 7.1";
					break;
				default:
					tmp = [NSString stringWithFormat:@"%d", codecpar->channels];
					break;
			}
			[str_audio appendFormat:@"
Channels: %d — %@
", codecpar->channels, tmp];

			tag = av_dict_get(stream->metadata, "title", NULL, 0);
			if (tag != NULL)
				[str_audio appendFormat:@"
Title: %@
", [NSString stringWithUTF8String:tag->value]];

			nb_audio_tracks++;
		}
		else if (AVMEDIA_TYPE_SUBTITLE == codecpar->codec_type) /* Subs stream(s) */
		{
			// Separator if multiple streams
			if (nb_subs_tracks > 0)
				[str_subs appendString:@"
----
"];

			// Language
			tag = av_dict_get(stream->metadata, "language", NULL, 0);
			if (tag != NULL)
				[str_subs appendFormat:@"
Language: %@%s", def ? @"" : @"", tag->value];
			else
				[str_subs appendFormat:@"
Language: %@Undefined", def ? @"" : @""];
			[str_subs appendFormat:@" %@%@
", forced ? @"[Forced]" : @"", def ? @"" : @""];
			// Format
			AVCodec* codec = avcodec_find_decoder(codecpar->codec_id);
			if (codec != NULL)
			{
				const char* cname = NULL;
				switch (codec->id)
				{
					case AV_CODEC_ID_ASS:
						cname = "ASS";
						break;
					case AV_CODEC_ID_SSA:
						cname = "SSA";
						break;
					case AV_CODEC_ID_HDMV_PGS_SUBTITLE:
						cname = "PGS";
						break;
					case AV_CODEC_ID_SRT:
					case AV_CODEC_ID_SUBRIP:
						cname = "SRT";
						break;
					case AV_CODEC_ID_DVD_SUBTITLE:
						cname = "VobSub";
						break;
					case AV_CODEC_ID_MICRODVD:
						cname = "SUB";
						break;
					case AV_CODEC_ID_SAMI:
						cname = "SMI";
						break;
					default:
						cname = codec->long_name ? codec->long_name : codec->name;
				}
				[str_subs appendFormat:@"
Format: %s", cname];
			}
			// Title
			tag = av_dict_get(stream->metadata, "title", NULL, 0);
			if (tag != NULL)
				[str_subs appendFormat:@"
Title: %@
", [NSString stringWithUTF8String:tag->value]];

			nb_subs_tracks++;
		}
	}
	if (nb_video_tracks > 0)
	{
		[str_video appendString:@"
"];
		NSMutableString* header = [[NSMutableString alloc] initWithFormat:@"
🎬 Video%@

", (nb_video_tracks > 1) ? @"s" : @""];
		[str_video insertString:header atIndex:0];
		out_dict[@"video"] = str_video;
	}
	if (nb_audio_tracks > 0)
	{
		[str_audio appendString:@"
"];
		NSMutableString* header = [[NSMutableString alloc] initWithFormat:@"
🔈 Audio%@

", (nb_audio_tracks > 1) ? @"s" : @""];
		[str_audio insertString:header atIndex:0];
		out_dict[@"audio"] = str_audio;
	}
	if (nb_subs_tracks > 0)
	{
		[str_subs appendString:@"
"];
		NSMutableString* header = [[NSMutableString alloc] initWithFormat:@"
📃 Subtitle%@

", (nb_subs_tracks > 1) ? @"s" : @""];
		[str_subs insertString:header atIndex:0];
		out_dict[@"subs"] = str_subs;
	}

	return out_dict;
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="envAwareBean" class="org.springframework.core.env.EnvironmentIntegrationTests$EnvironmentAwareBean"/>

	<import resource="classpath:org/springframework/core/env/EnvironmentIntegrationTests-context-dev.xml"/>
	<import resource="classpath:org/springframework/core/env/EnvironmentIntegrationTests-context-prod.xml"/>

</beans>

redpajama_set_name: RedPajamaGithub


text:
namespace sasm { namespace elf {

int elf::get_class(const sasm::utils::mapped_file& file)
{
  const byte* begin = &file.read<byte>(0);
  return begin[EI_CLASS];
}

int elf::get_dataenc(const sasm::utils::mapped_file& file)
{
  const byte* begin = &file.read<byte>(0);
  return begin[EI_DATA];
}

template<int elf_class> static int do_get_type(const sasm::utils::mapped_file& file)
{
  typedef typename sasm::elf::types<elf_class>::ehdr ehdr_type;
  auto ehdr = file.read<ehdr_type>(0);
  return ehdr.e_type;
}
int elf::get_type(const sasm::utils::mapped_file& file)
{
  int elf_class = get_class(file);

  if (elf_class == ELFCLASS32)
    return do_get_type<ELFCLASS32>(file);
  else if (elf_class == ELFCLASS64)
    return do_get_type<ELFCLASS64>(file);
  else
    throw sasm::exception::elf(file.get_path(), "invalid ELF file");
}

template<int elf_class> static int do_get_machine(const sasm::utils::mapped_file& file)
{
  typedef typename sasm::elf::types<elf_class>::ehdr ehdr_type;
  auto ehdr = file.read<ehdr_type>(0);
  return ehdr.e_machine;
}
int elf::get_machine(const sasm::utils::mapped_file& file)
{
  int elf_class = get_class(file);

  if (elf_class == ELFCLASS32)
    return do_get_machine<ELFCLASS32>(file);
  else if (elf_class == ELFCLASS64)
    return do_get_machine<ELFCLASS64>(file);
  else
    throw sasm::exception::elf(file.get_path(), "invalid ELF file");
}

template<int elf_class> static uint64 do_get_entry(const sasm::utils::mapped_file& file)
{
  typedef typename sasm::elf::types<elf_class>::ehdr ehdr_type;
  auto ehdr = file.read<ehdr_type>(0);
  return ehdr.e_entry;
}
uint64 elf::get_entry(const sasm::utils::mapped_file& file)
{
  int elf_class = get_class(file);

  if (elf_class == ELFCLASS32)
    return do_get_entry<ELFCLASS32>(file);
  else if (elf_class == ELFCLASS64)
    return do_get_entry<ELFCLASS64>(file);
  else
    throw sasm::exception::elf(file.get_path(), "invalid ELF file");
}

}}


text:
+++
Title = "Roberto Cárdenas Isla"
Twitter = ""
image = "r-cardenas.jpg"
type = "speaker"
linktitle = "roberto-isla"
+++

I am a passionate DevOps, always learning and working really hard to improve software development. I love AWS, Azure, Kubernetes, Ansible, Jenkins and any kind of tools that keep me doing continuous knowledge integration to my skills and continuous delivery challenges to my days. I am FAN of skydiving and scubadiving moments, But my number ONE hobby is spending time with my family.


text:
int my_add(int a, int b) {
    return a + b;
}

void no_return() {
}

bool test_function_no_args(sel::State &state) {
    state.Load("../test/test.lua");
    state["foo"]();
    return true;
}

bool test_add(sel::State &state) {
    state.Load("../test/test.lua");
    return state["add"](5, 2) == 7;
}

bool test_multi_return(sel::State &state) {
    state.Load("../test/test.lua");
    int sum, difference;
    sel::tie(sum, difference) = state["sum_and_difference"](3, 1);
    return (sum == 4 && difference == 2);
}

bool test_heterogeneous_return(sel::State &state) {
    state.Load("../test/test.lua");
    int x;
    bool y;
    std::string z;
    sel::tie(x, y, z) = state["bar"]();
    return x == 4 && y == true && z == "hi";
}

bool test_call_field(sel::State &state) {
    state.Load("../test/test.lua");
    int answer = state["mytable"]["foo"]();
    return answer == 4;
}

bool test_call_c_function(sel::State &state) {
    state.Load("../test/test.lua");
    state["cadd"] = std::function<int(int, int)>(my_add);
    int answer = state["cadd"](3, 6);
    return answer == 9;
}

bool test_call_c_fun_from_lua(sel::State &state) {
    state.Load("../test/test.lua");
    state["cadd"] = std::function<int(int, int)>(my_add);
    int answer = state["execute"]();
    return answer == 11;
}

bool test_no_return(sel::State &state) {
    state["no_return"] = &no_return;
    state["no_return"]();
    return true;
}

bool test_call_std_fun(sel::State &state) {
    state.Load("../test/test.lua");
    std::function<int(int, int)> mult = [](int x, int y){ return x * y; };
    state["cmultiply"] = mult;
    int answer = state["cmultiply"](5, 6);
    return answer == 30;
}

bool test_call_lambda(sel::State &state) {
    state.Load("../test/test.lua");
    state["cmultiply"] = [](int x, int y){ return x * y; };
    int answer = state["cmultiply"](5, 6);
    return answer == 30;
}

bool test_call_normal_c_fun(sel::State &state) {
    state.Load("../test/test.lua");
    state["cadd"] = &my_add;
    const int answer = state["cadd"](4, 20);
    return answer == 24;
}

bool test_call_normal_c_fun_many_times(sel::State &state) {
    // Ensures there isn't any strange overflow problem or lingering
    // state
    state.Load("../test/test.lua");
    state["cadd"] = &my_add;
    bool result = true;
    for (int i = 0; i < 25; ++i) {
        const int answer = state["cadd"](4, 20);
        result = result && (answer == 24);
    }
    return result;
}

bool test_call_functor(sel::State &state) {
    struct the_answer {
        int answer = 42;
        int operator()() {
            return answer;
        }
    };
    the_answer functor;
    state.Load("../test/test.lua");
    state["c_the_answer"] = std::function<int()>(functor);
    int answer = state["c_the_answer"]();
    return answer == 42;

}

std::tuple<int, int> my_sum_and_difference(int x, int y) {
    return std::make_tuple(x+y, x-y);
}

bool test_multivalue_c_fun_return(sel::State &state) {
    state.Load("../test/test.lua");
    state["test_fun"] = &my_sum_and_difference;
    int sum, difference;
    sel::tie(sum, difference) = state["test_fun"](-2, 2);
    return sum == 0 && difference == -4;
}

bool test_multivalue_c_fun_from_lua(sel::State &state) {
    state.Load("../test/test.lua");
    state["doozy_c"] = &my_sum_and_difference;
    int answer = state["doozy"](5);
    return answer == -75;
}

bool test_embedded_nulls(sel::State &state) {
    state.Load("../test/test.lua");
    const std::string result = state["embedded_nulls"]();
    return result.size() == 4;
}

bool test_coroutine(sel::State &state) {
    state.Load("../test/test.lua");
    bool check1 = state["resume_co"]() == 1;
    bool check2 = state["resume_co"]() == 2;
    bool check3 = state["resume_co"]() == 3;
    return check1 && check2 && check3;
}

struct Special {
    int foo = 3;
};

static Special special;

Special* return_special_pointer() { return &special; }

bool test_pointer_return(sel::State &state) {
    state["return_special_pointer"] = &return_special_pointer;
    return state["return_special_pointer"]() == &special;
}

Special& return_special_reference() { return special; }

bool test_reference_return(sel::State &state) {
    state["return_special_reference"] = &return_special_reference;
    Special &ref = state["return_special_reference"]();
    return &ref == &special;
}

bool test_nullptr_to_nil(sel::State &state) {
    state["getNullptr"] = []() {
        return nullptr;
    };
    state("x = getNullptr()");
    state("result = x == nil");
    return static_cast<bool>(state["result"]);
}


text:
var forecastApiKey = "71f593a93964af8f";
//function runs weather forecast API, and appends new data info into page
function weatherForecastApi() {
    //AJAX query url
    var weatherForecastURL = "http://api.wunderground.com/api/"+forecastApiKey+"/forecast10day/q/"+latitude+","+longitude+".json";
    //AJAX jquery call
    $.ajax({
        url: weatherForecastURL,
        method: 'GET'
    }).done(function(response){
        //variable points directly to array of relevant weather forecast data
        var data = response.forecast.simpleforecast.forecastday;
        //loops through forecast array data
        for(var i = 0; i < data.length; i++){
            //stores text string of Day
            var day = data[i].date.weekday;
            //stores text string description of day's weather condition(i.e. 'cloudy')
            var conditionsTxt = data[i].conditions;
            //stores high temperature for the day
            var tempHigh = data[i].high.fahrenheit;
            //stores low temperature for the day
            var tempLow = data[i].low.fahrenheit;
            //stores probability of precipitation for the day (%)
            var precipitationProb = data[i].pop;
            //stores the url for the image for that day's weather
            var imgURL = data[i].icon_url;
            //jquery creates new
 element
            var newLi = $('
');
            //jquery creates new img element with responsive class attribute (materialize) and src attribute with img url
            var imgElement = ('');
            // jquery stores h3 and h4 title elements for the day and conditon
            var dayTitle = $('
'+day+'

'+conditionsTxt+'
')
            //stores h5 title elemtns of weather data
            var weatherInfo = ('
Temperature (F)
 '+tempHigh+'/'+tempLow+'
Chance of Rain (%)
'+precipitationProb);
            //appends
 element in #weatherForecast location, at ul element
            var newChildLi = $('#weatherForecast').append(newLi);
            //appends title, img, weather info under
 element
            newLi.append(dayTitle);
            newLi.append(imgElement);
            newLi.append(weatherInfo);
        }
    });
};


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="@dimen/widget_margin"
             android:background="@drawable/touch_selector_white"
             android:theme="@style/AppTheme">
    <LinearLayout android:id="@+id/widget"
                  android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:padding="@dimen/abc_control_inset_material"
                  android:background="@color/primary">

        <ImageView
            android:id="@+id/widget_icon"
            android:layout_width="48dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            tools:src="@drawable/art_clear"/>

        <TextView
            android:id="@+id/widget_high_temperature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textAppearance="@style/TextAppearance.AppCompat.Title.Inverse"
            tools:text="27°"/>
    </LinearLayout>
</FrameLayout>


text:
package json

import (
	j "encoding/json"
	"io"
	"os"
	"sync"

	"github.com/apex/log"
)

// Default handler outputting to stderr.
var Default = New(os.Stderr)

// Handler implementation.
type Handler struct {
	*j.Encoder
	mu sync.Mutex
}

// New handler.
func New(w io.Writer) *Handler {
	return &Handler{
		Encoder: j.NewEncoder(w),
	}
}

// HandleLog implements log.Handler.
func (h *Handler) HandleLog(e *log.Entry) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	return h.Encoder.Encode(e)
}


text:
{% extends "theme_base.html" %}

{% load i18n %}
{% load ifsetting_tag %}
{% load bootstrap_tags %}

{% block head_title %}{% trans "Update" %} {{object}}{% endblock %}

{% block body_class %}{{form.instance.options.verbose_name}}{% endblock %}

{% block body %}

{% trans "Update" %} {{object}}

        <form action="{{form.instance.get_update_url}}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{form|as_bootstrap}}

                <button type="submit" class="btn btn-primary">Update</button>

        </form>

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace Fort.Aggregator
{
    ///<summary>
    /// Defines a base class to publish and subscribe to events.
    ///</summary>
    public abstract class EventBase
    {
        private readonly List<IEventSubscription> _subscriptions = new List<IEventSubscription>();

        /// <summary>
        /// Allows the SynchronizationContext to be set by the EventAggregator for UI Thread Dispatching
        /// </summary>
        public SynchronizationContext SynchronizationContext { get; set; }

        /// <summary>
        /// Gets the list of current subscriptions.
        /// </summary>
        /// <value>The current subscribers.</value>
        protected ICollection<IEventSubscription> Subscriptions
        {
            get { return _subscriptions; }
        }

        /// <summary>
        /// Adds the specified <see cref="IEventSubscription"/> to the subscribers' collection.
        /// </summary>
        /// <param name="eventSubscription">The subscriber.</param>
        /// <returns>The <see cref="SubscriptionToken"/> that uniquely identifies every subscriber.</returns>
        /// <remarks>
        /// Adds the subscription to the internal list and assigns it a new <see cref="SubscriptionToken"/>.
        /// </remarks>
        protected virtual SubscriptionToken InternalSubscribe(IEventSubscription eventSubscription)
        {
            if (eventSubscription == null) throw new ArgumentNullException("eventSubscription");

            eventSubscription.SubscriptionToken = new SubscriptionToken(Unsubscribe);

            lock (Subscriptions)
            {
                Subscriptions.Add(eventSubscription);
            }
            return eventSubscription.SubscriptionToken;
        }

        /// <summary>
        /// Calls all the execution strategies exposed by the list of <see cref="IEventSubscription"/>.
        /// </summary>
        /// <param name="arguments">The arguments that will be passed to the listeners.</param>
        /// <remarks>Before executing the strategies, this class will prune all the subscribers from the
        /// list that return a <see langword="null" /> <see cref="Action{T}"/> when calling the
        /// <see cref="IEventSubscription.GetExecutionStrategy"/> method.</remarks>
        protected virtual void InternalPublish(params object[] arguments)
        {
            List<Action<object[]>> executionStrategies = PruneAndReturnStrategies();
            foreach (var executionStrategy in executionStrategies)
            {
                executionStrategy(arguments);
            }
        }

        /// <summary>
        /// Removes the subscriber matching the <see cref="SubscriptionToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SubscriptionToken"/> returned by <see cref="EventBase"/> while subscribing to the event.</param>
        public virtual void Unsubscribe(SubscriptionToken token)
        {
            lock (Subscriptions)
            {
                IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);
                if (subscription != null)
                {
                    Subscriptions.Remove(subscription);
                }
            }
        }

        /// <summary>
        /// Returns <see langword="true"/> if there is a subscriber matching <see cref="SubscriptionToken"/>.
        /// </summary>
        /// <param name="token">The <see cref="SubscriptionToken"/> returned by <see cref="EventBase"/> while subscribing to the event.</param>
        /// <returns><see langword="true"/> if there is a <see cref="SubscriptionToken"/> that matches; otherwise <see langword="false"/>.</returns>
        public virtual bool Contains(SubscriptionToken token)
        {
            lock (Subscriptions)
            {
                IEventSubscription subscription = Subscriptions.FirstOrDefault(evt => evt.SubscriptionToken == token);
                return subscription != null;
            }
        }

        private List<Action<object[]>> PruneAndReturnStrategies()
        {
            List<Action<object[]>> returnList = new List<Action<object[]>>();

            lock (Subscriptions)
            {
                for (var i = Subscriptions.Count - 1; i >= 0; i--)
                {
                    Action<object[]> listItem =
                        _subscriptions[i].GetExecutionStrategy();

                    if (listItem == null)
                    {
                        // Prune from main list. Log?
                        _subscriptions.RemoveAt(i);
                    }
                    else
                    {
                        returnList.Add(listItem);
                    }
                }
            }

            return returnList;
        }
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/install-llvm-dis"
)

# Per-language clean rules from dependency scanning.
foreach(lang )
  include(CMakeFiles/install-llvm-dis.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ page.title }} - MPI</title>
    <link rel="stylesheet" href="/lib/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/main.css">

    <link rel="apple-touch-icon" sizes="57x57" href="/media/favicon/57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/media/favicon/60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/media/favicon/72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/media/favicon/76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/media/favicon/114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/media/favicon/120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/media/favicon/144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/media/favicon/152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/media/favicon/180x180.png">
    <link rel="icon" type="image/png" sizes="32x32"   href="/media/favicon/32x32.png">
    <link rel="icon" type="image/png" sizes="194x194" href="/media/favicon/194x194.png">
    <link rel="icon" type="image/png" sizes="96x96"   href="/media/favicon/96x96.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/media/favicon/192x192.png">
    <link rel="icon" type="image/png" sizes="16x16"   href="/media/favicon/16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/media/favicon/144x144.png">
    <meta name="theme-color" content="#ffffff">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Menu

          </button>

               Why Minetest?

               Assets

               Showcase


text:
title: Pig Latin
localeTitle: Porco Latino
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 "triangular_flag_on_post:") Lembre-se de usar **`Read-Search-Ask`** se você ficar preso. Tente emparelhar o programa ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ": busts_in_silhouette:") e escreva seu próprio código ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":lápis:")

### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ": checkered_flag:") Explicação do Problema:

Você precisa criar um programa que irá traduzir do inglês para o Pig Latin. Pig Latin pega a primeira consoante (ou consoante cluster) de uma palavra inglesa, move-a para o final da palavra e sufixa um "ay". Se uma palavra começa com uma vogal, você apenas adiciona "caminho" ao final. Pode não ser óbvio, mas você precisa remover todas as consoantes até a primeira vogal, caso a palavra não comece com uma vogal.

#### Links Relevantes

*   [Porco Latino](http://en.wikipedia.org/wiki/Pig_Latin)
*   [Correspondência de Protótipo de Cadeia JS](http://forum.freecodecamp.com/t/javascript-string-prototype-match/15941)

## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Sugestão: 1

Você provavelmente desejará usar expressões regulares. Isso permitirá que você converta as palavras facilmente.

> _tente resolver o problema agora_

## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Dica: 2

Se o primeiro caractere é uma vogal, então pegue a palavra inteira e adicione 'way' no final. Caso contrário, vem a parte complicada, pegue a (s) consoante (s) antes da primeira vogal e mova-a para o final e adicione 'ay'. Isso pode ser confuso, mas não é apenas a primeira consoante, mas todas antes da primeira vogal.

> _tente resolver o problema agora_

## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Dica: 3

Você precisará usar tudo o que sabe sobre a manipulação de strings para obter a última parte correta. No entanto, isso pode ser feito apenas com `substr` .

> _tente resolver o problema agora_

## Alerta de Spoiler!

![sinal de aviso](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)

**Solução à frente!**

## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":principiante:") Solução básica de código:
```
function translatePigLatin(str) {
  // Create variables to be used
  var pigLatin = '';
  var regex = /[aeiou]/gi;

  // Check if the first character is a vowel
  if (str[0].match(regex)) {
    pigLatin = str + 'way';

  } else if(str.match(regex) === null) {
    // Check if the string contains only consonants
    pigLatin = str + 'ay';
  } else {

    // Find how many consonants before the first vowel.
    var vowelIndice = str.indexOf(str.match(regex)[0]);

    // Take the string from the first vowel to the last char
    // then add the consonants that were previously omitted and add the ending.
    pigLatin = str.substr(vowelIndice) + str.substr(0, vowelIndice) + 'ay';
  }

  return pigLatin;
 }

 // test here
 translatePigLatin("consonant");
```

![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":foguete:") [Executar código](https://repl.it/CLmt/0)

### Explicação do código:

*   Faça uma corda vazia para segurar sua palavra latina.
*   Atribua sua expressão regular apropriada a uma variável.
*   Se o primeiro caractere for uma vogal, apenas adicione o **caminho** ao final da string e retorne-o.
*   Se o primeiro caractere não for uma vogal:
    *   Encontre o número de consoantes antes da primeira vogal com a ajuda de `indexOf()` , `match()` e regex.
    *   Comece a corda Latin do porco com primeira vogal até o fim.
    *   Adicione letras antes da primeira vogal ao final da string.
    *   `substr()` é usado para manipulação de string aqui.
    *   Adicione **ai** ao final da string e retorne-a.

#### Links Relevantes

*   Recursos JS Regex
*   [Índice de Protótipo de Cadeia JS](http://forum.freecodecamp.com/t/javascript-string-prototype-indexof/15936)
*   [JS String Prototype Substr](http://forum.freecodecamp.com/t/javascript-string-prototype-substr/15945)

## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":girassol:") Solução de Código Intermediário:
```
function translatePigLatin(str) {
  function check(obj) {
      return ['a','i','u','e','o'].indexOf(str.charAt(obj)) == -1 ? check(obj + 1) : obj;
  }

  return str.substr(check(0)).concat((check(0) === 0 ? 'w' : str.substr(0, check(0))) + 'ay');
 }

 // test here
 translatePigLatin("consonant");
```

![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":foguete:") [Executar código](https://repl.it/CLmw/0)

### Explicação do código:

*   Esta é uma abordagem declarativa e recursiva para este problema.
*   `check()` é uma função que verifica se a primeira letra da string está na matriz de vogais, `['a','i','u','e','o']` .
*   No caso de consoantes, `check()` chama-se nos próximos caracteres até encontrar a primeira vogal.
*   Ele retornará o índice de tudo o que encontrar para ser a última consoante inicial, isto é, a de Schmidtsville seria 3.
*   Em seguida, as cartas, até que o índice são removidos a partir da cadeia e concatenado com qualquer um que mesmo pedaço de corda removido ou **w** em conformidade, e, em seguida, **ay** independentemente.

#### Links Relevantes

*   [Caráter Protótipo de Cadeia JS](http://forum.freecodecamp.com/t/javascript-string-prototype-charat/15932)
*   [Concat de Protótipo de Cadeia JS](http://forum.freecodecamp.com/t/javascript-string-prototype-concat/15935)

## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ": rotating_light:") Solução avançada de código:
```
function translatePigLatin(str) {
    var strArr = [];
    var tmpChar;

    // check if the char is consonant using RegEx
    function isConsonant(char) {
        return !/[aeiou]/.test(char);
    }

    // return initial str + "way" if it starts with vowel
    // if not - convert str to array
    if (!isConsonant(str.charAt(0)))
        return str + "way";
    else
        strArr = str.split("");

    // push all consonats to the end of the array
    while (isConsonant(strArr[0])) {
        tmpChar = strArr.shift();
        strArr.push(tmpChar);
    }
 // convert array to string and concatenate "ay" at the end
 return strArr.join("")+"ay";
 }

 // test here
 translatePigLatin("consonant");
```

![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":foguete:") [Executar código](https://repl.it/CLmv/0)

### Explicação do código:

*   `isConsonant()` é usado para verificar se um caractere é uma consoante.
*   Se o primeiro caractere for vogal, adicione o **caminho** ao final da string e retorne-o.
*   Se o primeiro caractere não for uma vogal:
    *   Dividir string em array usando `split()` .
    *   Empurre todas as consoantes para o final do array com ajuda de `shift()` e `push()` .
    *   Converta array para string usando `join()` e adicione **ay** ao final da string. Devolver.

#### Links Relevantes

*   [Divisão de Protótipo de Cadeia JS](http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944)
*   [Mudança de Protótipo de Matriz JS](http://forum.freecodecamp.com/t/javascript-array-prototype-shift/14301)
*   [Push de protótipo de matriz JS](http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298)
*   [Junção de protótipo de matriz JS](http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292)

### ![:trophy:](https://forum.freecodecamp.com/images/emoji/emoji_one/trophy.png?v=3 ":troféu:") Créditos:

Se achou útil esta página, pode agradecer aos colaboradores copiando e colando a seguinte linha no chat principal:

**`Thanks @Rafase282 @sabahang @aganita @Hallaathrad for your help with Algorithm: Pig Latin`**

## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":prancheta:") NOTAS PARA CONTRIBUIÇÕES:

*   ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":Aviso:") **NÃO** adicione soluções semelhantes às soluções existentes. Se você acha que é **_semelhante, mas melhor_** , tente mesclar (ou substituir) a solução semelhante existente.
*   Adicione uma explicação da sua solução.
*   Categorize a solução em uma das seguintes categorias - **Básica** , **Intermediária** e **Avançada** . ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":semáforo:")
*   Por favor, adicione seu nome de usuário somente se você adicionou qualquer **conteúdo principal relevante** . ( ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":Aviso:") **_NÃO_** _remova nenhum nome de usuário existente_ )

> Vejo ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ": point_right:") [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) para referência.


text:
export default {
  configuredExpenseRates(specification) {
    return Object.keys(specification.configuredExpenseRates).map((name, key) => ({
      name,
      key,
      ...(specification.configuredExpenseRates[name]),
    }));
  },
};


text:
FOUNDATION_EXPORT double BeanVersionNumber;
FOUNDATION_EXPORT const unsigned char BeanVersionString[];


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;

using Internal.TypeSystem;
using ILCompiler.DependencyAnalysis;

using Debug = System.Diagnostics.Debug;

namespace ILCompiler
{
    class EmptyMetadataManager : MetadataManager
    {
        public EmptyMetadataManager(CompilationModuleGroup group, CompilerTypeSystemContext typeSystemContext) : base(group, typeSystemContext)
        {
        }

        public override IEnumerable<ModuleDesc> GetCompilationModulesWithMetadata()
        {
            return Array.Empty<ModuleDesc>();
        }

        public override bool IsReflectionBlocked(MetadataType type)
        {
            return true;
        }

        protected override void ComputeMetadata(NodeFactory factory, out byte[] metadataBlob, out List<MetadataMapping<MetadataType>> typeMappings, out List<MetadataMapping<MethodDesc>> methodMappings, out List<MetadataMapping<FieldDesc>> fieldMappings)
        {
            metadataBlob = Array.Empty<byte>();

            typeMappings = new List<MetadataMapping<MetadataType>>();
            methodMappings = new List<MetadataMapping<MethodDesc>>();
            fieldMappings = new List<MetadataMapping<FieldDesc>>();
        }

        /// <summary>
        /// Is there a reflection invoke stub for a method that is invokable?
        /// </summary>
        public override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method)
        {
            Debug.Assert(IsReflectionInvokable(method));
            return false;
        }

        /// <summary>
        /// Gets a stub that can be used to reflection-invoke a method with a given signature.
        /// </summary>
        public override MethodDesc GetCanonicalReflectionInvokeStub(MethodDesc method)
        {
            return null;
        }

        public override bool WillUseMetadataTokenToReferenceMethod(MethodDesc method)
        {
            return false;
        }

        public override bool WillUseMetadataTokenToReferenceField(FieldDesc field)
        {
            return false;
        }
    }
}


text:
namespace blink {

class Document;

class CORE_EXPORT SuboriginPolicy {
public:
    static void logSuboriginHeaderError(Document&, const String& message);
    static String parseSuboriginName(Document&, const String& header);
};

} // namespace blink

#endif // Suborigin_h


text:
Running CVE-2017-8759 exploit sample.

Flow of the exploit:

Word macro runs in the Doc1.doc file. The macro downloads a badly formatted txt file over wsdl, which triggers the WSDL parser log. Then the parsing log results in running mshta.exe which in turn runs a powershell commands that runs mspaint.exe

To test:

Run a webserver on port 8080, and put the files exploit.txt and cmd.hta on its root. For example python3 -m http.server -127.0.0.1 8080
Or you can use python3 server.py

If all is good mspaint should run.

Mohammed Aldoub @Voulnet

## References:

https://www.fireeye.com/blog/threat-research/2017/09/zero-day-used-to-distribute-finspy.html


text:
<!DOCTYPE HTML>

		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta charset="utf-8">

		<title>Button - sap.ui.commons</title>
		<link rel="shortcut icon" type="image/x-icon" href="images/controls/sap.ui.commons.Button.gif">

Test Page for sap.ui.commons.Button

		Width test:

		lite buttons:

		unstyled buttons:

		lite button with icon only:

		buttons with icon font:


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<AutoSaveDataInSettings>Use</AutoSaveDataInSettings>
	<SaveDataInSettings>UseList</SaveDataInSettings>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<Autofill>false</Autofill>
	</AutoCommandBar>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
		<Event name="BeforeLoadDataFromSettingsAtServer">ПередЗагрузкойДанныхИзНастроекНаСервере</Event>
	</Events>
	<ChildItems>
		<InputField name="ОрганизацияОтбор" id="34">
			<DataPath>Организация</DataPath>
			<Width>30</Width>
			<HorizontalStretch>false</HorizontalStretch>
			<Wrap>false</Wrap>
			<ContextMenu name="ОрганизацияОтборКонтекстноеМеню" id="35"/>
			<ExtendedTooltip name="ОрганизацияОтборExtendedTooltip" id="46"/>
			<Events>
				<Event name="OnChange">ОрганизацияОтборПриИзменении</Event>
			</Events>
		</InputField>
		<UsualGroup name="ГруппаГоризонтальная" id="33">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа горизонтальная</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Группа горизонтальная</v8:content>
				</v8:item>
			</ToolTip>
			<Group>Horizontal</Group>
			<Representation>None</Representation>
			<ShowTitle>false</ShowTitle>
			<ExtendedTooltip name="ГруппаГоризонтальнаяExtendedTooltip" id="47"/>
			<ChildItems>

					<TitleLocation>Top</TitleLocation>
					<UseAlternationRowColor>true</UseAlternationRowColor>
					<EnableStartDrag>true</EnableStartDrag>
					<EnableDrag>true</EnableDrag>
					<DataPath>СписокРегистрации</DataPath>
					<RowPictureDataPath>СписокРегистрации.DefaultPicture</RowPictureDataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Регистрация в налоговых органах</v8:content>
						</v8:item>
					</Title>
					<TitleFont ref="sys:DefaultGUIFont" kind="WindowsFont"/>
					<SearchStringLocation>None</SearchStringLocation>
					<ViewStatusLocation>None</ViewStatusLocation>
					<SearchControlLocation>None</SearchControlLocation>
					<AutoRefresh>false</AutoRefresh>
					<AutoRefreshPeriod>60</AutoRefreshPeriod>
					<Period xsi:type="v8:StandardPeriod">
						<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
						<v8:startDate>0001-01-01T00:00:00</v8:startDate>
						<v8:endDate>0001-01-01T00:00:00</v8:endDate>
					</Period>
					<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
					<RestoreCurrentRow>false</RestoreCurrentRow>
					<TopLevelParent xsi:nil="true"/>
					<ShowRoot>true</ShowRoot>
					<AllowRootChoice>false</AllowRootChoice>
					<UpdateOnDataChange>Auto</UpdateOnDataChange>
					<ContextMenu name="СписокРегистрацииКонтекстноеМеню" id="2">
						<ChildItems>
							<Button name="СписокРегистрацииКонтекстноеМенюНазначитьОсновнуюРегистрациюОрганизации" id="41">
								<Type>CommandBarButton</Type>
								<CommandName>Form.Command.НазначитьОсновнуюРегистрациюОрганизации</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокРегистрацииКонтекстноеМенюНазначитьОсновнуюРегистрациюОрганизацииExtendedTooltip" id="48"/>
							</Button>
						</ChildItems>
					</ContextMenu>
					<AutoCommandBar name="СписокРегистрацииКоманднаяПанель" id="3">
						<ChildItems>
							<Button name="СписокРегистрацииНазначитьОсновнуюРегистрациюОрганизации" id="40">
								<Type>CommandBarButton</Type>
								<CommandName>Form.Command.НазначитьОсновнуюРегистрациюОрганизации</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокРегистрацииНазначитьОсновнуюРегистрациюОрганизацииExtendedTooltip" id="49"/>
							</Button>
							<Button name="СписокРегистрацииКнопкаИзменитьФорму" id="42">
								<Type>CommandBarButton</Type>
								<OnlyInAllActions>false</OnlyInAllActions>
								<CommandName>Form.StandardCommand.CustomizeForm</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокРегистрацииКнопкаИзменитьФормуExtendedTooltip" id="50"/>
							</Button>
						</ChildItems>
					</AutoCommandBar>
					<ExtendedTooltip name="СписокРегистрацииExtendedTooltip" id="51"/>
					<SearchStringAddition name="СписокРегистрацииSearchString" id="52">
						<Source>
							<lf:elementId>1</lf:elementId>
							<lf:additionId>0</lf:additionId>
						</Source>
						<ContextMenu name="СписокРегистрацииSearchStringContextMenu" id="53"/>
						<ExtendedTooltip name="СписокРегистрацииSearchStringExtendedTooltip" id="54"/>
					</SearchStringAddition>
					<ViewStatusAddition name="СписокРегистрацииViewStatus" id="55">
						<Source>
							<lf:elementId>1</lf:elementId>
							<lf:additionId>1</lf:additionId>
						</Source>
						<ContextMenu name="СписокРегистрацииViewStatusContextMenu" id="56"/>
						<ExtendedTooltip name="СписокРегистрацииViewStatusExtendedTooltip" id="57"/>
					</ViewStatusAddition>
					<SearchControlAddition name="СписокРегистрацииSearchControl" id="58">
						<Source>
							<lf:elementId>1</lf:elementId>
							<lf:additionId>2</lf:additionId>
						</Source>
						<ContextMenu name="СписокРегистрацииSearchControlContextMenu" id="59"/>
						<ExtendedTooltip name="СписокРегистрацииSearchControlExtendedTooltip" id="60"/>
					</SearchControlAddition>
					<Events>
						<Event name="DragCheck">СписокРегистрацииПроверкаПеретаскивания</Event>
						<Event name="OnActivateRow">СписокРегистрацииПриАктивизацииСтроки</Event>
						<Event name="Drag">СписокРегистрацииПеретаскивание</Event>
					</Events>
					<ChildItems>
						<LabelField name="СписокРегистрацииНаименование" id="4">
							<DataPath>СписокРегистрации.Description</DataPath>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Налоговый орган</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="СписокРегистрацииНаименованиеКонтекстноеМеню" id="5"/>
							<ExtendedTooltip name="СписокРегистрацииНаименованиеExtendedTooltip" id="61"/>
						</LabelField>
						<LabelField name="СписокРегистрацииНаименованиеИФНС" id="14">
							<DataPath>СписокРегистрации.НаименованиеИФНС</DataPath>
							<UserVisible>
								<xr:Common>false</xr:Common>
							</UserVisible>
							<ContextMenu name="СписокРегистрацииНаименованиеИФНСКонтекстноеМеню" id="15"/>
							<ExtendedTooltip name="СписокРегистрацииНаименованиеИФНСExtendedTooltip" id="62"/>
						</LabelField>
						<LabelField name="СписокРегистрацииНаименованиеОбособленногоПодразделения" id="16">
							<DataPath>СписокРегистрации.НаименованиеОбособленногоПодразделения</DataPath>
							<UserVisible>
								<xr:Common>false</xr:Common>
							</UserVisible>
							<ContextMenu name="СписокРегистрацииНаименованиеОбособленногоПодразделенияКонтекстноеМеню" id="17"/>
							<ExtendedTooltip name="СписокРегистрацииНаименованиеОбособленногоПодразделенияExtendedTooltip" id="63"/>
						</LabelField>
						<LabelField name="СписокРегистрацииКПП" id="12">
							<DataPath>СписокРегистрации.КПП</DataPath>
							<UserVisible>
								<xr:Common>false</xr:Common>
							</UserVisible>
							<ContextMenu name="СписокРегистрацииКППКонтекстноеМеню" id="13"/>
							<ExtendedTooltip name="СписокРегистрацииКППExtendedTooltip" id="64"/>
						</LabelField>
						<LabelField name="СписокРегистрацииЦифровойИндексОбособленногоПодразделения" id="18">
							<DataPath>СписокРегистрации.ЦифровойИндексОбособленногоПодразделения</DataPath>
							<UserVisible>
								<xr:Common>false</xr:Common>
							</UserVisible>
							<ContextMenu name="СписокРегистрацииЦифровойИндексОбособленногоПодразделенияКонтекстноеМеню" id="19"/>
							<ExtendedTooltip name="СписокРегистрацииЦифровойИндексОбособленногоПодразделенияExtendedTooltip" id="65"/>
						</LabelField>
						<LabelField name="СписокРегистрацииКоличествоПодразделений" id="10">
							<DataPath>СписокРегистрации.КоличествоПодразделений</DataPath>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Подразделения</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="СписокРегистрацииКоличествоПодразделенийКонтекстноеМеню" id="11"/>
							<ExtendedTooltip name="СписокРегистрацииКоличествоПодразделенийExtendedTooltip" id="66"/>
						</LabelField>
					</ChildItems>

					<Representation>Tree</Representation>
					<TitleLocation>Top</TitleLocation>
					<UseAlternationRowColor>true</UseAlternationRowColor>
					<InitialTreeView>ExpandAllLevels</InitialTreeView>
					<EnableStartDrag>true</EnableStartDrag>
					<EnableDrag>true</EnableDrag>
					<DataPath>СписокПодразделения</DataPath>
					<RowPictureDataPath>СписокПодразделения.DefaultPicture</RowPictureDataPath>
					<Title>
						<v8:item>
							<v8:lang>ru</v8:lang>
							<v8:content>Структура предприятия</v8:content>
						</v8:item>
					</Title>
					<TitleFont ref="sys:DefaultGUIFont" kind="WindowsFont"/>
					<SearchStringLocation>None</SearchStringLocation>
					<ViewStatusLocation>None</ViewStatusLocation>
					<SearchControlLocation>None</SearchControlLocation>
					<AutoRefresh>false</AutoRefresh>
					<AutoRefreshPeriod>60</AutoRefreshPeriod>
					<Period xsi:type="v8:StandardPeriod">
						<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
						<v8:startDate>0001-01-01T00:00:00</v8:startDate>
						<v8:endDate>0001-01-01T00:00:00</v8:endDate>
					</Period>
					<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
					<RestoreCurrentRow>false</RestoreCurrentRow>
					<TopLevelParent xsi:nil="true"/>
					<ShowRoot>true</ShowRoot>
					<AllowRootChoice>false</AllowRootChoice>
					<UpdateOnDataChange>Auto</UpdateOnDataChange>
					<ContextMenu name="СписокПодразделенияКонтекстноеМеню" id="23">
						<ChildItems>
							<Button name="СписокПодразделенияКонтекстноеМенюНазначитьРегистрациюПодразделения" id="44">
								<Type>CommandBarButton</Type>
								<CommandName>Form.Command.НазначитьРегистрациюПодразделения</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокПодразделенияКонтекстноеМенюНазначитьРегистрациюПодразделенияExtendedTooltip" id="67"/>
							</Button>
							<Button name="СписокПодразделенияКонтекстноеМенюОтменитьРегистрациюПодразделения" id="45">
								<Type>CommandBarButton</Type>
								<CommandName>Form.Command.ОтменитьРегистрациюПодразделения</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокПодразделенияКонтекстноеМенюОтменитьРегистрациюПодразделенияExtendedTooltip" id="68"/>
							</Button>
						</ChildItems>
					</ContextMenu>
					<AutoCommandBar name="СписокПодразделенияКоманднаяПанель" id="24">
						<ChildItems>
							<Button name="СписокПодразделенияКнопкаИзменитьФорму" id="43">
								<Type>CommandBarButton</Type>
								<OnlyInAllActions>false</OnlyInAllActions>
								<CommandName>Form.StandardCommand.CustomizeForm</CommandName>
								<Parameter xsi:nil="true"/>
								<ExtendedTooltip name="СписокПодразделенияКнопкаИзменитьФормуExtendedTooltip" id="69"/>
							</Button>
						</ChildItems>
					</AutoCommandBar>
					<ExtendedTooltip name="СписокПодразделенияExtendedTooltip" id="70"/>
					<SearchStringAddition name="СписокПодразделенияSearchString" id="71">
						<Source>
							<lf:elementId>22</lf:elementId>
							<lf:additionId>0</lf:additionId>
						</Source>
						<ContextMenu name="СписокПодразделенияSearchStringContextMenu" id="72"/>
						<ExtendedTooltip name="СписокПодразделенияSearchStringExtendedTooltip" id="73"/>
					</SearchStringAddition>
					<ViewStatusAddition name="СписокПодразделенияViewStatus" id="74">
						<Source>
							<lf:elementId>22</lf:elementId>
							<lf:additionId>1</lf:additionId>
						</Source>
						<ContextMenu name="СписокПодразделенияViewStatusContextMenu" id="75"/>
						<ExtendedTooltip name="СписокПодразделенияViewStatusExtendedTooltip" id="76"/>
					</ViewStatusAddition>
					<SearchControlAddition name="СписокПодразделенияSearchControl" id="77">
						<Source>
							<lf:elementId>22</lf:elementId>
							<lf:additionId>2</lf:additionId>
						</Source>
						<ContextMenu name="СписокПодразделенияSearchControlContextMenu" id="78"/>
						<ExtendedTooltip name="СписокПодразделенияSearchControlExtendedTooltip" id="79"/>
					</SearchControlAddition>
					<Events>
						<Event name="Drag">СписокПодразделенияПеретаскивание</Event>
					</Events>
					<ChildItems>
						<LabelField name="СписокПодразделенияНаименование" id="25">
							<DataPath>СписокПодразделения.Description</DataPath>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Подразделение</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="СписокПодразделенияНаименованиеКонтекстноеМеню" id="26"/>
							<ExtendedTooltip name="СписокПодразделенияНаименованиеExtendedTooltip" id="80"/>
						</LabelField>
						<LabelField name="СписокПодразделенияКод" id="27">
							<DataPath>СписокПодразделения.Code</DataPath>
							<UserVisible>
								<xr:Common>false</xr:Common>
							</UserVisible>
							<ContextMenu name="СписокПодразделенияКодКонтекстноеМеню" id="28"/>
							<ExtendedTooltip name="СписокПодразделенияКодExtendedTooltip" id="81"/>
						</LabelField>
						<LabelField name="СписокПодразделенияРегистрацияВНалоговомОрганеНаименование" id="38">
							<DataPath>СписокПодразделения.РегистрацияВНалоговомОрганеDescription</DataPath>
							<Title>
								<v8:item>
									<v8:lang>ru</v8:lang>
									<v8:content>Налоговый орган</v8:content>
								</v8:item>
							</Title>
							<ContextMenu name="СписокПодразделенияРегистрацияВНалоговомОрганеНаименованиеКонтекстноеМеню" id="39"/>
							<ExtendedTooltip name="СписокПодразделенияРегистрацияВНалоговомОрганеНаименованиеExtendedTooltip" id="82"/>
						</LabelField>
					</ChildItems>

			</ChildItems>
		</UsualGroup>
	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<Settings xsi:type="DynamicList">
				<ManualQuery>false</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<MainTable>InformationRegister.РегистрацииВНалоговомОргане</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="СписокРегистрации" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Список регистрации</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<UseAlways>
				<Field>СписокРегистрации.Description</Field>
				<Field>СписокРегистрации.Owner</Field>
				<Field>СписокРегистрации.Ref</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>true</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<QueryText>ВЫБРАТЬ
	СправочникРегистрацииВНалоговомОргане.Ссылка,
	СправочникРегистрацииВНалоговомОргане.Владелец,
	СправочникРегистрацииВНалоговомОргане.Наименование,
	СправочникРегистрацииВНалоговомОргане.НаименованиеИФНС,
	СправочникРегистрацииВНалоговомОргане.КПП,
	СправочникРегистрацииВНалоговомОргане.НаименованиеОбособленногоПодразделения,
	СправочникРегистрацииВНалоговомОргане.ЦифровойИндексОбособленногоПодразделения,
	КОЛИЧЕСТВО(РАЗЛИЧНЫЕ РегистрРегистрацииВНалоговомОргане.Подразделение) КАК КоличествоПодразделений
ИЗ
	Справочник.РегистрацииВНалоговомОргане КАК СправочникРегистрацииВНалоговомОргане
		ЛЕВОЕ СОЕДИНЕНИЕ РегистрСведений.РегистрацииВНалоговомОргане КАК РегистрРегистрацииВНалоговомОргане
		ПО СправочникРегистрацииВНалоговомОргане.Ссылка = РегистрРегистрацииВНалоговомОргане.РегистрацияВНалоговомОргане

СГРУППИРОВАТЬ ПО
	СправочникРегистрацииВНалоговомОргане.Владелец,
	СправочникРегистрацииВНалоговомОргане.Наименование,
	СправочникРегистрацииВНалоговомОргане.НаименованиеИФНС,
	СправочникРегистрацииВНалоговомОргане.КПП,
	СправочникРегистрацииВНалоговомОргане.НаименованиеОбособленногоПодразделения,
	СправочникРегистрацииВНалоговомОргане.ЦифровойИндексОбособленногоПодразделения,
	СправочникРегистрацииВНалоговомОргане.Ссылка</QueryText>
				<MainTable>Catalog.РегистрацииВНалоговомОргане</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="СписокПодразделения" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Список подразделения</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<UseAlways>
				<Field>СписокПодразделения.РегистрацияВНалоговомОргане</Field>
				<Field>СписокПодразделения.РегистрацияВНалоговомОрганеDescription</Field>
				<Field>СписокПодразделения.Организация</Field>
				<Field>СписокПодразделения.Ref</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>true</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<QueryText>ВЫБРАТЬ
	СправочникСтруктураПредприятия.Ссылка,
	СправочникСтруктураПредприятия.ВерсияДанных,
	СправочникСтруктураПредприятия.ПометкаУдаления,
	СправочникСтруктураПредприятия.Предопределенный,
	СправочникСтруктураПредприятия.Родитель,
	СправочникСтруктураПредприятия.Код,
	СправочникСтруктураПредприятия.Наименование,
	СправочникСтруктураПредприятия.ТекущийРуководитель,
	СправочникСтруктураПредприятия.ВариантОбособленногоУчетаТоваров,
	РегистрРегистрацииВНалоговомОргане.Организация,
	РегистрРегистрацииВНалоговомОргане.РегистрацияВНалоговомОргане,
	РегистрРегистрацииВНалоговомОргане.РегистрацияВНалоговомОргане.Наименование
ИЗ
	Справочник.СтруктураПредприятия КАК СправочникСтруктураПредприятия
		ЛЕВОЕ СОЕДИНЕНИЕ РегистрСведений.РегистрацииВНалоговомОргане КАК РегистрРегистрацииВНалоговомОргане
		ПО СправочникСтруктураПредприятия.Ссылка = РегистрРегистрацииВНалоговомОргане.Подразделение
			И (РегистрРегистрацииВНалоговомОргане.Организация = &Организация)</QueryText>
				<MainTable>Catalog.СтруктураПредприятия</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
		<Attribute name="Организация" id="4">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Организация</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:CatalogRef.Организации</v8:Type>
			</Type>
			<Save>
				<Field>Организация</Field>
			</Save>
		</Attribute>
		<Attribute name="ТекущаяСтрокаРегистрации" id="5">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Текущая строка регистрации</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:CatalogRef.РегистрацииВНалоговомОргане</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="ОсновнаяРегистрацияОрганизации" id="6">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Основная регистрация организации</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:CatalogRef.РегистрацииВНалоговомОргане</v8:Type>
			</Type>
		</Attribute>
		<ConditionalAppearance>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>СписокПодразделения</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemGroup">
						<dcsset:groupType>AndGroup</dcsset:groupType>
						<dcsset:item xsi:type="dcsset:FilterItemComparison">
							<dcsset:left xsi:type="dcscor:Field">ТекущаяСтрокаРегистрации</dcsset:left>
							<dcsset:comparisonType>Filled</dcsset:comparisonType>
						</dcsset:item>
						<dcsset:item xsi:type="dcsset:FilterItemComparison">
							<dcsset:left xsi:type="dcscor:Field">СписокПодразделения.РегистрацияВНалоговомОргане</dcsset:left>
							<dcsset:comparisonType>Equal</dcsset:comparisonType>
							<dcsset:right xsi:type="dcscor:Field">ТекущаяСтрокаРегистрации</dcsset:right>
						</dcsset:item>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:use>false</dcscor:use>
						<dcscor:parameter>BackColor</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Color">style:ЦветФонаВыделения</dcscor:value>
					</dcscor:item>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Font</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Font" ref="sys:DefaultGUIFont" bold="true" italic="false" underline="false" strikeout="false" kind="WindowsFont"/>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>СписокРегистрации</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemGroup">
						<dcsset:groupType>AndGroup</dcsset:groupType>
						<dcsset:item xsi:type="dcsset:FilterItemComparison">
							<dcsset:left xsi:type="dcscor:Field">ОсновнаяРегистрацияОрганизации</dcsset:left>
							<dcsset:comparisonType>Filled</dcsset:comparisonType>
						</dcsset:item>
						<dcsset:item xsi:type="dcsset:FilterItemComparison">
							<dcsset:left xsi:type="dcscor:Field">СписокРегистрации.Ссылка</dcsset:left>
							<dcsset:comparisonType>Equal</dcsset:comparisonType>
							<dcsset:right xsi:type="dcscor:Field">ОсновнаяРегистрацияОрганизации</dcsset:right>
						</dcsset:item>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:use>false</dcscor:use>
						<dcscor:parameter>BackColor</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Color">style:ЦветФонаВыделения</dcscor:value>
					</dcscor:item>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Font</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Font" ref="sys:DefaultGUIFont" bold="true" italic="false" underline="false" strikeout="false" kind="WindowsFont"/>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>СписокРегистрацииКоличествоПодразделений</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">СписокРегистрации.КоличествоПодразделений</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="xs:decimal">0</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Text</dcscor:parameter>
						<dcscor:value xsi:type="xs:string">не привязаны</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
		</ConditionalAppearance>
	</Attributes>
	<Commands>
		<Command name="НазначитьОсновнуюРегистрациюОрганизации" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Назначить основной</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Назначить основную регистрацию организации</v8:content>
				</v8:item>
			</ToolTip>
			<Action>НазначитьОсновнуюРегистрациюОрганизации</Action>
		</Command>
		<Command name="НазначитьРегистрациюПодразделения" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Назначить регистрацию</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Назначить регистрацию подразделения</v8:content>
				</v8:item>
			</ToolTip>
			<Action>НазначитьРегистрациюПодразделения</Action>
		</Command>
		<Command name="ОтменитьРегистрациюПодразделения" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Отменить регистрацию</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Отменить регистрацию подразделения</v8:content>
				</v8:item>
			</ToolTip>
			<Action>ОтменитьРегистрациюПодразделения</Action>
		</Command>
	</Commands>
</Form>


text:
/* global require */
import { module, test } from 'qunit';

import { setupTest } from 'ember-qunit';

function assertPackageNotPresent(packageName, assert) {
  const entries = Object.keys(require.entries);
  const entriesFromPackage = entries.filter(m => m.indexOf(packageName) === 0);
  const importedDependencies = {};
  const entriesImportingPackage = entries.filter(m => {
    const deps = require.entries[m].deps;
    const moduleDeps = deps.filter(d => d.indexOf(packageName) === 0);

    if (moduleDeps.length) {
      importedDependencies[m] = moduleDeps;
    }
    return moduleDeps.length > 0;
  });

  assert.ok(entries.length > 0, 'We have modules');
  assert.ok(
    entriesFromPackage.length === 0,
    `We expect no modules from ${packageName} ${
      entriesFromPackage.length > 0 ? `found: [\n\t"${entriesFromPackage.join('",\n\t"')}"\n]` : ''
    }`
  );
  assert.ok(
    entriesImportingPackage.length === 0,
    `We expect no modules with dependencies on ${packageName} ${
      entriesImportingPackage.length > 0 ? `found:\n${JSON.stringify(importedDependencies, null, 2)}` : ''
    }`
  );
}

module('Serializer Encapsulation - Smoke Tests', function(hooks) {
  setupTest(hooks);

  test('No @ember-data/serializer modules are present', function(assert) {
    assertPackageNotPresent('@ember-data/serializer', assert);
  });

  test('No ember-data modules are present', function(assert) {
    assertPackageNotPresent('ember-data', assert);
  });
});


text:
package edu.usu.sdl.openstorefront.core.model;

import java.io.InputStream;

/**
 * Hold the context of an upload into the system
 *
 * @author dshurtleff
 */
public class ImportContext
{

	private InputStream input;
	private FileHistoryAll fileHistoryAll = new FileHistoryAll();

	public ImportContext()
	{
	}

	public InputStream getInput()
	{
		return input;
	}

	public void setInput(InputStream input)
	{
		this.input = input;
	}

	public FileHistoryAll getFileHistoryAll()
	{
		return fileHistoryAll;
	}

	public void setFileHistoryAll(FileHistoryAll fileHistoryAll)
	{
		this.fileHistoryAll = fileHistoryAll;
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Lozingle
 * Date: 11/04/2017
 * Time: 04:31 PM
 */
namespace Lts\Contact\Block\Adminhtml\Contact;

use Magento\Backend\Block\Widget\Form\Container;

class Edit extends Container
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * Contact edit block
     *
     * @return void
     */
    protected function _construct()
    {

        $this->_objectId = 'entity_id';
        $this->_blockGroup = 'Lts_Contact';
        $this->_controller = 'adminhtml_contact';

        parent::_construct();

        if ($this->_isAllowedAction('Lts_Contact::contact_save')) {
            $this->buttonList->update('save', 'label', __('Save Contact'));
            $this->buttonList->add(
                'saveandcontinue',
                [
                    'label' => __('Save and Continue Edit'),
                    'class' => 'save',
                    'data_attribute' => [
                        'mage-init' => [
                            'button' => ['event' => 'saveAndContinueEdit', 'target' => '#edit_form'],
                        ],
                    ]
                ],
                -100
            );
        } else {
            $this->buttonList->remove('save');
        }

    }

    /**
     * Get header with Contact name
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {

        if ($this->_coreRegistry->registry('contact_contact')->getId()) {
            return __("Edit Contact '%1'", $this->escapeHtml($this->_coreRegistry->registry('contact_contact')->getName()));
        } else {
            return __('New Contact');
        }
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

    /**
     * Getter of url for "Save and Continue" button
     * tab_id will be replaced by desired by JS later
     *
     * @return string
     */
    protected function _getSaveAndContinueUrl()
    {
        return $this->getUrl('contact/*/save', ['_current' => true, 'back' => 'edit', 'active_tab' => '']);
    }
}


text:
if (( $# < 2)); then
        echo "usage: $0 <image name> <container name> <optional - flags>"
        exit 1
elif (( $# > 3 )); then
        echo "too many arguments. usage: $0 <image name> <container name> <optional - flags>"
        exit 1
else
        echo "$1" > container.image
        echo "$2" > container.name
        if (( $# > 2 )); then
                echo "$3" > container.flags
        fi
fi