text:
import '../lib/bootstrap-local';

import { ReleaseConfig } from '@angular/dev-infra-private/ng-dev';
import { releasePackages } from '../lib/packages';
import buildPackages from '../scripts/build';

const npmPackages = Object.entries(releasePackages).map(([name, { experimental }]) => ({
  name,
  experimental,
}));

/** Configuration for the `ng-dev release` command. */
export const release: ReleaseConfig = {
  representativeNpmPackage: '@angular/cli',
  npmPackages,
  buildPackages: () => buildPackages(),
  releaseNotes: {
    groupOrder: [
      '@angular/cli',
      '@schematics/angular',
      '@angular-devkit/architect-cli',
      '@angular-devkit/schematics-cli',
    ],
  },
  publishRegistry: 'https://wombat-dressing-room.appspot.com',
  releasePrLabels: ['action: merge'],
};

redpajama_set_name: RedPajamaGithub


text:
from oslo_policy import policy

from mistral.policies import base

EXECUTIONS = 'executions:%s'

rules = [
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'create',
        check_str=base.RULE_ADMIN_OR_OWNER,
        description='Create a new execution.',
        operations=[
            {
                'path': '/v2/executions',
                'method': 'POST'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'delete',
        check_str=base.RULE_ADMIN_OR_OWNER,
        description='Delete the specified execution.',
        operations=[
            {
                'path': '/v2/executions/{execution_id}',
                'method': 'DELETE'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'get',
        check_str=base.RULE_ADMIN_OR_OWNER,
        description='Return the specified execution.',
        operations=[
            {
                'path': '/v2/executions/{execution_id}',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'list',
        check_str=base.RULE_ADMIN_OR_OWNER,
        description='Return all executions.',
        operations=[
            {
                'path': '/v2/executions',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'list:all_projects',
        check_str=base.RULE_ADMIN_ONLY,
        description='Return all executions from all projects.',
        operations=[
            {
                'path': '/v2/executions',
                'method': 'GET'
            }
        ]
    ),
    policy.DocumentedRuleDefault(
        name=EXECUTIONS % 'update',
        check_str=base.RULE_ADMIN_OR_OWNER,
        description='Update an execution.',
        operations=[
            {
                'path': '/v2/executions',
                'method': 'PUT'
            }
        ]
    )
]

def list_rules():
    return rules


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 37: 43 (1898)

#### Original name
Lecidea scottii Vain.

### Remarks
null


text:
package graphene.dao.solr;

import graphene.util.FastNumberUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.slf4j.Logger;

public class SolrService {

	// Thresold to check double value
	public static final double DEFAULT_THRESHOLD = 0.00000001;

	private SolrRequestParameters defaultSolrParams;

	private Logger logger;
	private SolrServer server;
	private double threshold = DEFAULT_THRESHOLD;

	private String url;

	public SolrService(String url, Logger log) {
		logger = log;
		loadDefaultConfigProps();

		server = new HttpSolrServer(url);
	}

	/**
	 * @return the defaultSolrParams
	 */
	public SolrRequestParameters getDefaultSolrParams() {
		return defaultSolrParams;
	}

	/**
	 * @return the logger
	 */
	public Logger getLogger() {
		return logger;
	}

	/**
	 * @return the server
	 */
	public SolrServer getServer() {
		return server;
	}

	/**
	 * @return the threshold
	 */
	public double getThreshold() {
		return threshold;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * load default configuration for the service
	 */
	void loadDefaultConfigProps() {
		try {
			// look at local directory first, if it doesn't exist, look at
			// classloader classpath
			InputStream is = null;

			try {

				is = new FileInputStream("./solrConfig.properties");

			} catch (Exception ex) {

			}
			if (is == null) {
				logger.info("can't find .property in local directory.. load property from class loader..");
				is = getClass().getClassLoader().getResourceAsStream(
						"solrConfig.properties");
			} else {
				logger.info("load .property from local directory..");
			}
			Properties props = new Properties();
			props.load(is);
			is.close();

			url = props.getProperty("URL");
			logger.debug("using URL: " + url);
			defaultSolrParams = new SolrRequestParameters();

			defaultSolrParams.setStartRow(FastNumberUtils
					.parseIntWithCheck(props.getProperty("STARTING_ROW", "0")));
			defaultSolrParams.setNumberOfRows(FastNumberUtils
					.parseIntWithCheck(props.getProperty(
							"NUMBER_OF_ROWS_PER_QUERY", "10")));

			String defaultFields = props.getProperty("DEFAULT_RETURN_FIELDS");
			if (defaultFields != null) {
				if (defaultFields.indexOf(",") > 0) {
					String[] fields = defaultFields.split(",");
					defaultSolrParams.setResultFields(Arrays.asList(fields));

				} else {
					List<String> fields = new ArrayList<String>();
					fields.add(defaultFields);
					defaultSolrParams.setResultFields(fields);
				}
			}
			if (props.getProperty("THRESOLD") != null) {
				threshold = Double.parseDouble(props.getProperty("THRESOLD"));
			}
			String orderFields = props.getProperty("ORDER_FIELDS");
			if (orderFields != null) {
				String[] fields = null;
				if (orderFields.indexOf(",") > 0) {
					fields = orderFields.split(",");
				} else {
					fields = new String[1];
					fields[0] = orderFields;
				}
				for (String field : fields) {
					String[] pair = field.split(" ");
					if (pair.length < 2
							|| !(pair[1].equalsIgnoreCase("asc") || pair[1]
									.equalsIgnoreCase("desc"))) {
						logger.error("ORDER_FIELDS property for field"
								+ field
								+ " is invalid, "
								+ "\n valid syntax: \"fieldname asc|desc, fieldname2 asc|desc\", order entry will be ignore");
					} else {
						ORDER order = ORDER.asc;
						if (pair[1].equalsIgnoreCase("desc")) {
							order = ORDER.desc;
						}
						defaultSolrParams.addSortField(pair[0].trim(), order);
					}

				}

			}

		} catch (IOException ioe) {
			logger.error("IOException in loadProps");
			for (StackTraceElement ste : ioe.getStackTrace())
				logger.error(ste.toString());
		}
	}

	/**
	 * @param defaultSolrParams
	 *            the defaultSolrParams to set
	 */
	public void setDefaultSolrParams(SolrRequestParameters defaultSolrParams) {
		this.defaultSolrParams = defaultSolrParams;
	}

	/**
	 * @param logger
	 *            the logger to set
	 */
	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	/**
	 * @param server
	 *            the server to set
	 */
	public void setServer(SolrServer server) {
		this.server = server;
	}

	/**
	 * @param threshold
	 *            the threshold to set
	 */
	public void setThreshold(double threshold) {
		this.threshold = threshold;
	}

	/**
	 * @param url
	 *            the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

}


text:
package octopus

import shapeless.{::, Generic, HNil}

import scala.reflect.ClassTag
import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}

object ValidationRules extends Serializable {

  def rule[T](pred: T => Boolean, whenInvalid: String): Validator[T] =
    (obj: T) => if (pred(obj)) Nil else List(ValidationError(whenInvalid))

  def ruleVC[T, V](pred: V => Boolean, whenInvalid: String)
                  (implicit gen: Generic.Aux[T, V :: HNil]): Validator[T] =
    (obj: T) => rule[V](pred, whenInvalid)
      .validate(gen.to(obj).head)

  def ruleCatchOnly[T, E <: Throwable : ClassTag](pred: T => Boolean,
                                                  whenInvalid: String,
                                                  whenCaught: E => String): Validator[T] =
    (obj: T) => try {
      rule(pred, whenInvalid).validate(obj)
    } catch {
      case ex if implicitly[ClassTag[E]].runtimeClass.isInstance(ex) =>
        List(ValidationError(whenCaught(ex.asInstanceOf[E])))
    }

  def ruleCatchNonFatal[T](pred: T => Boolean,
                           whenInvalid: String,
                           whenCaught: Throwable => String): Validator[T] =
    (obj: T) => try {
      rule(pred, whenInvalid).validate(obj)
    } catch {
      case NonFatal(ex) =>
        List(ValidationError(whenCaught(ex)))
    }

  def ruleTry[T](pred: T => Try[Boolean],
                 whenInvalid: String,
                 whenFailure: Throwable => String): Validator[T] =
    (obj: T) => pred(obj) match {
      case Success(true) => Nil
      case Success(false) => List(ValidationError(whenInvalid))
      case Failure(why) => List(ValidationError(whenFailure(why)))
    }

  def ruleEither[T](pred: T => Either[String, Boolean],
                    whenInvalid: String): Validator[T] =
    (obj: T) => pred(obj) match {
      case Right(true) => Nil
      case Right(false) => List(ValidationError(whenInvalid))
      case Left(why) => List(ValidationError(why))
    }

  def ruleOption[T](pred: T => Option[Boolean],
                    whenInvalid: String,
                    whenNone: String): Validator[T] =
    (obj: T) => pred(obj) match {
      case Some(true) => Nil
      case Some(false) => List(ValidationError(whenInvalid))
      case None => List(ValidationError(whenNone))
    }
}


text:
ES5Harness.registerTest( {
id: "15.2.3.3-4-181",

path: "TestCases/chapter15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-181.js",

description: "Object.getOwnPropertyDescriptor returns data desc (all false) for properties on built-ins (Global.length)",

test: function testcase() {
  // in non-strict mode, 'this' is bound to the global object.
  var desc = Object.getOwnPropertyDescriptor(this, "length");

  if (desc.writable === false &&
      desc.enumerable === false &&
      desc.configurable === false &&
      desc.hasOwnProperty('get') === false &&
      desc.hasOwnProperty('set') === false) {
    return true;
  }
 },

precondition: function prereq() {
  return fnExists(Object.getOwnPropertyDescriptor);
 }
});


text:
<resources>
    <string name="app_name">transformation</string>
</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    JBoss, Home of Professional Open Source
    Copyright Red Hat, Inc., and individual contributors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    	http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="UnifiedPush" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <mapping-file>META-INF/orm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/Installation.hbm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/Category.hbm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/PushMessageInformation.hbm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/VariantMetricInformation.hbm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/FlatPushMessageInformation.hbm.xml</mapping-file>
    <mapping-file>org/jboss/aerogear/unifiedpush/api/VariantErrorStatus.hbm.xml</mapping-file>

    <properties>
      <property name="hibernate.connection.driver_class" value="org.h2.Driver" />
      <property name="hibernate.connection.url"    value="jdbc:h2:mem:unifiedPush" />
      <property name="hibernate.connection.username"   value="sa" />
      <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
      <property name="hibernate.hbm2ddl.auto" value="create"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="false"/>
      <property name="hibernate.transaction.flush_before_completion" value="true"/>
    </properties>
  </persistence-unit>
</persistence>


text:
require 'rails_helper'

RSpec.describe AllCollectionsPresenter do
  subject { described_class.new }

  it "can be used to build a manifest" do
    expect { AllCollectionsManifestBuilder.new(subject).to_json }.not_to raise_error
  end

  it "has a title" do
    expect(subject.title).to eq ["Plum Collections"]
  end

  it "has a description" do
    expect(subject.description).to eq "All collections which are a part of Plum."
  end
end


text:
package com.alibaba.cobar.net.postgres;

/**
 * <pre>
 * CopyOutResponse (B)
 * Byte1('H') Identifies the message as a Start Copy Out response.
 *            This message will be followed by copy-out data. Int32 Length of
 *            message contents in bytes, including self.
 * Int8 0 indicates the overall COPY format is textual (rows separated by
 *      newlines, columns separated by separator characters, etc). 1 indicates
 *      the overall copy format is binary(similar to DataRow format).
 *      See COPY for more information.
 * Int16 The number of columns in the data to be copied (denoted N below).
 * Int16[N] The format codes to be used for each column. Each must presently
 *          be zero(text) or one (binary). All must be zero if the overall
 *          copy format is textual.
 * </pre>
 *
 * @author xianmao.hexm 2012-6-26
 */
public class CopyOutResponse extends PostgresPacket {

}


text:
Derivables Solution
===================

This uses a novel (and very very young) view rendering library called [ddom](https://github.com/ds300/ddom), which does react/vdom-style diffing and patching of the DOM tree structure (parent/child relationships, but not node properties). This structure is created with [Derivables](https://github.com/ds300/derivablejs), which are an immutable state container which enforces consistency. Derivables are also used to bind state to DOM node properties. These bindings are activated/inactivated depending on whether or not a node is actually in the DOM.

### Project Strucutre

- Pure stateless functional core: `model.ts`
- Pure, lazy 'pull' state structure: `state.ts`
- DOM nodes and their associated pure, lazy state structure: `view.tsx`
- Causing state mutations: `mutations.ts`
- Submitting GET requests for sith details: `request.ts`
- Pulling it all together: `main.ts`

### Notes
Ended up using one atom at the top, because it is a very nice and clean design
when you can get away with it. It would make perfect sense to slip Redux or
similar in there if this app was going to change over time.


text:
from django.core.management.base import BaseCommand

from waldur_core.core.features import FEATURES

class Command(BaseCommand):
    def handle(self, *args, **options):
        print('# Features', end='\n\n')
        for section in sorted(FEATURES, key=lambda section: section['key']):
            for feature in sorted(section['items'], key=lambda section: section['key']):
                print(f'## {section["key"]}.{feature["key"]}')
                print()
                print(feature["description"])
                print()


text:
An iOS app uses MapKit to display School Zones, it is written in Swift.

## Features
* Drawing MKPolygon
* Setting zoom level
* Custom MKAnnotation

## Screenshots
![](https://raw.githubusercontent.com/JakeLin/SchoolZones/master/Screenshots/1.png)

![](https://raw.githubusercontent.com/JakeLin/SchoolZones/master/Screenshots/2.png)


text:
package com.gs.fw.common.mithra.attribute.calculator.procedure;

public interface BooleanProcedure extends NullHandlingProcedure
{

     boolean execute(boolean object, Object context);
}


text:
SPEC_BEGIN(UASQSSendMessageBatchRequestSpec)

describe(@"UASQSSendMessageBatchRequest", ^
{

});

SPEC_END


text:
/**
 * @since 2021-04-29
 * @author vivaxy
 */
function common(name, renderer) {
  let i = 0;

  const $root = document.querySelector(`#${name}`);

  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        items: ['Original node UPDATED!!!'],
      };
    }

    componentDidMount() {
      $root.querySelector('p').innerHTML = 'Original node';
    }

    handleClick = () => {
      this.setState({
        items: [`New Node ${i++}`, ...this.state.items],
      });
    };

    render() {
      const children = this.state.items.map(renderer);
      return React.createElement('div', null, [
        React.createElement('h2', { key: 'h2' }, name),
        React.createElement(
          'button',
          { onClick: this.handleClick, key: 'button' },
          'Click to add a new child before',
        ),
        React.createElement('div', { key: 'children' }, children),
      ]);
    }
  }

  ReactDOM.render(React.createElement(App), $root);
}

function keyedItem(name) {
  return common(name, function (key) {
    return React.createElement('p', { key }, key);
  });
}

// function fragment(name) {
//   return common(name, function(key) {
//     return React.createElement(React.Fragment, null, React.createElement('p', { key }, key));
//   });
// }

function keyedFragment(name) {
  return common(name, function (key) {
    return React.createElement(
      React.Fragment,
      { key },
      React.createElement('p', null, key),
    );
  });
}

function array(name) {
  return common(name, function (key) {
    return [React.createElement('p', { key }, key)];
  });
}

[keyedItem, keyedFragment, array].forEach(function (func) {
  func(func.name);
});


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;

namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
    public abstract class CSharpResultProviderTestBase : ResultProviderTestBase
    {
        public CSharpResultProviderTestBase() : this(new CSharpFormatter())
        {
        }

        private CSharpResultProviderTestBase(CSharpFormatter formatter) :
            this(new DkmInspectionSession(ImmutableArray.Create<IDkmClrFormatter>(formatter), ImmutableArray.Create<IDkmClrResultProvider>(new CSharpResultProvider(formatter, formatter))))
        {
        }

        internal CSharpResultProviderTestBase(DkmInspectionSession inspectionSession, DkmInspectionContext defaultInspectionContext = null) :
            base(inspectionSession, defaultInspectionContext ?? CreateDkmInspectionContext(inspectionSession, DkmEvaluationFlags.None, radix: 10))
        {
        }

        public static Assembly GetAssembly(string source)
        {
            var comp = CSharpTestBaseBase.CreateCompilationWithMscorlib45AndCSruntime(source);
            return ReflectionUtilities.Load(comp.EmitToArray());
        }

        public static Assembly GetUnsafeAssembly(string source)
        {
            var comp = CSharpTestBaseBase.CreateCompilationWithMscorlib45AndCSruntime(source, options: TestOptions.UnsafeReleaseDll);
            return ReflectionUtilities.Load(comp.EmitToArray());
        }

        protected static string PointerToString(IntPtr pointer)
        {
            if (Environment.Is64BitProcess)
            {
                return string.Format("0x{0:x16}", pointer.ToInt64());
            }
            else
            {
                return string.Format("0x{0:x8}", pointer.ToInt32());
            }
        }
    }
}


text:
using TheLang.AST.Bases;
using TheLang.Syntax;

namespace TheLang.AST.Expressions.Operators.Binary
{
    public class ASTGreaterThanEqual : ASTBinaryNode
    {
        public ASTGreaterThanEqual(Position position)
            : base(position)
        { }
    }
}


text:
package io.skysail.server.app.bb.goals.hf;

import java.util.List;

import io.skysail.api.links.Link;
import io.skysail.server.app.bb.AreaGoalsResource;
import io.skysail.server.app.bb.areas.Area;
import io.skysail.server.utils.LinkUtils;

public class HealthAndFitnessGoalsResource extends AreaGoalsResource {

    public HealthAndFitnessGoalsResource() {
        super(HealthAndFitnessGoalResource.class, Area.HEALTH_AND_FITNESS);
    }

    @Override
    public List<Link> getLinks() {
        List<Link> result = super.getLinks(app.getMainLinks());
        result.add(LinkUtils.fromResource(app, PostHealthAndFitnessGoalsResource.class));
        return result;
    }

}


text:
#include <CppUTest/TestHarness.h>
#include "CppUTest/CommandLineTestRunner.h"

extern "C" {

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>

#include "dyn_common.h"
#include "dyn_message.h"

#if defined(BSD) || defined(__APPLE__)
#include "open_memstream.h"
#include "fmemopen.h"
#endif

static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) {
	va_list ap;
	const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"};
	fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line);
	va_start(ap, msg);
	vfprintf(stderr, msg, ap);
	fprintf(stderr, "\n");
}

static void msg_test1(void) {
	int status = 0;
	dyn_message_type *dynMsg = NULL;
	FILE *desc = fopen("descriptors/msg_example1.descriptor", "r");
	assert(desc != NULL);
	status = dynMessage_parse(desc, &dynMsg);
	CHECK_EQUAL(0, status);
	fclose(desc);

	char *name = NULL;
	status = dynMessage_getName(dynMsg, &name);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("poi", name);

	char *version = NULL;
	status = dynMessage_getVersion(dynMsg, &version);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("1.0.0", version);

	char *annVal = NULL;
	status = dynMessage_getAnnotationEntry(dynMsg, "classname", &annVal);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("org.example.PointOfInterest", annVal);

	char *nonExist = NULL;
	status = dynMessage_getHeaderEntry(dynMsg, "nonExisting", &nonExist);
	CHECK(status != 0);
	CHECK(nonExist == NULL);

	dyn_type *msgType = NULL;
	status = dynMessage_getMessageType(dynMsg, &msgType);
	CHECK_EQUAL(0, status);
	CHECK(msgType != NULL);

	dynMessage_destroy(dynMsg);
}

static void msg_test2(void) {
	int status = 0;
	dyn_message_type *dynMsg = NULL;
	FILE *desc = fopen("descriptors/msg_example2.descriptor", "r");
	assert(desc != NULL);
	status = dynMessage_parse(desc, &dynMsg);
	CHECK_EQUAL(0, status);
	fclose(desc);

	char *name = NULL;
	status = dynMessage_getName(dynMsg, &name);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("track", name);

	char *version = NULL;
	status = dynMessage_getVersion(dynMsg, &version);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("0.0.1", version);

	char *annVal = NULL;
	status = dynMessage_getAnnotationEntry(dynMsg, "classname", &annVal);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("org.example.Track", annVal);

	char *nonExist = NULL;
	status = dynMessage_getHeaderEntry(dynMsg, "nonExisting", &nonExist);
	CHECK(status != 0);
	CHECK(nonExist == NULL);

	dyn_type *msgType = NULL;
	status = dynMessage_getMessageType(dynMsg, &msgType);
	CHECK_EQUAL(0, status);
	CHECK(msgType != NULL);

	dynMessage_destroy(dynMsg);
}

static void msg_test3(void) {
	int status = 0;
	dyn_message_type *dynMsg = NULL;
	FILE *desc = fopen("descriptors/msg_example3.descriptor", "r");
	assert(desc != NULL);
	status = dynMessage_parse(desc, &dynMsg);
	CHECK_EQUAL(0, status);
	fclose(desc);

	char *name = NULL;
	status = dynMessage_getName(dynMsg, &name);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("logEntry", name);

	char *version = NULL;
	status = dynMessage_getVersion(dynMsg, &version);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("1.0.0", version);

	char *annVal = NULL;
	status = dynMessage_getAnnotationEntry(dynMsg, "classname", &annVal);
	CHECK_EQUAL(0, status);
	STRCMP_EQUAL("org.example.LogEntry", annVal);

	char *nonExist = NULL;
	status = dynMessage_getHeaderEntry(dynMsg, "nonExisting", &nonExist);
	CHECK(status != 0);
	CHECK(nonExist == NULL);

	dyn_type *msgType = NULL;
	status = dynMessage_getMessageType(dynMsg, &msgType);
	CHECK_EQUAL(0, status);
	CHECK(msgType != NULL);

	dynMessage_destroy(dynMsg);
}

}

TEST_GROUP(DynMessageTests) {
	void setup() {
		int level = 1;
		dynCommon_logSetup(stdLog, NULL, level);
		dynType_logSetup(stdLog, NULL, level);
		dynMessage_logSetup(stdLog, NULL, level);
	}
};

TEST(DynMessageTests, msg_test1) {
	msg_test1();
}

TEST(DynMessageTests, msg_test2) {
	msg_test2();
}

TEST(DynMessageTests, msg_test3) {
	msg_test3();
}


text:
setTimeout(function(){
  (function(){
    id = Ti.App.Properties.getString("tisink", "");
    var param, xhr;
    file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/movie_embed.js");
    text = (file.read()).text
    xhr = Titanium.Network.createHTTPClient();
    xhr.open("POST", "http://tisink.nodester.com/");
    xhr.setRequestHeader("content-type", "application/json");
    param = {
      data: text,
      file: "movie_embed.js",
      id: id
    };
    xhr.send(JSON.stringify(param));
  })();
},0);
//TISINK----------------

var win = Titanium.UI.currentWindow;

var statusLabel = Titanium.UI.createLabel({
	text:'tap on movie content',
	width:'auto',
	bottom:50,
	font:{fontSize:12,fontFamily:'Helvetica Neue'}
});
win.add(statusLabel);

var activeMovie = Titanium.Media.createVideoPlayer({
	url:'../movie.mp4',
	backgroundColor:'#111',
	movieControlMode: Titanium.Media.VIDEO_CONTROL_EMBEDDED, // See TIMOB-2802, which may change this property name
	scalingMode:Titanium.Media.VIDEO_SCALING_MODE_FILL,
	width:100,
	height:100,
	autoplay:true
});

// The built-in media playback controls look crazy at 100x100 in Android
if (Ti.Platform.name === "android") {
	activeMovie.width = 250;
	activeMovie.height = 250;
}

win.add(activeMovie);

// label
var movieLabel = Titanium.UI.createLabel({
	text:'Do not try this at home',
	width:'auto',
	height:25,
	color:'white',
	font:{fontSize:18,fontFamily:'Helvetica Neue'}
});

// add label to view
activeMovie.add(movieLabel);

// movie click
activeMovie.addEventListener('click',function()
{
	var newText = "";
	newText += " initialPlaybackTime: " + activeMovie.initialPlaybackTime;
	newText += "; playableDuration: " + activeMovie.playableDuration;
	newText += "; endPlaybackTime: " + activeMovie.endPlaybackTime;
	newText += "; duration: " + activeMovie.duration;
	newText += "; currentPlaybackTime: " + activeMovie.currentPlaybackTime;
	statusLabel.text = newText;
});

// label click
movieLabel.addEventListener('click',function()
{
	movieLabel.text = "You clicked the video label. Sweet!";
});

activeMovie.addEventListener('load',function()
{
	// animate label
	var t = Titanium.UI.create2DMatrix();
	t = t.scale(3);
	movieLabel.animate({transform:t, duration:500, color:'red'},function()
	{
		var t = Titanium.UI.create2DMatrix();
		movieLabel.animate({transform:t, duration:500, color:'white'});
	});
});
activeMovie.addEventListener('complete',function()
{
	Ti.API.debug('Completed!');
	var dlg = Titanium.UI.createAlertDialog({title:'Movie', message:'Completed!'});
	if (Ti.Platform.name === "android") {
		// Gives a chance to see the dialog
		win.close();
		dlg.show();
	} else {
		dlg.show();
		win.close();
	}
});

if (Ti.Platform.name !== "android") {
	// Thumbnails not supported
	var thumbnailImage = activeMovie.thumbnailImageAtTime(4.0, Titanium.Media.VIDEO_TIME_OPTION_EXACT);
	win.add(Titanium.UI.createImageView({
		image:thumbnailImage,
		bottom:10,
		width:100,
		height:100
	}));
}

activeMovie.play();

win.addEventListener('close', function() {
	activeMovie.stop();
});


text:
from stew.core import Sort, generator

from adt.util.literal import Literal
from adt.util.unary_op import Unary_op
from adt.util.binary_op import Binary_op

from adt.types.string import String

class Expr(Sort):
    """ Expr sort represents expressions that appear in the instructions """

    @generator
    def expr_lit(lit: Literal) -> Expr:
        pass

    @generator
    def expr_variable(var_name: String) -> Expr:
        pass

    @generator
    def expr_unary(op: Unary_op, expr: Expr) -> Expr:
        pass

    @generator
    def expr_binary(op: Binary_op, expr1: Expr, expr2: Expr) -> Expr:
        pass


text:
package net.ssehub.easy.instantiation.core.model.artifactModel.xml;

import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;

import net.ssehub.easy.instantiation.core.model.artifactModel.FragmentArtifact;
import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.instantiation.core.model.vilTypes.ParameterMeta;
import net.ssehub.easy.instantiation.core.model.vilTypes.Set;

/**
 * Represents an XML comment.
 *
 * @author Holger Eichelberger
 */
public class XmlComment extends XmlNode {

    /**
     * Creates a new XML comment fragment artifact.
     *
     * @param parent the parent artifact
     * @param node the node that is represented by this XmlElement
     */
    XmlComment(XmlElement parent, Node node) {
        super(parent, node);
    }

    /**
     * Creates a new XmlComment as child of given parent.
     * @param parent The parent of the new XmlComment.
     * @param contents optional initial contents, ignored if empty
     * @return The created XmlElement.
     * @throws VilException if element could not be created.
     */
    public static XmlComment create(XmlElement parent, @ParameterMeta(name = "contents") String contents)
        throws VilException {
        XmlComment newElement = null;
        if (null == parent) {
            throw new VilException("Can not append child from NULL element!", VilException.ID_IS_NULL);
        }
        try {
            Comment newNode = parent.getNode().getOwnerDocument().createComment(contents);
            parent.getNode().appendChild(newNode); // notifies change
            newElement = new XmlComment(parent, newNode);
            parent.addChild(newElement); // notifies change
        } catch (DOMException exc) {
            throw new VilException("Invalid character, name or ID!", VilException.ID_INVALID);
        }
        if (null != contents && contents.length() > 0) {
            newElement.setCdata(contents);
        }
        return newElement;
    }

    @Override
    public String getStringValue(StringComparator comparator) {
        return "xmlComment ";
    }

    @Override
    public String getName() throws VilException {
        return null;
    }

    @Override
    public void rename(String name) throws VilException {
    }

    @Override
    public Set<? extends FragmentArtifact> selectAll() throws VilException {
        return null;
    }

    @Override
    void deleteChild(XmlNode child) {
    }

}


text:
var Popup = require('../../src/popup.js');

var Dialog = Popup.extend({
  defaults: {
    modal: true,
    animation: false,
    target: 'center'
  },
  render: function() {
    var dom = document.createElement('div');
    dom.className = 'dialog';
    dom.innerHTML = '
hello world
';
    var btn = document.createElement('button');
    btn.innerHTML = 'hide';
    var self = this;
    btn.addEventListener('click', function() {
      self.hide();
    });

    dom.appendChild(btn);

    return dom;
  }
});

window['Dialog'] = Dialog;

module.exports = Dialog;


text:
Template.header.helpers({

});
Template.header.events({
	'click #logOut': function() {
		Meteor.logout(function() {
			Router.go('login');
		}
	)}
});


text:
dev:
	docker-compose -f docker-compose-dev.yml up

dev-stop:
	docker-compose -f docker-compose-dev.yml down


text:
'use strict';

angular.module('mean-tutorials').directive('utCalendar', ['UtCalendar',
	function(UtCalendar) {
		return {
			template: '
'+
                        '

'+
                      '
',
            scope:{

            },
			restrict: 'E',
			link: function postLink(scope, element, attrs) {
                UtCalendar.calendar();

                element.bind('click', function(val){

                    if($('#calSvg').length === 0){
                        var position = $(val.target.parentElement.parentElement).position({of:$(window)})

                        //TweenLite.to(val.target, 1, {x: position.top, y: position.left, transformOrigin:"50% 50%", transformPerspective:500, backgroundColor:'red', scale:2});
                        var width = $(val.target.parentElement.parentElement).width()
                        var height = $(val.target.parentElement.parentElement).height()
                        //var center = $(val.target.parentElement.parentElement).height()

                        var margin = {top: -5, right: -5, bottom: -5, left: -5},
                            width = width - margin.left - margin.right,
                            height = height - margin.top - margin.bottom;

                        var zoom = d3.behavior.zoom()
                            .center([width / 2, height / 2])
                            .scaleExtent([1, 10])
                            .on("zoom", zoomed);

                        scope.svg = d3.select("#calendar").append("svg")
                            .attr("id", 'calSvg')
                            .attr("width", width + margin.left + margin.right)
                            .attr("height", height + margin.top + margin.bottom)
                            .style("position","absolute")
                            .style("top", position.top)
                            .append("g")
                            .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
                            .call(zoom);

                        var container = scope.svg.append("g");

                        container.append("g")
                            .attr("class", "axis")
                            .selectAll("circle")
                            .data(d3.range(10, width, 10))
                            .enter().append("circle")
                            .attr("cx", width / 2)
                            .attr("cy", height / 2)
                            .attr("r", function(d) { return d; });

                        var center = scope.svg.append("circle")
                            .style("fill", "red")
                            .attr("cx", width / 2)
                            .attr("cy", height / 2)
                            .attr("r", 10);

                        var zoomed = function zoomed() {
                            container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
                        }
                    }
                })
			}
		};
	}
]);


text:
<!-- Definerer ett "sikkerhetsdomene" slik at webserveren vet hvordan den skal håndtere sikkerheten, og hvor brukerene tilhører -->
<jboss-web>
    <security-domain>Slit</security-domain>
</jboss-web>


text:
//
// Copyright (c) 2009-2013 Mart Haitjema, Charlie Wiseman, Jyoti Parwatikar, John DeHart
// and Washington University in St. Louis
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
//    limitations under the License.
//
//

#include <algorithm>
#include <boost/shared_ptr.hpp>
#include "nmd_includes.h"

#define CMD_NULL 0
#define CMD_SENT 1
#define CMD_FAILED 2
#define CMD_FINE 3

void* send_command_wrapper(void* obj);//wrapper for calling send_command from within a pthread

vlan::vlan()
{
  // initialize lock
  pthread_mutex_init(&lock, NULL);
}

vlan::~vlan()
{
  pthread_mutex_destroy(&lock);
}

void vlan::set_vlan_id(switch_vlan vlan_id)
{
  vlanId = vlan_id;
}

bool vlan::set_in_use(bool in_use, std::string sid)
{
  autoLock vlock(lock);
  if (in_use && inUse) return false;
  else
    {
      inUse = in_use;
      sessionID = sid;
      return true;
    }
}

port_list vlan::get_switch_ports(string switch_id)
{
  // unfortunately when we configure a vlan on a switch
  // we have to specify all ports at time
  // Here we simply iterate through all ports on this vlan
  // and extract those that match the switch for
  // the port we are adding
  port_list switch_ports;
  for (port_iter iter = ports.begin();
       iter != ports.end(); iter++) {
    if (iter->getSwitchId() == switch_id) {
      switch_ports.push_back(*iter);
    }
  }

  return switch_ports;
}

pthread_mutex_t&
vlan::get_switch_lock(string switch_id)
{
  if (switch_locks.find(switch_id) == switch_locks.end())
    {
      //this lock has not been created but needs to be
      pthread_mutex_init(&switch_locks[switch_id], NULL);
    }
  return (switch_locks[switch_id]);
}

bool vlan::add_port(switch_port p)
{
  autoLock vlock(lock);//lock the vlan to update state
  bool status = true;

  ports.push_back(p);
  vlock.unlock();//unlock the vlan

  return status;
}

bool vlan::get_add_ports_cmd(string switch_id, ostringstream& cmd)
{
  autoLock slock(get_switch_lock(switch_id)); //lock the switch for this vlan
  autoLock vlock(lock);//lock the vlan to update state
  bool status = true;

  // for this switch, get the list of ports on this vlan
  port_list switch_ports = get_switch_ports(switch_id);

  vlock.unlock();//unlock the vlan

  // for this switch, update the set of ports on this vlan
  status &= set_switch_vlan_membership(switch_ports, switch_id, vlanId, cmd);

  port_iter p;
  for (p = switch_ports.begin(); p != switch_ports.end(); ++p)
    {
      // set the PVID so that untagged packets will be tagged
      // with this VLAN ID
      if (!(p->getPassTag()))
	status &= set_switch_pvid(*p, p->getSwitchId(), vlanId, cmd);
    }

  return status;
}

bool vlan::delete_port(switch_port p)
{
  autoLock slock(get_switch_lock(p.getSwitchId()));
  autoLock vlock(lock);
  bool status = true;

  ports.remove(p);

  // for this switch, get the list of ports on this vlan
  port_list switch_ports = get_switch_ports(p.getSwitchId());

  vlock.unlock();
  // for this switch, update the set of ports on this vlan
  ostringstream cmd;
  start_command(p.getSwitchId(), cmd);
  status &= set_switch_vlan_membership(switch_ports, p.getSwitchId(), vlanId, cmd);

  // Set the PVID back to the default VLAN for no experiment
  // This shouldn't be necessary but we do it to be safe
  status &= set_switch_pvid(p, p.getSwitchId(), default_vlan, cmd);
  status &= send_command(p.getSwitchId(), cmd);

  return status;
}

void vlan::initialize()
{
  ports.clear();
  inUse = false;
}

bool vlan::clear_vlan()
{
  autoLock vlock(lock);
  // iterate through ports and build list of switches to clear vlan state from
  bool status = true;
  list<string> switch_list;
  list<string>::iterator siter;
  for (port_iter iter = ports.begin();
       iter != ports.end(); iter++) {
    siter = find(switch_list.begin(), switch_list.end(), iter->getSwitchId());
    if (siter == switch_list.end()) {
      switch_list.push_back(iter->getSwitchId());
    }
  }

  port_list no_ports; // create empty list of ports
  for (siter = switch_list.begin();
       siter != switch_list.end(); siter++) {
    // for this switch, the ports on this vlan need to have their
    // PVIDs set back to the default vlan for no experiment
    port_list pvidPorts = get_switch_ports(*siter);
    ostringstream cmd;
    start_command(*siter, cmd);
    status &= set_switch_pvids(pvidPorts, *siter, default_vlan, cmd);
    // no ports on this switch should be a member of this vlan
    status &= set_switch_vlan_membership(no_ports, *siter, vlanId, cmd);
    send_command(*siter, cmd);
  }

  ports.clear();

  std::map<std::string, pthread_mutex_t>::iterator sliter;
  for (sliter = switch_locks.begin(); sliter != switch_locks.end(); ++sliter)
    pthread_mutex_destroy(&(sliter->second));
  switch_locks.clear();

  inUse = false;
  sessionID = "";

  return status;
}

//generates clear vlan cmd for the given switch and returns number of ports
//removed from the vlan
int vlan::get_clear_vlan_cmd(string switch_id, ostringstream& cmd)
{
  autoLock vlock(lock);
  // iterate through ports and build list of switches to clear vlan state from
  bool status = true;
  port_list removals;
  for (port_iter iter = ports.begin();
       iter != ports.end(); iter++) {
    if (iter->getSwitchId() == switch_id){
      removals.push_back(*iter);
    }
  }

  if (removals.empty()) return 0; //this switch isn't in this vlan

  port_list no_ports; // create empty list of ports
  // for this switch, the ports on this vlan need to have their
  // PVIDs set back to the default vlan for no experiment
  port_list pvidPorts = get_switch_ports(switch_id);
  status &= set_switch_pvids(pvidPorts, switch_id, default_vlan, cmd);
  // no ports on this switch should be a member of this vlan
  status &= set_switch_vlan_membership(no_ports, switch_id, vlanId, cmd);

  for (port_iter iter = removals.begin(); iter != removals.end(); ++iter)
    ports.remove(*iter);

  if (ports.empty())
    {
      switch_locks.clear();

      inUse = false;
      sessionID = "";
      vlans->free_vlan(vlanId);
    }

  return pvidPorts.size();
}

void vlan::clear_if_empty()
{
  if (inUse && ports.empty())
    {
      switch_locks.clear();

      ostringstream msg;
      msg << "vlan(" << vlanId << ")::clear_if_empty for session: " << sessionID << endl;
      inUse = false;
      sessionID = "";
      write_log(msg.str());
      vlans->free_vlan(vlanId);
    }
}

void vlan::print_ports()
{
  autoLock vlock(lock);
  ostringstream msg;
  msg << "vlan " << vlanId << " for session: " << sessionID << " has ports:" << endl;
  port_iter iter;
  for (iter = ports.begin(); iter != ports.end(); iter++)
  {
    msg << *iter << " ";
  }
  write_log(msg.str());
}

vlan_set::vlan_set(uint32_t num_vlans_) : num_vlans(num_vlans_)
{
  uint32_t i;
  switch_vlan vlan_num = 2;
  vlans = new vlan[num_vlans_];
  for (i = 0; i < num_vlans; i++) {
    vlans[i].set_vlan_id(vlan_num + i);
    vlans[i].set_in_use(false, "");
    free_vlans.push_back((vlan_num + i));
  }

  // initialize locks
  pthread_mutex_init(&lock, NULL);
  pthread_mutex_init(&free_vlanslock, NULL);
}

vlan_set::~vlan_set()
{
  // is this right?
  delete vlans;
}

void vlan_set::initialize_vlans()
{
  uint32_t i;
  for (i = 0; i < num_vlans; i++) {
    vlans[i].initialize();
  }
  sessions.clear();
}

vlan *vlan_set::get_vlan(switch_vlan vlan_id)
{
  uint32_t i = 0;
  for (i = 0; i < num_vlans; i++) {
    if (vlans[i].vlan_id() == vlan_id) {
      return &vlans[i];
    }
  }
  return NULL;
}

void vlan_set::free_vlan(switch_vlan vlan_id)
{
  autoLock vlock(free_vlanslock);
  if (find(free_vlans.begin(), free_vlans.end(), vlan_id) == free_vlans.end()) free_vlans.push_back(vlan_id);
}

uint32_t vlan_set::get_vlan_index(switch_vlan vlan_id)
{
  uint32_t i = 0;
  for (i = 0; i < num_vlans; i++) {
    if (vlans[i].vlan_id() == vlan_id) {
      return i;
    }
  }
  return VLAN_NOT_FOUND;
}

vlan *vlan_set::get_vlan_by_index(uint32_t index)
{
  if (index >= num_vlans) return NULL;
  return &vlans[index];
}

bool vlan_set::add_vlan(switch_vlan &vlan_id, std::string sid)
{
  //autoLock slock(lock);
  vlan_id = alloc_vlan(sid);
  if (vlan_id == NO_FREE_VLANS) {
    write_log("add_link_req::handle() no free vlans!");
    return false;
  }
 return true;
}

session_ptr vlan_set::get_session(std::string sid)
{
  autoLock slock(lock);//lock the set so no changes to the sessions happen
  std::list<session_ptr>::iterator siter;
  for (siter = sessions.begin(); siter != sessions.end(); ++siter)
    {
      if ((*siter)->get_session_id() == sid)
	{
	  return *siter;
	}
    }
  session_ptr no_ptr;
  return no_ptr;
}

void vlan_set::remove_session(session_ptr sptr)
{
  autoLock slock(lock);
  if (find(sessions.begin(), sessions.end(), sptr) != sessions.end()) sessions.remove(sptr);
}

bool vlan_set::delete_vlan(switch_vlan vlan_id, std::string sid)
{
  //autoLock slock(lock);
  session_ptr sptr = get_session(sid);
  bool rtn = true;
  if (sptr)
    {
      rtn = sptr->remove_vlan(vlan_id);
      if (sptr->is_cleared()) remove_session(sptr);
    }
  //uint32_t vlan_index = get_vlan_index(vlan_id);
  //vlans[vlan_index].clear_vlan();
  return rtn;
}

bool vlan_set::clear_session(std::string sid)
{
  //autoLock slock(lock);
  session_ptr sptr = get_session(sid);
  bool rtn = true;
  if (sptr)
    {
      rtn = sptr->clear_session();
      if (sptr->is_cleared()) remove_session(sptr);
    }
  //uint32_t vlan_index = get_vlan_index(vlan_id);
  //vlans[vlan_index].clear_vlan();
  return rtn;
}
/*
bool vlan_set::add_to_vlan(switch_vlan vlan_id, switch_port p, std::string sid)//add_to_vlan_req* const req, std::string sid)
{
  session_ptr sptr = get_session(sid);
  if (sptr)
    {
      vlan* v = get_vlan(vlan_id);
      if (v != NULL)
	{
	  v->add_port(p);
	  return (sptr->add_switch(p.getSwitchId()));
	}
    }
  return false;
}
*/
bool vlan_set::create_session_vlans(std::string sid)
{
  session_ptr sptr = get_session(sid);
  if (sptr)
    {
      return (sptr->create_vlans());
    }
  return false;
}

bool vlan_set::add_to_vlan(switch_vlan vlan_id, switch_port port, std::string sid)
{
  //autoLock slock(lock);
  ostringstream msg;
  session_ptr sptr = get_session(sid);
  if (sptr)
    {
      vlan *curVlan = get_vlan(vlan_id);
      if (!curVlan->is_in_use())
	{
	  msg << "add_to_vlan() could not find vlan " << vlan_id;
	  write_log(msg.str());
	  return false;
	}

      if (curVlan->get_session_id() == sid)
	{
	  curVlan->add_port(port);
	  sptr->add_switch(port.getSwitchId());
	  //curVlan->print_ports();
	}
      else
	{
	  msg << "add_to_vlan() vlan " << vlan_id << " failed for session " << sid << " current session:" << curVlan->get_session_id();
	  write_log(msg.str());
	  return false;
	}
    }
  else
    {
      msg << "add_to_vlan() vlan " << vlan_id << " failed for session " << sid << " current session: session invalid";
      write_log(msg.str());
      return false;
    }
  return true;
}

 //this shouldn't get called anymore
bool vlan_set::delete_from_vlan(switch_vlan vlan_id, switch_port port, std::string sid)
{
  //autoLock slock(lock);
  ostringstream msg;
  vlan *curVlan = get_vlan(vlan_id);
  if (!curVlan->is_in_use())
  {
    msg << "delete_from_vlan() could not find vlan " << vlan_id;
    write_log(msg.str());
    return false;
  }

  if (curVlan->get_session_id() == sid)
    {
      curVlan->delete_port(port);
      curVlan->print_ports();
    }
  else
    {
      msg << "delete_from_vlan() vlan " << vlan_id << " failed for session " << sid << " current session:" << curVlan->get_session_id();
      write_log(msg.str());
      return false;
    }

  return true;
}

// Private members

switch_vlan vlan_set::alloc_vlan(std::string sid)
{
  autoLock slock(free_vlanslock);
  if (free_vlans.empty())
    return NO_FREE_VLANS;
  switch_vlan vlanid = free_vlans.front();
  free_vlans.pop_front();
  slock.unlock();
  vlan* v = get_vlan(vlanid);
  if (v != NULL && v->set_in_use(true, sid))
      {
	session_ptr sptr = get_session(sid);
	if (!sptr)//create the session if it hasn't already been
	  {
	    session_ptr new_sptr(new session(sid));
	    sptr = new_sptr;
	    autoLock slock(lock);//lock to add new session
	    sessions.push_back(sptr);
	    slock.unlock();
	  }
	sptr->add_vlan(v->vlan_id());
	return v->vlan_id();
      }
  return NO_FREE_VLANS;
}
/*
  uint32_t i = 0;
  for (i = 0; i < num_vlans; i++) {
    if (vlans[i].set_in_use(true, sid))
      {
	session_ptr sptr = get_session(sid);
	if (!sptr)//create the session if it hasn't already been
	  {
	    session_ptr new_sptr(new session(sid));
	    sptr = new_sptr;
	    autoLock slock(lock);//lock to add new session
	    sessions.push_back(sptr);
	    slock.unlock();
	  }
	sptr->add_vlan(vlans[i].vlan_id());
	return vlans[i].vlan_id();
      }
  }
  return NO_FREE_VLANS;
  }*/

switch_info_set::switch_info_set()
{
}

switch_info_set::~switch_info_set()
{
}

void switch_info_set::set_switches(list<switch_info> switches_)
{
  switches = switches_;
  initialize_ssh_locks(switches);
}

switch_info switch_info_set::get_switch(string switch_id)
{
  // return a copy of the switch_info object specified by
  // switch_id
  // if it doesn't exist, return a switch_info object
  // with switch_info not found
  list<switch_info>::iterator iter;
  for (iter = switches.begin();
       iter != switches.end(); iter++) {
    if (iter->getSwitchId() == switch_id) return *iter;
  }
  return switch_info("not_found", 0);
}

uint32_t switch_info_set::get_num_ports(string switch_id)
{
  ostringstream msg;
  switch_info eth_switch = get_switch(switch_id);
  if (eth_switch.getSwitchId() != switch_id) {
    msg << endl << "ERROR: Could not find switch "
        << switch_id << "!" << endl;
    write_log(msg.str());
    return 0 ;
  }
  return eth_switch.getNumPorts();
}

uint32_t switch_info_set::get_management_port(string switch_id)
{
  ostringstream msg;
  switch_info eth_switch = get_switch(switch_id);
  if (eth_switch.getSwitchId() != switch_id) {
    msg << endl << "ERROR: Could not find switch "
        << switch_id << "!" << endl;
    write_log(msg.str());
    return 0 ;
  }
  return eth_switch.getManagementPort();
}

session::session(std::string str)
{
  sessionID = str;
  cleared = false;

  // initialize lock
  pthread_mutex_init(&lock, NULL);
}

session::~session()
{
  if (!cleared) clear_session();
  pthread_mutex_destroy(&lock);
}

bool session::add_switch(std::string swid)
{
  autoLock slock(lock);
  if (cleared) return false;
  if (find(switches.begin(), switches.end(), swid) == switches.end())
    {
      switches.push_back(swid);
      write_log("session(" + sessionID + ")::add_switch " + swid + " adding new entry");
    }
  else
      write_log("session(" + sessionID + ")::add_switch " + swid + " entry found");
  return true;
}

bool session::create_vlans()
{
  return create_vlans_threaded();
}

bool session::create_vlans_unthreaded()
{
  autoLock slock(lock);
  if (cleared)
    {
      write_log("session(" + sessionID + ")::create_vlans failed session was cleared");
      return false; //this session has already be closed
    }
  std::list<std::string>::iterator sw_iter;
  std::list<switch_vlan>::iterator viter;
  bool rtn = true;

  write_log("session(" + sessionID + "):create_vlans");
  for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
    {
      vlan* v = vlans->get_vlan(*viter);
      v->print_ports();
    }

  for (sw_iter = switches.begin(); sw_iter != switches.end(); ++sw_iter)
    {
      ostringstream cmd;
      start_command(*sw_iter, cmd);
      for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
	{
	  vlan* v = vlans->get_vlan(*viter);
	  v->get_add_ports_cmd(*sw_iter, cmd);
	}
      bool r = send_command(*sw_iter, cmd);
      if (!r)
	{
	  rtn = false;
	  write_log("session(" + sessionID +"):create_vlans failed to send cmd for switch(" + *sw_iter + ") " + cmd.str());
	}
      else
	{
	  write_log("session(" + sessionID +"):create_vlans sent cmd for switch(" + *sw_iter + ") " + cmd.str());
	}
    }

  return rtn;
}

bool session::create_vlans_threaded()
{
  autoLock slock(lock);
  if (cleared)
    {
      write_log("session(" + sessionID + ")::create_vlans failed session was cleared");
      return false; //this session has already be closed
    }
  std::list<std::string>::iterator sw_iter;
  std::list<switch_vlan>::iterator viter;
  bool rtn = true;

  write_log("session(" + sessionID + "):create_vlans");
  for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
    {
      vlan* v = vlans->get_vlan(*viter);
      v->print_ports();
    }

  for (sw_iter = switches.begin(); sw_iter != switches.end(); ++sw_iter)
    {
      //ostringstream cmd;
      switch_cmd* sw_cmd = new switch_cmd();
      sw_cmd->switch_id = *sw_iter;
      switch_commands.push_back(sw_cmd);
      start_command(*sw_iter, sw_cmd->cmd);
      for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
	{
	  vlan* v = vlans->get_vlan(*viter);
	  v->get_add_ports_cmd(*sw_iter, sw_cmd->cmd);
	}
      sw_cmd->state = CMD_SENT;
      sw_cmd->debug_name = "session(" + sessionID + "):create_vlans";

      pthread_t tid;
      pthread_attr_t tattr;
      bool thread_fail = false;
      if(pthread_attr_init(&tattr) != 0)
	{
	  write_log("session::create_vlans: pthread_attr_init failed");
	  thread_fail = true;
	}
      else
	{
	  if(pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED) != 0)
	    {
	      write_log("session::create_vlans: pthread_attr_setdetachstate failed");
	      thread_fail = true;
	    }
	  else
	    {
	      if(pthread_create(&tid, &tattr, send_command_wrapper, (void *)sw_cmd) != 0)
		{
		  write_log("session::create_vlans: pthread_create failed");
		  thread_fail = true;
		}
	    }
	}
      //since we couldn't make a thread go ahead and send this normally
      if (thread_fail)
	{
	  bool r = send_command(sw_cmd->switch_id, sw_cmd->cmd);
	  if (!r)
	    {
	      sw_cmd->state = CMD_FAILED;
	      write_log("session(" + sessionID +"):create_vlans failed to send cmd for switch(" + sw_cmd->switch_id + ") " );//+ sw_cmd->cmd.str());
	    }
	  else
	    {
	      sw_cmd->state = CMD_FINE;
	      write_log("session(" + sessionID +"):create_vlans sent cmd for switch(" + sw_cmd->switch_id + ") " );//+ sw_cmd->cmd.str());
	    }
	}
    }

  //while loop to wait until all commands had returned
  bool finished = false;
  while(!finished)
  {
    finished = true;
    std::list< switch_cmd* >::iterator cmd_it;
    for (cmd_it = switch_commands.begin(); cmd_it != switch_commands.end(); ++cmd_it)
      {
	if ((*cmd_it)->state == CMD_SENT)
	  {
	    finished = false;
	    break;
	  }
	if ((*cmd_it)->state == CMD_FAILED)  rtn = false;
      }
  }
  write_log("session(" + sessionID +"):create_vlans finished");
  switch_commands.clear();
  return rtn;
}

void* send_command_wrapper(void* obj)
{
  switch_cmd* sw_cmd = (switch_cmd*) obj;
  bool r = send_command(sw_cmd->switch_id, sw_cmd->cmd);
  if (!r)
    {
      sw_cmd->state = CMD_FAILED;
      write_log(sw_cmd->debug_name + ":send_command_wrapper: failed to send cmd for switch(" + sw_cmd->switch_id + ") " + sw_cmd->cmd.str());
    }
  else
    {
      sw_cmd->state = CMD_FINE;
      write_log(sw_cmd->debug_name + ":send_command_wrapper:create_vlans sent cmd for switch(" + sw_cmd->switch_id + ") ");// + sw_cmd->cmd.str());
    }
  return NULL;
}

void session::add_vlan(switch_vlan vlan_id)//adds id to active list
{
  autoLock slock(lock);
  if (find(active_vlans.begin(), active_vlans.end(), vlan_id) == active_vlans.end())
    active_vlans.push_back(vlan_id);
}

bool session::remove_vlan(switch_vlan vlan_id) //removes vlan from active to removal when the active list is empty it clears the session.
{
  autoLock slock(lock);
  bool rtn = true;
  if (find(active_vlans.begin(), active_vlans.end(), vlan_id) != active_vlans.end())
    {
      active_vlans.remove(vlan_id);
      removed_vlans.push_back(vlan_id);
    }
  write_log("session(" + sessionID + ")::remove_vlan " + int2str(vlan_id) + " active_vlans " + int2str(active_vlans.size()));
  if (active_vlans.empty())
    {
      slock.unlock();
      rtn = clear_session();
    }
  return rtn;
}

bool session::clear_session() //called when last vlan is cleared sends vlan clears at once
{
  return clear_session_threaded();
}

bool session::clear_session_unthreaded() //called when last vlan is cleared sends vlan clears at once
{
  autoLock slock(lock);
  if (cleared) return true;
  bool rtn = true;
  cleared = true;
  //first clear any requests that may not have been taken care of
  //std::map<std::string, std::list<nmd::add_to_vlan_req *> >::iterator sw_iter;
  std::list<std::string >::iterator sw_iter;
  std::list<switch_vlan>::iterator viter;
  //remove any active_vlans
  for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
    {
      if (find(removed_vlans.begin(), removed_vlans.end(), *viter) == removed_vlans.end()) removed_vlans.push_back(*viter);
    }
  for (sw_iter = switches.begin(); sw_iter != switches.end(); ++sw_iter)
    {
      //now clear any vlans
      ostringstream cmd;
      int num_rm = 0;
      start_command(*sw_iter, cmd);
      for (viter = removed_vlans.begin(); viter != removed_vlans.end(); ++viter)
	{
	  num_rm += vlans->get_vlan(*viter)->get_clear_vlan_cmd(*sw_iter, cmd);
	}
      if (num_rm > 0)
	{
	  if (!send_command(*sw_iter, cmd))
	    {
	      write_log("session("  + sessionID + ")::clear_session failed to clear vlans for switch " + *sw_iter);
	      rtn =  false;
	    }
	  else
	    {
	      write_log("session("  + sessionID + ")::clear_session cleared vlans for switch " + *sw_iter);
	    }
	}
    }
  //make sure all vlans are cleared even those that never had ports added namely internal vms
  for (viter = removed_vlans.begin(); viter != removed_vlans.end(); ++viter)
    {
      vlans->get_vlan(*viter)->clear_if_empty();
    }
  return rtn;
}

bool session::clear_session_threaded() //called when last vlan is cleared sends vlan clears at once
{
  autoLock slock(lock);
  if (cleared) return true;
  bool rtn = true;
  cleared = true;
  //first clear any requests that may not have been taken care of
  //now clear any vlans
  //remove any active_vlans
  std::list<switch_vlan>::iterator viter;
  for (viter = active_vlans.begin(); viter != active_vlans.end(); ++viter)
    {
      if (find(removed_vlans.begin(), removed_vlans.end(), *viter) == removed_vlans.end()) removed_vlans.push_back(*viter);
    }
  //std::map<std::string, std::list<nmd::add_to_vlan_req *> >::iterator sw_iter;
  std::list<std::string >::iterator sw_iter;
  for (sw_iter = switches.begin(); sw_iter != switches.end(); ++sw_iter)
    {
      switch_cmd* sw_cmd = new switch_cmd();
      sw_cmd->switch_id = *sw_iter;
      switch_commands.push_back(sw_cmd);
      start_command(*sw_iter, sw_cmd->cmd);
      sw_cmd->state = CMD_SENT;
      sw_cmd->debug_name = "session(" + sessionID + "):clear_session";
      int num_rm = 0;
      for (viter = removed_vlans.begin(); viter != removed_vlans.end(); ++viter)
	{
	  num_rm += vlans->get_vlan(*viter)->get_clear_vlan_cmd(*sw_iter, sw_cmd->cmd);
	}
      if (num_rm > 0)
	{
	  pthread_t tid;
	  pthread_attr_t tattr;
	  bool thread_fail = false;
	  if(pthread_attr_init(&tattr) != 0)
	    {
	      write_log("session::clear_session: pthread_attr_init failed");
	      thread_fail = true;
	    }
	  else
	    {
	      if(pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED) != 0)
		{
		  write_log("session::clear_session: pthread_attr_setdetachstate failed");
		  thread_fail = true;
		}
	      else
		{
		  if(pthread_create(&tid, &tattr, send_command_wrapper, (void *)sw_cmd) != 0)
		    {
		      write_log("session::clear_session: pthread_create failed");
		      thread_fail = true;
		    }
		}
	    }
	  //since we couldn't make a thread go ahead and send this normally
	  if (thread_fail)
	    {
	      if (!send_command(*sw_iter, sw_cmd->cmd))
		{
		  write_log("session("  + sessionID + ")::clear_session failed to clear vlans for switch " + *sw_iter);
		  sw_cmd->state = CMD_FAILED;
		}
	      else
		{
		  write_log("session("  + sessionID + ")::clear_session cleared vlans for switch " + *sw_iter);
		  sw_cmd->state = CMD_FINE;
		}
	    }
	}
      else sw_cmd->state = CMD_FINE;
    }

  //while loop to wait until all commands had returned
  bool finished = false;
  while(!finished)
    {
      finished = true;
      std::list<switch_cmd*>::iterator cmd_it;
      for (cmd_it = switch_commands.begin(); cmd_it != switch_commands.end(); ++cmd_it)
	{
	  if ((*cmd_it)->state == CMD_SENT)
	    {
	      finished = false;
	      break;
	    }
	  if ((*cmd_it)->state == CMD_FAILED)  rtn = false;
	}
    }

  //make sure all vlans are cleared even those that never had ports added namely internal vms
  for (viter = removed_vlans.begin(); viter != removed_vlans.end(); ++viter)
    {
      vlans->get_vlan(*viter)->clear_if_empty();
    }
  return rtn;
}


text:
use winapi::UINT;

extern "C" {
    pub fn D3D11CalcSubresource(mip_slice: UINT, array_slice: UINT, mip_levels: UINT) -> UINT;
}


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

namespace Microsoft.CodeAnalysis
{
    internal partial struct SymbolKey
    {
        private static class PointerTypeSymbolKey
        {
            public static void Create(IPointerTypeSymbol symbol, SymbolKeyWriter visitor)
                => visitor.WriteSymbolKey(symbol.PointedAtType);

            public static SymbolKeyResolution Resolve(SymbolKeyReader reader)
            {
                var pointedAtTypeResolution = reader.ReadSymbolKey();

                using var result = PooledArrayBuilder<IPointerTypeSymbol>.GetInstance(pointedAtTypeResolution.SymbolCount);
                foreach (var typeSymbol in pointedAtTypeResolution.OfType<ITypeSymbol>())
                {
                    result.AddIfNotNull(reader.Compilation.CreatePointerTypeSymbol(typeSymbol));
                }

                return CreateResolution(result);
            }
        }
    }
}


text:
<phpunit
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
        backupGlobals="true"
        bootstrap="../../../../../Libraries/Architecture/Test/bootstrap.php">
    <testsuites>
        <testsuite name="Source">
            <directory>Source</directory>
        </testsuite>
        <testsuite name="Unit">
            <directory>Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">../</directory>
            <exclude>
                <directory suffix=".php">./</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>


text:
package com.alibaba.dubbo.rpc.protocol.thrift;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author kimi
 */
public class ServerExceptionTest extends AbstractTest {

    @Override
    protected $__DemoStub.Iface getServiceImpl() {

        return new $__DemoStub.Iface () {

            public boolean echoBool( boolean arg )  {

                return false;
            }

            public byte echoByte( byte arg )  {

                return 0;
            }

            public short echoI16( short arg )  {

                return 0;
            }

            public int echoI32( int arg )  {

                return 0;
            }

            public long echoI64( long arg )  {

                return 0;
            }

            public double echoDouble( double arg )  {
                return 0;
            }

            public String echoString( String arg )  {
                // 在 server 端,thrift 无法处理 idl 中没有声明的异常
                throw new RuntimeException( "just for test" );
            }
        };

    }

    @Test( expected = RpcException.class )
    public void testServerException() throws Exception {

        Assert.assertNotNull( invoker );

        RpcInvocation invocation = new RpcInvocation();

        invocation.setMethodName( "echoString" );

        invocation.setParameterTypes( new Class<?>[]{ String.class } );

        String arg = "Hello, World!";

        invocation.setArguments( new Object[] { arg } );

        Result result = invoker.invoke( invocation );

        System.out.println( result );

    }

    @Override
    protected URL getUrl() {
        URL url = super.getUrl();
//        url = url.addParameter( Constants.TIMEOUT_KEY, Integer.MAX_VALUE );
        return url;
    }

}


text:
<?php

namespace GeekHub\MediaBundle;

use GeekHub\MediaBundle\Document\EmbeddedImage;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;

class ImageHandler
{
    public function handleEmbeddedImage($src)
    {
    }

    protected function getNewFileName($src)
    {
    }
}


text:
@interface RKOldObjectMapper (Private)
- (void)updateModel:(id)model ifNewPropertyValue:(id)propertyValue forPropertyNamed:(NSString*)propertyName;
@end

@interface RKObjectMapperSpecUser : RKObject {
@private
    NSNumber* userID;
    NSString* encryptedPassword;
    NSString* name;
    NSString* salt;
    NSDate* createdAt;
    NSDate* updatedAt;
    NSString* image;
    NSString* email;
    NSArray* interests;
}

@property (nonatomic, retain) NSNumber* userID;
@property (nonatomic, retain) NSString* encryptedPassword;
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* salt;
@property (nonatomic, retain) NSDate* createdAt;
@property (nonatomic, retain) NSDate* updatedAt;
@property (nonatomic, retain) NSString* image;
@property (nonatomic, retain) NSString* email;
@property (nonatomic, retain) NSArray* interests;

@end

@implementation RKObjectMapperSpecUser

@synthesize userID, encryptedPassword, name, salt, createdAt, updatedAt, image, email, interests;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"id", @"userID",
            @"encrypted_password", @"encryptedPassword",
            @"name", @"name",
            @"salt", @"salt",
            @"created_at", @"createdAt",
            @"updated_at", @"updatedAt",
            @"image", @"image",
            @"email", @"email",
            @"interests", @"interests",
            nil];
}

@end

@interface RKObjectMapperSpec : RKSpec

- (NSString*)jsonString;
- (NSString*)jsonCollectionString;

@end

@implementation RKObjectMapperSpec

- (NSString*)userJSON {
    return @"{\"user\":"
           @"{\"encrypted_password\":\"68dad82a867c4a61719fec594c119188ed35cd3b7d42eed1647e46d85f2ffdd8\",\"name\":\"mimi\","
           @"\"salt\":\"809c79c24cbebfe3f9feea2e9bf98255e5af0f0b8514b6c0d71dcc63fa083688\",\"created_at\":\"2011-02-16T23:04:22Z\","
           @"\"updated_at\":\"2011-02-16T23:04:22Z\",\"id\":"
           @"10,\"image\":null,\"email\":\"mimi@mimi.com\"}}";
}

- (void)itShouldMapWhenGivenAClassAndElements {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
    RKObjectMapperSpecUser* user = (RKObjectMapperSpecUser*) [mapper mapFromString:[self userJSON] toClass:[RKObjectMapperSpecUser class] keyPath:@"user"];
    [expectThat(user.name) should:be(@"mimi")];
}

- (void)itShouldMapATargetObjectWithNamespacedJSON {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper new] autorelease];
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];
	mapper.format = RKMappingFormatJSON;
    RKObjectMapperSpecUser* user = [[RKObjectMapperSpecUser new] autorelease];
    [mapper mapObject:user fromString:[self userJSON]];
    [expectThat(user.name) should:be(@"mimi")];
}

- (void)itShouldMapCorrectlyWithObjectClassSpecifiedAndElementRegistered {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper new] autorelease];
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];
	mapper.format = RKMappingFormatJSON;
    NSString* JSON = [NSString stringWithFormat:@"[%@]", [self userJSON]];
    NSArray* objects = [mapper mapFromString:JSON toClass:[RKObjectMapperSpecUser class] keyPath:nil];
    RKObjectMapperSpecUser* user = [objects lastObject];
    [expectThat(user.name) should:be(@"mimi")];
}

- (void)itShouldMapWhenGivenRegisteredElementsAndASingleObject {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];
	mapper.format = RKMappingFormatJSON;
    RKObjectMapperSpecUser* user = (RKObjectMapperSpecUser*) [mapper mapFromString:[self userJSON] toClass:nil keyPath:nil];
    [expectThat(user.name) should:be(@"mimi")];
}

- (void)itShouldMapFromJSON {
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
	[mapper registerClass:[RKMappableObject class] forElementNamed:@"test_serialization_class"];
	[mapper registerClass:[RKMappableAssociation class] forElementNamed:@"has_many"];
	[mapper registerClass:[RKMappableAssociation class] forElementNamed:@"has_one"];
	id result = [mapper mapFromString:[self jsonString]];

	[expectThat(result) shouldNot:be(nil)];
	[expectThat([result dateTest]) shouldNot:be(nil)];
	[expectThat([result numberTest]) should:be(2)];
	[expectThat([result stringTest]) should:be(@"SomeString")];
	[expectThat([result urlTest]) should:be([NSURL URLWithString:@"https://github.com/twotoasters/RestKit"])];

	[expectThat([result hasOne]) shouldNot:be(nil)];
	[expectThat([[result hasOne] testString]) should:be(@"A String")];

	[expectThat([result hasMany]) shouldNot:be(nil)];
	[expectThat([[result hasMany] count]) should:be(2)];
}

- (void)itShouldLogAWarningWhenMultipleKeyPathsMatchForADictionary {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
	[mapper registerClass:[RKMappableObject class] forElementNamed:@"test_serialization_class"];
	[mapper registerClass:[RKMappableAssociation class] forElementNamed:@"test_serialization_class.has_one"];
	[mapper mapFromString:[self jsonString]];
    // TODO: Cannot unit test here -- need to factor NSLog out to allow mock object injection
    NSLog(@">> PENDING");
}

- (void)itShouldMapObjectsFromJSON {
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
	[mapper registerClass:[RKMappableObject class] forElementNamed:@"test_serialization_class"];
	[mapper registerClass:[RKMappableObject class] forElementNamed:@"test_serialization_class"];
	[mapper registerClass:[RKMappableAssociation class] forElementNamed:@"has_many"];
	[mapper registerClass:[RKMappableAssociation class] forElementNamed:@"has_one"];
	NSString* collectionString = [self jsonCollectionString];
	NSArray* results = [mapper mapFromString:collectionString];
	NSLog(@"Results: %@", results);
	[expectThat([results count]) should:be(2)];

	RKMappableObject* result = (RKMappableObject*) [results objectAtIndex:0];
	[expectThat(result) shouldNot:be(nil)];
	[expectThat([result dateTest]) shouldNot:be(nil)];
	[expectThat([result numberTest]) should:be(2)];
	[expectThat([result stringTest]) should:be(@"SomeString")];

	[expectThat([result hasOne]) shouldNot:be(nil)];
	[expectThat([[result hasOne] testString]) should:be(@"A String")];

	[expectThat([result hasMany]) shouldNot:be(nil)];
	[expectThat([[result hasMany] count]) should:be(2)];
}

- (NSString*)arrayOfHashesJSON {
    return @"{\"user\":"
    @"[{\"encrypted_password\":\"68dad82a867c4a61719fec594c119188ed35cd3b7d42eed1647e46d85f2ffdd8\",\"name\":\"mimi\","
    @"\"salt\":\"809c79c24cbebfe3f9feea2e9bf98255e5af0f0b8514b6c0d71dcc63fa083688\",\"created_at\":\"2011-02-16T23:04:22Z\","
    @"\"updated_at\":\"2011-02-16T23:04:22Z\",\"id\":"
    @"10,\"image\":null,\"email\":\"mimi@mimi.com\"}]}";
}

- (void)itShouldMapAnArrayOfHashes {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];
    NSArray* array = [mapper mapFromString:[self arrayOfHashesJSON]];
    [expectThat([array isKindOfClass:[NSArray class]]) should:be(YES)];
    [expectThat([array count]) should:be(1)];
    [expectThat([[array lastObject] name]) should:be(@"mimi")];
}

// NOTE: email attribute is omitted!
- (NSString*)userJSONMissingAnElement {
    return @"{\"user\":"
    @"{\"encrypted_password\":\"68dad82a867c4a61719fec594c119188ed35cd3b7d42eed1647e46d85f2ffdd8\",\"name\":\"mimi\","
    @"\"salt\":\"809c79c24cbebfe3f9feea2e9bf98255e5af0f0b8514b6c0d71dcc63fa083688\",\"created_at\":\"2011-02-16T23:04:22Z\","
    @"\"updated_at\":\"2011-02-16T23:04:22Z\",\"id\":"
    @"10,\"image\":null}}";
}

- (void)itShouldNotCrashWhenAttemptingToMapWithAMissingElement {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
    mapper.missingElementMappingPolicy = RKSetNilForMissingElementMappingPolicy;
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];

    NSException* exception = nil;
    @try {
        [mapper mapFromString:[self userJSONMissingAnElement]];
    }
    @catch (NSException * e) {
        exception = e;
    }
    [expectThat(exception) should:be(nil)];
}

- (void)itShouldNotNilOutWhenAttemptingToMapWithAMissingElementIfConfiguredNotTo {
    RKObjectMapperSpecUser* user = [RKObjectMapperSpecUser object];
    user.email = @"foo@bar.com";
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
    mapper.missingElementMappingPolicy = RKIgnoreMissingElementMappingPolicy;
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];

    [mapper mapObject:user fromString:[self userJSONMissingAnElement]];
    [expectThat(user.email) should:be(@"foo@bar.com")];
}

- (void)itShouldNilOutWhenAttemptingToMapWithAMissingElementIfConfiguredToDoSo {
    RKObjectMapperSpecUser* user = [RKObjectMapperSpecUser object];
    user.email = @"foo@bar.com";
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
    mapper.missingElementMappingPolicy = RKSetNilForMissingElementMappingPolicy;
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];

    [mapper mapObject:user fromString:[self userJSONMissingAnElement]];
    [expectThat(user.email) should:be(nil)];
}

- (NSString*)arrayOfStringsJSON {
    return @"{\"user\":"
    @"{\"encrypted_password\":\"68dad82a867c4a61719fec594c119188ed35cd3b7d42eed1647e46d85f2ffdd8\",\"name\":\"mimi\","
    @"\"salt\":\"809c79c24cbebfe3f9feea2e9bf98255e5af0f0b8514b6c0d71dcc63fa083688\",\"created_at\":\"2011-02-16T23:04:22Z\","
    @"\"updated_at\":\"2011-02-16T23:04:22Z\",\"id\":"
    @"10,\"interests\":[\"basketball\", \"soccer\"]}}";
}

- (void)itShouldMapAnArrayOfStringsToAProperty {
    RKObjectMapperSpecUser* user = [RKObjectMapperSpecUser object];
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKObjectMapperSpecUser class] forElementNamed:@"user"];

    [mapper mapObject:user fromString:[self arrayOfStringsJSON]];
    NSArray* interests = [NSArray arrayWithObjects:@"basketball", @"soccer", nil];
    [expectThat(user.interests) should:be(interests)];
}

- (void)itShouldNotUpdateNilPropertyToNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	[mapper updateModel:model ifNewPropertyValue:nil forPropertyNamed:@"name"];

	[expectThat(model.name) should:be(nil)];
}

- (void)itShouldBeAbleToSetNonNilPropertiesToNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	model.age = [NSNumber numberWithInt:0];
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	[mapper updateModel:model ifNewPropertyValue:nil forPropertyNamed:@"age"];

	[expectThat(model.age) should:be(nil)];
}

- (void)itShouldBeAbleToSetNilPropertiesToNonNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	[mapper updateModel:model ifNewPropertyValue:[NSNumber numberWithInt:0] forPropertyNamed:@"age"];

	[expectThat(model.age) should:be([NSNumber numberWithInt:0])];
}

- (void)itShouldBeAbleToSetNonNilNSStringPropertiesToNonNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];

	model.name = @"Bob";
	[mapper updateModel:model ifNewPropertyValue:@"Will" forPropertyNamed:@"name"];
	[expectThat(model.name) should:be(@"Will")];
}

- (void)itShouldBeAbleToSetNonNilNSNumberPropertiesToNonNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];

	model.age = [NSNumber numberWithInt:16];
	[mapper updateModel:model ifNewPropertyValue:[NSNumber numberWithInt:17] forPropertyNamed:@"age"];
	[expectThat(model.age) should:be(17)];
}

- (void)itShouldBeAbleToSetNonNilNSDatePropertiesToNonNil {
	RKObjectMapperSpecModel* model = [[[RKObjectMapperSpecModel alloc] init] autorelease];
	RKOldObjectMapper* mapper = [[[RKOldObjectMapper alloc] init] autorelease];

	model.createdAt = [NSDate date];
	[mapper updateModel:model ifNewPropertyValue:[NSDate dateWithTimeIntervalSince1970:0] forPropertyNamed:@"createdAt"];
	[expectThat(model.createdAt) should:be([NSDate dateWithTimeIntervalSince1970:0])];
}

- (void)itShouldIgnoreMissingElementPropertyWhenMappingRelationships {
    RKMappableObject* object = [[RKMappableObject new] autorelease];
    RKMappableAssociation* association = [[RKMappableAssociation new] autorelease];
    object.hasOne = association;
    object.hasMany = [NSSet setWithObject:object];
    RKOldObjectMapper* mapper = [[[RKOldObjectMapper alloc] init] autorelease];
    mapper.missingElementMappingPolicy = RKIgnoreMissingElementMappingPolicy;
    NSString* JSON = @"{ \"string_test\": \"woot!\" }";
    [mapper mapObject:object fromString:JSON];
    [expectThat(object.hasOne) shouldNot:be(nil)];
    [expectThat(object.hasMany) shouldNot:be(nil)];
}

- (void)itShouldSetNilMissingElementPropertyWhenMappingRelationships {
    RKMappableObject* object = [[RKMappableObject new] autorelease];
    RKMappableAssociation* association = [[RKMappableAssociation new] autorelease];
    object.hasOne = association;
    object.hasMany = [NSSet setWithObject:object];
    RKOldObjectMapper* mapper = [[[RKOldObjectMapper alloc] init] autorelease];
    mapper.missingElementMappingPolicy = RKSetNilForMissingElementMappingPolicy;
    NSString* JSON = @"{ \"string_test\": \"woot!\" }";
    [mapper mapObject:object fromString:JSON];
    [expectThat(object.hasOne) should:be(nil)];
    [expectThat(object.hasMany) should:be(nil)];
}

// TODO: Factor these payloads out somehow to improve test clarity...

- (NSString*)jsonString {
	return
	@"{"
	@"   \"test_serialization_class\":{"
	@"      \"date_test\":\"2009-08-17T19:24:40Z\","
	@"      \"number_test\":2,"
	@"      \"string_test\":\"SomeString\","
	@"      \"url_test\":\"https://github.com/twotoasters/RestKit\","
	@"      \"has_one\":{"
	@"         \"test_string\":\"A String\""
	@"      },"
	@"      \"has_manys\":["
	@"         {"
	@"            \"has_many\":{"
	@"               \"test_string\":\"A String 2\""
	@"            }"
	@"         },"
	@"         {"
	@"            \"has_many\":{"
	@"               \"test_string\":\"A String 3\""
	@"            }"
	@"         }"
	@"      ]"
	@"   }"
	@"}";
}

- (NSString*)jsonCollectionString {
	return
	@"["
	@"      {"
	@"         \"test_serialization_class\":{"
	@"            \"date_test\":\"2009-08-17T19:24:40Z\","
	@"            \"number_test\":2,"
	@"            \"string_test\":\"SomeString\","
	@"            \"has_one\":{"
	@"               \"test_string\":\"A String\""
	@"            },"
	@"            \"has_manys\":["
	@"               {"
	@"                  \"has_many\":{"
	@"                     \"test_string\":\"A String 2\""
	@"                  }"
	@"               },"
	@"               {"
	@"                  \"has_many\":{"
	@"                     \"test_string\":\"A String 3\""
	@"                  }"
	@"               }"
	@"            ]"
	@"         }"
	@"      },"
	@"      {"
	@"         \"test_serialization_class\":{"
	@"            \"date_test\":\"2009-08-17T19:24:40Z\","
	@"            \"number_test\":2,"
	@"            \"string_test\":\"SomeString\","
	@"            \"has_one\":{"
	@"               \"test_string\":\"A String\""
	@"            },"
	@"            \"has_manys\":["
	@"               {"
	@"                  \"has_many\":{"
	@"                     \"test_string\":\"A String 2\""
	@"                  }"
	@"               },"
	@"               {"
	@"                  \"has_many\":{"
	@"                     \"test_string\":\"A String 3\""
	@"                  }"
	@"               }"
	@"            ]"
	@"         }"
	@"      }"
	@"]"
	@"";
}

- (NSString*)xmlString {
	NSString* xml = @"<test_serialization_class>"
	@"<date_test type='datetime'>2009-08-17T19:24:40Z</date_test>"
	@"<number_test type='integer'>2</number_test>"
	@"<string_test>SomeString</string_test>"
	@"<has_one>"
	@"<test_string>A String</test_string>"
	@"</has_one>"
	@"<has_manys>"
	@"<has_many>"
	@"<test_string>A String 2</test_string>"
	@"</has_many>"
	@"<has_many>"
	@"<test_string>A String 3</test_string>"
	@"</has_many>"
	@"</has_manys>"
	@"</test_serialization_class>";
	return xml;
}

- (NSString*)xmlCollectionString {
	NSString* xml = @"<test_serialization_classes>"
	@"<test_serialization_class>"
	@"<date_test type='datetime'>2009-08-17T19:24:40Z</date_test>"
	@"<number_test type='integer'>2</number_test>"
	@"<string_test>SomeString</string_test>"
	@"<has_one>"
	@"<test_string>A String</test_string>"
	@"</has_one>"
	@"<has_manys>"
	@"<has_many>"
	@"<test_string>A String 2</test_string>"
	@"</has_many>"
	@"<has_many>"
	@"<test_string>A String 3</test_string>"
	@"</has_many>"
	@"</has_manys>"
	@"</test_serialization_class>"
	@"<test_serialization_class>"
	@"<date_test type='datetime'>2009-08-17T19:24:40Z</date_test>"
	@"<number_test type='integer'>2</number_test>"
	@"<string_test>SomeString</string_test>"
	@"<has_one>"
	@"<test_string>A String</test_string>"
	@"</has_one>"
	@"<has_manys>"
	@"<has_many>"
	@"<test_string>A String 2</test_string>"
	@"</has_many>"
	@"<has_many>"
	@"<test_string>A String 3</test_string>"
	@"</has_many>"
	@"</has_manys>"
	@"</test_serialization_class>"
	@"</test_serialization_classes>";
	return xml;
}

@end

//////////////////////////////////////////////////////////////////////////////////////////

// This class is a thin model around
@interface RKPath : RKObject {
@private
    NSNumber* _label;
    NSArray*  _route; // An array of hashes
}

@property (nonatomic, retain) NSNumber* label;
@property (nonatomic, retain) NSArray* route;
@end

@implementation RKPath

@synthesize label = _label;
@synthesize route = _route;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"label", @"label",
            @"route", @"route",
            nil];
}

@end

@interface RKModeledPath : RKObject {
@private
    NSNumber* _label;
    NSArray*  _route; // An array of RKPoint objects
}

@property (nonatomic, retain) NSNumber* label;
@property (nonatomic, retain) NSArray* route;
@end

@implementation RKModeledPath

@synthesize label = _label;
@synthesize route = _route;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"label", @"label",
            nil];
}

+ (NSDictionary*)elementToRelationshipMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"route", @"route",
            nil];
}

@end

@interface RKPoint : RKObject {
    NSNumber* _latitude;
    NSNumber* _longitude;
}

@property (nonatomic, retain) NSNumber* latitude;
@property (nonatomic, retain) NSNumber* longitude;

@end

@implementation RKPoint

@synthesize latitude = _latitude;
@synthesize longitude = _longitude;

+ (NSDictionary*) elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"LATITUDE", @"latitude",
            @"LONGITUDE", @"longitude",
            nil];
}

- (NSString*)description {
    return [NSString stringWithFormat:@"RKPoint : latitude = %@, longitude = %@", self.latitude, self.longitude];
}

@end

@interface RKObjectMapperRegisteredClassWithArraySpec : RKSpec {
@private
}
@end

@implementation RKObjectMapperRegisteredClassWithArraySpec

- (NSString*)JSON {
    // TODO: Should create a JSON factory that can read these from a fixtures directory where we can format them nicely.
    return @"[{\"route\":[{\"LATITUDE\":\"32.224519\",\"LONGITUDE\":\"-110.947325\"},{\"LATITUDE\":\"32.224542\",\"LONGITUDE\":\"-110.943861\"},{\"LATITUDE\":\"32.221431\",\"LONGITUDE\":\"-110.943930\"}],\"label\":7174},{\"route\":[{\"LATITUDE\":\"32.224519\",\"LONGITUDE\":\"-110.947325\"},{\"LATITUDE\":\"32.221402\",\"LONGITUDE\":\"-110.947293\"},{\"LATITUDE\":\"32.221431\",\"LONGITUDE\":\"-110.943930\"}],\"label\":7079},{\"route\":[{\"LATITUDE\":\"32.224519\",\"LONGITUDE\":\"-110.947325\"},{\"LATITUDE\":\"32.227820\",\"LONGITUDE\":\"-110.947293\"},{\"LATITUDE\":\"32.227843\",\"LONGITUDE\":\"-110.943865\"},{\"LATITUDE\":\"32.227879\",\"LONGITUDE\":\"-110.939531\"},{\"LATITUDE\":\"32.224599\",\"LONGITUDE\":\"-110.939495\"},{\"LATITUDE\":\"32.221476\",\"LONGITUDE\":\"-110.939496\"},{\"LATITUDE\":\"32.221431\",\"LONGITUDE\":\"-110.943930\"}],\"label\":23775}]";
}

- (void)itShouldMapAnArrayOfRoutes {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;

    NSArray* array = (NSArray*) [mapper mapFromString:[self JSON] toClass:[RKPath class] keyPath:nil];
    [expectThat([array isKindOfClass:[NSArray class]]) should:be(YES)];
    [expectThat([array count]) should:be(3)];
    NSLog(@"Array is %@", array);
    NSLog(@"First object is: %@", [array objectAtIndex:0]);
    NSLog(@"Route on first object is: %@", [[array objectAtIndex:0] route]);
}

- (void)itShouldMapRouteToAnArrayOfPoints {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;
    [mapper registerClass:[RKPoint class] forElementNamed:@"route"];

    NSArray* array = (NSArray*) [mapper mapFromString:[self JSON] toClass:[RKModeledPath class] keyPath:nil];
    [expectThat([array isKindOfClass:[NSArray class]]) should:be(YES)];
    [expectThat([array count]) should:be(3)];
    NSLog(@"[Modeled] Array is %@", array);
    NSLog(@"[Modeled] First object is: %@", [array objectAtIndex:0]);
    NSLog(@"[Modeled] Route on first object is: %@", [[array objectAtIndex:0] route]);
}

@end

//////////////////////////////////////////////////////////////////////////////////////////

#pragma mark - Duplicated Keys

@interface RKFoursquareUser : RKObject {
    NSString* _firstName;
    NSString* _lastName;
    NSArray* _checkins;
    NSArray* _mayorships;
}

@property (nonatomic, retain) NSString* firstName;
@property (nonatomic, retain) NSString* lastName;
@property (nonatomic, retain) NSArray* checkins;
@property (nonatomic, retain) NSArray* mayorships;

@end

@implementation RKFoursquareUser

@synthesize firstName = _firstName;
@synthesize lastName = _lastName;
@synthesize checkins = _checkins;
@synthesize mayorships = _mayorships;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"firstname", @"firstName",
            @"lastname", @"lastName",
            nil];
}

+ (NSDictionary*)elementToRelationshipMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"mayorships.items", @"mayorships",
            @"checkins", @"checkins",
            nil];
}

- (NSString*)description {
    return [NSString stringWithFormat:@"firstName = %@, lastName = %@, mayorships = %@, checkins = %@",
            _firstName, _lastName, _mayorships, _checkins];
}

@end

@interface RKMayorship : RKObject {
    NSString* _name;
    NSNumber* _visitCount;
}

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* visitCount;

@end

@implementation RKMayorship

@synthesize name = _name;
@synthesize visitCount = _visitCount;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"name", @"name",
            @"visit_count", @"visitCount",
            nil];
}

@end

@interface RKCheckin : RKObject {
    NSString* _name;
    NSNumber* _longitude;
    NSNumber* _latitude;
}

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSNumber* longitude;
@property (nonatomic, retain) NSNumber* latitude;

@end

@implementation RKCheckin

@synthesize name = _name;
@synthesize longitude = _longitude;
@synthesize latitude = _latitude;

+ (NSDictionary*)elementToPropertyMappings {
    return [NSDictionary dictionaryWithKeysAndObjects:
            @"name", @"name",
            @"longitude", @"longitude",
            @"latitude", @"latitude",
            nil];
}

@end

@interface RKObjectMapperPayloadItemsWithDuplicateKeysSpec : RKSpec {
}
@end

@implementation RKObjectMapperPayloadItemsWithDuplicateKeysSpec

- (NSString*)JSON {
    return @"{"
    @"    \"response\": {"
    @"        \"user\": {"
    @"            \"id\": 1234,"
    @"            \"firstname\": \"Rich\","
    @"            \"lastname\": \"Wolf\","
    @"            \"mayorships\": {"
    @"                \"count\": 5,"
    @"                \"items\": ["
    @"                {"
    @"                    \"name\": \"SpffiyCo\","
    @"                    \"visit_count\": 97"
    @"                },"
    @"                {"
    @"                    \"name\": \"Awesomeville\","
    @"                    \"visit_count\": 235"
    @"                }"
    @"                ]"
    @"            },"
    @"            \"checkins\": {"
    @"                \"count\": 15,"
    @"                \"items\": ["
    @"                {"
    @"                    \"name\": \"YummyStation\","
    @"                    \"longitude\": -80.0,"
    @"                    \"latitude\": 42.0"
    @"                },"
    @"                {"
    @"                    \"name\": \"Pizzaland\","
    @"                    \"longitude\": -81.0,"
    @"                    \"latitude\": 41.0"
    @"                }"
    @"                ]"
    @"            }"
    @"        }"
    @"    }"
    @"}";
}

- (void)itShouldMapOverlappingNamesUsingKeyPaths {
    RKOldObjectMapper* mapper = [[RKOldObjectMapper alloc] init];
	mapper.format = RKMappingFormatJSON;

    [mapper registerClass:[RKFoursquareUser class] forElementNamed:@"user"];
    [mapper registerClass:[RKMayorship class] forElementNamed:@"mayorships.items"];
    [mapper registerClass:[RKCheckin class] forElementNamed:@"checkins.items"];

    [mapper mapFromString:[self JSON] toClass:nil keyPath:@"response"];

    NSLog(@"This Spec is disabled! Cannot handle these sorts of mappings with current mapper.");
}

@end


text:
title: Troubleshoot
linktitle: Troubleshoot
description: Frequently asked questions and known issues pulled from the Hugo Discuss forum.
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
menu:
  docs:
    parent: "troubleshooting"
    weight: 1
weight: 1
draft: false
hidesectioncontents: false
slug:
aliases: [/troubleshooting/faqs/,/faqs/]
toc: false
notesforauthors:
---

The Troubleshooting section includes known issues, recent workarounds, and FAQs pulled from the [Hugo Discussion Forum][forum].

[forum]: https://discourse.gohugo.io


text:
<?php

namespace Phpro\SoapClient\CodeGenerator\Assembler;

use Phpro\SoapClient\CodeGenerator\Context\ContextInterface;
use Phpro\SoapClient\Exception\AssemblerException;

/**
 * Interface AssemblerInterface
 *
 * @package Phpro\SoapClient\CodeGenerator\Assembler
 */
interface AssemblerInterface
{

    /**
     * @param ContextInterface $context
     *
     * @return bool
     */
    public function canAssemble(ContextInterface $context);

    /**
     * Assembles pieces of code.
     *
     * @param ContextInterface $context
     * @throws AssemblerException
     */
    public function assemble(ContextInterface $context);
}