text:
Angular Tablist Tutorial Full Source Code
=========================================

Please see http://maniekq.github.io/angular-tablist#usage for more information.


text:
Enviar evento

*Obligatorio

<form action="https://docs.google.com/forms/d/1QyYux0Yo5-ppE267pVwyTn4bD98aEYJkJvgdogg4H00/formResponse" method="POST" id="ss-form" target="_self" onsubmit="">

nombre

					*

				<input type="text" name="entry.1397730804" value="" class="ss-q-short" id="entry_1397730804" dir="auto" aria-label="nombre  " aria-required="true" required="" title="">

Esta pregunta es obligatoria.

fecha

				*

			<input type="date" name="entry.1153063349" value="" class="ss-q-date" dir="auto" id="entry_1153063349" aria-label="fecha  " aria-required="true" required="">

Esta pregunta es obligatoria.

hora

				*

			<input type="time" name="entry.1905836409" value="" class="ss-q-time" dir="auto" id="entry_1905836409" aria-label="hora  " aria-required="true" required="">

Ejemplo: 11:00 a.m.

Esta pregunta es obligatoria.

fecha final

				*

			<input type="date" name="entry.1105586097" value="" class="ss-q-date" dir="auto" id="entry_1105586097" aria-label="fecha final  " aria-required="true" required="">

Esta pregunta es obligatoria.

precio

			<input type="number" name="entry.230527241" value="" class="ss-q-short" id="entry_230527241" dir="auto" aria-label="precio  Debe ser un número mayor que 0" step="any" title="Debe ser un número mayor que 0">

Debe ser un número mayor que 0

Esta pregunta es obligatoria.

enlace

			<input type="url" name="entry.664653371" value="" class="ss-q-short" id="entry_664653371" dir="auto" aria-label="enlace  Debe ser una URL válida" title="Debe ser una URL v&aaacute;lida">

Debe ser una URL válida

Esta pregunta es obligatoria.

lugar

				*

			<input type="text" name="entry.285209250" value="" class="ss-q-short" id="entry_285209250" dir="auto" aria-label="lugar  " aria-required="true" required="" title="">

Esta pregunta es obligatoria.

contactoMovil

			<input type="number" name="entry.92370035" value="" class="ss-q-short" id="entry_92370035" dir="auto" aria-label="contactoMovil  Debe ser un número entero" step="1" title="Debe ser un número entero">

Debe ser un número entero

Esta pregunta es obligatoria.

contactoFijo

			<input type="number" name="entry.1223190954" value="" class="ss-q-short" id="entry_1223190954" dir="auto" aria-label="contactoFijo  Debe ser un número entero" step="1" title="Debe ser un número entero">

Debe ser un número entero

Esta pregunta es obligatoria.

contactoEmail

			<input type="email" name="entry.1203580862" value="" class="ss-q-short" id="entry_1203580862" dir="auto" aria-label="contactoEmail  Debe ser una dirección de correo electrónico válida" title="Debe ser una dirección de correo electrónico válida">

Debe ser una dirección de correo electrónico válida

Esta pregunta es obligatoria.

URLimagen

				*

			<input type="url" name="entry.1603577571" value="" class="ss-q-short" id="entry_1603577571" dir="auto" aria-label="URLimagen  Debe ser una URL válida" aria-required="true" required="" title="Debe ser una URL válida">

Debe ser una URL válida

Esta pregunta es obligatoria.

miniatura

			<input type="text" name="entry.28550810" value="" class="ss-q-short" id="entry_28550810" dir="auto" aria-label="miniatura  " title="">

Esta pregunta es obligatoria.

descripcion

				*

			<textarea name="entry.856078647" rows="8" cols="0" class="ss-q-long" id="entry_856078647" dir="auto" aria-label="descripcion  Debe tener por lo menos 100 caracteres." aria-required="true" required=""></textarea>

Debe tener por lo menos 100 caracteres.

Esta pregunta es obligatoria.

categoria

				*

			<select name="entry.2031034806" id="entry_2031034806" aria-label="categoria  " aria-required="true" required=""><option value=""></option>
				<option value="opcion1">opcion1</option> <option value="opcion2">opcion2</option> <option value="opcion3">opcion3</option></select>

Esta pregunta es obligatoria.

hashtag1

				*

			<input type="text" name="entry.1038845584" value="" class="ss-q-short" id="entry_1038845584" dir="auto" aria-label="hashtag1  " aria-required="true" required="" title="">

Esta pregunta es obligatoria.

hastag2

				*

			<input type="text" name="entry.962584395" value="" class="ss-q-short" id="entry_962584395" dir="auto" aria-label="hastag2  " aria-required="true" required="" title="">

Esta pregunta es obligatoria.

		<input type="hidden" name="draftResponse" value="[,,"-3457002355821322647"]
														 ">
		<input type="hidden" name="pageHistory" value="0">
		<input type="hidden" name="fvv" value="0">

		<input type="hidden" name="fbzx" value="-3457002355821322647">

			<input type="submit" name="submit" value="Enviar" id="ss-submit" class="jfk-button jfk-button-action ">

Nunca envíes contraseñas a través de Formularios de Google.

</form>

Con la tecnología de

					Formularios de Google

Este contenido no ha sido creado ni aprobado por Google.

					Informar sobre abusos
					-
					Condiciones del servicio
					-
					Otros términos

Editar este formulario

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ The MIT License (MIT)
  ~
  ~ Copyright (c) 2015 Piasy
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in all
  ~ copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  ~ SOFTWARE.
  -->

<resources>
    <declare-styleable name="ClearableEditText">
        <attr name="hasIcon" format="boolean"/>
        <attr name="iconRes" format="reference"/>
        <attr name="iconMarginLeft" format="dimension"/>
        <attr name="iconMarginRight" format="dimension"/>

        <attr name="clearableEditTextColor" format="color"/>
        <attr name="clearableEditTextHintColor" format="color"/>
        <attr name="editTextContent" format="string"/>
        <attr name="editTextHintContent" format="string"/>
        <attr name="editTextSize" format="dimension"/>
        <attr name="editTextAutoFocus" format="boolean"/>
        <attr name="clearableEditTextBackground" format="reference"/>

        <attr name="clearIconRes" format="reference"/>
        <attr name="clearIconMarginLeft" format="dimension"/>
        <attr name="clearIconMarginRight" format="dimension"/>

        <attr name="hasVisibilitySwitch" format="boolean"/>
        <attr name="visibilitySwitchMarginRight" format="dimension"/>
        <attr name="visibilitySwitchWidth" format="dimension"/>
        <attr name="visibilitySwitchHeight" format="dimension"/>
        <attr name="visibilitySwitchBg" format="reference"/>
    </declare-styleable>
</resources>


text:
import displayTool from './displayTool.js';
import drawTextBox from '../util/drawTextBox.js';

function onImageRendered (e) {
  const eventData = e.detail;
  const image = eventData.image;
  const stats = image.stats;

  const context = eventData.canvasContext.canvas.getContext('2d');

  context.setTransform(1, 0, 0, 1, 0, 0);

  const textLines = [];

  Object.keys(stats).forEach(function (key) {
    const text = `${key} : ${stats[key]}`;

    textLines.push(text);
  });

  drawTextBox(context, textLines, 0, 0, 'orange');

  textLines.forEach(function (text) {
    console.log(text);
  });
}

const imageStats = displayTool(onImageRendered);

export default imageStats;


text:
package de.ozzc.iot.example;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * Created by Ozkan Can on 10/04/16.
 */
class ExampleCallback implements MqttCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExampleCallback.class);

    @Override
    public void connectionLost(Throwable cause) {
        LOGGER.info("Connection Lost.", cause);
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        LOGGER.info("Message arrived on topic {}. Contents: {}", topic, new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        LOGGER.info("Completed delivery of message with id {}", token.getMessageId());
    }
}


text:
package org.robolectric.res.android;

import java.nio.file.Path;

public class AssetPath {
  public final Path file;
  public final boolean isSystem;

  public AssetPath(Path file, boolean isSystem) {
    this.file = file;
    this.isSystem = isSystem;
  }
}


text:
package manager

import(
	"time"
	"testing"
)

func assert(t *testing.T, expr bool, format string, args ...interface{}) {
	if expr == false {
		t.Fatalf(format, args...)
	}
}

func TestHandleNotifyWhenProcessFinish(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)
	m.Handle(i)

	select {
	case _ = <- time.After(1 * time.Second):
		t.Fatal("Notification wait expired")
	case _ = <- m.Chan:
	}
}

func TestHandleWithInvalidCommand(t *testing.T) {
	m := New()
	i := NewInstance("_INVALID_CMD_", nil)
	err := m.Handle(i)
	assert(t, err != nil, "Should return an error")
}

func TestHandleRegisterInstance(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)
	m.Handle(i)
	<- m.Chan

	instances := m.GetInstances()

	assert(t, len(instances) == 1, "Instance not registered")

	expected := instances["ls"];
	assert(t, i.Name == expected.Name,
		"Failed asserting %#v == %#v", i, &expected)
}

func TestHandleSetsStartAndEndTimestamps(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)
	i.Max = 1
	m.Handle(i)

	<- m.Chan
	assert(t, i.EndedAt.UnixNano() > i.StartedAt.UnixNano(),
		"Failed asserting %#v > %#v", i.EndedAt, i.StartedAt)
}

func TestHandleFailsRegisteringTheSameInstance(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)

	if err := m.Handle(i); err != nil { t.Fatal(err) }

	err := m.Handle(i);
	assert(t, err != nil, "Failed asserting err != nil")
}

func TestHandleRestartsInstanceExecutionNTimes(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)
	max := i.Max
	m.Handle(i);

	for c := 0; c < max; c++ {
		select {
		case _ = <- time.After(1 * time.Second):
			t.Fatal("Notification wait expired")
		case _ = <- m.Chan:
		}
	}

	assert(t, i.Attempts() == 3,
		"Failed asserting 3 == %d", i.Attempts())
}

func TestHandleInstanceMax0(t *testing.T) {
	m := New()
	i := NewInstance("ls", nil)
	i.Max = 0
	x := m.Handle(i);

	assert(t, x != nil, "should return an error")

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _SvgIcon = require('../../SvgIcon');

var _SvgIcon2 = _interopRequireDefault(_SvgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ActionViewModule = function ActionViewModule(props) {
  return _react2.default.createElement(
    _SvgIcon2.default,
    props,
    _react2.default.createElement('path', { d: 'M4 11h5V5H4v6zm0 7h5v-6H4v6zm6 0h5v-6h-5v6zm6 0h5v-6h-5v6zm-6-7h5V5h-5v6zm6-6v6h5V5h-5z' })
  );
};
ActionViewModule = (0, _pure2.default)(ActionViewModule);
ActionViewModule.displayName = 'ActionViewModule';
ActionViewModule.muiName = 'SvgIcon';

exports.default = ActionViewModule;


text:
var Joi = require('joi');
var timespan = require('./lib/timespan');
var xtend = require('xtend');
var jws = require('jws');

var sign_options_schema = Joi.object().keys({
  expiresIn: [Joi.number().integer(), Joi.string()],
  notBefore: [Joi.number().integer(), Joi.string()],
  audience:  [Joi.string(), Joi.array()],
  algorithm: Joi.string().valid('RS256','RS384','RS512','ES256','ES384','ES512','HS256','HS384','HS512','none'),
  header:    Joi.object(),
  encoding:  Joi.string(),
  issuer:    Joi.string(),
  subject:   Joi.string(),
  jwtid:     Joi.string(),
  noTimestamp: Joi.boolean()
});

var registered_claims_schema = Joi.object().keys({
  iat: Joi.number(),
  exp: Joi.number(),
  nbf: Joi.number()
}).unknown();

var options_to_payload = {
  'audience': 'aud',
  'issuer':   'iss',
  'subject':  'sub',
  'jwtid':    'jti'
};

var options_for_objects = [
  'expiresIn',
  'notBefore',
  'noTimestamp',
  'audience',
  'issuer',
  'subject',
  'jwtid',
];

module.exports = function(payload, secretOrPrivateKey, options, callback) {
  options = options || {};

  var header = xtend({
    alg: options.algorithm || 'HS256',
    typ: typeof payload === 'object' ? 'JWT' : undefined
  }, options.header);

  if (typeof payload === 'undefined') {
    throw new Error('payload is required');
  } else if (typeof payload === 'object') {
    var payload_validation_result = registered_claims_schema.validate(payload);

    if (payload_validation_result.error) {
      throw payload_validation_result.error;
    }

    payload = xtend(payload);
  } else if (typeof payload !== 'object') {
    var invalid_options = options_for_objects.filter(function (opt) {
      return typeof options[opt] !== 'undefined';
    });

    if (invalid_options.length > 0) {
      throw new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload' );
    }
  }

  if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {
    throw new Error('Bad "options.expiresIn" option the payload already has an "exp" property.');
  }

  if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {
    throw new Error('Bad "options.notBefore" option the payload already has an "nbf" property.');
  }

  var validation_result = sign_options_schema.validate(options);

  if (validation_result.error) {
    throw validation_result.error;
  }

  var timestamp = payload.iat || Math.floor(Date.now() / 1000);

  if (!options.noTimestamp) {
    payload.iat = timestamp;
  } else {
    delete payload.iat;
  }

  if (typeof options.notBefore !== 'undefined') {
    payload.nbf = timespan(options.notBefore);
    if (typeof payload.nbf === 'undefined') {
      throw new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
    payload.exp = timespan(options.expiresIn);
    if (typeof payload.exp === 'undefined') {
      throw new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  Object.keys(options_to_payload).forEach(function (key) {
    var claim = options_to_payload[key];
    if (typeof options[key] !== 'undefined') {
      if (typeof payload[claim] !== 'undefined') {
        throw new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.');
      }
      payload[claim] = options[key];
    }
  });

  var encoding = options.encoding || 'utf8';

  if(typeof callback === 'function') {
    jws.createSign({
      header: header,
      privateKey: secretOrPrivateKey,
      payload: JSON.stringify(payload),
      encoding: encoding
    })
    .once('error', callback)
    .once('done', function(signature) {
      callback(null, signature);
    });
  } else {
    return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
  }
};


text:
package com.hribol.bromium.common.generation.helper;

import com.hribol.bromium.core.config.ContextProvider;
import com.hribol.bromium.core.config.WebDriverActionConfiguration;
import com.hribol.bromium.core.generation.RegistryInformation;

/**
 * Represents a packaged event name and a {@link WebDriverActionConfiguration}
 */
public class NameWebDriverActionConfiguration implements RegistryInformation<WebDriverActionConfiguration> {
    private String eventName;
    private WebDriverActionConfiguration webDriverActionConfiguration;
    private ContextProvider contextProvider;

    public NameWebDriverActionConfiguration(String eventName,
                                            WebDriverActionConfiguration webDriverActionConfiguration,
                                            ContextProvider contextProvider) {
        this.eventName = eventName;
        this.webDriverActionConfiguration = webDriverActionConfiguration;
        this.contextProvider = contextProvider;
    }

    public WebDriverActionConfiguration getWebDriverActionConfiguration() {
        return webDriverActionConfiguration;
    }

    public String getEventName() {
        return eventName;
    }

    public ContextProvider getContextProvider() {
        return contextProvider;
    }

    @Override
    public WebDriverActionConfiguration getGenerationFunctionInformation() {
        return webDriverActionConfiguration;
    }
}


text:
"""Module to compare filtered and unfiltered taxa deduced from their respective trees to assert that they match."""

from shared import parse_options
import logging as log
import sys

__author__ = "Tim te Beek"
__copyright__ = "Copyright 2011, Netherlands Bioinformatics Centre"
__license__ = "MIT"

def fail(unfiltered_a, unfiltered_b, filtered_a, filtered_b):
    """Report error back to the user and exit with error code 1."""

    def _log_error_and_print_stderr(msg, dictionary=None):
        """Both log an error and print it to sys.stderr"""
        log.error(msg)
        print >> sys.stderr, msg
        if dictionary:
            for key, value in dictionary.iteritems():
                log.error('{0}\t{1}'.format(key, value))
                print >> sys.stderr, '{0}\t{1}'.format(key, value)

    _log_error_and_print_stderr('Failure: Unfiltered & filtered tree clusterings do not match!')
    _log_error_and_print_stderr('Unfiltered taxon A:', unfiltered_a)
    _log_error_and_print_stderr('Unfiltered taxon B:', unfiltered_b)
    _log_error_and_print_stderr('Filtered taxon A:', filtered_a)
    _log_error_and_print_stderr('Filtered taxon B:', filtered_b)

    sys.exit(1)

def main(args):
    """Main function called when run from command line or as part of pipeline."""
    usage = """
Usage: compare_taxa.py
--unfiltered-taxon-a=FILE    genome IDs for taxon A as deduced from phylogenetic tree of unfiltered concatemers
--unfiltered-taxon-b=FILE    genome IDs for taxon B as deduced from phylogenetic tree of unfiltered concatemers
--filtered-taxon-a=FILE      genome IDs for taxon A as deduced from phylogenetic tree of filtered concatemers
--filtered-taxon-b=FILE      genome IDs for taxon B as deduced from phylogenetic tree of filtered concatemers
"""
    options = ['unfiltered-taxon-a', 'unfiltered-taxon-b', 'filtered-taxon-a', 'filtered-taxon-b']
    unfiltered_a_file, unfiltered_b_file, filtered_a_file, filtered_b_file = parse_options(usage, options, args)

    # Parse ID files to extract GenBank Project IDs & Organism Name
    with open(unfiltered_a_file) as read_handle:
        unfiltered_a = dict((line.split('\t')[0], line.strip().split('\t')[1]) for line in read_handle)
    with open(unfiltered_b_file) as read_handle:
        unfiltered_b = dict((line.split('\t')[0], line.strip().split('\t')[1]) for line in read_handle)
    with open(filtered_a_file) as read_handle:
        filtered_a = dict((line.split('\t')[0], line.strip().split('\t')[1]) for line in read_handle)
    with open(filtered_b_file) as read_handle:
        filtered_b = dict((line.split('\t')[0], line.strip().split('\t')[1]) for line in read_handle)

    # Otherwise fail after
    if unfiltered_a.keys()[0] in filtered_a:
        if not (set(unfiltered_a.keys()) == set(filtered_a.keys())
                and set(unfiltered_b.keys()) == set(filtered_b.keys())):
            fail(unfiltered_a, unfiltered_b, filtered_a, filtered_b)
    else:
        if not (set(unfiltered_a.keys()) == set(filtered_b.keys())
                and set(unfiltered_b.keys()) == set(filtered_a.keys())):
            fail(unfiltered_a, unfiltered_b, filtered_b, filtered_a)

    # Else: no problems were found
    log.info('Succes: Unfiltered & filtered tree clustering did not result in different taxa.')

if __name__ == '__main__':
    main(sys.argv[1:])


text:
#pragma warning disable 1591

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;

namespace DotNetCasClient.Validation.Schema.Xenc
{
    [Serializable]
    [DebuggerStepThrough]
    [DesignerCategory("code")]
    [XmlType(AnonymousType=true, Namespace="http://www.w3.org/2001/04/xmlenc#")]
    [XmlRoot(Namespace="http://www.w3.org/2001/04/xmlenc#", IsNullable=false)]
    public class ReferenceList {
        [XmlElement("DataReference", typeof(ReferenceType))]
        [XmlElement("KeyReference", typeof(ReferenceType))]
        [XmlChoiceIdentifier("ItemsElementName")]
        public ReferenceType[] Items
        {
            get;
            set;
        }

        [XmlElement("ItemsElementName")]
        [XmlIgnore]
        public ItemsElementNames[] ItemsElementName
        {
            get;
            set;
        }

        [Serializable]
        [XmlType(Namespace = "http://www.w3.org/2001/04/xmlenc#", IncludeInSchema = false)]
        public enum ItemsElementNames
        {
            DataReference,
            KeyReference,
        }
    }
}

#pragma warning restore 1591


text:
.. ref-ship

xoinvader.ship
--------------

.. automodule:: xoinvader.ship
   :members:
   :undoc-members:


text:
Cloud, DCOS and Docker
======================

Amazon Web Services (AWS)
-------------------------

- [Running on AWS](Aws.md)

- [Update on AWS](AwsUpdate.md)

Microsoft Azure
---------------

- [Running on Azure](Azure.md)

Docker
------

- [Docker ArangoDB](DockerContainer.md)

- [Docker with NodeJS App](NodeJsDocker.md)

GiantSwarm
----------

- [In the GiantSwarm](GiantSwarm.md)

Mesos / DCOS
------------

- [ArangoDB in Mesos](Mesosphere.md)

- [DC/OS: Full example](DcosFullExample.md)


text:
namespace PIT.WPF.ViewModels.Issues
{
    public interface IIssueStatusFilterViewModel
    {
        void ClearAllFilters();
        void LoadIssues();
    }
}


text:
package org.bridj;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AndroidTest {

	@Test
	public void testPackageNameExtraction() {
		String expected = "com.example.hellojni";
		for (String url : new String[] {
			"jar:file:/mnt/asec/com.example.hellojni-1/pkg.apk!/lib/armeabi/libhello-jni.so",
			"jar:file:/data/app/com.example.hellojni-1.apk!/lib/armeabi/libhello-jni.so"

		})
			assertEquals("URL not recognized : " + url, expected, AndroidSupport.getAndroidPackageNameFromResourceURL(url));
	}
}


text:
using GammaJul.ReSharper.EnhancedTooltip.DocumentMarkup;
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon.CSharp.Errors;
using JetBrains.ReSharper.Psi.CodeAnnotations;

namespace GammaJul.ReSharper.EnhancedTooltip.Presentation.Highlightings.CSharp {

	[SolutionComponent]
	internal sealed class ClassOrStructConstraintMustBeFirstErrorEnhancer : CSharpHighlightingEnhancer<ClassOrStructConstraintMustBeFirstError> {

		protected override void AppendTooltip(ClassOrStructConstraintMustBeFirstError highlighting, CSharpColorizer colorizer) {
			colorizer.AppendPlainText("The '");
			colorizer.AppendKeyword("class");
			colorizer.AppendPlainText("' or '");
			colorizer.AppendKeyword("struct");
			colorizer.AppendPlainText("' constraint must come before any other constraints");
		}

		public ClassOrStructConstraintMustBeFirstErrorEnhancer(
			[NotNull] TextStyleHighlighterManager textStyleHighlighterManager,
			[NotNull] CodeAnnotationsCache codeAnnotationsCache,
			[NotNull] HighlighterIdProviderFactory highlighterIdProviderFactory)
			: base(textStyleHighlighterManager, codeAnnotationsCache, highlighterIdProviderFactory) {
		}

	}

}


text:
#ifndef SPRITERENDERCOMPONENT_H_
#define SPRITERENDERCOMPONENT_H_
#include "rendersystem/base/RenderDeviceTypes.h"
#include "graphicfeature/components/spritebaserendercomponent.h"

namespace App
{
	class GraphicsFeature;
	class SpriteRenderComponent: public App::SpriteBaseRenderComponent
	{
		__DeclareSubClass(SpriteRenderComponent, App::SpriteBaseRenderComponent)
	public:
		SpriteRenderComponent();
		virtual ~SpriteRenderComponent();
		/// @Component::SetupCallbacks setup callbacks for this component, call by Actor in OnActivate()
		virtual void SetupCallbacks();

		virtual void Setup(const Resources::ResourceId& packId);

		virtual void StandaloneRender(const GPtr<Graphic::Material>& customMat);

		void MaterialDirty();

		void SetBlock(const Util::String& blockName);

		void SetAnimation(const Util::String& name, int loops = 0 , bool play = true, float speed = 1.0f);

		void SetAnimationSpeed(float speed);

		void RemoveBlock();

		void RemoveAnimation();

		void Replay();

		void Play();

		void Pause();

		void Stop();

		Util::String GetBlockName() const;

		Util::String GetAnimationName() const;

		int GetAnimationLoops() const;

		float GetAnimationSpeed() const;

		bool IsAnimationPlaying() const;

		void SetPlayOnWake(bool bPlayOnWake);

		bool GetPlayOnWake() const;

		int GetFrameCount() const;

		int GetCurrentFrameIndex() const;

		void SetCurrentFrame(int frameIndex);

		float GetTotalUnits() const;

		float GetCurrentUnits() const;

		void SetCurrentUnits(float units);

		//	Serialization
		// @ISerialization::GetVersion. when change storage, must add SerializeVersion count
		virtual Version GetVersion() const;
		// @ISerialization::Load
		virtual void Load( Version ver, AppReader* pReader, const Serialization::SerializationArgs* args );

		// @ISerialization::Save
		virtual void Save( AppWriter* pWriter ) const;

		// copy from other component
		virtual void CopyFrom( const GPtr<Component>& pComponent );

	protected:
		/// @Component::OnActivate  called from Actor::ActivateComponents()
		virtual void OnActivate();

		/// @Component::OnDeactivate called from Actor::DeactivateComponents()
		virtual void OnDeactivate();

		virtual void _OnFrame();

		void _Update();

		void _OnDeviceLost(GraphicsFeature* sender);

		void Load_1( Version ver, AppReader* pReader, const Serialization::SerializationArgs* args );
		void Load_2( Version ver, AppReader* pReader, const Serialization::SerializationArgs* args );
	private:
		typedef SpriteRenderObject RenderObjectType;
		typedef GPtr<RenderObjectType> RenderObjectPtr;
		Sprite::SpritePlayer mPlayer;
		bool mPlayOnWake;

	};

	inline Util::String SpriteRenderComponent::GetBlockName() const
	{
		return mPlayer.GetBlockName();
	}

	inline Util::String SpriteRenderComponent::GetAnimationName() const
	{
		return mPlayer.GetAnimationName();
	}

	inline void SpriteRenderComponent::SetAnimationSpeed(float speed)
	{
		mPlayer.SetAnimationSpeed(speed);
	}

	inline void SpriteRenderComponent::RemoveBlock()
	{
		mPlayer.RemoveBlock();
	}

	inline void SpriteRenderComponent::RemoveAnimation()
	{
		mPlayer.RemoveAnimation();
	}

	inline void SpriteRenderComponent::Replay()
	{
		mPlayer.Replay();
	}

	inline void SpriteRenderComponent::Play()
	{
		mPlayer.Play();
	}

	inline void SpriteRenderComponent::Pause()
	{
		mPlayer.Pause();
	}

	inline void SpriteRenderComponent::Stop()
	{
		mPlayer.Stop();
	}
	inline int SpriteRenderComponent::GetAnimationLoops() const
	{
		return mPlayer.GetAnimationLoops();
	}

	inline float SpriteRenderComponent::GetAnimationSpeed() const
	{
		return mPlayer.GetAnimationSpeed();
	}

	inline bool SpriteRenderComponent::IsAnimationPlaying() const
	{
		return mPlayer.IsAnimationPlaying();
	}

	inline void SpriteRenderComponent::SetPlayOnWake(bool bPlayOnWake)
	{
		mPlayOnWake = bPlayOnWake;
	}

	inline bool SpriteRenderComponent::GetPlayOnWake() const
	{
		return mPlayOnWake;
	}

	inline int SpriteRenderComponent::GetFrameCount() const
	{
		return mPlayer.GetAnimationLoops();
	}

	inline int SpriteRenderComponent::GetCurrentFrameIndex() const
	{
		return mPlayer.GetCurrentFrameIndex();
	}

	inline void SpriteRenderComponent::SetCurrentFrame(int frameIndex)
	{
		return mPlayer.SetCurrentFrame(frameIndex);
	}

	inline float SpriteRenderComponent::GetTotalUnits() const
	{
		return mPlayer.GetTotalUnits();
	}

	inline float SpriteRenderComponent::GetCurrentUnits() const
	{
		return mPlayer.GetCurrentUnits();
	}

	inline void SpriteRenderComponent::SetCurrentUnits(float units)
	{
		mPlayer.SetCurrentUnits(units);
	}
}

#endif // SPRITERENDERCOMPONENT_H_


text:
layout: post
title: "Identifying AWS EBS volumes on instance"
description: ""
category: "tips"
tags:
  - aws
  - amazon
  - ebs
  - bash
  - cloud-init
---
{% include JB/setup %}

If you have ever developed a user data script for an AWS instance, you maybe also initialized instances' volumes. And there's always a big problem: how to map AWS volumes to Linux instance's volumes and back? Here's how to solve it for modern AWS instance types (m5/c5/t3 and upper).

## Where the mapping is

In previous versions you could use instance metadata to request device mappings, and in some old times it even worked:

```bash
$ curl http://169.254.169.254/latest/meta-data/block-device-mapping/
/dev/sda1
$ curl http://169.254.169.254/latest/meta-data/block-device-mapping/ebs54
sdb
```

In theory you could map this to kernel's `/dev/sd*` or `/dev/xvd*`. But in modern AWS instance types all volumes are mounted using NVMe emulation, so typical setup looks like:

```
$ ls /dev/nvm*
/dev/nvme0  /dev/nvme0n1  /dev/nvme1  /dev/nvme1n1  /dev/nvme2  /dev/nvme2n1  /dev/nvme3  /dev/nvme3n1  /dev/nvme4  /dev/nvme4n1  /dev/nvme5n1  /dev/nvme5n1p1
```

For the root volume you can use a filesystem label to identify it (for some distributions like Ubuntu):

```
$ ls -lh  /dev/disk/by-label/
total 0
lrwxrwxrwx 1 root root 15 Jul 17 05:54 cloudimg-rootfs -> ../../nvme5n1p1
```

But if you need to bootstrap your instance, you usually want to create filesystems, so you have no labels. And here `nvme-cli` comes. It's a tool that can manipulate NVMe-specific settings and metadata. Install it using `apt` and let's look at one of the volumes:

```
~$ sudo nvme id-ctrl -v /dev/nvme0n1
NVME Identify Controller:
vid     : 0x1d0f
ssvid   : 0x1d0f
sn      : vol00112233445566778
mn      : Amazon Elastic Block Store
............................................
vs[]:
       0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
0000: 73 64 68 20 20 20 20 20 20 20 20 20 20 20 20 20 "xvda............."
............................................
```

So, here we see 2 important things: in `sn` field there's a serial number and in the very beginning of `vs` field there's a volume name for EC2 attachment. Pay attention to the device names: you need `/dev/nvmeXn1`, not `/dev/nvmeX` as we're looking for volumes, not controllers.

## Scripts

Let's write a simple script that will list all our volumes with their AWS mapping:

```bash
#!/bin/bash
for d in /dev/nvme*n1 ; do
  _attachment="$(sudo nvme id-ctrl -v "$d" | grep '^0000: ' | cut -d '"' -f 2 | tr -d '.')"
  _vol_id="$(sudo nvme id-ctrl -v "$d" | grep '^sn' | cut -d ':' -f 2 | tr -d ' ')"
  printf "%s %25s %5s\n" "$d" "vol-${_vol_id#vol}" "${_attachment}"
done
```

So, now you can use your provisioning tool (like Terraform, Ansible or any other one) to map the devices to their actual attachment and volume IDs. For example, the following script adds such mapping to ansible [local facts](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#local-facts-facts-d):

```bash
_return='{}'

for d in /dev/nvme*n1 ; do
  _attachment="$(sudo nvme id-ctrl -v "$d" | grep '^0000: ' | cut -d '"' -f 2 | tr -d '.')"
  _vol_id="$(sudo nvme id-ctrl -v "$d" | grep '^sn' | cut -d ':' -f 2 | tr -d ' ')"
  _return="$(echo "${_return}" | jq --arg d "$(basename "$d")" --arg v "vol-${_vol_id#vol}" --arg a "${_attachment}" '. * { ($d): { "volume_id": ($v), "attachment": ($a) } }')"
done

echo "${_return}"
```

Put it into `/etc/ansible/facts.d/volume_mapping.fact` with executable permissions (`chmod +x /etc/ansible/facts.d/volume_mapping.fact`) and use the facts like: `{% raw %}{{ ansible_local['volume_mapping']['nvme0n1']['attachment'] }}{% endraw %}`. Reverse mapping is also fairly simple:

```bash
_return='{}'

for d in /dev/nvme*n1 ; do
  _attachment="$(sudo nvme id-ctrl -v "$d" | grep '^0000: ' | cut -d '"' -f 2 | tr -d '.')"
  _vol_id="$(sudo nvme id-ctrl -v "$d" | grep '^sn' | cut -d ':' -f 2 | tr -d ' ')"
  _return="$(echo "${_return}" | jq --arg d "$(basename "$d")" --arg v "vol-${_vol_id#vol}" --arg a "${_attachment}" '. * { ($a): { "volume_id": ($v), "device": ($d) } }')"
done

echo "${_return}"
```


text:
%&latex

\documentclass{article}
\usepackage{amsmath}
\usepackage{graphicx}

\DeclareMathOperator*{\argmax}{argmax}

\begin{document}

%+Title
\title{Interactive Video Lecture Summary}
\author{Hijung V.Shin}
\date{\today}
\maketitle
%-Title

%+Abstract
%\begin{abstract}
%    There is abstract text that you should replace with your own.
%\end{abstract}
%-Abstract

%+Contents
%\tableofcontents
%-Contents

\section{Segmentation}

\subsection{Line break algorithm}
\subsection{Energy function}
In summary, the score for a set of lines is the sum of the following terms (multiplied by constant coefficients and raised to constant powers):
\begin{itemize}
\item{sum of the number of horizontally aligned strokes in each line}
\item{sum of number of strokes in each line}
\item{weighted average of the compactness of each line}
\item{negative of the maximum horizontal gap in each line (xgap)}
\item{negative of the maximum vertical gap in each line}
\item{negative of the overlapping area between lines}
\end{itemize}

\begin{figure}[!h]
\center\includegraphics[width=\textwidth]{figures/proj_function_example}

\end{figure}
\begin{figure}[!h]
\center
\end{figure}

More formally, consider $C_s$ the set of all strokes drawn during a lecture. Our goal is to segment the strokes into mutually exclusive lines or figures, $C_{s_1}, C_{s_2}, ...$ such that
\begin{align}
\bigcup \limits_{i} C_i = C_s\\
C_i \cap C_j = \emptyset\quad \forall i \ne j
\end{align} \\
To this purpose we define a scoring function which, given a set of sets of strokes $C_{s_i}$'s returns a scalar value indicating the \textit{badness} of the segmentation. The scoring function depends on several factors.
\\
\begin{enumerate}
\item The number of strokes in each line:

\begin{equation}
n_\text{strokes}(C_{s_i}) = \big{|}C_{s_i}\big{|}
\end{equation}\\
\item The number of horizontally aligned strokes in each line: In order to identify strokes that are aligned horizontally, we define a \textit{horizontal projection function}, $proj_h$, as\\
\begin{equation}
proj_h(y, C_{s_i}) = \big{|}\{s\in C_{s_i} \small{|} y_\text{min}(s)\le y \le y_{max}(s) \}\big{|}
\end{equation}\\
where $y_\text{min}(s)$ and $y_\text{max}(s)$ return the minimum and maximum y coordinate of the bounding box for stroke $s$. \\
Then given a candidate line $C_{s_i}$, the maximum number of horizontally aligned strokes, $n_\text{aligned}(C_{s_i})$, is defined as
\begin{equation}
n_\text{aligned}(C_{s_i}) = \argmax_{y_\text{min}(C_{s_i}) \le y \le y_\text{max}(C_{s_i})} f(y)
\end{equation}\\
\item
The maximum horizontal gap in a line. $x_\text{gap}(C_{s_i})$, is defined using the \textit{vertical projection function}
\begin{equation}
proj_v(x, C_{s_i}) = \big|\{s \in C_{s_i} \small| x_\text{min}(s) \le x \le x_\text{max}(s)\}\big|
\end{equation}
\begin{equation}
x_\text{gap}(C_{s_i}) = \argmax_{x_i, x_{i+1} \in proj_{v:C_{s_i} \ne 0}} (x_{i+1} - x_i)
\end{equation}
where $proj_{v:C_{s_i} \ne 0}$ is an ordered set such that $x_{i} \in proj_{v:C_{s_i}}$ if $proj_v(x_{i}, C_{s_i}) \ne 0$, and $x_i \le x_{i+1}$.\\
\item
Similarly, we can define the maximum vertical gap in a line, $y_\text{gap}(C_{s_i})$.
\item The compactness of a line, measured as:
\begin{equation}
comp(C_{s_i}) = \frac{\sum\limits_{s\in C_s}area(s)}{area(C_{s_i})}
\end{equation}
where $area(s)$ is the area of the bounding box of stroke $s$.
\item Finally, given a set of lines $L$, the overlap penalty, $P_{overlap}$, is defined as
\begin{equation}
P_{overlap}(L) = \sum \limits_{C_{s_i}, C_{s_j} \in L} \frac{area(overlap(C_{s_i}, C_{s_j}))}{min(area(C_{s_i}), area(C_{s_j}))}
\end{equation}
\end{enumerate}
The score of a segmentation $L$ is defined as:
\begin{align}
score(L) &=\sum\limits_{C_{s_i}\in L}\Bigg{(}n_\text{aligned}(C_{s_i})^{\alpha_{1}}+n_\text{strokes}(C_{s_i})^{\alpha_{2}}\Bigg{)}\\ &-\sum\limit_{C_{s_i}\in L}\Bigg{(}x_\text{gap}(C_{s_i})^{\alpha_3}+y_\text{gap}(C_{s_i})^{\alpha_4}\Bigg{)}\\
&+\frac{\sum\limits_{C_{s_i} \in L} (npix(C_{s_i})\times comp(C_{s_i}))}{\sum\limits_{C_{s_i} \in L}npix(C_{s_i})}\\
&- P_{overlap}(L)
\end{align}

%+Bibliography
\begin{thebibliography}{}
\bibitem{}
\end{thebibliography}
%-Bibliography

\end{document}


text:
package s3

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	s3cust "github.com/aws/aws-sdk-go-v2/service/s3/internal/customizations"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Retrieves an object's retention settings. For more information, see Locking
// Objects (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock.html). This
// action is not supported by Amazon S3 on Outposts. The following action is
// related to GetObjectRetention:
//
// * GetObjectAttributes
// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectAttributes.html)
func (c *Client) GetObjectRetention(ctx context.Context, params *GetObjectRetentionInput, optFns ...func(*Options)) (*GetObjectRetentionOutput, error) {
	if params == nil {
		params = &GetObjectRetentionInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "GetObjectRetention", params, optFns, c.addOperationGetObjectRetentionMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*GetObjectRetentionOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type GetObjectRetentionInput struct {

	// The bucket name containing the object whose retention settings you want to
	// retrieve. When using this action with an access point, you must direct requests
	// to the access point hostname. The access point hostname takes the form
	// AccessPointName-AccountId.s3-accesspoint.Region.amazonaws.com. When using this
	// action with an access point through the Amazon Web Services SDKs, you provide
	// the access point ARN in place of the bucket name. For more information about
	// access point ARNs, see Using access points
	// (https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-access-points.html)
	// in the Amazon S3 User Guide.
	//
	// This member is required.
	Bucket *string

	// The key name for the object whose retention settings you want to retrieve.
	//
	// This member is required.
	Key *string

	// The account ID of the expected bucket owner. If the bucket is owned by a
	// different account, the request fails with the HTTP status code 403 Forbidden
	// (access denied).
	ExpectedBucketOwner *string

	// Confirms that the requester knows that they will be charged for the request.
	// Bucket owners need not specify this parameter in their requests. For information
	// about downloading objects from Requester Pays buckets, see Downloading Objects
	// in Requester Pays Buckets
	// (https://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html)
	// in the Amazon S3 User Guide.
	RequestPayer types.RequestPayer

	// The version ID for the object whose retention settings you want to retrieve.
	VersionId *string

	noSmithyDocumentSerde
}

type GetObjectRetentionOutput struct {

	// The container element for an object's retention settings.
	Retention *types.ObjectLockRetention

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationGetObjectRetentionMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsRestxml_serializeOpGetObjectRetention{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsRestxml_deserializeOpGetObjectRetention{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = swapWithCustomHTTPSignerMiddleware(stack, options); err != nil {
		return err
	}
	if err = addOpGetObjectRetentionValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetObjectRetention(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addMetadataRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addGetObjectRetentionUpdateEndpoint(stack, options); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = v4.AddContentSHA256HeaderMiddleware(stack); err != nil {
		return err
	}
	if err = disableAcceptEncodingGzip(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opGetObjectRetention(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "s3",
		OperationName: "GetObjectRetention",
	}
}

// getGetObjectRetentionBucketMember returns a pointer to string denoting a
// provided bucket member valueand a boolean indicating if the input has a modeled
// bucket name,
func getGetObjectRetentionBucketMember(input interface{}) (*string, bool) {
	in := input.(*GetObjectRetentionInput)
	if in.Bucket == nil {
		return nil, false
	}
	return in.Bucket, true
}
func addGetObjectRetentionUpdateEndpoint(stack *middleware.Stack, options Options) error {
	return s3cust.UpdateEndpoint(stack, s3cust.UpdateEndpointOptions{
		Accessor: s3cust.UpdateEndpointParameterAccessor{
			GetBucketFromInput: getGetObjectRetentionBucketMember,
		},
		UsePathStyle:                   options.UsePathStyle,
		UseAccelerate:                  options.UseAccelerate,
		SupportsAccelerate:             true,
		TargetS3ObjectLambda:           false,
		EndpointResolver:               options.EndpointResolver,
		EndpointResolverOptions:        options.EndpointOptions,
		UseARNRegion:                   options.UseARNRegion,
		DisableMultiRegionAccessPoints: options.DisableMultiRegionAccessPoints,
	})
}


text:
<PackageItem xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.sdltridion.com/ContentManager/ImportExport/Package/2013">
  <BinaryFileLocation>Binaries\4-495.jpg</BinaryFileLocation>
  <Data>
    <tcm:Data>
      <tcm:Title>Red Bicycle Image</tcm:Title>
      <tcm:Type>Multimedia</tcm:Type>
      <tcm:Schema xlink:type="simple" xlink:title="Image" xlink:href="/webdav/200%20Example%20Content/Building%20Blocks/Modules/Core/Editor/Schemas/Image.xsd" IsMandatory="false" />
      <tcm:Content />
      <tcm:Metadata>
        <Metadata xmlns="http://www.sdl.com/web/schemas/core" />
      </tcm:Metadata>
      <tcm:IsBasedOnTridionWebSchema>true</tcm:IsBasedOnTridionWebSchema>
      <tcm:MultimediaType xlink:type="simple" xlink:title="Jpeg image" xlink:href="tcm:0-2-65544" />
      <tcm:MultimediaFilename>photo-1507609752873-44646188a77d.jpg</tcm:MultimediaFilename>
      <tcm:MultimediaFileSize>427190</tcm:MultimediaFileSize>
      <tcm:IsExternalMultimediaFile>false</tcm:IsExternalMultimediaFile>
    </tcm:Data>
  </Data>
  <Dependencies>
    <Dependency dependencyType="Publication" itemUrl="/webdav/200%20Example%20Content" linkName="LocationInfo/ContextRepository" />
    <Dependency dependencyType="OrganizationalItemFolder" itemUrl="/webdav/200%20Example%20Content/Building%20Blocks/Modules%20Content/TridionDocsMashup/Content/Products/Bicycles" linkName="LocationInfo/OrganizationalItem" />
    <Dependency dependencyType="MultimediaType" itemUrl="/webdav//Jpeg%20image.tmt" linkName="BinaryContent/MultimediaType" />
    <Dependency dependencyType="Schema" itemUrl="/webdav/200%20Example%20Content/Building%20Blocks/Modules/Core/Editor/Schemas/Image.xsd" linkName="Schema" />
  </Dependencies>
</PackageItem>


text:
#pragma once
#include <aws/workspaces/WorkSpaces_EXPORTS.h>
#include <aws/workspaces/WorkSpacesRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/workspaces/model/Tenancy.h>
#include <aws/workspaces/model/Tag.h>
#include <utility>

namespace Aws
{
namespace WorkSpaces
{
namespace Model
{

  /**
   */
  class AWS_WORKSPACES_API RegisterWorkspaceDirectoryRequest : public WorkSpacesRequest
  {
  public:
    RegisterWorkspaceDirectoryRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "RegisterWorkspaceDirectory"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline const Aws::String& GetDirectoryId() const{ return m_directoryId; }

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline bool DirectoryIdHasBeenSet() const { return m_directoryIdHasBeenSet; }

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline void SetDirectoryId(const Aws::String& value) { m_directoryIdHasBeenSet = true; m_directoryId = value; }

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline void SetDirectoryId(Aws::String&& value) { m_directoryIdHasBeenSet = true; m_directoryId = std::move(value); }

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline void SetDirectoryId(const char* value) { m_directoryIdHasBeenSet = true; m_directoryId.assign(value); }

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline RegisterWorkspaceDirectoryRequest& WithDirectoryId(const Aws::String& value) { SetDirectoryId(value); return *this;}

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline RegisterWorkspaceDirectoryRequest& WithDirectoryId(Aws::String&& value) { SetDirectoryId(std::move(value)); return *this;}

    /**
     *
The identifier of the directory. You cannot register a directory if it does
     * not have a status of Active. If the directory does not have a status of Active,
     * you will receive an InvalidResourceStateException error. If you have already
     * registered the maximum number of directories that you can register with Amazon
     * WorkSpaces, you will receive a ResourceLimitExceededException error. Deregister
     * directories that you are not using for WorkSpaces, and try again.

     */
    inline RegisterWorkspaceDirectoryRequest& WithDirectoryId(const char* value) { SetDirectoryId(value); return *this;}

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline const Aws::Vector<Aws::String>& GetSubnetIds() const{ return m_subnetIds; }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline bool SubnetIdsHasBeenSet() const { return m_subnetIdsHasBeenSet; }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline void SetSubnetIds(const Aws::Vector<Aws::String>& value) { m_subnetIdsHasBeenSet = true; m_subnetIds = value; }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline void SetSubnetIds(Aws::Vector<Aws::String>&& value) { m_subnetIdsHasBeenSet = true; m_subnetIds = std::move(value); }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline RegisterWorkspaceDirectoryRequest& WithSubnetIds(const Aws::Vector<Aws::String>& value) { SetSubnetIds(value); return *this;}

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline RegisterWorkspaceDirectoryRequest& WithSubnetIds(Aws::Vector<Aws::String>&& value) { SetSubnetIds(std::move(value)); return *this;}

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline RegisterWorkspaceDirectoryRequest& AddSubnetIds(const Aws::String& value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(value); return *this; }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline RegisterWorkspaceDirectoryRequest& AddSubnetIds(Aws::String&& value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(std::move(value)); return *this; }

    /**
     *
The identifiers of the subnets for your virtual private cloud (VPC). Make
     * sure that the subnets are in supported Availability Zones. The subnets must also
     * be in separate Availability Zones. If these conditions are not met, you will
     * receive an OperationNotSupportedException error.

     */
    inline RegisterWorkspaceDirectoryRequest& AddSubnetIds(const char* value) { m_subnetIdsHasBeenSet = true; m_subnetIds.push_back(value); return *this; }

    /**
     *
Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled
     * this parameter and WorkDocs is not available in the Region, you will receive an
     * OperationNotSupportedException error. Set EnableWorkDocs to
     * disabled, and try again.

     */
    inline bool GetEnableWorkDocs() const{ return m_enableWorkDocs; }

    /**
     *
Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled
     * this parameter and WorkDocs is not available in the Region, you will receive an
     * OperationNotSupportedException error. Set EnableWorkDocs to
     * disabled, and try again.

     */
    inline bool EnableWorkDocsHasBeenSet() const { return m_enableWorkDocsHasBeenSet; }

    /**
     *
Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled
     * this parameter and WorkDocs is not available in the Region, you will receive an
     * OperationNotSupportedException error. Set EnableWorkDocs to
     * disabled, and try again.

     */
    inline void SetEnableWorkDocs(bool value) { m_enableWorkDocsHasBeenSet = true; m_enableWorkDocs = value; }

    /**
     *
Indicates whether Amazon WorkDocs is enabled or disabled. If you have enabled
     * this parameter and WorkDocs is not available in the Region, you will receive an
     * OperationNotSupportedException error. Set EnableWorkDocs to
     * disabled, and try again.

     */
    inline RegisterWorkspaceDirectoryRequest& WithEnableWorkDocs(bool value) { SetEnableWorkDocs(value); return *this;}

    /**
     *
Indicates whether self-service capabilities are enabled or disabled.

     */
    inline bool GetEnableSelfService() const{ return m_enableSelfService; }

    /**
     *
Indicates whether self-service capabilities are enabled or disabled.

     */
    inline bool EnableSelfServiceHasBeenSet() const { return m_enableSelfServiceHasBeenSet; }

    /**
     *
Indicates whether self-service capabilities are enabled or disabled.

     */
    inline void SetEnableSelfService(bool value) { m_enableSelfServiceHasBeenSet = true; m_enableSelfService = value; }

    /**
     *
Indicates whether self-service capabilities are enabled or disabled.

     */
    inline RegisterWorkspaceDirectoryRequest& WithEnableSelfService(bool value) { SetEnableSelfService(value); return *this;}

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline const Tenancy& GetTenancy() const{ return m_tenancy; }

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline bool TenancyHasBeenSet() const { return m_tenancyHasBeenSet; }

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline void SetTenancy(const Tenancy& value) { m_tenancyHasBeenSet = true; m_tenancy = value; }

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline void SetTenancy(Tenancy&& value) { m_tenancyHasBeenSet = true; m_tenancy = std::move(value); }

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline RegisterWorkspaceDirectoryRequest& WithTenancy(const Tenancy& value) { SetTenancy(value); return *this;}

    /**
     *
Indicates whether your WorkSpace directory is dedicated or shared. To use
     * Bring Your Own License (BYOL) images, this value must be set to
     * DEDICATED and your AWS account must be enabled for BYOL. If your
     * account has not been enabled for BYOL, you will receive an
     * InvalidParameterValuesException error. For more information about BYOL images,
     * see Bring
     * Your Own Windows Desktop Images.

     */
    inline RegisterWorkspaceDirectoryRequest& WithTenancy(Tenancy&& value) { SetTenancy(std::move(value)); return *this;}

    /**
     *
The tags associated with the directory.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
The tags associated with the directory.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
The tags associated with the directory.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The tags associated with the directory.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
The tags associated with the directory.

     */
    inline RegisterWorkspaceDirectoryRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
The tags associated with the directory.

     */
    inline RegisterWorkspaceDirectoryRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The tags associated with the directory.

     */
    inline RegisterWorkspaceDirectoryRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
The tags associated with the directory.

     */
    inline RegisterWorkspaceDirectoryRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_directoryId;
    bool m_directoryIdHasBeenSet;

    Aws::Vector<Aws::String> m_subnetIds;
    bool m_subnetIdsHasBeenSet;

    bool m_enableWorkDocs;
    bool m_enableWorkDocsHasBeenSet;

    bool m_enableSelfService;
    bool m_enableSelfServiceHasBeenSet;

    Tenancy m_tenancy;
    bool m_tenancyHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;
  };

} // namespace Model
} // namespace WorkSpaces
} // namespace Aws


text:
require "active_record"
require "active_support"
require "action_view"

$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'acts_as_wiki/acts_as_wiki'
require 'acts_as_wiki/wiki_markup'
require 'acts_as_wiki/acts_as_wiki/core'
require 'acts_as_wiki/acts_as_wiki/view_helpers'

$LOAD_PATH.shift

if defined?(ActiveRecord::Base)
  ActiveRecord::Base.extend ActsAsWiki::Markable
  ActiveRecord::Base.send :include, ActsAsWiki::Markable
end

if defined?(ActionView::Helpers::FormBuilder)
	# ActionView::Helpers::FormBuilder.send :include, ActsAsWiki::Markable::WikiFormBuilder
end


text:
function stripPEM(pem){
    let lines = pem.split(/\r?\n/);
    let str = '';
    for(let l of lines){
        if(!l.startsWith('-')){
            str += l;
        }
    }
    return str;
}

function pems2pkcs12(certPEMStr, keyPEMStr, password) {
    keyPEMStr = stripPEM(keyPEMStr);
    certPEMStr = stripPEM(certPEMStr);
    // #region Initial variables
    var sequence = Promise.resolve();

    let keyLocalIDBuffer = new ArrayBuffer(4);
    let keyLocalIDView = new Uint8Array(keyLocalIDBuffer);

    org.pkijs.getRandomValues(keyLocalIDView)

    let certLocalIDBuffer = new ArrayBuffer(4);
    let certLocalIDView = new Uint8Array(certLocalIDBuffer);

    org.pkijs.getRandomValues(certLocalIDView)

    // #region "KeyUsage" attribute
    let bit_array = new ArrayBuffer(1);
    let bit_view = new Uint8Array(bit_array);

    bit_view[0] = bit_view[0] | 0x80;

    let key_usage = new org.pkijs.asn1.BITSTRING({
        value_hex: bit_array,
        unused_bits: 7
    });

    // #region Create simplified structires for certificate and private key
    let asn1 = org.pkijs.fromBER(str2ab(window.atob(certPEMStr)));
    let cert_simpl = new org.pkijs.simpl.CERT({schema: asn1.result});

    asn1 = org.pkijs.fromBER(str2ab(window.atob(keyPEMStr)));
    let pkcs8_simpl = new org.pkijs.simpl.PKCS8({schema: asn1.result});

    // #region Add "keyUsage" attribute
    pkcs8_simpl.attributes = [
        new org.pkijs.simpl.ATTRIBUTE({
            type: "2.5.29.15",
            values: [
                key_usage
            ]
        })
    ];

    // #region Put initial values for PKCS#12 structures
    var pkcs12 = new org.pkijs.simpl.PFX({
        parsedValue: {
            integrityMode: 0, // Password-Based Integrity Mode
            authenticatedSafe: new org.pkijs.simpl.pkcs12.AuthenticatedSafe({
                parsedValue: {
                    safeContents: [
                        {
                            privacyMode: 0, // "No-privacy" Protection Mode
                            value: new org.pkijs.simpl.pkcs12.SafeContents({
                                safeBags: [
                                    new org.pkijs.simpl.pkcs12.SafeBag({
                                        bagId: "1.2.840.113549.1.12.10.1.2",
                                        bagValue: new org.pkijs.simpl.pkcs12.PKCS8ShroudedKeyBag({
                                            parsedValue: pkcs8_simpl
                                        }),
                                        bagAttributes: [
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.2.840.113549.1.9.20", // friendlyName
                                                attrValues: [
                                                    new org.pkijs.asn1.BMPSTRING({value: "PKCS8ShroudedKeyBag from PKIjs"})
                                                ]
                                            }),
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.2.840.113549.1.9.21", // localKeyID
                                                attrValues: [
                                                    new org.pkijs.asn1.OCTETSTRING({value_hex: keyLocalIDBuffer})
                                                ]
                                            }),
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.3.6.1.4.1.311.17.1", // pkcs12KeyProviderNameAttr
                                                attrValues: [
                                                    new org.pkijs.asn1.BMPSTRING({value: "http://www.pkijs.org"})
                                                ]
                                            })
                                        ]
                                    })
                                ]
                            })
                        },
                        {
                            privacyMode: 1, // Password-Based Privacy Protection Mode
                            value: new org.pkijs.simpl.pkcs12.SafeContents({
                                safeBags: [
                                    new org.pkijs.simpl.pkcs12.SafeBag({
                                        bagId: "1.2.840.113549.1.12.10.1.3",
                                        bagValue: new org.pkijs.simpl.pkcs12.CertBag({
                                            parsedValue: cert_simpl
                                        }),
                                        bagAttributes: [
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.2.840.113549.1.9.20", // friendlyName
                                                attrValues: [
                                                    new org.pkijs.asn1.BMPSTRING({value: "CertBag from PKIjs"})
                                                ]
                                            }),
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.2.840.113549.1.9.21", // localKeyID
                                                attrValues: [
                                                    new org.pkijs.asn1.OCTETSTRING({value_hex: certLocalIDBuffer})
                                                ]
                                            }),
                                            new org.pkijs.simpl.cms.Attribute({
                                                attrType: "1.3.6.1.4.1.311.17.1", // pkcs12KeyProviderNameAttr
                                                attrValues: [
                                                    new org.pkijs.asn1.BMPSTRING({value: "http://www.pkijs.org"})
                                                ]
                                            })
                                        ]
                                    })
                                ]
                            })
                        }
                    ]
                }
            })
        }
    });
    // #endregion

    // #region Encode internal values for "PKCS8ShroudedKeyBag"
    sequence = sequence.then(
        function () {
            return pkcs12.parsedValue.authenticatedSafe.parsedValue.safeContents[0].value.safeBags[0].bagValue.makeInternalValues({
                password: str2ab(password),
                contentEncryptionAlgorithm: {
                    name: "AES-CBC", // OpenSSL can handle AES-CBC only
                    length: 128
                },
                hmacHashAlgorithm: "SHA-1", // OpenSSL can handle SHA-1 only
                iterationCount: 100000
            });
        }
    );
    // #endregion

    // #region Encode internal values for all "SafeContents" firts (create all "Privacy Protection" envelopes)
    sequence = sequence.then(
        function (result) {
            return pkcs12.parsedValue.authenticatedSafe.makeInternalValues({
                safeContents: [
                    {
                        // Empty parameters for first SafeContent since "No Privacy" protection mode there
                    },
                    {
                        password: str2ab(password),
                        contentEncryptionAlgorithm: {
                            name: "AES-CBC", // OpenSSL can handle AES-CBC only
                            length: 128
                        },
                        hmacHashAlgorithm: "SHA-1", // OpenSSL can handle SHA-1 only
                        iterationCount: 100000
                    }
                ]
            });
        }
    );

    // #region Encode internal values for "Integrity Protection" envelope
    sequence = sequence.then(
        function () {
            return pkcs12.makeInternalValues({
                password: str2ab(password),
                iterations: 100000,
                pbkdf2HashAlgorithm: "SHA-256", // OpenSSL can not handle usage of PBKDF2, only PBKDF1
                hmacHashAlgorithm: "SHA-256"
            });
        }
    );

    // #region Save encoded data
    sequence = sequence.then(
        function () {
            var pkcs12AsBlob = new Blob([pkcs12.toSchema().toBER(false)], {type: 'application/x-pkcs12'});
            var downloadLink = document.createElement("a");
            downloadLink.download = "pkijs_pkcs12.p12";
            downloadLink.innerHTML = "Download File";

            downloadLink.href = window.URL.createObjectURL(pkcs12AsBlob);
            downloadLink.onclick = (event)=>{document.body.removeChild(event.target);};
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
            downloadLink.click();
        }
    );
}


text:
<?php namespace Wetcat\Fortie\Providers\Articles;

use Wetcat\Fortie\FortieRequest;
use Wetcat\Fortie\Providers\ProviderBase;
use Wetcat\Fortie\Traits\CountTrait;
use Wetcat\Fortie\Traits\CreateTrait;
use Wetcat\Fortie\Traits\DeleteTrait;
use Wetcat\Fortie\Traits\FetchTrait;
use Wetcat\Fortie\Traits\FindTrait;
use Wetcat\Fortie\Traits\UpdateTrait;

class Provider extends ProviderBase {

  use CountTrait,
      CreateTrait,
      DeleteTrait,
      FetchTrait,
      FindTrait,
      UpdateTrait;

  protected $wrapper = 'Article';
  protected $wrapperGroup = 'Articles';

  protected $attributes = [
    'Url',
    'ArticleNumber',
    'Bulky',
    'ConstructionAccount',
    'Depth',
    'Description',
    'DisposableQuantity',
    'EAN',
    'EUAccount',
    'EUVATAccount',
    'ExportAccount',
    'Height',
    'Housework',
    'HouseworkType',
    'Manufacturer',
    'ManufacturerArticleNumber',
    'Note',
    'PurchaseAccount',
    'PurchasePrice',
    'QuantityInStock',
    'ReservedQuantity',
    'SalesAccount',
    'SalesPrice',
    'StockGoods',
    'StockPlace',
    'StockValue',
    'StockWarning',
    'SupplierName',
    'SupplierNumber',
    'Type',
    'Unit',
    'VAT',
    'WebshopArticle',
    'Weight',
    'Width',
    'Expired',
  ];

  protected $writeable = [
    'ArticleNumber',
    'Bulky',
    'ConstructionAccount',
    'Depth',
    'Description',
    'EAN',
    'EUAccount',
    'EUVATAccount',
    'ExportAccount',
    'Height',
    'Housework',
    'HouseworkType',
    'Manufacturer',
    'ManufacturerArticleNumber',
    'Note',
    'PurchaseAccount',
    'PurchasePrice',
    'QuantityInStock',
    'ReservedQuantity',
    'SalesAccount',
    'StockGoods',
    'StockPlace',
    'StockWarning',
    'SupplierNumber',
    'Type',
    'Unit',
    'VAT',
    'WebshopArticle',
    'Weight',
    'Width',
    'Expired',
  ];

  protected $required_create = [
    'Description',
  ];

  protected $required_update = [
    'ArticleNumber',
  ];

  /**
   * The possible values for filtering the articles.
   *
   * @var array
   */
  protected $available_filters = [
    'active',
    'inactive'
  ];

  /**
   * Override the REST path
   */
  protected $basePath = 'articles';
}


text:
//---------------------------------------------------------------------------
// wscitecm.h
//---------------------------------------------------------------------------

// Old GUID
// {120b94b5-2e6a-4f13-94d0-414bcb64fa0f}
//DEFINE_GUID(CLSID_ShellExtension, 0x120b94b5, 0x2e6a, 0x4f13, 0x94, 0xd0, 0x41, 0x4b, 0xcb, 0x64, 0xfa, 0x0f);

// New GUID since version 1.3.1
// Created to avoid conflict with Notpad++ reusing this code with the GUID above
// {C4ACBD3E-6114-4618-904C-B206ABA9DEB0}
DEFINE_GUID(CLSID_ShellExtension,
            0xc4acbd3e, 0x6114, 0x4618, 0x90, 0x4c, 0xb2, 0x6, 0xab, 0xa9, 0xde, 0xb0);

class CShellExtClassFactory : public IClassFactory {
protected:
  ULONG m_cRef;

public:
  CShellExtClassFactory();
  ~CShellExtClassFactory();

  STDMETHODIMP QueryInterface(REFIID, LPVOID FAR *);
  STDMETHODIMP_(ULONG) AddRef();
  STDMETHODIMP_(ULONG) Release();
  STDMETHODIMP CreateInstance(LPUNKNOWN, REFIID, LPVOID FAR *);
  STDMETHODIMP LockServer(BOOL);
};
typedef CShellExtClassFactory *LPCSHELLEXTCLASSFACTORY;

class CShellExt : public IContextMenu, IShellExtInit {
public:
protected:
  ULONG m_cRef;
  UINT m_cbFiles;
  STGMEDIUM m_stgMedium;
  LPDATAOBJECT m_pDataObj;
  HBITMAP m_hSciteBmp;
  LPMALLOC m_pAlloc;
  TCHAR m_szDllDir [MAX_PATH];

  STDMETHODIMP InvokeSciTE(HWND hParent,
    LPCSTR pszWorkingDir,
    LPCSTR pszCmd,
    LPCSTR pszParam,
    int iShowCmd);

public:
  CShellExt();
  ~CShellExt();

  STDMETHODIMP QueryInterface(REFIID, LPVOID FAR *);
  STDMETHODIMP_(ULONG) AddRef();
  STDMETHODIMP_(ULONG) Release();

  STDMETHODIMP QueryContextMenu(HMENU hMenu,
    UINT indexMenu,
    UINT idCmdFirst,
    UINT idCmdLast,
    UINT uFlags);

  STDMETHODIMP InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi);

  STDMETHODIMP GetCommandString(UINT_PTR idCmd,
    UINT uFlags,
    UINT FAR *reserved,
    LPSTR pszName,
    UINT cchMax);

  STDMETHODIMP Initialize(LPCITEMIDLIST pIDFolder,
    LPDATAOBJECT pDataObj,
    HKEY hKeyID);
};

typedef CShellExt *LPCSHELLEXT;


text:
package com.cinnamon.system;

import com.cinnamon.object.GObject;
import com.cinnamon.object.GObjectFactory;
import com.cinnamon.utils.IndexedFactory;

/**
 *

 *     ComponentFactory is a base class for producing {@link Component}s. This class offers id and version tracking
 *     as well as object pooling for produced Components.
 *

 */
public abstract class ComponentFactory<E extends ComponentFactory.Component, R> extends IndexedFactory<E, R>
{
    /**
     *
Constructor for ComponentFactory.

     *
     * @param resource resource to help assemble {@link Component}s.
     * @param load initial Component capacity.
     * @param growth normalized capacity expansion.
     */
    protected ComponentFactory(R resource, int load, float growth)
    {
        super(resource, load, growth);
    }

    /**
     *

     *     Classes extending Component are meant to be associated with a {@link GObject} such that the Component
     *     not only knows the id and version of its owning GObject but that the GObject may also retrieve the
     *     Component. This latter requirement means that GObject and {@link GObjectFactory} need to be subclassed in
     *     order to integrate new Components.
     *

     */
    public static abstract class Component extends IndexedFactory.Identifiable
    {
        /**
         *
{@link GObject} id constant for {@link ComponentFactory.Component}s that have been abandoned (i.e. no
         * GObject uses them). This occurs when {@link #setGObject(GObject)} is given the value null.

         */
        public static final int NULL = -1;

        // Listener for changes to orphan status
        private OnOrphanChangedListener mOnOrphanChangedListener;

        // Owning GObject's id and version
        private int mOwnerId = NULL;
        private int mOwnerVersion = NULL;

        /**
         *
Gets the owning {@link GObject}'s id.

         *
         * @return owner's id.
         */
        public final int getGObjectId()
        {
            return mOwnerId;
        }

        /**
         *
Gets the owning {@link GObject}'s version.

         *
         * @return owner's version.
         */
        public final int getGObjectVersion()
        {
            return mOwnerVersion;
        }

        /**
         *
Sets the owning {@link GObject}.

         *
         * @param object owner.
         */
        public final void setGObject(GObject object)
        {
            final boolean orphan = isOrphan();
            final boolean statusChanged;

            // Gaining owner
            if (orphan && object != null) {
                mOwnerId = object.getId();
                mOwnerVersion = object.getVersion();
                statusChanged = true;

                // Losing owner
            } else if (!orphan && object == null) {
                mOwnerId = NULL;
                mOwnerVersion = NULL;
                statusChanged = true;
            } else {
                // Didn't gain or lose an owner
                statusChanged = false;
            }

            // Notify orphan listener if there's been a change in orphan status
            if (statusChanged && mOnOrphanChangedListener != null) {
                mOnOrphanChangedListener.onOrphanChanged(getId(), object == null);
            }
        }

        /**
         *
Checks whether or not the Component has orphan status (i.e. has no owning {@link GObject}).

         *
         * @return true if Component has been orphaned.
         */
        public final boolean isOrphan()
        {
            return mOwnerId == NULL && mOwnerVersion == NULL;
        }

        /**
         *
Sets an {@link OnOrphanChangedListener} to be notified of orphan status changes.

         *
         * @param listener OnOrphanChangedListener.
         */
        public final void setOnOrphanChangedListener(OnOrphanChangedListener listener)
        {
            mOnOrphanChangedListener = listener;
        }
    }
}


text:
package com.j256.ormlite.field;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.FIELD})
public @interface DatabaseField
{
  public static final int DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL = 2;
  public static final String DEFAULT_STRING = "__ormlite__ no default value string was specified";
  public static final int NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED = -1;

  public abstract boolean allowGeneratedIdInsert();

  public abstract boolean canBeNull();

  public abstract String columnDefinition();

  public abstract String columnName();

  public abstract DataType dataType();

  public abstract String defaultValue();

  public abstract boolean foreign();

  public abstract boolean foreignAutoCreate();

  public abstract boolean foreignAutoRefresh();

  public abstract String foreignColumnName();

  public abstract String format();

  public abstract boolean generatedId();

  public abstract String generatedIdSequence();

  public abstract boolean id();

  public abstract boolean index();

  public abstract String indexName();

  public abstract int maxForeignAutoRefreshLevel();

  public abstract boolean persisted();

  public abstract Class<? extends DataPersister> persisterClass();

  public abstract boolean throwIfNull();

  public abstract boolean unique();

  public abstract boolean uniqueCombo();

  public abstract boolean uniqueIndex();

  public abstract String uniqueIndexName();

  public abstract String unknownEnumName();

  public abstract boolean useGetSet();

  public abstract boolean version();

  public abstract int width();
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.j256.ormlite.field.DatabaseField
 * JD-Core Version:    0.6.2
 */


text:
package ch3_24;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import ch3_23.Pair;

/**
 * Q:Pair<T>に対するflatMapメソッドを定義することができますか?
 *
 * A:Pairの要素は2個と固定のため、PairをListのようには利用してflatMapは定義できない。
 * flatMapはStream内の要素を受け取りStreamを返すメソッドである。
 * Collectionの中にネストしたCollectionがある場合になどに使える。 Pairを入れ子にした場合、Pair<Paire<T>>となる。
 */
public class Hoge {

	public static void main(String[] args) {
		Pair<Pair<Integer>> hoge = new Pair<Pair<Integer>>(new Pair<Integer>(1, 1), new Pair<Integer>(1, 1));

		// A:streamを以下のように用意すればできる。
		List<Integer> result1 = Stream.of(hoge.first, hoge.second).flatMap((p1) -> {
			return Stream.of(p1.first, p1.second);
		}).collect(Collectors.toList());

		for (Integer i : result1) {
			System.out.println(i);
		}
	}
}


text:
package com.zdc.netconnect;

import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * description:高效地加载大图
 *
 * @author zhaodecang
 * @date 2016-9-21下午3:42:59
 */
public class BitmapLoadUtil {
	/**
	 * 屏幕宽度
	 */
	private static int mScreen_width;
	/**
	 * 屏幕高度
	 */
	private static int mScreen_height;

	/**
	 * 初始化屏幕尺寸大小
	 *
	 * @param context
	 */
	private static void initScreenSize(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display defaultDisplay = wm.getDefaultDisplay();
		Point outSize = new Point();
		defaultDisplay.getSize(outSize);
		mScreen_width = outSize.x;
		mScreen_height = outSize.y;
	}

	/**
	 *
	 * 计算缩放比
	 *
	 * @param context
	 * @param img_width
	 * @param img_height
	 * @return
	 */
	private static int calculaeScale(Context context, int img_width, int img_height) {
		// 初始化
		initScreenSize(context);
		int inSampleSize = 1;// 默认缩放比
		if (img_width > mScreen_width || img_height > mScreen_height) {
			int scale_x = Math.round((float) img_width / mScreen_width);
			int scale_y = Math.round((float) img_height / mScreen_height);
			inSampleSize = Math.max(scale_x, scale_y);
		}
		return inSampleSize;
	}

	/**
	 * 通过计算出一个合适的缩放比加载图片(整体效率最优)
	 *
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap loadBitmapFine(Context context, int resId) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		// 只读取图片属性 避免内存分配
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(context.getResources(), resId, opts);
		// 计算合适的缩放比
		int img_width = opts.outWidth;
		int img_height = opts.outHeight;
		int inSampleSize = calculaeScale(context, img_width, img_height);
		// 设置缩放比
		opts.inSampleSize = inSampleSize;
		Log.i("BitmapLoadUtil", "计算出来的缩放比为:" + inSampleSize);
		// 正真加载图片
		opts.inJustDecodeBounds = false;
		return BitmapFactory.decodeResource(context.getResources(), resId, opts);
	}

	/**
	 * 来自网络:以最省内存的方式读取本地资源的图片(节约时间,加载的是原图)
	 *
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	/**
	 * 尝试加载,不断尝试最佳缩放比(这种方式容易导致oom)
	 *
	 * @param resId
	 * @return
	 */
	public static Bitmap tryLoadBitmap(Context context, int resId) {
		Bitmap bitmap = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		int i = 1;
		for (;;) {
			try {
				opts.inSampleSize = i;
				// 如果当前的压缩比例能够加载图片循环就会退出
				bitmap = BitmapFactory.decodeResource(context.getResources(), resId, opts);
				Log.i("BitmapLoadUtil", "尝试加载成功,缩放比为:" + i);
				break;
			} catch (Error e) {
				// 如果走到异常了就提高压缩比例 继续试验
				// inSampleSize 这个值要取2的幂指数 如果不是2的N次幂 系统也会把这个数转化为最近2的N次幂的值
				i *= 2;
			}
		}
		return bitmap;
	}
}


text:
#import <Foundation/NSKeyedArchiver.h>

#import <AppKit/NSParagraphStyle.h>
#import <AppKit/NSRaise.h>
#import <AppKit/NSTextTab.h>

@implementation NSParagraphStyle

+(NSParagraphStyle *)defaultParagraphStyle {
   static NSParagraphStyle *shared=nil;

   if(shared==nil)
    shared=[self new];

   return shared;
}

+(NSArray *)_defaultTabStops {
   static NSArray *shared=nil;

   if(shared==nil){
    int        i,count=12;
    NSTextTab *tabs[count];

    for(i=0;i<count;i++){
     tabs[i]=[[[NSTextTab alloc] initWithType:NSLeftTabStopType location:(i+1)*28.0] autorelease];
    }
    shared=[[NSArray alloc] initWithObjects:tabs count:count];
   }

   return shared;
}

-(void)_initWithDefaults {
   _writingDirection=NSWritingDirectionLeftToRight;
   _paragraphSpacing=0;
   _paragraphSpacingBefore=0;
   _textBlocks=nil;
   _textLists=nil;
   _headerLevel=0;
   _firstLineHeadIndent=0;
   _headIndent=0;
   _tailIndent=0;
   _alignment=NSLeftTextAlignment;
   _lineBreakMode=NSLineBreakByWordWrapping;
   _minimumLineHeight=0;
   _maximumLineHeight=0;
   _lineHeightMultiple=0;
   _lineSpacing=0;
   _defaultTabInterval=0;
   _tabStops=[[isa _defaultTabStops] retain];
   _hyphenationFactor=0;
   _tighteningFactorForTruncation=0;
}

-initWithCoder:(NSCoder *)coder {
   if([coder allowsKeyedCoding]){
	   _writingDirection = [coder decodeIntForKey: @"BaseWritingDirection"];
	   _paragraphSpacing = [coder decodeFloatForKey: @"ParagraphSpacing"];
	   _paragraphSpacingBefore = [coder decodeFloatForKey: @"ParagraphSpacingBefore"];
	   _textBlocks = [[coder decodeObjectForKey: @"Blocks"] retain];
	   _textLists = [coder decodeObjectForKey: @"Lists"];
	   _headerLevel = [coder decodeIntForKey: @"HeaderLevel"];
	   _firstLineHeadIndent = [coder decodeFloatForKey: @"FirstLineHeadIndent"];
	   _headIndent = [coder decodeFloatForKey: @"HeadIndent"];
	   _tailIndent = [coder decodeFloatForKey: @"TailIndent"];
	   _alignment = [coder decodeIntForKey: @"Alignment"];
	   _lineBreakMode = [coder decodeIntForKey: @"LineBreakMode"];
	   _minimumLineHeight = [coder decodeFloatForKey: @"MinimumLineHeight"];
	   _maximumLineHeight = [coder decodeFloatForKey: @"MaximumLineHeight"];
	   _lineHeightMultiple = [coder decodeFloatForKey: @"LineHeightMultiple"];
	   _lineSpacing = [coder decodeFloatForKey: @"LineSpacing"];
	   _defaultTabInterval = [coder decodeFloatForKey: @"DefaultTabInterval"];
	   _tabStops = [[coder decodeObjectForKey: @"Tabs"] retain];
	   _hyphenationFactor = [coder decodeFloatForKey: @"HyphenationFactor"];
	   _tighteningFactorForTruncation = [coder decodeFloatForKey: @"TighteningFactor"];
   }
   else {
    [NSException raise:NSInvalidArgumentException format:@"-[%@ %s] is not implemented for coder %@",isa,sel_getName(_cmd),coder];
   }

   return self;
}

-init {
   [self _initWithDefaults];
   return self;
}

-initWithParagraphStyle:(NSParagraphStyle *)other {
   _writingDirection=other->_writingDirection;
   _paragraphSpacing=other->_paragraphSpacing;
   _paragraphSpacingBefore=other->_paragraphSpacingBefore;
   _textBlocks=[other->_textBlocks copy];
   _textLists=[other->_textLists copy];
   _headerLevel=other->_headerLevel;
   _firstLineHeadIndent=other->_firstLineHeadIndent;
   _headIndent=other->_headIndent;
   _tailIndent=other->_tailIndent;
   _alignment=other->_alignment;
   _lineBreakMode=other->_lineBreakMode;
   _minimumLineHeight=other->_minimumLineHeight;
   _maximumLineHeight=other->_maximumLineHeight;
   _lineHeightMultiple=other->_lineHeightMultiple;
   _lineSpacing=other->_lineSpacing;
   _defaultTabInterval=other->_defaultTabInterval;
   _tabStops=[other->_tabStops copy];
   _hyphenationFactor=other->_hyphenationFactor;
   _tighteningFactorForTruncation=other->_tighteningFactorForTruncation;
   return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
	if ([coder isKindOfClass: [NSKeyedArchiver class]]) {
		[coder encodeInt: _writingDirection forKey: @"BaseWritingDirection"];
		[coder encodeFloat: _paragraphSpacing forKey: @"ParagraphSpacing"];
		[coder encodeFloat: _paragraphSpacingBefore forKey: @"ParagraphSpacingBefore"];
		[coder encodeObject: _textBlocks forKey: @"Blocks"];
		[coder encodeObject: _textLists forKey: @"Lists"];
		[coder encodeInt: _headerLevel forKey: @"HeaderLevel"];
		[coder encodeFloat: _firstLineHeadIndent forKey: @"FirstLineHeadIndent"];
		[coder encodeFloat: _headIndent forKey: @"HeadIndent"];
		[coder encodeFloat: _tailIndent forKey: @"TailIndent"];
		[coder encodeInt: _alignment forKey: @"Alignment"];
		[coder encodeInt: _lineBreakMode forKey: @"LineBreakMode"];
		[coder encodeFloat: _minimumLineHeight forKey: @"MinimumLineHeight"];
		[coder encodeFloat: _maximumLineHeight forKey: @"MaximumLineHeight"];
		[coder encodeFloat: _lineHeightMultiple forKey: @"LineHeightMultiple"];
		[coder encodeFloat: _lineSpacing forKey: @"LineSpacing"];
		[coder encodeFloat: _defaultTabInterval forKey: @"DefaultTabInterval"];
		[coder encodeObject: _tabStops forKey: @"Tabs"];
		[coder encodeFloat: _hyphenationFactor forKey: @"HyphenationFactor"];
		[coder encodeFloat: _tighteningFactorForTruncation forKey: @"TighteningFactor"];
	} else {
		NSUnimplementedMethod();
	}
}

-(void)dealloc {
   [_textBlocks release];
   [_textLists release];
   [_tabStops release];
   [super dealloc];
}

-copy {
   return [self retain];
}

-copyWithZone:(NSZone *)zone {
   return [self retain];
}

static inline id mutableCopyWithZone(NSParagraphStyle *self,NSZone *zone){
   return [[NSMutableParagraphStyle allocWithZone:zone] initWithParagraphStyle:self];
}

-mutableCopy {
   return mutableCopyWithZone(self,NULL);
}

-mutableCopyWithZone:(NSZone *)zone {
   return mutableCopyWithZone(self,zone);
}

-(NSWritingDirection)baseWritingDirection {
   return _writingDirection;
}

-(float)paragraphSpacing {
   return _paragraphSpacing;
}

-(float)paragraphSpacingBefore {
   return _paragraphSpacingBefore;
}

-(NSArray *)textBlocks {
   return _textBlocks;
}

-(NSArray *)textLists {
   return _textLists;
}

-(int)headerLevel {
   return _headerLevel;
}

-(float)firstLineHeadIndent {
   return _firstLineHeadIndent;
}

-(float)headIndent {
   return _headIndent;
}

-(float)tailIndent {
   return _tailIndent;
}

-(NSTextAlignment)alignment {
   return _alignment;
}

-(NSLineBreakMode)lineBreakMode {
   return _lineBreakMode;
}

-(float)minimumLineHeight {
   return _minimumLineHeight;
}

-(float)maximumLineHeight {
   return _maximumLineHeight;
}

-(float)lineHeightMultiple {
   return _lineHeightMultiple;
}

-(float)lineSpacing {
   return _lineSpacing;
}

-(float)defaultTabInterval {
   return _defaultTabInterval;
}

-(NSArray *)tabStops {
   return _tabStops;
}

-(float)hyphenationFactor {
   return _hyphenationFactor;
}

-(float)tighteningFactorForTruncation {
   return _tighteningFactorForTruncation;
}

- (NSString*)description
{
	NSMutableString* tabsString = [NSMutableString stringWithString: @" (\n"];

	for (NSTextTab* tab in _tabStops) {
		switch ([tab tabStopType]) {
			case NSLeftTabStopType:
				[tabsString appendString: [NSString stringWithFormat: @"%fL", [tab location]]];
				break;
			case NSRightTabStopType:
				[tabsString appendString: [NSString stringWithFormat: @"%fR", [tab location]]];
				break;
			case NSCenterTabStopType:
				[tabsString appendString: [NSString stringWithFormat: @"%fC", [tab location]]];
				break;
			case NSDecimalTabStopType:
				[tabsString appendString: [NSString stringWithFormat: @"%fD", [tab location]]];
				break;
		}
	}
	[tabsString appendString: @")"];

	return [NSString stringWithFormat: @"Alignment %d, LineSpacing %f, ParagraphSpacing %f, "
										@"ParagraphSpacingBefore %f, HeadIndent %f, TailIndent %f, FirstLineHeadIndent %f, "
										@"LineHeight %f/%f, LineHeightMultiple %f, LineBreakMode %d, Tabs %@, "
										@"DefaultTabInterval %f, Blocks %@, Lists %@, BaseWritingDirection %d, "
										@"HyphenationFactor %f, TighteningFactor %f, HeaderLevel %d",
										_alignment, _lineSpacing, _paragraphSpacing, _paragraphSpacingBefore, _headIndent, _firstLineHeadIndent,
										_minimumLineHeight, _maximumLineHeight, _lineHeightMultiple, _lineBreakMode, _tabStops, _defaultTabInterval,
			_textBlocks, _textLists, _writingDirection, _hyphenationFactor, _tighteningFactorForTruncation, _headerLevel];
}

@end


text:
int main(int argc __attribute__((unused)), char **argv __attribute__((unused)))
{
	int ret;
	struct board *b;

	b = get_new_board();
	board_print(b);

	ret = main_loop();
	if (ret) {
		fprintf(stderr, "main_loop exit with error code: %d\n", ret);
		exit(ret);
	}

	return 0;
}


text:
namespace spvtools {
namespace opt {

Pass::Status Workaround1209::Process() {
  bool modified = false;
  modified = RemoveOpUnreachableInLoops();
  return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
}

bool Workaround1209::RemoveOpUnreachableInLoops() {
  bool modified = false;
  for (auto& func : *get_module()) {
    std::list<BasicBlock*> structured_order;
    cfg()->ComputeStructuredOrder(&func, &*func.begin(), &structured_order);

    // Keep track of the loop merges.  The top of the stack will always be the
    // loop merge for the loop that immediately contains the basic block being
    // processed.
    std::stack<uint32_t> loop_merges;
    for (BasicBlock* bb : structured_order) {
      if (!loop_merges.empty() && bb->id() == loop_merges.top()) {
        loop_merges.pop();
      }

      if (bb->tail()->opcode() == spv::Op::OpUnreachable) {
        if (!loop_merges.empty()) {
          // We found an OpUnreachable inside a loop.
          // Replace it with an unconditional branch to the loop merge.
          context()->KillInst(&*bb->tail());
          std::unique_ptr<Instruction> new_branch(
              new Instruction(context(), spv::Op::OpBranch, 0, 0,
                              {{spv_operand_type_t::SPV_OPERAND_TYPE_ID,
                                {loop_merges.top()}}}));
          context()->AnalyzeDefUse(&*new_branch);
          bb->AddInstruction(std::move(new_branch));
          modified = true;
        }
      } else {
        if (bb->GetLoopMergeInst()) {
          loop_merges.push(bb->MergeBlockIdIfAny());
        }
      }
    }
  }
  return modified;
}
}  // namespace opt
}  // namespace spvtools