text:
<?php

namespace Drupal\Tests\webform\Unit\Utility;

use Drupal\webform\Utility\WebformFormHelper;
use Drupal\Tests\UnitTestCase;

/**
 * Tests webform helper utility.
 *
 * @group webform
 *
 * @coversDefaultClass \Drupal\webform\Utility\WebformFormHelper
 */
class WebformFormHelperTest extends UnitTestCase {

  /**
   * Tests WebformFormHelper::cleanupFormStateValues().
   *
   * @param array $values
   *   The array to run through WebformFormHelper::cleanupFormStateValues().
   * @param array $keys
   *   (optional) An array of custom keys to be removed.
   * @param string $expected
   *   The expected result from calling the function.
   *
   * @see WebformFormHelper::cleanupFormStateValues()
   *
   * @dataProvider providerCleanupFormStateValues
   */
  public function testCleanupFormStateValues(array $values, array $keys, $expected) {
    $result = WebformFormHelper::cleanupFormStateValues($values, $keys);
    $this->assertEquals($expected, $result);
  }

  /**
   * Data provider for testCleanupFormStateValues().
   *
   * @see testCleanupFormStateValues()
   */
  public function providerCleanupFormStateValues() {
    $tests[] = [['key' => 'value'], [], ['key' => 'value']];
    $tests[] = [['key' => 'value', 'form_token' => 'ignored'], [], ['key' => 'value']];
    $tests[] = [['key' => 'value', 'form_token' => 'ignored'], ['key'], []];
    return $tests;
  }

  /**
   * Tests WebformFormHelper::flattenElements().
   *
   * @see WebformFormHelper::flattenElements()
   */
  public function testFlattenElements() {
    $elements = [
      'one' => [
        '#title' => 'one',
        'two' => [
          '#title' => 'two',
        ],
      ],
    ];
    $flattenend_elements = WebformFormHelper::flattenElements($elements);

    // Check flattened elements.
    $this->assertEquals($flattenend_elements, [
      'one' => [
        '#title' => 'one',
        'two' => [
          '#title' => 'two',
        ],
      ],
      'two' => [
        '#title' => 'two',
      ],
    ]);

    // Check flattened elements references.
    $elements['one']['#title'] .= '-UPDATED';
    $elements['one']['two']['#title'] .= '-UPDATED';
    $elements['one']['two']['#type'] = 'textfield';

    $this->assertEquals($flattenend_elements, [
      'one' => [
        '#title' => 'one-UPDATED',
        'two' => [
          '#title' => 'two-UPDATED',
          '#type' => 'textfield',
        ],
      ],
      'two' => [
        '#title' => 'two-UPDATED',
        '#type' => 'textfield',
      ],
    ]);

    // Check flattened elements with duplicate keys.
    $elements = [
      'one' => [
        '#title' => 'one',
        'two' => [
          '#title' => 'two-FIRST',
        ],
      ],
      'two' => [
        '#title' => 'two-SECOND',
      ],
    ];
    $flattenend_elements = WebformFormHelper::flattenElements($elements);
    $this->assertEquals($flattenend_elements, [
      'one' => [
        '#title' => 'one',
        'two' => [
          '#title' => 'two-FIRST',
        ],
      ],
      'two' => [
        [
          '#title' => 'two-FIRST',
        ],
        [
          '#title' => 'two-SECOND',
        ],
      ],
    ]);

    // Check flattened elements references with duplicate keys.
    $elements['one']['#title'] .= '-UPDATED';
    $elements['one']['two']['#title'] .= '-UPDATED';
    $elements['one']['two']['#type'] = 'textfield';

    $this->assertEquals($flattenend_elements, [
      'one' => [
        '#title' => 'one-UPDATED',
        'two' => [
          '#title' => 'two-FIRST-UPDATED',
          '#type' => 'textfield',
        ],
      ],
      'two' => [
        [
          '#title' => 'two-FIRST-UPDATED',
          '#type' => 'textfield',
        ],
        [
          '#title' => 'two-SECOND',
        ],
      ],
    ]);
  }

}


text:
using UnityEngine;
using System.Collections;

public class Navig : MonoBehaviour {

	NavMeshAgent nav;
	GameObject target;
	// Use this for initialization
	void Start () {
		nav = GetComponent<NavMeshAgent> ();
		target = GameObject.FindWithTag ("Player");
		//ComponentManager<CManagerTest>.instance.Get(target).doit();
	}

	// Update is called once per frame
	void Update () {
		nav.SetDestination (target.transform.position);

	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "erasure_code.h"

void gf_vect_dot_prod(int len, int vlen, unsigned char *v,
		      unsigned char **src, unsigned char *dest)
{
	gf_vect_dot_prod_base(len, vlen, v, src, dest);
}

void gf_vect_mad(int len, int vec, int vec_i,
		 unsigned char *v, unsigned char *src, unsigned char *dest)
{
	gf_vect_mad_base(len, vec, vec_i, v, src, dest);

}

void ec_encode_data(int len, int srcs, int dests, unsigned char *v,
		    unsigned char **src, unsigned char **dest)
{
	ec_encode_data_base(len, srcs, dests, v, src, dest);
}

void ec_encode_data_update(int len, int k, int rows, int vec_i, unsigned char *v,
			   unsigned char *data, unsigned char **dest)
{
	ec_encode_data_update_base(len, k, rows, vec_i, v, data, dest);
}

int gf_vect_mul(int len, unsigned char *a, void *src, void *dest)
{
	gf_vect_mul_base(len, a, (unsigned char *)src, (unsigned char *)dest);
	return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using XgxFrameWork.CacheLayer.RedisCacheManager;
using Dos.Model;

namespace XgxFrameWork.Presentation.Client.ConsoleUI
{
    class Program
    {
        static void Main(string[] args)
        {

            #region 生成接口拥有的方法
            var type = typeof (IDal<AppendCC>);
            var gettype = type.GetMethods();

            StringBuilder Methods = new StringBuilder();
            string returnType= string.Empty;
            string classType = string.Empty;
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder stringBuilder2 = new StringBuilder();
            foreach (var VARIABLE in gettype)
            {
                returnType = VARIABLE.ReturnType.ToString()

                                .Replace(typeof(List<>).Namespace+".", string.Empty)
                                .Replace(typeof(int).Namespace + ".", string.Empty)
                                .Replace(typeof(AppendCC).Namespace+".",string.Empty)
                                .Replace("`1", "")
                                .Replace("[", "<")
                                .Replace("]", ">");

                if (VARIABLE.IsPublic)
                {
                    classType = "Public ";
                }
                if (VARIABLE.IsPrivate)
                {
                    classType = "Public ";
                }
                if (VARIABLE.IsStatic)
                {
                    classType += " Static";
                }
                var Parameters = VARIABLE.GetParameters();
                foreach (var VARIABLEP in Parameters)
                {
                        stringBuilder.Append(",");
                        stringBuilder.Append(
                            VARIABLEP.ToString()
                               .Replace(typeof(List<>).Namespace + ".", string.Empty)
                                .Replace(typeof(int).Namespace + ".", string.Empty)
                                .Replace(typeof(AppendCC).Namespace + ".", string.Empty)
                                .Replace("`1", "")
                                .Replace("[", "<")
                                .Replace("]", ">"));

                }
                if (Parameters.Length > 0)
                {
                    stringBuilder.Remove(0, 1);

                }
                else
                {
                    stringBuilder.Clear();
                }

                stringBuilder2.Append(classType).Append(returnType).Append(" ").Append(VARIABLE.Name).Append("(").Append(stringBuilder).Append(")");
                stringBuilder.Clear();
                stringBuilder2.AppendLine();
                stringBuilder2.AppendLine("{");
                stringBuilder2.AppendLine("     throw new NotImplementedException();");
                stringBuilder2.AppendLine("}");
                Methods.Append(stringBuilder2);

                stringBuilder2.Clear();

            }

            #endregion
        }
        public class MyClass
        {

            public void a()
            {
                #region 生成接口拥有的方法
                var type = typeof(IDal<AppendCC>);
                var gettype = type.GetMethods();

                StringBuilder Methods = new StringBuilder();
                string returnType = string.Empty;
                string classType = string.Empty;
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder2 = new StringBuilder();
                foreach (var VARIABLE in gettype)
                {
                    returnType = VARIABLE.ReturnType.ToString()

                                    .Replace(typeof(List<>).Namespace + ".", string.Empty)
                                    .Replace(typeof(int).Namespace + ".", string.Empty)
                                    .Replace(typeof(AppendCC).Namespace + ".", string.Empty)
                                    .Replace("`1", "")
                                    .Replace("[", "<")
                                    .Replace("]", ">");

                    if (VARIABLE.IsPublic)
                    {
                        classType = "Public ";
                    }
                    if (VARIABLE.IsPrivate)
                    {
                        classType = "Public ";
                    }
                    if (VARIABLE.IsStatic)
                    {
                        classType += " Static";
                    }
                    var Parameters = VARIABLE.GetParameters();
                    foreach (var VARIABLEP in Parameters)
                    {
                        stringBuilder.Append(",");
                        stringBuilder.Append(
                            VARIABLEP.ToString()
                               .Replace(typeof(List<>).Namespace + ".", string.Empty)
                                .Replace(typeof(int).Namespace + ".", string.Empty)
                                .Replace(typeof(AppendCC).Namespace + ".", string.Empty)
                                .Replace("`1", "")
                                .Replace("[", "<")
                                .Replace("]", ">"));

                    }
                    if (Parameters.Length > 0)
                    {
                        stringBuilder.Remove(0, 1);

                    }
                    else
                    {
                        stringBuilder.Clear();
                    }

                    stringBuilder2.Append(classType).Append(returnType).Append(" ").Append(VARIABLE.Name).Append("(").Append(stringBuilder).Append(")");
                    stringBuilder.Clear();
                    stringBuilder2.AppendLine();
                    stringBuilder2.AppendLine("{");
                    stringBuilder2.AppendLine("     throw new NotImplementedException();");
                    stringBuilder2.AppendLine("}");
                    Methods.Append(stringBuilder2);

                    stringBuilder2.Clear();

                }

                #endregion

            }
        }
    }
}


text:
title:  Kain Og Arfleifð Hans
date:  09/04/2022
---

### Lesefni vikunnar
1Mós 4; Heb 11.4; Mík 6.7; Jes 1.11; 1Kor 10.13; 1Jóh 3.12; 1Mós 5; 1Mós 6.1-5.

>
Minnistexti

> "Er ekki svo að þú getir verið upplitsdjarfur ef þú gerir rétt, en gerir þú rangt þá liggur syndin við dyrnar? Hún girnist þig en þú getur sigrast á henni" (1Mós 4.7).

Eftir frásögnina um syndafallið og brottrekstur Adams og Evu úr aldingarðinum fjallar 1. Mósebók aðallega um fæðingar og dauða sem uppfylla spádóma Guðs í fyrstu köflunum. Þriðji og fjórði kaflinn eru hliðstæðir og innihalda mörg sameiginleg þemu og orð: lýsingin á syndinni (1Mós 3.6-8 og 1Mós 4.8), bölvanir tengdar jörðinni (1Mós 3.17 og 1Mós 4.11) og brottrekstur Adams og Evu (1Mós 3.24 og 1Mós 4.12, 16).

Hlutverk þessara hliðstæðna er að beina athyglinni að uppfyllingu þess sem á undan fór, þeim spádómum sem Guð gaf Adam og Evu eftir syndafallið. Fyrsti atburðurinn eftir brottrekstur Adams er fullur vonar: það var fæðing fyrsta sonarins sem Eva taldi vera uppfyllingu fyrirheitsins sem hún heyrði í spádóminum um Messías (1Mós 3.15). Hún taldi jafnvel að hann gæti verið hinn fyrirheitni Messías.

Næstu viðburðirnir eru glæpur Kains og glæpur Lameks, stytting æviskeiðins og aukning illskunnar, en þeir eru allir uppfylling bölvunarinnar í þriðja kaflanum.

En þrátt fyrir allt þetta er ekki úti um vonina!


text:
package org.antlr.codebuff.gui;

import javax.swing.*;
import java.awt.*;

public class BuffScope {
	private JSplitPane codeAndResultsSplitPane;
	private JSplitPane origVsBuffedSplitPane;
	protected JPanel overallPanel;
	protected JTextArea injectNLConsole;
	protected JTextPane origTextPane;
	protected JTextPane formattedTextPane;
	public JTextArea alignConsole;
	public JTabbedPane analysisTabbedPane;
	public JPanel injectNLTab;
	public JPanel alignTab;

	public JTextArea getInjectNLConsole() {
		return injectNLConsole;
	}

	public JTextPane getFormattedTextPane() {
		return formattedTextPane;
	}

	public JTextPane getOrigTextPane() {
		return origTextPane;
	}

	private void createUIComponents() {
		// TODO: place custom component creation code here
	}

	{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
		$$$setupUI$$$();
	}

	/**
	 * Method generated by IntelliJ IDEA GUI Designer
	 * >>> IMPORTANT!! <<<
	 * DO NOT edit this method OR call it in your code!
	 *
	 * @noinspection ALL
	 */
	private void $$$setupUI$$$() {
		overallPanel = new JPanel();
		overallPanel.setLayout(new BorderLayout(0, 0));
		overallPanel.setPreferredSize(new Dimension(800, 800));
		codeAndResultsSplitPane = new JSplitPane();
		codeAndResultsSplitPane.setContinuousLayout(true);
		codeAndResultsSplitPane.setOrientation(0);
		codeAndResultsSplitPane.setResizeWeight(0.5);
		overallPanel.add(codeAndResultsSplitPane, BorderLayout.CENTER);
		origVsBuffedSplitPane = new JSplitPane();
		origVsBuffedSplitPane.setContinuousLayout(true);
		origVsBuffedSplitPane.setDividerLocation(400);
		origVsBuffedSplitPane.setResizeWeight(0.0);
		codeAndResultsSplitPane.setLeftComponent(origVsBuffedSplitPane);
		final JPanel panel1 = new JPanel();
		panel1.setLayout(new BorderLayout(0, 0));
		origVsBuffedSplitPane.setLeftComponent(panel1);
		final JLabel label1 = new JLabel();
		label1.setHorizontalAlignment(0);
		label1.setText("Original source");
		panel1.add(label1, BorderLayout.NORTH);
		final JScrollPane scrollPane1 = new JScrollPane();
		panel1.add(scrollPane1, BorderLayout.CENTER);
		origTextPane = new JTextPane();
		origTextPane.setEditable(false);
		origTextPane.setMinimumSize(new Dimension(200, 100));
		origTextPane.setText("Buffed text");
		scrollPane1.setViewportView(origTextPane);
		final JPanel panel2 = new JPanel();
		panel2.setLayout(new BorderLayout(0, 0));
		origVsBuffedSplitPane.setRightComponent(panel2);
		final JLabel label2 = new JLabel();
		label2.setHorizontalAlignment(0);
		label2.setText("Formatted output");
		panel2.add(label2, BorderLayout.NORTH);
		final JScrollPane scrollPane2 = new JScrollPane();
		panel2.add(scrollPane2, BorderLayout.CENTER);
		formattedTextPane = new JTextPane();
		formattedTextPane.setEditable(false);
		formattedTextPane.setMinimumSize(new Dimension(200, 100));
		formattedTextPane.setText("original");
		scrollPane2.setViewportView(formattedTextPane);
		analysisTabbedPane = new JTabbedPane();
		codeAndResultsSplitPane.setRightComponent(analysisTabbedPane);
		injectNLTab = new JPanel();
		injectNLTab.setLayout(new BorderLayout(0, 0));
		analysisTabbedPane.addTab("Inject \\n", injectNLTab);
		final JScrollPane scrollPane3 = new JScrollPane();
		scrollPane3.setVerticalScrollBarPolicy(20);
		injectNLTab.add(scrollPane3, BorderLayout.CENTER);
		injectNLConsole = new JTextArea();
		injectNLConsole.setEditable(false);
		scrollPane3.setViewportView(injectNLConsole);
		alignTab = new JPanel();
		alignTab.setLayout(new BorderLayout(0, 0));
		analysisTabbedPane.addTab("Alignment", alignTab);
		final JScrollPane scrollPane4 = new JScrollPane();
		alignTab.add(scrollPane4, BorderLayout.CENTER);
		alignConsole = new JTextArea();
		scrollPane4.setViewportView(alignConsole);
	}

	/**
	 * @noinspection ALL
	 */
	public JComponent $$$getRootComponent$$$() {
		return overallPanel;
	}
}


text:
<?php

namespace Acme\FilmsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GenreType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
//            ->add('films')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\FilmsBundle\Entity\Genre'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'genre';
    }
}


text:
        Push
        <button class='btn btn-default' ng-click="pushMessage1Endpoints()" style="margin-bottom: 2em;">Message 1 - Endpoints</button>
        <button class='btn btn-default' ng-click="pushMessage2Endpoint()" style="margin-bottom: 2em;">Push Message 2 - Endpoint Update</button>

    <gb-endpoints></gb-endpoints>


text:
#region License

#endregion

namespace Spring.IocQuickStart.AppContext
{
	/// <summary>
	/// Contain keys for localization
	/// </summary>
	public class Keys
	{
        public static string HELLO_MESSAGE = "HelloMessage";

        public static string FEMALE_GREETING = "FemaleGreeting";

        public static string BUBBLECHAMBER = "bubblechamber";

		public Keys()
		{
		}
	}
}


text:
'use strict';

const chai = require('chai'),
  expect = chai.expect,
  Support = require('../support'),
  DataTypes = require('../../../lib/data-types');

describe(Support.getTestDialectTeaser('Model'), () => {
  beforeEach(function() {
    this.User = this.sequelize.define('User', {
      username: DataTypes.STRING,
      age: DataTypes.INTEGER
    });
    this.Project = this.sequelize.define('Project', {
      name: DataTypes.STRING
    });

    this.User.hasMany(this.Project);
    this.Project.belongsTo(this.User);

    return this.sequelize.sync({force: true});
  });

  describe('count', () => {
    beforeEach(function() {
      return this.User.bulkCreate([
        {username: 'boo'},
        {username: 'boo2'}
      ]).then(() => {
        return this.User.findOne();
      }).then(user => {
        return user.createProject({
          name: 'project1'
        });
      });
    });

    it('should count rows', function() {
      return expect(this.User.count()).to.eventually.equal(2);
    });

    it('should support include', function() {
      return expect(this.User.count({
        include: [{
          model: this.Project,
          where: {
            name: 'project1'
          }
        }]
      })).to.eventually.equal(1);
    });

    it('should return attributes', function() {
      return this.User.create({
        username: 'valak',
        createdAt: (new Date()).setFullYear(2015)
      })
        .then(() =>
          this.User.count({
            attributes: ['createdAt'],
            group: ['createdAt']
          })
        )
        .then(users => {
          expect(users.length).to.be.eql(2);

          // have attributes
          expect(users[0].createdAt).to.exist;
          expect(users[1].createdAt).to.exist;
        });
    });

    it('should not return NaN', function() {
      return this.sequelize.sync({ force: true })
        .then(() =>
          this.User.bulkCreate([
            { username: 'valak', age: 10},
            { username: 'conjuring', age: 20},
            { username: 'scary', age: 10}
          ])
        )
        .then(() =>
          this.User.count({
            where: { age: 10 },
            group: ['age'],
            order: ['age']
          })
        )
        .then(result => {
          expect(parseInt(result[0].count)).to.be.eql(2);
          return this.User.count({
            where: { username: 'fire' }
          });
        })
        .then(count => {
          expect(count).to.be.eql(0);
          return this.User.count({
            where: { username: 'fire' },
            group: 'age'
          });
        })
        .then(count => {
          expect(count).to.be.eql([]);
        });
    });

    it('should be able to specify column for COUNT()', function() {
      return this.sequelize.sync({ force: true })
        .then(() =>
          this.User.bulkCreate([
            { username: 'ember', age: 10},
            { username: 'angular', age: 20},
            { username: 'mithril', age: 10}
          ])
        )
        .then(() =>
          this.User.count({
            col: 'username'
          })
        )
        .then(count => {
          expect(parseInt(count)).to.be.eql(3);
          return this.User.count({
            col: 'age',
            distinct: true
          });
        })
        .then(count => {
          expect(parseInt(count)).to.be.eql(2);
        });
    });

    it('should be able to use where clause on included models', function() {
      const queryObject = {
        col: 'username',
        include: [this.Project],
        where: {
          '$Projects.name$': 'project1'
        }
      };
      return this.User.count(queryObject).then(count => {
        expect(parseInt(count)).to.be.eql(1);
        queryObject.where['$Projects.name$'] = 'project2';
        return this.User.count(queryObject);
      }).then(count => {
        expect(parseInt(count)).to.be.eql(0);
      });
    });

    it('should be able to specify column for COUNT() with includes', function() {
      return this.sequelize.sync({ force: true }).then(() =>
        this.User.bulkCreate([
          { username: 'ember', age: 10},
          { username: 'angular', age: 20},
          { username: 'mithril', age: 10}
        ])
      ).then(() =>
        this.User.count({
          col: 'username',
          distinct: true,
          include: [this.Project]
        })
      ).then(count => {
        expect(parseInt(count)).to.be.eql(3);
        return this.User.count({
          col: 'age',
          distinct: true,
          include: [this.Project]
        });
      }).then(count => expect(parseInt(count)).to.be.eql(2));
    });

  });
});


text:
package org.openehealth.ipf.commons.ihe.xds.core.validate;

import static org.junit.Assert.*;

import org.junit.Test;
import org.openehealth.ipf.commons.ihe.xds.core.validate.PidValidator;
import org.openehealth.ipf.commons.ihe.xds.core.validate.XDSMetaDataException;

/**
 * Tests for {@link PidValidator}.
 * @author Jens Riemschneider
 */
public class PidValidatorTest {
    private static final PidValidator validator = new PidValidator();

    @Test
    public void testValidateGoodCases() throws XDSMetaDataException {
        validator.validate("PID-3|");
        validator.validate("PID-3|something");
        validator.validate("PID-44|something");
    }

    @Test
    public void testValidateBadCases() throws XDSMetaDataException {
        assertFails("");
        assertFails("PID-N|something");
        assertFails("PID-0|something");
        assertFails("PID-|something");
        assertFails("POD-3|something");
        assertFails("PI-3|something");
        assertFails("PID-3");
        assertFails("PID-2|something");
        assertFails("PID-4|something");
        assertFails("PID-12|something");
        assertFails("PID-19|something");
    }

    private static void assertFails(String value) {
        try {
            validator.validate(value);
            fail("Expected exception: " + XDSMetaDataException.class + " for " + value);
        } catch (XDSMetaDataException e) {
            // Expected
        }
    }
}


text:
import {
  Component,
  OnInit,
  ViewEncapsulation
} from '@angular/core';

/**
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.Emulated,
  styleUrls: [
    './app.component.css'
  ],
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  constructor() {}

  public ngOnInit() {}

  onActivate(e, outlet){
     window.scrollTo(0, 0);
  }
}

/**
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */


text:
libgdx + artemis-odb based java project, focused on creation of a new game engine to learn and experiment

Uses a modified setup of https://github.com/DaanVanYperen/libgdx-artemis-quickstart


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require File.dirname(__FILE__) + '/../../../../lib/dpkg-tools/package/gem/gem_format'

describe DpkgTools::Package::Gem::GemFormat do
  before(:each) do
    klass = Class.new
    klass.send(:include, DpkgTools::Package::Gem::GemFormat)
    @module = klass.new
  end

  describe "creating Gem::Format objects" do
    it "should be able to turn a byte string of a gem into a Gem::Format" do
      StringIO.expects(:new).with('gem_byte_string').returns(:string_io)
      Gem::Format.expects(:from_io).with(:string_io)

      @module.format_from_string('gem_byte_string')
    end

    it "should be able to turn an old-format gem's byte string into a Gem::OldFormat" do
      StringIO.expects(:new).with(anything).returns(:string_io)
      Gem::OldFormat.expects(:from_io).with(:string_io)

      @module.format_from_string(File.read(File.dirname(__FILE__) + '/../../../fixtures/BlueCloth-1.0.0.gem'))
    end
  end
end


text:
require(["helper/lazysizes.min"], function(lazySizes) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});


text:
export class Logger {
     public
}

//// [parser509546.js]
"use strict";
exports.__esModule = true;
var Logger = (function () {
    function Logger() {
    }
    return Logger;
}());
exports.Logger = Logger;


text:
module Raven
  module Transports
    class Transport
      attr_accessor :configuration

      def initialize(configuration)
        @configuration = configuration
      end

      def send_event # (auth_header, data, options = {})
        raise NotImplementedError, 'Abstract method not implemented'
      end
    end
  end
end

require "raven/transports/dummy"
require "raven/transports/http"
require "raven/transports/stdout"


text:
package scuff.concurrent

import scuff._
import scala.concurrent._
import scala.util.Random

class RandomDelayExecutionContext(exeCtx: ExecutionContext) extends ExecutionContext {

  def execute(runnable: Runnable) = exeCtx execute new Runnable {
    def run(): Unit = {
      if (Random.nextBoolean()) {
        val delay = Random.nextBetween(1, 51)
        Thread sleep delay
      }
      runnable.run()
    }
  }

  def reportFailure(th: Throwable) = exeCtx reportFailure th

}

object RandomDelayExecutionContext
  extends RandomDelayExecutionContext(ExecutionContext.global)


text:
package file.server.service;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.filters.Caption;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sun.jersey.api.NotFoundException;

import file.server.model.bean.Metadata;
import file.server.model.bean.Revision;
import file.server.model.dao.MetadataDAO;
import file.server.model.dao.RevisionDAO;

@Service
public class FileService {

	@Autowired
	private MetadataDAO metadataDAO;

	@Autowired
	private RevisionDAO revisionDAO;

	private Log log = LogFactory.getLog(FileService.class);

	private static List<String> canPutWatermark;

	/**
	 * Upload file, if this file already exists and overwrite is true, then a
	 * new revision of file will be generated
	 *
	 * @param file
	 * @param metadata
	 * @param overwrite2
	 * @return
	 */
	public Metadata upload(InputStream file, Metadata metadata, boolean draft,  boolean overwrite)
			throws Exception {

		Metadata existsMeta = metadataDAO.findByPathAndName(metadata.getPath(),
				metadata.getName());

		if (existsMeta == null) {
			metadata.createRevision();
			metadataDAO.insert(metadata);
			revisionDAO.insert(metadata.createRevision());
			metadata.updateCurrentRevision();
			metadataDAO.update(metadata);
		} else if (overwrite) {
			revisionDAO.loadRevisions(existsMeta);
			revisionDAO.insert(existsMeta.createRevision());
			existsMeta.updateCurrentRevision();
			metadataDAO.update(existsMeta);

			metadata = existsMeta;
		} else {
			// nothing to do
			throw new FileNotFoundException();
		}

		// save file
		String pathToSaveFile = GedFileUtil.getPathById(metadata.getCurrentRevision());
		File fileToSave = new File(pathToSaveFile);
		writeToFile(file, fileToSave);

		if(draft && canPutWaterMark(metadata)) {
			putWaterMark(fileToSave,metadata);
		}

		return metadata;

	}

	private void putWaterMark(File file,Metadata metadata) throws IOException {

		BufferedImage bufferedImage = ImageIO.read(file);

		// Set up the caption properties
		String caption = "RASCUNHO";
		Font font = new Font("Monospaced", Font.PLAIN, 100);
		Color c = Color.GRAY;
		float opacity = 0.6f;
		Position[] positions = {Positions.TOP_LEFT,Positions.CENTER,Positions.BOTTOM_RIGHT};
		int insetPixels = 0;

		// Apply caption to the image
		Builder<BufferedImage> builder = Thumbnails.of(bufferedImage).size(bufferedImage.getHeight(),bufferedImage.getWidth()).outputFormat(metadata.getFileExtension());

		for(Position position: positions) {
			builder.addFilter(new Caption(caption, font, c, opacity, position, insetPixels));
		}
		BufferedImage result = builder.asBufferedImage();

		ImageIO.write(result, metadata.getFileExtension(), file);
	}

	private boolean canPutWaterMark(Metadata metadata) {
		return metadata.getMimeType().startsWith("image/");
	}

	/**
	 * Load file
	 *
	 * @param id
	 * @param revision
	 * @return
	 * @throws Exception
	 */
	public Metadata load(Long id, Long revision) throws Exception {
		Metadata retVal = metadataDAO.get(id);
		Revision rev = null;
		File file = null;
		Long revisionId;

		if(retVal != null) {

			//if sent revision and thats not the current revision, then load that revision
			if(revision > 0 && retVal.getCurrentRevision() != revision) {
				rev = revisionDAO.get(revision);
				if(rev.getMetadataId() == retVal.getId()) {
					revisionId = rev.getId();
				} else {
					throw new NotFoundException("invalid revision");
				}

			} else {
				revisionId = retVal.getCurrentRevision();
			}

			file = new File(GedFileUtil.getPathById(revisionId));
			retVal.setFile(file);
		}

		return retVal;
	}

	public Metadata getRevisions(long id) throws Exception {

		Metadata metadata = metadataDAO.get(id);
		revisionDAO.loadRevisions(metadata);

		return metadata;
	}

	private void writeToFile(InputStream uploadedInputStream,	File uploadedFileLocation) {

		try {

			uploadedFileLocation.getParentFile().mkdirs();
			IOUtils.copy(uploadedInputStream, FileUtils.openOutputStream(uploadedFileLocation));

		} catch (IOException e) {
			String msg = String.format("Can't write file to %s.",uploadedFileLocation.getAbsolutePath());
			log.error(msg,e);
			throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
		}

	}

	public List<Metadata> loadByPath(String path) throws Exception {
		return metadataDAO.findByPath(path);
	}

}


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content_shell_apk;

import org.chromium.base.CommandLine;
import org.chromium.base.PathUtils;
import org.chromium.content.app.ContentApplication;

/**
 * Entry point for the content shell application.  Handles initialization of information that needs
 * to be shared across the main activity and the child services created.
 */
public class ContentShellApplication extends ContentApplication {

    public static final String COMMAND_LINE_FILE = "/data/local/tmp/content-shell-command-line";
    private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "content_shell";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void initializeLibraryDependencies() {
        PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX, this);
    }

    @Override
    public void initCommandLine() {
        if (!CommandLine.isInitialized()) {
            CommandLine.initFromFile(COMMAND_LINE_FILE);
        }
    }

}


text:
require 'spec_helper'

describe JIRA::Resource::Issue do

  class JIRAResourceDelegation < SimpleDelegator # :nodoc:
  end

  let(:client) do
    client = double(options: {rest_base_path: '/jira/rest/api/2'}  )
    allow(client).to receive(:Field).and_return(JIRA::Resource::FieldFactory.new(client))
    allow(client).to receive(:cache).and_return(OpenStruct.new)
    client
  end

  describe "#respond_to?" do
    describe "when decorated by SimpleDelegator" do
      before(:each) do
        response = double()
        allow(response).to receive(:body).and_return('{"key":"foo","id":"101"}')
        allow(JIRA::Resource::Issue).to receive(:collection_path).and_return('/jira/rest/api/2/issue')
        allow(client).to receive(:get).with('/jira/rest/api/2/issue/101').
          and_return(response)

        issue = JIRA::Resource::Issue.find(client,101)
        @decorated = JIRAResourceDelegation.new( issue )
      end
      it "responds to key" do
        expect(@decorated.respond_to?(:key)).to eq(true)
      end
      it "does not raise an error" do
        expect {
          @issue.respond_to?(:project)
        }.not_to raise_error
      end
    end
  end

  it "should find all issues" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues":[{"id":"1","summary":"Bugs Everywhere"}]}')
    expect(client).to receive(:get).with('/jira/rest/api/2/search?expand=transitions.fields').
      and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with({"id"=>"1","summary"=>"Bugs Everywhere"})

    issues = JIRA::Resource::Issue.all(client)
  end

  it "should find an issue by key or id" do
    response = double()

    allow(response).to receive(:body).and_return('{"key":"foo","id":"101"}')
    allow(JIRA::Resource::Issue).to receive(:collection_path).and_return('/jira/rest/api/2/issue')
    expect(client).to receive(:get).with('/jira/rest/api/2/issue/foo').
      and_return(response)
    expect(client).to receive(:get).with('/jira/rest/api/2/issue/101').
      and_return(response)

    issue_from_id = JIRA::Resource::Issue.find(client,101)
    issue_from_key = JIRA::Resource::Issue.find(client,'foo')

    expect(issue_from_id.attrs).to eq(issue_from_key.attrs)
  end

  it "should search an issue with a jql query string" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues": {"key":"foo"}}')
    expect(client).to receive(:get).with('/jira/rest/api/2/search?jql=foo+bar').
      and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with(["key", "foo"]).and_return('')

    expect(JIRA::Resource::Issue.jql(client,'foo bar')).to eq([''])
  end

  it "should search an issue with a jql query string and fields" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues": {"key":"foo"}}')
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/search?jql=foo+bar&fields=foo,bar')
      .and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with(["key", "foo"]).and_return('')

    expect(JIRA::Resource::Issue.jql(client, 'foo bar', fields: ['foo','bar'])).to eq([''])
  end

  it "should search an issue with a jql query string, start at, and maxResults" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues": {"key":"foo"}}')
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/search?jql=foo+bar&startAt=1&maxResults=3')
      .and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with(["key", "foo"]).and_return('')

    expect(JIRA::Resource::Issue.jql(client,'foo bar', start_at: 1, max_results: 3)).to eq([''])
  end

  it "should search an issue with a jql query string and maxResults equals zero and should return the count of tickets" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"total": 1, "issues": []}')
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/search?jql=foo+bar&maxResults=0')
      .and_return(response)

    expect(JIRA::Resource::Issue.jql(client,'foo bar', max_results: 0)).to eq(1)
  end

  it "should search an issue with a jql query string and string expand" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues": {"key":"foo"}}')
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/search?jql=foo+bar&expand=transitions')
      .and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with(["key", "foo"]).and_return('')

    expect(JIRA::Resource::Issue.jql(client,'foo bar', expand: 'transitions')).to eq([''])
  end

  it "should search an issue with a jql query string and array expand" do
    response = double()
    issue = double()

    allow(response).to receive(:body).and_return('{"issues": {"key":"foo"}}')
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/search?jql=foo+bar&expand=transitions')
      .and_return(response)
    expect(client).to receive(:Issue).and_return(issue)
    expect(issue).to receive(:build).with(["key", "foo"]).and_return('')

    expect(JIRA::Resource::Issue.jql(client,'foo bar', expand: %w(transitions))).to eq([''])
  end

  it 'should return meta data available for editing an issue' do
    subject = JIRA::Resource::Issue.new(client, :attrs => {'fields' => {'key' =>'TST=123'}})
    response = double()

    allow(response).to receive(:body).and_return(
      '{"fields":{"summary":{"required":true,"name":"Summary","operations":["set"]}}}'
    )
    expect(client).to receive(:get)
      .with('/jira/rest/api/2/issue/TST=123/editmeta')
      .and_return(response)

    expect(subject.editmeta).to eq({'summary' => {'required' => true, 'name' => 'Summary', 'operations' => ['set']}})
  end

  it "provides direct accessors to the fields" do
    subject = JIRA::Resource::Issue.new(client, :attrs => {'fields' => {'foo' =>'bar'}})
    expect(subject).to respond_to(:foo)
    expect(subject.foo).to eq('bar')
  end

  describe "relationships" do
    subject {
      JIRA::Resource::Issue.new(client, :attrs => {
        'id' => '123',
        'fields' => {
          'reporter'    => {'foo' => 'bar'},
          'assignee'    => {'foo' => 'bar'},
          'project'     => {'foo' => 'bar'},
          'priority'    => {'foo' => 'bar'},
          'issuetype'   => {'foo' => 'bar'},
          'status'      => {'foo' => 'bar'},
          'components'  => [{'foo' => 'bar'}, {'baz' => 'flum'}],
          'versions'    => [{'foo' => 'bar'}, {'baz' => 'flum'}],
          'comment'     => { 'comments' => [{'foo' => 'bar'}, {'baz' => 'flum'}]},
          'attachment'  => [{'foo' => 'bar'}, {'baz' => 'flum'}],
          'worklog'     => { 'worklogs' => [{'foo' => 'bar'}, {'baz' => 'flum'}]},
        }
      })
    }

    it "has the correct relationships" do
      expect(subject).to have_one(:reporter, JIRA::Resource::User)
      expect(subject.reporter.foo).to eq('bar')

      expect(subject).to have_one(:assignee, JIRA::Resource::User)
      expect(subject.assignee.foo).to eq('bar')

      expect(subject).to have_one(:project, JIRA::Resource::Project)
      expect(subject.project.foo).to eq('bar')

      expect(subject).to have_one(:issuetype, JIRA::Resource::Issuetype)
      expect(subject.issuetype.foo).to eq('bar')

      expect(subject).to have_one(:priority, JIRA::Resource::Priority)
      expect(subject.priority.foo).to eq('bar')

      expect(subject).to have_one(:status, JIRA::Resource::Status)
      expect(subject.status.foo).to eq('bar')

      expect(subject).to have_many(:components, JIRA::Resource::Component)
      expect(subject.components.length).to eq(2)

      expect(subject).to have_many(:comments, JIRA::Resource::Comment)
      expect(subject.comments.length).to eq(2)

      expect(subject).to have_many(:attachments, JIRA::Resource::Attachment)
      expect(subject.attachments.length).to eq(2)

      expect(subject).to have_many(:versions, JIRA::Resource::Version)
      expect(subject.attachments.length).to eq(2)

      expect(subject).to have_many(:worklogs, JIRA::Resource::Worklog)
      expect(subject.worklogs.length).to eq(2)
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObjectTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <layouts>
        <layout>EDA Incident Layout</layout>
        <sections>
            項目

Fields

        </sections>
        <sections>
            カスタムリンク

Custom Links

        </sections>
    </layouts>
</CustomObjectTranslation>


text:
module SalesLeadx
  module SalesLeadsHelper
  end
end


text:
package io.virtdata.ast;

public class Assignment {
    private String variableName;

    public Assignment(String variableName) {
        this.variableName = variableName;
    }

    public String getVariableName() {
        return variableName;
    }
}


text:
define(function(require) {

var Protocol = require("core/protocol");

function Conn(uri) {
	var self = this;
	var WS_OPEN = 1;

	if (!uri) {
		throw "URI required, but not provided to Conn constructor.";
	}
	var ws = new WebSocket(uri);
	ws.binaryType = "arraybuffer";

	var messageQueue = [];
	self.queue = function(message, data) {
		self.queueMessage(Protocol.marshalMessage(message, data));
	};
	self.queueMessage = function (dataView) {
		if (ws.readyState === WS_OPEN) {
			ws.send(dataView);
		} else {
			messageQueue.push(dataView);
		}
	};

	ws.onopen = function () {
		for (var i = 0; i < messageQueue.length; i++) {
			ws.send(messageQueue[i]);
		}
		messageQueue = [];
	};

	var handlers = {};
	self.on = function (id, cb) {
		handlers[id] = handlers[id] || [];
		handlers[id].push(cb);
	};

	function handleMessage(dataView) {
		var id = dataView.getUint8(0);
		if (!handlers[id]) {
			console.warn("Recieved server message of unknown id:", id, "with data", dataView);
			return;
		}
		var message = Protocol.unmarshalMessage(0, dataView).value;
		var h = handlers[id];
		for (var i = 0; i < h.length; h++) {
			h[i](message);
		}
	}

	// Should messages be parsed, and their handlers called, immediately?
	// If false, we wait until update() is called to process messages.
	var immediate = true;
	self.setImmediate = function (isImmediate) {
		immediate = !!isImmediate;
	};

	var incomingQueue = [];
	self.update = function () {
		while (incomingQueue.length) {
			var data = incomingQueue.shift();
			handleMessage(data);
		}
	};

	ws.onmessage = function (ev) {
		if (immediate) {
			handleMessage(new DataView(ev.data));
		} else {
			incomingQueue.push(new DataView(ev.data));
		}
	};

	ws.onerror = function (ev) {
		throw new Error("Alas, it seems I have errd. Forgive me master!", ev);
	};

	ws.onclose = function (ev) {
		throw new Error("Someone closed my websocket :(", ev);
	};
}

Conn.socketURI = function (path) {
	//self == window, but also works when in a worker.
	var loc = self.location;
	var uri = loc.protocol === "https:" ? "wss:" : "ws:";
	uri += "//" + loc.host + "/sockets/" + path;

	if (uri[uri.length - 1] !== '/') {
		uri += '/';
	}

	return uri;
};

return Conn;
});


text:
import forEach from '../util/forEach'
import isString from '../util/isString'
import isNil from '../util/isNil'
import isNumber from '../util/isNumber'
import last from '../util/last'
import inBrowser from '../util/inBrowser'
import ElementType from '../vendor/domelementtype'
import cssSelect from '../vendor/css-select'
import DomUtils from './domutils'
import DOMElement from './DOMElement'
import parseMarkup from './parseMarkup'

// Singleton for browser window stub
let _browserWindowStub

export default class MemoryDOMElement extends DOMElement {
  constructor (type, args = {}) {
    super()

    this.type = type
    if (!type) throw new Error("'type' is mandatory")

    this.ownerDocument = args.ownerDocument
    /* istanbul ignore next */
    if (type !== 'document' && !this.ownerDocument) {
      throw new Error("'ownerDocument' is mandatory")
    }

    // NOTE: there are some properties which are named so that this
    // can be used together with htmlparser2 and css-select
    // but which could have a better naming, e.g., name -> tagName

    switch (type) {
      case ElementType.Tag: {
        if (!args.name) throw new Error("'name' is mandatory.")
        this.name = this._normalizeName(args.name)
        this.nameWithoutNS = nameWithoutNS(this.name)
        this.properties = new Map()
        this.attributes = new Map()
        this.classes = new Set()
        this.styles = new Map()
        this.eventListeners = []
        this.childNodes = args.children || args.childNodes || []
        this._assign(args)
        break
      }
      case ElementType.Text:
      case ElementType.Comment: {
        this.data = args.data || ''
        break
      }
      case ElementType.CDATA: {
        this.data = args.data || ''
        break
      }
      case ElementType.Directive: {
        if (!args.name) throw new Error("'name' is mandatory.")
        this.name = this._normalizeName(args.name)
        this.nameWithoutNS = nameWithoutNS(this.name)
        this.data = args.data
        break
      }
      case ElementType.Doctype: {
        this.data = args.data
        break
      }
      case 'document': {
        const format = args.format
        this.format = format
        if (!format) throw new Error("'format' is mandatory.")
        this.childNodes = args.children || args.childNodes || []
        this._index = null
        switch (format) {
          case 'xml':
            this.contentType = 'application/xml'
            break
          case 'html':
            this.contentType = 'text/html'
            break
          default:
            throw new Error('Unsupported format ' + format)
        }
        break
      }
      default:
        this.name = null
        this.properties = new Map()
        this.attributes = new Map()
        this.classes = new Set()
        this.styles = new Map()
        this.eventListeners = []
        this.childNodes = args.children || args.childNodes || []
    }
  }

  getNativeElement () {
    return this
  }

  getNodeType () {
    switch (this.type) {
      case ElementType.Tag:
      case ElementType.Script:
      case ElementType.Style:
        return 'element'
      default:
        return this.type
    }
  }

  isTextNode () {
    return this.type === 'text'
  }

  isElementNode () {
    return this.type === 'tag' || this.type === 'script'
  }

  isCommentNode () {
    return this.type === 'comment'
  }

  isDocumentNode () {
    return this.type === 'document'
  }

  isComponentNode () {
    return this.type === 'component'
  }

  clone (deep) {
    const clone = new MemoryDOMElement(this.type, this)
    if (this.childNodes) {
      clone.childNodes.length = 0
      if (deep) {
        this.childNodes.forEach((child) => {
          clone.appendChild(child.clone(deep))
        })
      }
    }
    return clone
  }

  get tagName () {
    return this.getTagName()
  }

  set tagName (tagName) {
    this.setTagName(tagName)
  }

  getTagName () {
    return this.name
  }

  setTagName (tagName) {
    if (this._isXML()) {
      this.name = String(tagName)
    } else {
      this.name = String(tagName).toLowerCase()
    }
    this.nameWithoutNS = nameWithoutNS(this.name)
    return this
  }

  hasAttribute (name) {
    if (this.attributes) {
      return this.attributes.has(name)
    }
  }

  getAttribute (name) {
    if (this.attributes) {
      return this.attributes.get(name)
    }
  }

  setAttribute (name, value) {
    if (this.attributes) {
      value = String(value)
      // Note: keeping the Set version of classes and styles in sync
      switch (name) {
        case 'id': {
          this._invalidateIndex()
          break
        }
        case 'class':
          this.classes = new Set()
          parseClasses(this.classes, value)
          break
        case 'style':
          this.styles = new Map()
          parseStyles(this.styles, value)
          break
        default:
          //
      }
      this.attributes.set(name, value)
      if (this._isHTML()) {
        deriveHTMLPropertyFromAttribute(this, name, value)
      }
    }
    return this
  }

  removeAttribute (name) {
    if (this.attributes) {
      switch (name) {
        case 'id':
          this._invalidateIndex()
          break
        case 'class':
          this.classes = new Set()
          break
        case 'style':
          this.styles = new Map()
          break
        default:
          //
      }
      this.attributes.delete(name)
    }
    return this
  }

  getAttributes () {
    return this.attributes
  }

  getProperty (name) {
    if (this.properties) {
      return this.properties.get(name)
    }
  }

  setProperty (name, value) {
    if (this.properties) {
      if (this._isXML()) {
        throw new Error('setProperty() is only be used on HTML elements')
      }
      _setHTMLPropertyValue(this, name, value)
    }
    return this
  }

  hasClass (name) {
    if (this.classes) {
      return this.classes.has(name)
    }
  }

  addClass (name) {
    if (this.classes) {
      this.classes.add(name)
      this.attributes.set('class', stringifyClasses(this.classes))
    }
    return this
  }

  removeClass (name) {
    if (this.classes && this.classes.has(name)) {
      this.classes.delete(name)
      this.attributes.set('class', stringifyClasses(this.classes))
    }
    return this
  }

  getContentType () {
    return this.getOwnerDocument().contentType
  }

  getDoctype () {
    if (this.isDocumentNode()) {
      return _findDocTypeElement(this)
    } else {
      return this.getOwnerDocument().getDoctype()
    }
  }

  setDoctype (qualifiedNameStr, publicId, systemId) {
    // NOTE: there must be only one <!DOCTYPE> before the first content element
    const doc = this.getOwnerDocument()
    const oldDocType = _findDocTypeElement(doc)
    const newDocType = this.createDocumentType(qualifiedNameStr, publicId, systemId)
    if (oldDocType) {
      doc.replaceChild(oldDocType, newDocType)
    } else {
      // insert it before the first ELEMENT
      doc.insertBefore(newDocType, doc.getChildren()[0])
    }
    doc.doctype = newDocType
  }

  getInnerHTML () {
    const isXML = this._isXML()
    return DomUtils.getInnerHTML(this, { xmlMode: isXML, decodeEntities: !isXML })
  }

  // TODO: parse html using settings from el,
  // clear old childNodes and append new childNodes
  setInnerHTML (html) {
    if (this.childNodes) {
      const isXML = this._isXML()
      const _doc = parseMarkup(html, {
        ownerDocument: this.getOwnerDocument(),
        format: isXML ? 'xml' : 'html',
        decodeEntities: !isXML,
        elementFactory: MemoryDOMElementFactory
      })
      this.empty()
      // ATTENTION: important to copy the childNodes array first
      // as appendChild removes from parent
      _doc.childNodes.slice(0).forEach(child => {
        this.appendChild(child)
      })
    }
    return this
  }

  getOuterHTML () {
    const isXML = this._isXML()
    return DomUtils.getOuterHTML(this, { xmlMode: isXML, decodeEntities: !isXML })
  }

  getTextContent () {
    return DomUtils.getText(this)
  }

  setTextContent (text) {
    switch (this.type) {
      case ElementType.Text:
      case ElementType.Comment:
      case ElementType.CDATA: {
        this.data = text
        break
      }
      default: {
        if (this.childNodes) {
          const child = this.createTextNode(text)
          this.empty()
          this.appendChild(child)
        }
      }
    }
    return this
  }

  getStyle (name) {
    if (this.styles) {
      return this.styles.get(name)
    }
  }

  setStyle (name, value) {
    if (this.styles) {
      if (DOMElement.pxStyles[name] && isNumber(value)) {
        value = value + 'px'
      }
      this.styles.set(name, value)
      this.attributes.set('style', stringifyStyles(this.styles))
    }
    return this
  }

  is (cssSelector) {
    return cssSelect.is(this, cssSelector, { xmlMode: this._isXML() })
  }

  // TODO: it would be nice if we could use an index here
  // however,
  getElementById (id) {
    const doc = this.getOwnerDocument()
    if (!doc._index) {
      doc._createIndex()
    }
    return doc._index.get(id)
  }

  find (cssSelector) {
    return cssSelect.selectOne(cssSelector, this, { xmlMode: this._isXML() })
  }

  findAll (cssSelector) {
    return cssSelect.selectAll(cssSelector, this, { xmlMode: this._isXML() })
  }

  getChildCount () {
    if (this.childNodes) {
      return this.childNodes.length
    } else {
      return 0
    }
  }

  getChildNodes () {
    return this.childNodes.slice(0)
  }

  getChildren () {
    return this.childNodes.filter(function (node) {
      return node.type === 'tag'
    })
  }

  get children () {
    return this.getChildren()
  }

  getChildAt (pos) {
    if (this.childNodes) {
      return this.childNodes[pos]
    }
  }

  getChildIndex (child) {
    if (this.childNodes) {
      return this.childNodes.indexOf(child)
    }
  }

  getLastChild () {
    if (this.childNodes) {
      return last(this.childNodes)
    }
  }

  getFirstChild () {
    if (this.childNodes) {
      return this.childNodes[0]
    }
  }

  getNextSibling () {
    return this.next
  }

  getPreviousSibling () {
    return this.prev
  }

  getParent () {
    // TODO: to be consistent with the Browser implementation
    // root elements should return null as parent element.
    // However, this breaks other code ATM.
    // let parent = this.parent
    // if (parent && parent.type !== 'document') {
    //   return this.parent
    // } else {
    //   return null
    // }
    return this.parent
  }

  getOwnerDocument () {
    return (this.type === 'document') ? this : this.ownerDocument
  }

  getFormat () {
    return this.getOwnerDocument().format
  }

  createDocument (format) {
    return MemoryDOMElement.createDocument(format)
  }

  createElement (tagName) {
    return new MemoryDOMElement(ElementType.Tag, { name: tagName, ownerDocument: this.getOwnerDocument() })
  }

  createTextNode (text) {
    return new MemoryDOMElement(ElementType.Text, { data: text, ownerDocument: this.getOwnerDocument() })
  }

  createComment (data) {
    return new MemoryDOMElement(ElementType.Comment, { data: data, ownerDocument: this.getOwnerDocument() })
  }

  createProcessingInstruction (name, data) {
    return new MemoryDOMElement(ElementType.Directive, { name: name, data: data, ownerDocument: this.getOwnerDocument() })
  }

  createDocumentType (qualifiedNameStr, publicId, systemId) {
    return new MemoryDOMDoctype(ElementType.Doctype, { data: { name: qualifiedNameStr, publicId, systemId }, ownerDocument: this.getOwnerDocument() })
  }

  createCDATASection (data) {
    return new MemoryDOMElement(ElementType.CDATA, { data: data, ownerDocument: this.getOwnerDocument() })
  }

  appendChild (child) {
    if (this.childNodes && !isNil(child)) {
      child = this._normalizeChild(child)
      if (!child) return this
      if (child.id) this._invalidateIndex()
      DomUtils.appendChild(this, child)
      child.ownerDocument = this.getOwnerDocument()
    }
    return this
  }

  removeChild (child) {
    if (child.parentNode === this) {
      if (child.id) this._invalidateIndex()
      child.remove()
    }
  }

  insertAt (pos, child) {
    child = this._normalizeChild(child)
    if (!child) return this
    if (child.id) this._invalidateIndex()
    const childNodes = this.childNodes
    if (childNodes) {
      // NOTE: manipulating htmlparser's internal children array
      if (pos >= childNodes.length) {
        DomUtils.appendChild(this, child)
      } else {
        DomUtils.prepend(childNodes[pos], child)
      }
      child.ownerDocument = this.getOwnerDocument()
    }
    return this
  }

  insertBefore (newChild, before) {
    if (newChild.id) this._invalidateIndex()
    if (isNil(before)) {
      return this.appendChild(newChild)
    } else if (this.childNodes) {
      var pos = this.childNodes.indexOf(before)
      if (pos > -1) {
        DomUtils.prepend(before, newChild)
        newChild.ownerDocument = this.getOwnerDocument()
      } else {
        throw new Error('insertBefore(): reference node is not a child of this element.')
      }
    }
    return this
  }

  removeAt (pos) {
    const childNodes = this.childNodes
    if (childNodes) {
      const child = childNodes[pos]
      if (child.id) this._invalidateIndex()
      child.remove()
    }
    return this
  }

  empty () {
    this._invalidateIndex()
    const childNodes = this.childNodes
    if (childNodes) {
      childNodes.forEach((child) => {
        child.next = child.prev = child.parent = null
      })
      childNodes.length = 0
    }
    this._invalidateIndex()
    return this
  }

  remove () {
    if (this.id) this._invalidateIndex()
    DomUtils.removeElement(this)
    return this
  }

  replaceChild (oldChild, newChild) {
    if (oldChild.id || newChild.id) this._invalidateIndex()
    if (oldChild.parent === this) {
      oldChild.replaceWith(newChild)
    }
    return this
  }

  replaceWith (newEl) {
    if (this.id || newEl.id) this._invalidateIndex()
    newEl = this._normalizeChild(newEl)
    DomUtils.replaceElement(this, newEl)
    newEl.ownerDocument = this.getOwnerDocument()
    return this
  }

  getEventListeners () {
    return this.eventListeners || []
  }

  click () {
    this.emit('click', { target: this, currentTarget: this })
    return true
  }

  emit (name, data) {
    this._propagateEvent(new MemoryDOMElementEvent(name, this, data))
  }

  getBoundingClientRect () {
    return { top: 0, left: 0, height: 0, width: 0 }
  }

  getClientRects () {
    return [{ top: 0, left: 0, height: 0, width: 0 }]
  }

  _propagateEvent (event) {
    const listeners = this.eventListeners
    if (listeners) {
      listeners.forEach(l => {
        if (l.eventName === event.type) {
          l.handler(event)
        }
      })
      if (event.stopped) return
      const p = this.parentNode
      if (p) p._propagateEvent(event)
    }
  }

  removeAllEventListeners () {
    this.eventListeners = []
    return this
  }

  _assign (other) {
    if (other.name) this.name = other.name
    if (this.classes && other.classes) {
      other.classes.forEach((val) => {
        this.classes.add(val)
      })
    }
    if (this.styles && other.styles) {
      forEach(other.styles, (val, name) => {
        this.styles.set(name, val)
      })
    }
    // TODO: while it is 'smart' to deal with 'style' and 'class'
    // implicitly, it introduces some confusion here
    const otherAttributes = other.attributes || other.attribs
    if (this.attributes && otherAttributes) {
      forEach(otherAttributes, (val, name) => {
        switch (name) {
          case 'class': {
            parseClasses(this.classes, val)
            break
          }
          case 'style': {
            parseStyles(this.styles, val)
            break
          }
          default:
            //
        }
        this.attributes.set(name, val)
      })
    }
    if (this.eventListeners && other.eventListeners) {
      this.eventListeners = this.eventListeners.concat(other.eventListeners)
    }
  }

  _normalizeChild (child) {
    if (isNil(child)) return

    if (isString(child)) {
      child = this.createTextNode(child)
    }
    /* istanbul ignore next */
    if (!child || !child._isMemoryDOMElement) {
      throw new Error('Illegal argument: only String and MemoryDOMElement instances are valid.')
    }
    return child
  }

  _normalizeName (name) {
    if (this._isXML()) {
      return name
    } else {
      return name.toLowerCase()
    }
  }

  _isHTML () {
    return this.getFormat() === 'html'
  }

  _isXML () {
    return this.getFormat() === 'xml'
  }

  _invalidateIndex () {
    this.getOwnerDocument()._index = null
  }

  _createIndex () {
    const elementsWithId = this.getOwnerDocument().findAll('[id]')
    this._index = new Map(elementsWithId.map(el => [el.id, el]))
  }

  // TODO: do we really need this?
  get _isMemoryDOMElement () { return true }

  static createDocument (format, opts = {}) {
    if (format === 'xml') {
      const doc = new MemoryDOMElement('document', { format: format })
      const xmlInstruction = []
      if (opts.version) {
        xmlInstruction.push(`version="${opts.version}"`)
      }
      if (opts.encoding) {
        xmlInstruction.push(`encoding="${opts.encoding}"`)
      }
      if (xmlInstruction.length > 0) {
        doc._xmlInstruction = doc.createProcessingInstruction('xml', xmlInstruction.join(' '))
      }
      return doc
    } else {
      return MemoryDOMElement.parseMarkup(DOMElement.EMPTY_HTML, 'html')
    }
  }

  static parseMarkup (str, format, options = {}) {
    if (!str) {
      return MemoryDOMElement.createDocument(format)
    }
    // decodeEntities by default only in HTML mode
    const decodeEntities = format === 'html'
    const parserOpts = Object.assign({
      format,
      decodeEntities,
      elementFactory: MemoryDOMElementFactory
    }, options)
    // opt-out from HTML structure sanitization
    if (options.raw) {
      return parseMarkup(str, parserOpts)
    }
    if (options.snippet) {
      str = `<__snippet__>${str}</__snippet__>`
    }
    let doc
    if (format === 'html') {
      doc = parseMarkup(str, parserOpts)
      _sanitizeHTMLStructure(doc)
    } else if (format === 'xml') {
      doc = parseMarkup(str, parserOpts)
    }
    if (options.snippet) {
      const childNodes = doc.find('__snippet__').childNodes
      if (childNodes.length === 1) {
        return childNodes[0]
      } else {
        return childNodes
      }
    } else {
      return doc
    }
  }

  static wrapNativeElement (el) {
    if (inBrowser) {
      // HACK: at many places we have an `isBrowser` check
      // to skip code that uses window or window.document
      // To be able to test such code together with the memory DOM implementation
      // we stub out window and document
      if (el === window || el === window.document) {
        return new DOMElementStub()
      // HACK: additionally, if a window.document.Node or a BrowserDOMElement is given
      // as it happens when trying to mount onto t.sandbox with DefaultDOMElement using MemoryDOMElement as default
      // we just return a new root element
      } else if (el instanceof window.Node || el._isBrowserDOMElement) {
        // return MemoryDOMElement.createDocument('html').createElement('div')
      }
    }
    /* istanbul ignore next */
    if (!el._isMemoryDOMElement) {
      throw new Error('Illegal argument: expected MemoryDOMElement instance')
    }
    return el
  }

  static wrap (el) { return MemoryDOMElement.wrapNativeElement(el) }

  static unwrap (el) {
    /* istanbul ignore next */
    if (!el._isMemoryDOMElement) {
      throw new Error('Illegal argument: expected MemoryDOMElement instance')
    }
    return el
  }

  // TODO: this is used only in browser to determine if
  // a selection  is reverse.
  /* istanbul ignore next */
  static isReverse () {
    return false
  }

  static getBrowserWindow () {
    // HACK: this is a bit awkward
    if (!_browserWindowStub) {
      _browserWindowStub = new MemoryWindowStub()
    }
    return _browserWindowStub
  }
}

function MemoryDOMElementFactory (type, data) {
  return new MemoryDOMElement(type, data)
}

class MemoryDOMDoctype extends MemoryDOMElement {
  get name () { return this.data.name }
  get publicId () { return this.data.publicId }
  get systemId () { return this.data.systemId }
}

function parseClasses (classes, classStr) {
  classStr.split(/\s+/).forEach((name) => {
    classes.add(name)
  })
}

function stringifyClasses (classes) {
  return Array.from(classes).join(' ')
}

function parseStyles (styles, styleStr) {
  styleStr = (styleStr || '').trim()
  if (!styleStr) return
  styleStr.split(';').forEach((style) => {
    const n = style.indexOf(':')
    // skip if there is no :, or if it is the first/last character
    if (n < 1 || n === style.length - 1) return
    const name = style.slice(0, n).trim()
    const val = style.slice(n + 1).trim()
    styles.set(name, val)
  })
}

function stringifyStyles (styles) {
  if (!styles) return ''
  let str = Object.keys(styles).map((name) => {
    return name + ':' + styles[name]
  }).join(';')
  if (str.length > 0) str += ';'
  return str
}

const BUILTIN_EVENTS = [
  'keydown', 'keyup', 'keypress',
  'mousedown', 'mouseup', 'mouseover', 'click', 'dblclick'
].reduce((m, k) => { m[k] = true; return m }, {})

class MemoryDOMElementEvent {
  constructor (type, target, detail) {
    this.type = type
    this.timeStamp = Date.now()
    this.target = target

    if (BUILTIN_EVENTS[type]) {
      // TODO: dunno if this is the best way of doing it
      if (detail) {
        Object.assign(this, detail)
      }
    } else {
      this.detail = detail
    }
  }

  stopPropagation () {
    this.stopped = true
  }

  preventDefault () {
    this.defaultPrevented = true
  }
}

class DOMElementStub {
  on () {}
  off () {}
}

// EXPERIMENTAL: we want to be able to use the Router in
// tests using MemoryDOM
class MemoryWindowStub extends MemoryDOMElement {
  constructor () {
    super('window', { ownerDocument: MemoryDOMElement.createDocument('html') })

    const location = {
      href: '',
      hash: ''
    }

    function _updateLocation (url) {
      const hashIdx = url.indexOf('#')
      location.href = url
      if (hashIdx >= 0) {
        location.hash = url.slice(hashIdx)
      }
    }

    const history = {
      replaceState (stateObj, title, url) {
        _updateLocation(url)
      },
      pushState (stateObj, title, url) {
        _updateLocation(url)
      }
    }

    this.location = location
    this.history = history
  }
}

function nameWithoutNS (name) {
  const idx = name.indexOf(':')
  if (idx > 0) {
    return name.slice(idx + 1)
  } else {
    return name
  }
}

// Note: some attributes are used to initialize an
// element property
const ATTR_TO_PROPS = {
  input: {
    value: true,
    checked: (el, name, value) => {
      const checked = (value !== 'off')
      el.setProperty('checked', checked)
    }
  }
}

function deriveHTMLPropertyFromAttribute (el, name, value) {
  const mappings = ATTR_TO_PROPS[el.tagName]
  if (mappings) {
    const mapper = mappings[name]
    if (mapper === true) {
      el.setProperty(name, value)
    } else if (mapper) {
      mapper(el, name, value)
    }
  }
}

const PROPERTY_TRANSFORMATIONS = {
  input: {
    checked: (el, name, value) => {
      if (value === true) {
        el.properties.set(name, true)
        el.properties.set('value', 'on')
      } else {
        el.properties.set(name, false)
        el.properties.set('value', 'off')
      }
    },
    value: (el, name, value) => {
      const type = el.getAttribute('type')
      switch (type) {
        case 'checkbox':
          if (value === 'on') {
            el.properties.set(name, true)
            el.properties.set('value', 'on')
          } else {
            el.properties.set(name, false)
            el.properties.set('value', 'off')
          }
          break
        default:
          _setProperty(el, name, value)
      }
    }
  }
}

function _setProperty (el, name, value) {
  if (value === undefined) {
    el.properties.delete(name)
  } else {
    el.properties.set(name, String(value))
  }
}

function _setHTMLPropertyValue (el, name, value) {
  const trafos = PROPERTY_TRANSFORMATIONS[el.tagName]
  if (trafos) {
    const mapper = trafos[name]
    if (mapper) {
      mapper(el, name, value)
      return
    }
  }
  _setProperty(el, name, value)
}

function _sanitizeHTMLStructure (doc) {
  // as opposed to DOMParser in the browser
  // htmlparser2 does not create <head> and <body> per se
  // thus we need to make sure that everything is working
  // similar as in the browser
  let htmlEl = doc.find('html')
  if (!htmlEl) {
    // remove head and nodes which must go into the head
    // so they do not go into the body
    let headEl = doc.find('head')
    const titleEl = doc.find('title')
    const metaEls = doc.findAll('meta')
    let bodyEl = doc.find('body')
    if (headEl) headEl.remove()
    if (titleEl) titleEl.remove()
    metaEls.forEach(e => e.remove())
    if (bodyEl) bodyEl.remove()

    // keep the remaining content nodes,
    // we will add them to the body
    const contentNodes = doc.childNodes.slice()
    contentNodes.forEach((c) => { c.parent = null })
    doc.childNodes.length = 0

    htmlEl = doc.createElement('html')
    // if not there create a <head> and
    // add all the elements that are supposed to
    // go there
    if (!headEl) {
      headEl = doc.createElement('head')
      headEl.appendChild(titleEl)
      headEl.append(metaEls)
      htmlEl.appendChild(headEl)
    }
    if (!bodyEl) {
      bodyEl = doc.createElement('body')
      bodyEl.append(contentNodes)
    }
    htmlEl.appendChild(bodyEl)

    doc.append(htmlEl)
  }
}

function _findDocTypeElement (doc) {
  // Note: the looked up doctype element will be cached on the document element
  if (doc.doctype) return doc.doctype
  const childNodes = doc.childNodes
  for (let i = 0; i < childNodes.length; i++) {
    const child = childNodes[i]
    if (child.type === ElementType.Doctype) {
      doc.doctype = child
      return child
    }
  }
}


text:
package edu.mayo.mprc.swift.commands;

import joptsimple.OptionParser;

import java.io.File;
import java.util.List;

/**
 * Encapsulates information passed to Swift through the command line.
 *
 * @author Roman Zenka
 */
public final class SwiftCommandLine {
	public static final String RUN_OR_CONFIG = "run-or-config";
	public static final String DEFAULT_RUN_COMMAND = "run-swift";
	public static final String CONFIG_COMMAND = "config";

	private final String command;
	private final List<String> parameters;
	private final File installFile;
	private final String daemonId;
	private final String error;
	private final OptionParser parser;

	public SwiftCommandLine(final String command, final List<String> parameters, final File installFile, final String daemonId, final String error, final OptionParser parser) {
		this.command = command;
		this.parameters = parameters;
		this.installFile = installFile;
		this.daemonId = daemonId;
		this.error = error;
		this.parser = parser;
	}

	/**
	 * @return The command the user wants to invoke.
	 */
	public String getCommand() {
		return command;
	}

	/**
	 * @return List of the parameters the users want to invoke.
	 */
	public List<String> getParameters() {
		return parameters;
	}

	/**
	 * @return Configuration file for Swift.
	 */
	public File getInstallFile() {
		return installFile;
	}

	/**
	 * @return ID of the daemon the user wants to run.
	 */
	public String getDaemonId() {
		return daemonId;
	}

	public String getError() {
		return error;
	}

	/**
	 * @return Parser that parsed all the command-line options.
	 */
	public OptionParser getParser() {
		return parser;
	}
}


text:
querydsl
========

practicing querydsl


text:
// .NAME vtkUnstructuredGridCellIterator - Implementation of vtkCellIterator
// specialized for vtkUnstructuredGrid.

#ifndef vtkUnstructuredGridCellIterator_h
#define vtkUnstructuredGridCellIterator_h

#include "vtkCommonDataModelModule.h" // For export macro
#include "vtkCellIterator.h"
#include "vtkSmartPointer.h" // For vtkSmartPointer

class vtkCellArray;
class vtkUnsignedCharArray;
class vtkUnstructuredGrid;
class vtkPoints;

class VTKCOMMONDATAMODEL_EXPORT vtkUnstructuredGridCellIterator :
    public vtkCellIterator
{
public:
  static vtkUnstructuredGridCellIterator *New();
  vtkTypeMacro(vtkUnstructuredGridCellIterator, vtkCellIterator)
  virtual void PrintSelf(ostream &os, vtkIndent indent);

  bool IsDoneWithTraversal();
  vtkIdType GetCellId();

protected:
  vtkUnstructuredGridCellIterator();
  ~vtkUnstructuredGridCellIterator();

  void ResetToFirstCell();
  void IncrementToNextCell();
  void FetchCellType();
  void FetchPointIds();
  void FetchPoints();
  void FetchFaces();

  friend class vtkUnstructuredGrid;
  void SetUnstructuredGrid(vtkUnstructuredGrid *ug);

  unsigned char *CellTypeBegin;
  unsigned char *CellTypePtr;
  unsigned char *CellTypeEnd;

  vtkIdType *ConnectivityBegin;
  vtkIdType *ConnectivityPtr;
  vtkIdType *FacesBegin;
  vtkIdType *FacesLocsBegin;
  vtkIdType *FacesLocsPtr;

  // Cache misses make updating ConnectivityPtr in IncrementToNextCell too
  // expensive, so we wait to walk through the array until the point ids are
  // needed. This variable keeps track of how far we need to increment.
  vtkIdType SkippedCells;
  void CatchUpSkippedCells();

  vtkSmartPointer<vtkPoints> UnstructuredGridPoints;

private:
  vtkUnstructuredGridCellIterator(const vtkUnstructuredGridCellIterator &); // Not implemented.
  void operator=(const vtkUnstructuredGridCellIterator &);   // Not implemented.
};

#endif //vtkUnstructuredGridCellIterator_h


text:
using System.Runtime.InteropServices;
using GenerationAttributes;
using tlplib.collection;

namespace com.tinylabproductions.TLPLib.iOS {
  public static class TLPLibIOSBinding {
    ///
    /// Fetches arguments for the process from
    /// https://developer.apple.com/documentation/foundation/nsprocessinfo/1415596-arguments
    ///
    /// The first argument will be a path to the process executable, for example:
    /// /var/containers/Bundle/Application/GUID/your_bundle_id.app/your_bundle_id
    ///
    /// Beware that you can only pass these arguments from a debug build of the application.
    ///
    /// So if you have a production .ipa file, the process of launching it with command line interface (CLI)
    /// arguments is this:
    ///
    /// 1. Resign the .ipa file using the DEBUG certificate that includes the device on which you are going to run
    ///    the application. fastlane tool is useful for this: https://docs.fastlane.tools/actions/resign/
    ///
    ///    Beware that at the time of writing this fastlane fails on Ruby 3.x, so you need to use 2.7.2. A tool like
    ///    [rbenv](https://github.com/rbenv/rbenv) is your friend here.
    ///
    ///    Example:
    ///    /// <![CDATA[
    ///      bundle exec fastlane run resign ipa:your.ipa signing_identity:"your dev identity" \
    ///        provisioning_profile:"your-dev.mobileprovision"
    ///    ]]>
    ///
    ///    You can find your signing identity name by running `security find-identity -v -p codesigning`.
    ///
    ///    Provisioning profiles that you already imported to XCode are stored in
    ///    "~/Library/MobileDevice/Provisioning Profiles".
    ///
    /// 2. Launch the modified .ipa.
    ///
    ///    Method a)
    ///      Use the [ios-deploy](https://github.com/ios-control/ios-deploy) tool.
    ///
    ///      From our experience this gives you an attached debugger and fast transmission of application logs from
    ///      the device to the terminal.
    ///
    ///      Example:
    ///      /// <![CDATA[
    ///        # unzip the package
    ///        unzip your.ipa
    ///        # deploy & launch the bundle
    ///        #
    ///        # The argument parser supports quotes, so --foo="bar baz" will be passed as "--foo=bar baz" to C#.
    ///        #
    ///        # It uses https://docs.python.org/3/library/shlex.html#shlex.split to parse the arguments and errors
    ///        # out if you use single quotes (') because internally it sticks your arguments into a Python script in
    ///        # the following way:
    ///        #
    ///        #    args-arr = args_arr + shlex.split('your args string goes here')
    ///        ios-deploy --bundle Payload/your_bundle_id.app --debug --args "your command line arguments go here"
    ///      ]]>
    ///
    ///    Method b)
    ///      Use the [ideviceinstaller](https://github.com/libimobiledevice/ideviceinstaller) shell tools.
    ///
    ///      For some reason the transmission of application logs from the device to the terminal is a lot slower than
    ///      using method a.
    ///
    ///      Example:
    ///      /// <![CDATA[
    ///        # install the package
    ///        ideviceinstaller -i your.ipa
    ///        # launch the bundle
    ///        idevicedebug run your_bundle_id your command line arguments go here
    ///      ]]>
    ///
    [LazyProperty] public static ImmutableArrayC<string> cliArguments {
      get {
        var count = tlplibGetCliArgumentCount();
        if (count == 0) return ImmutableArrayC<string>.empty;

        var args = new string[count];
        for (var idx = 0ul; idx < count; idx++) {
          args[idx] = tlplibGetCliArgument(idx);
        }

        return ImmutableArrayC.move(args);
      }
    }

    [DllImport("__Internal")] static extern ulong tlplibGetCliArgumentCount();
    [DllImport("__Internal")] static extern string tlplibGetCliArgument(ulong index);
  }
}
#endif


text:
static dispatch_queue_t af_image_request_operation_processing_queue;
static dispatch_queue_t image_request_operation_processing_queue() {
    if (af_image_request_operation_processing_queue == NULL) {
        af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
    }

    return af_image_request_operation_processing_queue;
}

@interface AFImageRequestOperation ()
#if __IPHONE_OS_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) UIImage *responseImage;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) NSImage *responseImage;
#endif

+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end

@implementation AFImageRequestOperation
@synthesize responseImage = _responseImage;
#if __IPHONE_OS_VERSION_MIN_REQUIRED
@synthesize imageScale = _imageScale;
#endif

#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                      success:(void (^)(UIImage *image))success
{
    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
        if (success) {
            success(image);
        }
    } failure:nil];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                      success:(void (^)(NSImage *image))success
{
    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
        if (success) {
            success(image);
        }
    } failure:nil];
}
#endif

#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                         imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
                                                    cacheName:(NSString *)cacheNameOrNil
                                                      success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                                                      failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
    AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            UIImage *image = responseObject;
            if (imageProcessingBlock) {
                dispatch_async(image_request_operation_processing_queue(), ^(void) {
                    UIImage *processedImage = imageProcessingBlock(image);

                    dispatch_async(dispatch_get_main_queue(), ^(void) {
                        success(operation.request, operation.response, processedImage);
                    });
                });
            } else {
                success(operation.request, operation.response, image);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(operation.request, operation.response, error);
        }
    }];

    return requestOperation;
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                         imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
                                                    cacheName:(NSString *)cacheNameOrNil
                                                      success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
                                                      failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
    AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            NSImage *image = responseObject;
            if (imageProcessingBlock) {
                dispatch_async(image_request_operation_processing_queue(), ^(void) {
                    NSImage *processedImage = imageProcessingBlock(image);

                    dispatch_async(dispatch_get_main_queue(), ^(void) {
                        success(operation.request, operation.response, processedImage);
                    });
                });
            } else {
                success(operation.request, operation.response, image);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(operation.request, operation.response, error);
        }
    }];

    return requestOperation;
}
#endif

+ (NSSet *)defaultAcceptableContentTypes {
    return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}

+ (NSSet *)defaultAcceptablePathExtensions {
    return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
}

- (id)initWithRequest:(NSURLRequest *)urlRequest {
    self = [super initWithRequest:urlRequest];
    if (!self) {
        return nil;
    }

    self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];

#if __IPHONE_OS_VERSION_MIN_REQUIRED
    self.imageScale = [[UIScreen mainScreen] scale];
#endif

    return self;
}

- (void)dealloc {
    [_responseImage release];
    [super dealloc];
}

#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (UIImage *)responseImage {
    if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
        UIImage *image = [UIImage imageWithData:self.responseData];

        self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
    }

    return _responseImage;
}

- (void)setImageScale:(CGFloat)imageScale {
    if (imageScale == _imageScale) {
        return;
    }

    _imageScale = imageScale;

    self.responseImage = nil;
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSImage *)responseImage {
    if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
        // Ensure that the image is set to it's correct pixel width and height
        NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
        self.responseImage = [[[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])] autorelease];
        [self.responseImage addRepresentation:bitimage];
        [bitimage release];
    }

    return _responseImage;
}
#endif

#pragma mark - AFHTTPClientOperation

+ (BOOL)canProcessRequest:(NSURLRequest *)request {
    return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}

#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                    success:(void (^)(id object))success
                                                    failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
        success(image);
    } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
        failure(response, error);
    }];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                    success:(void (^)(id object))success
                                                    failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
        success(image);
    } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
        failure(response, error);
    }];
}
#endif

- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    self.completionBlock = ^ {
        if ([self isCancelled]) {
            return;
        }

        dispatch_async(image_request_operation_processing_queue(), ^(void) {
            if (self.error) {
                if (failure) {
                    dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
                        failure(self, self.error);
                    });
                }
            } else {
                if (success) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED
                    UIImage *image = nil;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
                    NSImage *image = nil;
#endif

                    image = self.responseImage;

                    dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
                        success(self, image);
                    });
                }
            }
        });
    };
}

@end


text:
.class Landroid/support/v4/app/NavUtils$NavUtilsImplJB;
.super Landroid/support/v4/app/NavUtils$NavUtilsImplBase;
.source "NavUtils.java"

# annotations
.annotation build Landroid/annotation/TargetApi;
    value = 0x10
.end annotation

.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/NavUtils;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "NavUtilsImplJB"
.end annotation

# direct methods
.method constructor <init>()V
    .registers 1

    .prologue
    .line 97
    invoke-direct {p0}, Landroid/support/v4/app/NavUtils$NavUtilsImplBase;-><init>()V

    return-void
.end method

# virtual methods
.method public getParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;
    .registers 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 103
    invoke-static {p1}, Landroid/support/v4/app/NavUtilsJB;->getParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;

    move-result-object v0

    .line 104
    .local v0, "result":Landroid/content/Intent;
    if-nez v0, :cond_a

    .line 105
    invoke-virtual {p0, p1}, Landroid/support/v4/app/NavUtils$NavUtilsImplJB;->superGetParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;

    move-result-object v0

    .line 107
    :cond_a
    return-object v0
.end method

.method public getParentActivityName(Landroid/content/Context;Landroid/content/pm/ActivityInfo;)Ljava/lang/String;
    .registers 4
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "info"    # Landroid/content/pm/ActivityInfo;

    .prologue
    .line 126
    invoke-static {p2}, Landroid/support/v4/app/NavUtilsJB;->getParentActivityName(Landroid/content/pm/ActivityInfo;)Ljava/lang/String;

    move-result-object v0

    .line 127
    .local v0, "result":Ljava/lang/String;
    if-nez v0, :cond_a

    .line 128
    invoke-super {p0, p1, p2}, Landroid/support/v4/app/NavUtils$NavUtilsImplBase;->getParentActivityName(Landroid/content/Context;Landroid/content/pm/ActivityInfo;)Ljava/lang/String;

    move-result-object v0

    .line 130
    :cond_a
    return-object v0
.end method

.method public navigateUpTo(Landroid/app/Activity;Landroid/content/Intent;)V
    .registers 3
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "upIntent"    # Landroid/content/Intent;

    .prologue
    .line 121
    invoke-static {p1, p2}, Landroid/support/v4/app/NavUtilsJB;->navigateUpTo(Landroid/app/Activity;Landroid/content/Intent;)V

    .line 122
    return-void
.end method

.method public shouldUpRecreateTask(Landroid/app/Activity;Landroid/content/Intent;)Z
    .registers 4
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "targetIntent"    # Landroid/content/Intent;

    .prologue
    .line 116
    invoke-static {p1, p2}, Landroid/support/v4/app/NavUtilsJB;->shouldUpRecreateTask(Landroid/app/Activity;Landroid/content/Intent;)Z

    move-result v0

    return v0
.end method

.method superGetParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;
    .registers 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 111
    invoke-super {p0, p1}, Landroid/support/v4/app/NavUtils$NavUtilsImplBase;->getParentActivityIntent(Landroid/app/Activity;)Landroid/content/Intent;

    move-result-object v0

    return-object v0
.end method


text:
using System;
using System.Linq;
using MVP.Api.Models;

namespace MVP.App.UWP.Cortana
{
    using System.Threading.Tasks;

    using Windows.ApplicationModel.VoiceCommands;

    public sealed partial class VoiceCommandService
    {
        private async Task HandleContributionCommand(VoiceCommand command)
        {
            // Step - Request type
            var typeResponse = await ReportForContributionTypeAsync();
            if (typeResponse != null)
            {
                var selectedType = typeResponse.SelectedItem;
                var type = selectedType?.AppContext as ContributionType;
                if (type != null)
                {
                    // Step - Request area
                    var areaResponse = await this.ReportForContributionAreaAsync();
                    if (areaResponse != null)
                    {
                        var selectedArea = areaResponse.SelectedItem;
                        var area = selectedArea?.AppContext as ActivityTechnology;

                        if (area != null)
                        {
                            // Step - Request title (Blocked as this doesn't appear possible... sad times)
                            var titleResponse = await this.ReportForContributionTitleAsync();
                            if (titleResponse != null)
                            {

                                await this.ReportResultAsync(
                                    VoiceReportResult.Success,
                                    "Your contribution has been submitted!");
                                return;
                            }
                        }
                    }
                }
            }

            await this.ReportResultAsync(
                VoiceReportResult.Fail,
                "Failed to find contribution types. Open the app to update them.");
        }

        private async Task<VoiceCommandDisambiguationResult> ReportForContributionTitleAsync()
        {
            var userPrompt = new VoiceCommandUserMessage();
            userPrompt.DisplayMessage = userPrompt.SpokenMessage = "What is the title of this contribution?";

            var repeatPrompt = new VoiceCommandUserMessage();
            repeatPrompt.DisplayMessage = repeatPrompt.SpokenMessage = "Sorry, what would you like the title to be?";

            var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, repeatPrompt);

            return await voiceServiceConnection.RequestDisambiguationAsync(response);
        }

        private async Task<VoiceCommandDisambiguationResult> ReportForContributionAreaAsync()
        {
            var allAreas = this.areaContainer.GetMyAreaTechnologies().ToList();
            var areas = allAreas.Count > 10 ? allAreas.Take(10).ToList() : allAreas;

            if (areas.Any())
            {
                var userPrompt = new VoiceCommandUserMessage();
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = "Which area is it?";

                var repeatPrompt = new VoiceCommandUserMessage();
                repeatPrompt.DisplayMessage = repeatPrompt.SpokenMessage = "Sorry, which area is it?";

                var areaTiles = areas.Select(area => new VoiceCommandContentTile
                {
                    ContentTileType = VoiceCommandContentTileType.TitleOnly,
                    AppContext = area,
                    Title = area.Name
                }).ToList();

                var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, repeatPrompt, areaTiles);

                return await voiceServiceConnection.RequestDisambiguationAsync(response);
            }

            return null;
        }

        private async Task<VoiceCommandDisambiguationResult> ReportForContributionTypeAsync()
        {
            var types = this.typeContainer.GetCommonTypes().ToList();

            if (types.Any())
            {
                var userPrompt = new VoiceCommandUserMessage();
                userPrompt.DisplayMessage = userPrompt.SpokenMessage = "What type of contribution is it?";

                var repeatPrompt = new VoiceCommandUserMessage();
                repeatPrompt.DisplayMessage = repeatPrompt.SpokenMessage = "Sorry, what type of contribution is it?";

                var typeTiles = types.Select(type => new VoiceCommandContentTile
                {
                    ContentTileType = VoiceCommandContentTileType.TitleOnly,
                    AppContext = type,
                    Title = type.Name
                }).ToList();

                var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, repeatPrompt, typeTiles);

                return await voiceServiceConnection.RequestDisambiguationAsync(response);
            }

            return null;
        }
    }
}