text:
package ua.rainbow.exam.stream.exercise;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Speakjava (Simon Ritter)
 */
public class Lesson1 {
  /**
   * Run the exercises to ensure we got the right answers
   */
  public void runExercises() {
    System.out.println("JDK 8 Lambdas and Streams MOOC Lesson 1");
    System.out.println("Running exercise 1 solution...");
    exercise1();
    System.out.println("Running exercise 2 solution...");
    exercise2();
    System.out.println("Running exercise 3 solution...");
    exercise3();
    System.out.println("Running exercise 4 solution...");
    exercise4();
    System.out.println("Running exercise 5 solution...");
    exercise5();
  }

  /**
   * All exercises should be completed using Lambda expressions and the new
   * methods added to JDK 8 where appropriate. There is no need to use an
   * explicit loop in any of the code. Use method references rather than full
   * lambda expressions wherever possible.
   */
  /**
   * Exercise 1
   *
   * Create a string that consists of the first letter of each word in the list
   * of Strings provided.
   */
  private void exercise1() {
    List<String> list = Arrays.asList(
        "alpha", "bravo", "charlie", "delta", "echo", "foxtrot");
    StringBuilder builder = new StringBuilder();
    String result;

    list.forEach(it -> builder.append(it.charAt(0)));
    result = builder.toString();
  }

  /**
   * Exercise 2
   *
   * Remove the words that have odd lengths from the list.
   */
  private void exercise2() {
    List<String> list = new ArrayList<>(Arrays.asList(
        "alpha", "bravo", "charlie", "delta", "echo", "foxtrot"));

    list.removeIf(it -> it.length() % 2 != 0);
  }

  /**
   * Exercise 3
   *
   * Replace every word in the list with its upper case equivalent.
   */
  private void exercise3() {
    List<String> list = new ArrayList<>(Arrays.asList(
        "alpha", "bravo", "charlie", "delta", "echo", "foxtrot"));

    list.replaceAll(String::toUpperCase);
  }

  /**
   * Exercise 4
   *
   * Convert every key-value pair of the map into a string and append them all
   * into a single string, in iteration order.
   */
  private void exercise4() {
    Map<String, Integer> map = new TreeMap<>();
    StringBuilder builder = new StringBuilder();
    String result;
    map.put("c", 3);
    map.put("b", 2);
    map.put("a", 1);

    map.forEach((k, v) -> builder.append(k).append(v));
  }

  /**
   * Exercise 5
   *
   * Create a new thread that prints the numbers from the list.
   */
  private void exercise5() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    new Thread(() -> list.forEach(System.out::println)).start();
  }

  /**
   * Main entry point for application
   *
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    Lesson1 lesson = new Lesson1();
    lesson.runExercises();
  }
}


text:
@interface DistanceHelper : NSObject
+ (NSString *) convertDistanceToString:(double)distance;
@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.beam.runners.direct;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.apache.beam.runners.direct.DirectExecutionContext.DirectStepContext;
import org.apache.beam.runners.direct.DirectRunner.CommittedBundle;
import org.apache.beam.runners.direct.DirectRunner.UncommittedBundle;
import org.apache.beam.runners.direct.WatermarkManager.TimerUpdate;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.AppliedPTransform;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.util.IdentitySideInputWindowFn;
import org.apache.beam.sdk.util.ReadyCheckingSideInputReader;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.util.common.CounterSet;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;

import org.hamcrest.Matchers;
import org.joda.time.Instant;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Tests for {@link ParDoEvaluator}.
 */
@RunWith(JUnit4.class)
public class ParDoEvaluatorTest {
  @Mock private EvaluationContext evaluationContext;
  private PCollection<Integer> inputPc;
  private TupleTag<Integer> mainOutputTag;
  private List<TupleTag<?>> sideOutputTags;
  private BundleFactory bundleFactory;

  @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
    TestPipeline p = TestPipeline.create();
    inputPc = p.apply(Create.of(1, 2, 3));
    mainOutputTag = new TupleTag<Integer>() {};
    sideOutputTags = TupleTagList.empty().getAll();

    bundleFactory = ImmutableListBundleFactory.create();
  }

  @Test
  public void sideInputsNotReadyResultHasUnprocessedElements() {
    PCollectionView<Integer> singletonView =
        inputPc
            .apply(Window.into(new IdentitySideInputWindowFn()))
            .apply(View.<Integer>asSingleton().withDefaultValue(0));
    RecorderFn fn = new RecorderFn(singletonView);
    PCollection<Integer> output = inputPc.apply(ParDo.of(fn).withSideInputs(singletonView));

    CommittedBundle<Integer> inputBundle =
        bundleFactory.createRootBundle(inputPc).commit(Instant.now());
    UncommittedBundle<Integer> outputBundle = bundleFactory.createBundle(inputBundle, output);
    when(evaluationContext.createBundle(inputBundle, output))
        .thenReturn(outputBundle);

    ParDoEvaluator<Integer> evaluator =
        createEvaluator(singletonView, fn, inputBundle, output);

    IntervalWindow nonGlobalWindow = new IntervalWindow(new Instant(0), new Instant(10_000L));
    WindowedValue<Integer> first = WindowedValue.valueInGlobalWindow(3);
    WindowedValue<Integer> second =
        WindowedValue.of(2, new Instant(1234L), nonGlobalWindow, PaneInfo.NO_FIRING);
    WindowedValue<Integer> third =
        WindowedValue.of(
            1,
            new Instant(2468L),
            ImmutableList.of(nonGlobalWindow, GlobalWindow.INSTANCE),
            PaneInfo.NO_FIRING);

    evaluator.processElement(first);
    evaluator.processElement(second);
    evaluator.processElement(third);
    TransformResult result = evaluator.finishBundle();

    assertThat(
        result.getUnprocessedElements(),
        Matchers.<WindowedValue<?>>containsInAnyOrder(
            second, WindowedValue.of(1, new Instant(2468L), nonGlobalWindow, PaneInfo.NO_FIRING)));
    assertThat(result.getOutputBundles(), Matchers.<UncommittedBundle<?>>contains(outputBundle));
    assertThat(fn.processed, containsInAnyOrder(1, 3));
    assertThat(
        Iterables.getOnlyElement(result.getOutputBundles()).commit(Instant.now()).getElements(),
        Matchers.<WindowedValue<?>>containsInAnyOrder(
            first.withValue(8),
            WindowedValue.timestampedValueInGlobalWindow(6, new Instant(2468L))));
  }

  private ParDoEvaluator<Integer> createEvaluator(
      PCollectionView<Integer> singletonView,
      RecorderFn fn,
      DirectRunner.CommittedBundle<Integer> inputBundle,
      PCollection<Integer> output) {
    when(
            evaluationContext.createSideInputReader(
                ImmutableList.<PCollectionView<?>>of(singletonView)))
        .thenReturn(new ReadyInGlobalWindowReader());
    DirectExecutionContext executionContext = mock(DirectExecutionContext.class);
    DirectStepContext stepContext = mock(DirectStepContext.class);
    when(
            executionContext.getOrCreateStepContext(
                Mockito.any(String.class), Mockito.any(String.class)))
        .thenReturn(stepContext);
    when(stepContext.getTimerUpdate()).thenReturn(TimerUpdate.empty());
    when(
            evaluationContext.getExecutionContext(
                Mockito.any(AppliedPTransform.class), Mockito.any(StructuralKey.class)))
        .thenReturn(executionContext);
    when(evaluationContext.createCounterSet()).thenReturn(new CounterSet());

    return ParDoEvaluator.create(
        evaluationContext,
        inputBundle,
        (AppliedPTransform<PCollection<Integer>, ?, ?>) output.getProducingTransformInternal(),
        fn,
        ImmutableList.<PCollectionView<?>>of(singletonView),
        mainOutputTag,
        sideOutputTags,
        ImmutableMap.<TupleTag<?>, PCollection<?>>of(mainOutputTag, output));
  }

  private static class RecorderFn extends DoFn<Integer, Integer> {
    private Collection<Integer> processed;
    private final PCollectionView<Integer> view;

    public RecorderFn(PCollectionView<Integer> view) {
      processed = new ArrayList<>();
      this.view = view;
    }

    @Override
    public void processElement(DoFn<Integer, Integer>.ProcessContext c) throws Exception {
      processed.add(c.element());
      c.output(c.element() + c.sideInput(view));
    }
  }

  private static class ReadyInGlobalWindowReader implements ReadyCheckingSideInputReader {
    @Override
    @Nullable
    public <T> T get(PCollectionView<T> view, BoundedWindow window) {
      if (window.equals(GlobalWindow.INSTANCE)) {
        return (T) (Integer) 5;
      }
      fail("Should only call get in the Global Window, others are not ready");
      throw new AssertionError("Unreachable");
    }

    @Override
    public <T> boolean contains(PCollectionView<T> view) {
      return true;
    }

    @Override
    public boolean isEmpty() {
      return false;
    }

    @Override
    public boolean isReady(PCollectionView<?> view, BoundedWindow window) {
      return window.equals(GlobalWindow.INSTANCE);
    }
  }
}


text:
package com.cloudera.flume.conf;

import com.cloudera.flume.core.EventSink;
import com.cloudera.flume.core.EventSinkDecorator;
import com.google.common.base.Preconditions;

/**
 * This provides a linked symbol table structure useful for handling symbolic
 * sinks generated by let declarations contexts.
 */
public class LinkedSinkFactory extends SinkFactory {
  SinkFactory parent;
  String sinkname;
  EventSink sink;

  public LinkedSinkFactory(SinkFactory parent, String name, EventSink snk) {
    Preconditions.checkArgument(parent != null);
    Preconditions.checkArgument(name != null);
    Preconditions.checkArgument(snk != null);

    this.parent = parent;
    this.sinkname = name;
    this.sink = snk;
  }

  @Override
  public EventSinkDecorator<EventSink> getDecorator(Context context,
      String name, String... args) throws FlumeSpecException {
    return parent.getDecorator(context, name, args);
  }

  @Override
  public EventSink getSink(Context context, String name, String... args)
      throws FlumeSpecException {
    if (sinkname.equals(name)) {
      // TODO (jon) we are actually close to allowing in sink templates
      return sink;
    }

    return parent.getSink(context, name, args);
  }

}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System.Management.Automation;
using System.Security.Permissions;

namespace Microsoft.WindowsAzure.Commands.Profile
{
    [Cmdlet(VerbsLifecycle.Disable, "AzureDataCollection")]
    public class DisableAzureDataCollectionCommand : EnableAzureDataCollectionCommand
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public override void ExecuteCmdlet()
        {
            SetDataCollectionProfile(false);
        }
    }
}


text:
<?php

namespace tests\Nicofuma\SwaggerBundle\EventListener;

use Nicofuma\SwaggerBundle\EventListener\ValidatorListener;
use Nicofuma\SwaggerBundle\Exception\ConstraintViolationException;
use Nicofuma\SwaggerBundle\Exception\NoValidatorException;
use Nicofuma\SwaggerBundle\Validator\Validator;
use Nicofuma\SwaggerBundle\Validator\ValidatorMap;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelInterface;
use tests\Nicofuma\SwaggerBundle\SwaggerTestCase;

/**
 * @covers \Nicofuma\SwaggerBundle\EventListener\ValidatorListener
 */
class ValidatorListenerTest extends SwaggerTestCase
{
    public function testOnKernelRequestNoValidator()
    {
        $kernel = $this->prophesize(KernelInterface::class);

        $request = $this->createMockRequest('GET', '/none', []);

        $map = $this->prophesize(ValidatorMap::class);
        $map->getValidator($request)->will(function () {
            throw new NoValidatorException();
        });

        $listener = new ValidatorListener($map->reveal());

        $event = new GetResponseEvent($kernel->reveal(), $request, KernelInterface::MASTER_REQUEST);
        $listener->onKernelRequest($event);

        static::assertTrue(true);
    }

    public function testOnKernelRequest()
    {
        $kernel = $this->prophesize(KernelInterface::class);

        $request = $this->createMockRequest('GET', '/api/v1/users', []);

        $validator = $this->prophesize(Validator::class);
        $validator->validate($request)->shouldBeCalled();

        $map = $this->prophesize(ValidatorMap::class);
        $map->getValidator($request)->willReturn($validator);

        $listener = new ValidatorListener($map->reveal());

        $event = new GetResponseEvent($kernel->reveal(), $request, KernelInterface::MASTER_REQUEST);
        $listener->onKernelRequest($event);

        static::assertTrue(true);
    }

    public function testOnKernelRequestValidationError()
    {
        $this->expectException(ConstraintViolationException::class);

        $kernel = $this->prophesize(KernelInterface::class);

        $request = $this->createMockRequest('GET', '/api/v1/users', []);

        $validator = $this->prophesize(Validator::class);
        $validator->validate($request)->will(function () {
            throw new \PHPUnit_Framework_ExpectationFailedException(
                <<<'EOF'
Failed asserting that {"id":123456789} is a valid request body.
[name] The property name is required
[] Failed to match all schemas

EOF
            );
        })->shouldBeCalled();

        $map = $this->prophesize(ValidatorMap::class);
        $map->getValidator($request)->willReturn($validator);

        $listener = new ValidatorListener($map->reveal());

        $event = new GetResponseEvent($kernel->reveal(), $request, KernelInterface::MASTER_REQUEST);

        try {
            $listener->onKernelRequest($event);
        } catch (ConstraintViolationException $e) {
            $violations = $e->getViolations();

            static::assertCount(2, $violations);
            static::assertSame('[name]', $violations->get(0)->getPropertyPath());
            static::assertSame('The property name is required', $violations->get(0)->getMessage());
            static::assertSame('[]', $violations->get(1)->getPropertyPath());
            static::assertSame('Failed to match all schemas', $violations->get(1)->getMessage());

            throw $e;
        }
    }
}


text:
#include <string.h>
#include <sys/stat.h>

#include <limits.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <stdint.h>

#include "tee_storage_api.h"
#include "tee_memory.h"
#include "tee_logging.h"
#include "tee_time_api.h" /*TEE_TIMEOUT_INFINITE*/
#include "com_protocol.h" /*MGR CMD IDs*/
#include "tee_internal_client_api.h"
#include "tee_list.h"

#include "ext_storage_stream_api.h"

#include "opentee_manager_storage_api.h"
#include "core_control_resources.h"

struct storage_element {
	struct list_head list;
	uint32_t storage_blob_id;
	char objectid[TEE_OBJECT_ID_MAX_LEN];
	size_t objectid_len;
	FILE *file;
};

#define MAX_EXT_PATH_NAME MAX_PATH_NAME

#define TEE_OBJ_ID_LEN_HEX (TEE_OBJECT_ID_MAX_LEN * 2 + 1)
#define TEE_UUID_LEN_HEX (sizeof(TEE_UUID) * 2 + 1)
#define ADD_NULL_CHAR_END_TO_HEX(obj_id_len) ((obj_id_len * 2) + 1)
static uint32_t next_enum_ID = 1; /* provide unique ID for enumerators */
static char secure_storage_path[MAX_EXT_PATH_NAME] = {0};

static uint32_t next_storage_id = 1;

static struct storage_enumerator *enumerators_head;

struct storage_enumerator {
	struct storage_enumerator *next;
	DIR *dir;
	uint32_t ID;
};

static struct list_head elements_head;

static bool __attribute__((constructor)) storage_ext_init()
{
	char *tee_storage_dir = getenv("OPENTEE_STORAGE_PATH");
	int res;

	if (tee_storage_dir != NULL) {
		/* if it doesn't end with a backslash, add it */
		char *pathspec = (tee_storage_dir[strlen(tee_storage_dir) - 1] != '/') ? "%s/" : "%s" ;
		res = snprintf(secure_storage_path, MAX_EXT_PATH_NAME, pathspec, tee_storage_dir);
	} else {
		/* fallback to $HOME or /data if OPENTEE_STORAGE_PATH isn't defined */
		#ifndef ANDROID
		tee_storage_dir = getenv("HOME");
		#else
		tee_storage_dir = "/data";
		#endif
		res = snprintf(secure_storage_path, MAX_EXT_PATH_NAME, "%s/%s", tee_storage_dir, ".TEE_secure_storage/");
	}

	if (res == MAX_EXT_PATH_NAME) {
		OT_LOG(LOG_ERR, "Failed to malloc secure storage path\n");
		return false;
	}

	OT_LOG(LOG_ERR, "storage path(%s)\n", secure_storage_path);
	INIT_LIST(&elements_head);

	return true;
}

/*!
 * \brief get_uuid
 * Retrieve TAs UUID
 * \param uuid is filled with TAs uuid. UUID is converted to HEX format and containing NULL
 * character.
 * Use TEE_UUID_LEN_HEX for buffer size reservation.
 * \return
 */
static bool get_uuid(char *uuid)
{
	size_t i;

	if (uuid == NULL)
		return false;

	for (i = 0; i < sizeof(TEE_UUID); ++i)
		sprintf(uuid + i * 2, "%02x", *((unsigned char *)&current_TA_uuid + i));

	uuid[TEE_UUID_LEN_HEX] = '\0';

	return true;
}

static bool is_directory_empty(char *dir_path)
{
	struct dirent *entry;
	int file_count = 0;

	if (dir_path == NULL) {
		OT_LOG(LOG_ERR, "Dir path is NULL\n");
		return false;
	}

	DIR *dir = opendir(dir_path);
	if (dir == NULL)
		return false;

	while ((entry = readdir(dir)) != NULL) {
		++file_count;
		if (file_count > 2) {
			closedir(dir);
			return false;
		}
	}

	closedir(dir);
	return true;
}

static uint32_t add_file_to_list(FILE *file, char *objectid, size_t objectid_len)
{
	struct storage_element *new_element = calloc(1, sizeof(struct storage_element));
	new_element->file = file;
	new_element->storage_blob_id = next_storage_id++;
	new_element->objectid_len = objectid_len;
	memcpy(new_element->objectid, objectid, new_element->objectid_len);
	list_add_after(&new_element->list, &elements_head);
	return new_element->storage_blob_id;
}

static FILE *storage_id_to_file(uint32_t storage_blob_id)
{
	struct list_head *pos;
	struct storage_element *current_element;

	LIST_FOR_EACH(pos, &elements_head) {
		current_element = LIST_ENTRY(pos, struct storage_element, list);
		if (storage_blob_id == current_element->storage_blob_id)
			return current_element->file;
	}
	return NULL;
}

static uint32_t close_object(uint32_t storage_blob_id, void *objectID, size_t objectIDLen)
{
	struct list_head *pos;
	struct storage_element *current_element = NULL;

	if (!IS_VALID_STORAGE_BLOB(storage_blob_id)) {
		OT_LOG(LOG_ERR, "Not a valid storage object");
		return 1;
	}

	LIST_FOR_EACH(pos, &elements_head) {
		current_element = LIST_ENTRY(pos, struct storage_element, list);
		if (storage_blob_id == current_element->storage_blob_id)
			break;
	}

	if (current_element) {

		list_unlink(&current_element->list);

		if (memcmp(objectID, current_element->objectid, objectIDLen))
			OT_LOG(LOG_ERR,
			       "objectID does not match internal object id, closing file anyways\n");

		if (current_element->file && fclose(current_element->file) != 0) {
			OT_LOG(LOG_ERR, "Something went wrong with file closing\n");
			return 1;
		}

		free(current_element);
	}

	return 0;
}

TEE_Result alloc_storage_path(void *objectID,
			      size_t objectIDLen,
			      char **name_with_dir_path,
			      char **return_dir_path)
{
	size_t i;
	char hex_ID[TEE_OBJ_ID_LEN_HEX] = {0};
	char UUID[TEE_UUID_LEN_HEX];
	char *dir_path;

	if ((objectIDLen > TEE_OBJECT_ID_MAX_LEN) ||
	    (objectID == NULL) ||
	    (!get_uuid(UUID)) ||
	    (name_with_dir_path == NULL && return_dir_path == NULL))
		return TEE_ERROR_BAD_PARAMETERS;

	dir_path = calloc(1, MAX_EXT_PATH_NAME);
	if (dir_path == NULL)
		return TEE_ERROR_OUT_OF_MEMORY;

	if (snprintf(dir_path, MAX_EXT_PATH_NAME, "%s%s/", secure_storage_path, UUID)
	    == MAX_EXT_PATH_NAME){
		OT_LOG(LOG_ERR, "secure storage dir path is too long");
		free(dir_path);
		return TEE_ERROR_OVERFLOW;
	}

	if (name_with_dir_path) {
		*name_with_dir_path = calloc(1, MAX_EXT_PATH_NAME + 1);
		if (*name_with_dir_path == NULL) {
			free(dir_path);
			return TEE_ERROR_OUT_OF_MEMORY;
		}

		for (i = 0; i < objectIDLen; ++i)
			sprintf(hex_ID + i * 2, "%02x", *((unsigned char *)objectID + i));

		if (snprintf(*name_with_dir_path, MAX_EXT_PATH_NAME, "%s%s", dir_path, hex_ID)
		    == MAX_EXT_PATH_NAME) {
			OT_LOG(LOG_ERR, "secure storage name path is too long");
			free(dir_path);
			free(*name_with_dir_path);
			*name_with_dir_path = NULL;
			return TEE_ERROR_OVERFLOW;
		}
	}

	if (return_dir_path)
		*return_dir_path = dir_path;
	else
		free(dir_path);

	return TEE_SUCCESS;
}

uint32_t ext_object_id_to_storage_id(char *objectid, size_t objectid_len)
{
	struct list_head *pos;
	struct storage_element *current_element;

	LIST_FOR_EACH(pos, &elements_head) {
		current_element = LIST_ENTRY(pos, struct storage_element, list);
		if (objectid_len == current_element->objectid_len &&
		    !memcmp(objectid, current_element->objectid, objectid_len)) {
			return current_element->storage_blob_id;
		}
	}

	return 0;
}

uint32_t ext_delete_storage_blob(uint32_t storage_blob_id, void *objectID, size_t objectIDLen)
{
	char *name_with_dir_path;
	char *dir_path;
	FILE *object_file;

	object_file = storage_id_to_file(storage_blob_id);

	if (object_file && close_object(storage_blob_id, objectID, objectIDLen)) {
		return 1;

	}

	if (alloc_storage_path(objectID, objectIDLen, &name_with_dir_path, &dir_path)) {
		OT_LOG(LOG_ERR, "Bad parameters\n");
		return 1;
	}

	/* TODO: Check that correct file is closed and removed! FILE == objectID */

	if (remove(name_with_dir_path) < 0) {
		OT_LOG(LOG_ERR, "Failed to remove file: %s", name_with_dir_path);
		return 1;
	}

	if (is_directory_empty(dir_path))
		rmdir(dir_path);

	free(name_with_dir_path);
	free(dir_path);
	return 0;
}

void ext_close_storage_blob(uint32_t storage_blob_id)
{
	close_object(storage_blob_id, NULL, 0);
}

uint32_t ext_open_storage_blob(char *objectID, size_t objectIDlen, bool create_if_not_exist)
{
	FILE *opened_file = NULL;
	char *file_name_with_path = NULL;
	char *dir_path = NULL;
	uint32_t return_storage_blob = 0;
	int ret_mkdir;

	if (alloc_storage_path(objectID, objectIDlen, &file_name_with_path, &dir_path)) {
		OT_LOG(LOG_ERR, "Bad parameters\n");
		return 0;
	}

	/* test if exists */
	opened_file = fopen(file_name_with_path, "rb+");

	if (create_if_not_exist && opened_file == NULL) {
		/* not existing, open new */
		opened_file = fopen(file_name_with_path, "w+b");

		if (opened_file == NULL) {
			/* might fail if secure storage path not exist */
			ret_mkdir = mkdir(secure_storage_path, 0777);
			if (ret_mkdir != 0 && errno != EEXIST) {
				OT_LOG(LOG_ERR, "Cannot create Secure Storage directory: %s\n",
				strerror(errno));
				goto ret;
			}

			ret_mkdir = mkdir(dir_path, 0777);
			if (ret_mkdir != 0 && errno != EEXIST) {
				OT_LOG(LOG_ERR, "Cannot create UUID directory: %s\n",
				strerror(errno));
				goto ret;
			}

			opened_file = fopen(file_name_with_path, "w+b");

			if (is_directory_empty(dir_path))
				rmdir(dir_path);
		}
	}

	if (opened_file)
		return_storage_blob = add_file_to_list(opened_file, objectID, objectIDlen);

ret:
	free(dir_path);
	free(file_name_with_path);

	return return_storage_blob;
}

size_t ext_get_storage_blob_size(uint32_t storage_blob_id)
{
	FILE *file = storage_id_to_file(storage_blob_id);
	struct stat st;

	if (file) {
		if (fstat(fileno(file), &st))
			return 0; /* some error occured */
		return st.st_size;
	}
	return 0;
}

bool ext_change_object_ID(uint32_t storage_blob_id,
			  void *objectID,
			  size_t objectIDLen,
			  void *new_objectID,
			  size_t new_objectIDLen)
{
	struct list_head *pos;
	struct storage_element *current_element;

	char *name_with_dir_path = NULL;
	char *new_name_with_dir_path = NULL;

	bool ret_val = true;

	if (alloc_storage_path(objectID, objectIDLen, &name_with_dir_path, NULL)) {
		OT_LOG(LOG_ERR, "Bad parameters\n");
		ret_val = false;
		goto exit;
	}

	if (alloc_storage_path(new_objectID, new_objectIDLen, &new_name_with_dir_path, NULL)) {
		OT_LOG(LOG_ERR, "Bad parameters\n");
		ret_val = false;
		goto exit;
	}

	/* TODO: Check if TA can change object ID */

	if (access(new_name_with_dir_path, F_OK) == 0) {
		OT_LOG(LOG_ERR, "Cannot change object ID, because new ID is in use [%d]", errno);
		ret_val = false;
		goto exit;
	}

	if (rename(name_with_dir_path, new_name_with_dir_path) != 0) {
		OT_LOG(LOG_ERR, "Rename function failed\n");
		ret_val = false;
		goto exit;
	}

	/* update info */
	LIST_FOR_EACH(pos, &elements_head) {
		current_element = LIST_ENTRY(pos, struct storage_element, list);
		if (storage_blob_id == current_element->storage_blob_id) {
			current_element->objectid_len = new_objectIDLen;
			memcpy(current_element->objectid,
			       new_objectID,
			       current_element->objectid_len);
			break;
		}
	}

exit:
	free(name_with_dir_path);
	free(new_name_with_dir_path);
	return ret_val;
}

uint32_t ext_read_stream(uint32_t storage_blob_id, uint32_t offset, void *data, size_t datalen)
{
	FILE *file = storage_id_to_file(storage_blob_id);
	uint32_t readed = 0;

	if (fseek(file, offset, SEEK_SET) != 0) {
		OT_LOG(LOG_ERR, "fseek failed\n");
		return readed;
	}

	readed = fread(data, 1, datalen, file);
	return readed;
}

uint32_t ext_write_stream(uint32_t storage_blob_id, uint32_t offset, void *data, size_t datalen)
{
	FILE *file = storage_id_to_file(storage_blob_id);
	uint32_t written = 0;

	if (!file) {
		OT_LOG(LOG_ERR, "trying to write non-existing storage blob\n");
		return TEE_ERROR_ITEM_NOT_FOUND;
	}

	if (fseek(file, offset, SEEK_SET) != 0) {
		OT_LOG(LOG_ERR, "fseek failed\n");
		return written;
	}

	written = fwrite(data, 1, datalen, file);

	if (fflush(file)) {
		OT_LOG(LOG_ERR, "file flush failed after read\n");
	}
	return written;
}

TEE_Result ext_truncate_storage_blob(uint32_t storage_blob_id, uint32_t size)
{
	FILE *file = storage_id_to_file(storage_blob_id);

	if (!file) {
		OT_LOG(LOG_ERR, "trying to truncate non-existing storage blob\n");
		return TEE_ERROR_ITEM_NOT_FOUND;
	}

	if (ftruncate(fileno(file), size) != 0) {
		if (errno == ENOSPC)
			return TEE_ERROR_STORAGE_NO_SPACE;
		return TEE_ERROR_GENERIC;

	}
	return TEE_SUCCESS;
}

bool ext_alloc_for_enumerator(uint32_t *ID)
{
	struct storage_enumerator *new_enumerator;

	if (ID == NULL)
		return false;

	/* MAlloc for handle and fill */
	new_enumerator = calloc(sizeof(struct storage_enumerator), 1);
	if (new_enumerator == NULL) {
		OT_LOG(LOG_ERR, "Cannot malloc for enumerator: Out of memory\n");
		return false;
	}

	new_enumerator->ID = next_enum_ID;
	++next_enum_ID; /* check if ID free */

	/* Add new enumerator end of list */
	if (enumerators_head == NULL) {
		enumerators_head = new_enumerator;
	} else {
		new_enumerator->next = enumerators_head;
		enumerators_head = new_enumerator;
	}

	*ID = new_enumerator->ID;
	return true;
}

void ext_free_enumerator(uint32_t free_enum_ID)
{
	struct storage_enumerator *del_enum, *prev_enum;

	if (enumerators_head == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Not a valid enumerator\n");
		/*TEE_Panic(TEE_ERROR_GENERIC)*/
		return;
	}

	del_enum = enumerators_head;
	prev_enum = del_enum;

	if (enumerators_head->ID == free_enum_ID) {
		del_enum = enumerators_head;
		enumerators_head = enumerators_head->next;
		goto free_and_close;
	}

	while (del_enum) {
		if (del_enum->ID == free_enum_ID) {
			prev_enum->next = del_enum->next;
			goto free_and_close;
		}
		prev_enum = del_enum;
		del_enum = del_enum->next;
	}

	/* should never end up here */
	OT_LOG(LOG_ERR, "Enumerator: Something went wrong with file closening\n");
	return;

free_and_close:
	if (del_enum->dir != NULL)
		closedir(del_enum->dir);
	free(del_enum);
}

static struct storage_enumerator *get_enum(uint32_t ID)
{
	struct storage_enumerator *iter_enum = enumerators_head;

	while (iter_enum != NULL) {
		if (iter_enum->ID == ID)
			return iter_enum;

		iter_enum = iter_enum->next;
	}

	return NULL;
}

bool ext_start_enumerator(uint32_t start_enum_ID)
{
	char dir_path[MAX_EXT_PATH_NAME] = {0};
	char UUID[TEE_UUID_LEN_HEX];
	struct storage_enumerator *start_enum;

	if (!get_uuid(UUID)) {
		OT_LOG(LOG_ERR, "UUID Not found");
		return false;
	}

	if (snprintf(dir_path, MAX_EXT_PATH_NAME, "%s%s/", secure_storage_path, UUID)
	    == MAX_EXT_PATH_NAME) {
		/* TEE_ERROR_OUT_OF_MEMORY */
		OT_LOG(LOG_ERR, "Out of memory");
		return false;
	}

	start_enum = get_enum(start_enum_ID);
	if (start_enum == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Enumerator not valid");
		return false;
	}

	if (start_enum->dir != NULL)
		ext_reset_enumerator(start_enum_ID);

	start_enum->dir = opendir(dir_path);
	if (start_enum->dir == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Something went wrong (dirent failure)\n");
		return false; /* NULL == directory empty */
	}

	if (is_directory_empty(dir_path)) {
		return false; /* FALSE == directory empty -> tee_error_item_not_found */
	}

	return true;
}

void ext_reset_enumerator(uint32_t reset_enum_ID)
{
	struct storage_enumerator *reset_enum;

	if (enumerators_head == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Not a valid enumerator\n");
		return /*TEE_ERROR_GENERIC*/;
	}

	reset_enum = get_enum(reset_enum_ID);
	if (reset_enum == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Enumerator not valid\n");
		return; /*(TEE_ERROR_GENERIC);*/
	}

	/* stop enumeration if needed */
	if (reset_enum->dir != NULL)
		closedir(reset_enum->dir);

	reset_enum->dir = NULL;
}

bool ext_get_next_obj_from_enumeration(uint32_t get_next_ID,
				       struct ss_object_meta_info *recv_data_to_caller)
{
	char name_with_path[MAX_EXT_PATH_NAME] = {0};
	char UUID[TEE_UUID_LEN_HEX];
	struct storage_enumerator *get_from_enum;
	struct dirent *entry;
	FILE *next_object = NULL;
	long end_pos;

	if (!get_uuid(UUID))
		return false;

	get_from_enum = get_enum(get_next_ID);
	if (get_from_enum == NULL) {
		OT_LOG(LOG_ERR, "Enumerator: Enumerator not valid\n");
		return false;
	}

	if (get_from_enum->dir == NULL)
		return false; /* enumeration not started */

	/* Init struct where next object to be read */
	memset(recv_data_to_caller, 0, sizeof(struct ss_object_meta_info));

	/* Open next persistant object from storage */
	do {
		while ((entry = readdir(get_from_enum->dir)) != NULL) {
			if (entry->d_name[0] == '.')
				continue;
			else
				break;
		}

		if (entry == NULL) {
			/* Enumeration has reached end */
			return false;
		}

		if (snprintf(name_with_path, MAX_EXT_PATH_NAME, "%s%s/%s",
			     secure_storage_path, UUID, entry->d_name) == MAX_EXT_PATH_NAME) {

			OT_LOG(LOG_ERR, "Enumerator: name path size overflow\n");
			return false; /* TEE_ERROR_GENERIC */
		}

		next_object = fopen(name_with_path, "rb");

		if (next_object == NULL) {
			continue;
		}

		if (fread(recv_data_to_caller, sizeof(struct ss_object_meta_info), 1,
			  next_object) != 1) {
			OT_LOG(LOG_ERR, "Error at read file (enumeration); errno: %i\n", errno);
			memset(recv_data_to_caller, 0, sizeof(struct ss_object_meta_info));
			fclose(next_object); /* Skip to next object */
			next_object = NULL;
			continue;
		}

		// calculate data size
		// NOTE: Why we are not using data_size from ss_object_meta_info
		if (fseek(next_object, 0, SEEK_END) != 0)
			OT_LOG(LOG_ERR, "fseek error at get next enumeration; errno: %i\n", errno);

		end_pos = ftell(next_object);
		if (end_pos == -1L)
			OT_LOG(LOG_ERR, "ftell error at get next enumeration; errno: %i\n", errno);

		if (end_pos - recv_data_to_caller->data_begin > UINT32_MAX)
			recv_data_to_caller->info.dataSize = UINT32_MAX;
		else
			recv_data_to_caller->info.dataSize =
			    ftell(next_object) - recv_data_to_caller->data_begin;

		/* Zero data position */
		recv_data_to_caller->info.dataPosition = 0;

	} while (next_object == NULL);

	if (next_object != NULL)
		fclose(next_object);

	return true;
}


text:
source $IROOT/java8.installed

sed -i 's|mongodb.host=.*|mongodb.host='"${DBHOST}"'|g' src/main/resources/application.conf

mvn clean package -Dmaven.test.skip=true

java -jar target/mangooioapp.jar &


text:
<meta charset="utf-8">
(#) TargetSdkVersion Soon Expiring

!!! ERROR: TargetSdkVersion Soon Expiring
   This is an error.

Id
:   `ExpiringTargetSdkVersion`
Summary
:   TargetSdkVersion Soon Expiring
Severity
:   Error
Category
:   Compliance
Platform
:   Android
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Affects
:   Gradle build files
Editing
:   This check runs on the fly in the IDE editor
See
:   https://support.google.com/googleplay/android-developer/answer/113469#targetsdk
See
:   https://developer.android.com/distribute/best-practices/develop/target-sdk.html
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/GradleDetector.kt)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/GradleDetectorTest.kt)
Copyright Year
:   2014

In the second half of 2018, Google Play will require that new apps and
app updates target API level 26 or higher. This will be required for new
apps in August 2018, and for updates to existing apps in November 2018.

Configuring your app to target a recent API level ensures that users
benefit from significant security and performance improvements, while
still allowing your app to run on older Android versions (down to the
`minSdkVersion`).

This lint check starts warning you some months **before** these changes
go into effect if your `targetSdkVersion` is 25 or lower. This is
intended to give you a heads up to update your app, since depending on
your current `targetSdkVersion` the work can be nontrivial.

To update your `targetSdkVersion`, follow the steps from "Meeting Google
Play requirements for target API level",
https://developer.android.com/distribute/best-practices/develop/target-sdk.html.

!!! Tip
   This lint check has an associated quickfix available in the IDE.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
build.gradle:6:Error: Google Play will soon require that apps target API
level  or higher. This will be required for new apps in August , and for
updates to existing apps in November . [ExpiringTargetSdkVersion]

    targetSdkVersion
    -------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`build.gradle`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~groovy linenumbers
apply plugin: 'com.android.application'

android {
    defaultConfig {
        // Already meeting last year's requirement but not this year's requirement
        targetSdkVersion
        targetSdkVersion  // OK
 // OK
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/GradleDetectorTest.kt)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `GradleDetector.testExpiring2`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection ExpiringTargetSdkVersion
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <lint>
      <issue id="ExpiringTargetSdkVersion" severity="ignore" />
  </lint>
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'ExpiringTargetSdkVersion'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore ExpiringTargetSdkVersion ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>


text:
python-raumfeld
===============

A pythonic library for discovering and controlling Teufel Raumfeld
devices.

Tested with a Raumfeld One. Hardware donations to improve the library
are welcome :smile:

Supports Python >2.7, 3.x

Installation
------------

::

    pip install raumfeld

Quickstart
----------

.. code:: python

    import raumfeld

    # discovery returns a list of RaumfeldDevices
    devices = raumfeld.discover(timeout=1, retries=1)
    if len(devices) > 0:
        speaker = devices[0]

        # now you can control your raumfeld speaker
        speaker.mute = True     # mute
        print(speaker.volume)   # print current volume
        speaker.volume = 50     # set volume

        speaker.pause()
        speaker.play()
    else:
        print('No devices found.')


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Clock: V1</title>
    <script type="text/javascript" src="js/app.js"> </script>
    <link rel="stylesheet" type="text/css" href="css/style.css">
  </head>
  <body>
    <button type="button" id="notifyButton">Notify Me!</button>
    <button type="button" id="notifyLaterButton">Notify Me, but 5 seconds later!</button>
  </body>
</html>


text:
<app-demo
  [datasource]="datasource"
  [context]="demoContext"
  [sources]="sources"
>

    <button (click)="doAppend()">Append</button> /
    <button (click)="doPrepend()">Prepend</button>
    <input [ngModel]="inputValue" (change)="onInputChanged($any($event.target))" size="2">

      Adding items at the end and at the beginning of the uiScroll items buffer is possible with
      {{appendCallSample}} and {{prependCallSample}} methods respectively.
      The items parameter is an array of items we want to add.
      Both methods act in the same way, so let's discuss prepend.

      In this demo we have 20 items on start and 5 of them (95-99) are invisible on the backward direction.
      By pushing "Prepend" button we are going to add 4 (which is the input value) new items
      to the top of the list. After they are prepended, they become visible when scrolling up.
      The uiScroll accurately injects prepended items into
      its internal buffer consisting of 95-114 rows initially,
      so 1-4 new items temporary take place of items with indexes 91-94.

      But if we scroll away and make '90s items invisible and deleted from the viewport,
      and then scroll back, we will realise that nothing changes:
      "new" items are gone and the old 91-94 items returned to initial position.
      The point is that the Datasource does not take into account our dataset changes.
      It is our responsibility to take care of data passing to the uiScroll via Datasource.
      Next sample provides one of the approach of consistent Datasource implementation with
      Adapter.append and Adapter.prepend methods usage.

</app-demo>


text:
$(document).ready(function() {
    $('#slider-container ul').bxSlider({
        buildPager: function(slideIndex) {
            switch(slideIndex){
                case 0:
                    return 'Sponsorballen';
                case 1:
                    return 'Vrienden van';
                case 2:
                    return 'Bouw mee';
                case 3:
                    return 'Eendjesrace';
                case 4:
                    return 'Adopteer een speler';
            }
        },
        controls: false
    });

    $('#quotes-container ul').bxSlider({
        controls: false
    });

    $('.newsletter a.button').click(function() {
        if($('.newsletter input').val() != '') {
            $.post('/home/newsletter', { 'email': $('#email').val() }, function(data, status) {
                $('.newsletter').slideUp();
                $('.confirmation').slideDown();
            });
        } else {
            $('.newsletter input').addClass('error');
        }
    });
});


text:
#ifndef PCL_TEXTUREMESH_H_
#define PCL_TEXTUREMESH_H_

#include <Eigen/Core>
#include <string>
#include <pcl/PCLPointCloud2.h>
#include <pcl/Vertices.h>

namespace pcl
{
  /** \author Khai Tran */
  struct TexMaterial
  {
    TexMaterial () : tex_name (), tex_file (), tex_Ka (), tex_Kd (), tex_Ks (), tex_d (), tex_Ns (), tex_illum () {}

    struct RGB
    {
      float r;
      float g;
      float b;
    }; //RGB

    /** \brief Texture name. */
    std::string tex_name;

    /** \brief Texture file. */
    std::string tex_file;

    /** \brief Defines the ambient color of the material to be (r,g,b). */
    RGB         tex_Ka;

    /** \brief Defines the diffuse color of the material to be (r,g,b). */
    RGB         tex_Kd;

    /** \brief Defines the specular color of the material to be (r,g,b). This color shows up in highlights. */
    RGB         tex_Ks;

    /** \brief Defines the transparency of the material to be alpha. */
    float       tex_d;

    /** \brief Defines the shininess of the material to be s. */
    float       tex_Ns;

    /** \brief Denotes the illumination model used by the material.
      *
      * illum = 1 indicates a flat material with no specular highlights, so the value of Ks is not used.
      * illum = 2 denotes the presence of specular highlights, and so a specification for Ks is required.
      */
    int         tex_illum;
  }; // TexMaterial

  /** \author Khai Tran */
  struct TextureMesh
  {
    TextureMesh () :
      cloud (), tex_polygons (), tex_coordinates (), tex_materials () {}

    pcl::PCLPointCloud2  cloud;
    pcl::PCLHeader  header;

    std::vector<std::vector<pcl::Vertices> >    tex_polygons;     // polygon which is mapped with specific texture defined in TexMaterial
    std::vector<std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > > tex_coordinates;  // UV coordinates
    std::vector<pcl::TexMaterial>               tex_materials;    // define texture material

    public:
      typedef boost::shared_ptr<pcl::TextureMesh> Ptr;
      typedef boost::shared_ptr<pcl::TextureMesh const> ConstPtr;
   }; // struct TextureMesh

   typedef boost::shared_ptr<pcl::TextureMesh> TextureMeshPtr;
   typedef boost::shared_ptr<pcl::TextureMesh const> TextureMeshConstPtr;
} // namespace pcl

#endif /* PCL_TEXTUREMESH_H_ */


text:
package genecode.function;

import java.util.Arrays;

/**
 * A function which negates a value.
 */
public class Neg
    extends Function
{
    private static final long serialVersionUID = 417864237362487687L;

    /**
     * CTOR.
     *
     * @param type The subclass of {@link Number} which we take and
     *             give back. Only boxed versions of primitive types
     *             are supported.
     */
    public Neg(final Class<? extends Number> type)
    {
        super(Arrays.asList(type), type);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object safeCall(final Object[] args)
    {
        final Object value = args[0];
        if (!(value instanceof Number)) {
            return null;
        }

        if (getReturnType().equals(Byte.class)) {
            return Byte.valueOf((byte)(-((Number)value).byteValue()));
        }
        else if (getReturnType().equals(Short.class)) {
            return Short.valueOf((short)(-((Number)value).shortValue()));
        }
        else if (getReturnType().equals(Integer.class)) {
            return Integer.valueOf(-((Number)value).intValue());
        }
        else if (getReturnType().equals(Long.class)) {
            return Long.valueOf(-((Number)value).longValue());
        }
        else if (getReturnType().equals(Float.class)) {
            return Float.valueOf(-((Number)value).floatValue());
        }
        else if (getReturnType().equals(Double.class)) {
            return Double.valueOf(-((Number)value).doubleValue());
        }
        else {
            return null;
        }
    }
}


text:
#include"audio_internal.h"

#ifdef PLATFORM_WINDOWS_64

#include <windows.h>
#include <mmsystem.h>

HWAVEOUT hWaveOut; /* device handle */
WAVEFORMATEX wfx; /* look this up in your documentation */

void audio_internal_init()
{
//	MMRESULT result;/* for waveOut return values */
					/*
					* first we need to set up the WAVEFORMATEX structure.
					* the structure describes the format of the audio.
					*/
	wfx.nSamplesPerSec = 22050; /* sample rate */
	wfx.wBitsPerSample = 16; /* sample size */
	wfx.nChannels = 1; /* channels*/
					   /*
					   * WAVEFORMATEX also has other fields which need filling.
					   * as long as the three fields above are filled this should
					   * work for any PCM (pulse code modulation) format.
					   */
	wfx.cbSize = 0; /* size of _extra_ info */
	wfx.wFormatTag = WAVE_FORMAT_PCM;
	wfx.nBlockAlign = (wfx.wBitsPerSample >> 3) * wfx.nChannels;
	wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
	/*
	* try to open the default wave device. WAVE_MAPPER is
	* a constant defined in mmsystem.h, it always points to the
	* default wave device on the system (some people have 2 or
	* more sound cards).
	*/
	if (waveOutOpen(
		&hWaveOut,
		WAVE_MAPPER,
		&wfx,
		0,
		0,
		CALLBACK_NULL
		) != MMSYSERR_NOERROR) {
		fprintf(stderr, "unable to open WAVE_MAPPER device\n");
		ExitProcess(1);
	}
	else
	{
		printf("success!\n");
	}
}
void audio_internal_shutdown()
{
	/*
	* device is now open so print the success message
	* and then close the device again.
	*/
	printf("The Wave Mapper device was opened successfully!\n");
	waveOutClose(hWaveOut);
	return;
}

void writeAudioBlock(HWAVEOUT hWaveOut, LPSTR block, DWORD size)
{
	WAVEHDR header;
	/*
	* initialise the block header with the size
	* and pointer.
	*/
	ZeroMemory(&header, sizeof(WAVEHDR));
	header.dwBufferLength = size;
	header.lpData = block;
	/*
	* prepare the block for playback
	*/
	waveOutPrepareHeader(hWaveOut, &header, sizeof(WAVEHDR));
	/*
	* write the block to the device. waveOutWrite returns immediately
	* unless a synchronous driver is used (not often).
	*/
	waveOutWrite(hWaveOut, &header, sizeof(WAVEHDR));
	/*
	* wait a while for the block to play then start trying
	* to unprepare the header. this will fail until the block has
	* played.
	*/
	Sleep(500);
	while (waveOutUnprepareHeader(
		hWaveOut,
		&header,
		sizeof(WAVEHDR)
	) == WAVERR_STILLPLAYING)
		Sleep(100);
}

LPSTR loadAudioBlock(const char* filename, DWORD* blockSize)
{
	HANDLE hFile = INVALID_HANDLE_VALUE;
	DWORD size = 0;
	DWORD readBytes = 0;
	void* block = NULL;
	/*
	* open the file
	*/
	if ((hFile = CreateFile(
		filename,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		0,
		NULL
	)) == INVALID_HANDLE_VALUE)
		return NULL;
	/*
	* get it's size, allocate memory and read the file
	* into memory. don't use this on large files!
	*/
	do {
		if ((size = GetFileSize(hFile, NULL)) == 0)
			break;
		if ((block = HeapAlloc(GetProcessHeap(), 0, size)) == NULL)
			break;
		ReadFile(hFile, block, size, &readBytes, NULL);
	} while (0);
	CloseHandle(hFile);
	*blockSize = size;
	return (LPSTR)block;
}

void audio_internal_test()
{
	LPSTR block;/* pointer to the block */
	DWORD blockSize;/* holds the size of the block */

	if ((block = loadAudioBlock("../media/audio/raw/pb-death.raw", &blockSize)) == NULL)
	{
		fprintf(stderr, "Unable to load file\n");
		exit(1);
	}

	writeAudioBlock(hWaveOut, block, blockSize);
}

#endif


text:
using BepuPhysics.CollisionDetection;
using BepuUtilities;
using BepuUtilities.Memory;
using System;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using static BepuUtilities.GatherScatter;
namespace BepuPhysics.Constraints
{
    /// <summary>
    /// Angular component of a hinge. Constrains the angular degrees of freedom of two bodies such that they can only rotate relative to each other around the hinge's axis.
    /// </summary>
    public struct AngularHinge : ITwoBodyConstraintDescription<AngularHinge>
    {
        /// <summary>
        /// Hinge axis in the local space of A.
        /// </summary>
        public Vector3 LocalHingeAxisA;
        /// <summary>
        /// Hinge axis in the local space of B.
        /// </summary>
        public Vector3 LocalHingeAxisB;
        /// <summary>
        /// Spring frequency and damping parameters.
        /// </summary>
        public SpringSettings SpringSettings;

        public readonly int ConstraintTypeId
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                return AngularHingeTypeProcessor.BatchTypeId;
            }
        }

        public readonly Type TypeProcessorType => typeof(AngularHingeTypeProcessor);
        public readonly TypeProcessor CreateTypeProcessor() => new AngularHingeTypeProcessor();

        public readonly void ApplyDescription(ref TypeBatch batch, int bundleIndex, int innerIndex)
        {
            ConstraintChecker.AssertUnitLength(LocalHingeAxisA, nameof(AngularHinge), nameof(LocalHingeAxisA));
            ConstraintChecker.AssertUnitLength(LocalHingeAxisB, nameof(AngularHinge), nameof(LocalHingeAxisB));
            ConstraintChecker.AssertValid(SpringSettings, nameof(AngularHinge));
            Debug.Assert(ConstraintTypeId == batch.TypeId, "The type batch passed to the description must match the description's expected type.");
            ref var target = ref GetOffsetInstance(ref Buffer<AngularHingePrestepData>.Get(ref batch.PrestepData, bundleIndex), innerIndex);
            Vector3Wide.WriteFirst(LocalHingeAxisA, ref target.LocalHingeAxisA);
            Vector3Wide.WriteFirst(LocalHingeAxisB, ref target.LocalHingeAxisB);
            GetFirst(ref target.SpringSettings.AngularFrequency) = SpringSettings.AngularFrequency;
            GetFirst(ref target.SpringSettings.TwiceDampingRatio) = SpringSettings.TwiceDampingRatio;
        }

        public readonly void BuildDescription(ref TypeBatch batch, int bundleIndex, int innerIndex, out AngularHinge description)
        {
            Debug.Assert(ConstraintTypeId == batch.TypeId, "The type batch passed to the description must match the description's expected type.");
            ref var source = ref GetOffsetInstance(ref Buffer<AngularHingePrestepData>.Get(ref batch.PrestepData, bundleIndex), innerIndex);
            Vector3Wide.ReadFirst(source.LocalHingeAxisA, out description.LocalHingeAxisA);
            Vector3Wide.ReadFirst(source.LocalHingeAxisB, out description.LocalHingeAxisB);
            description.SpringSettings.AngularFrequency = GetFirst(ref source.SpringSettings.AngularFrequency);
            description.SpringSettings.TwiceDampingRatio = GetFirst(ref source.SpringSettings.TwiceDampingRatio);
        }
    }

    public struct AngularHingePrestepData
    {
        public Vector3Wide LocalHingeAxisA;
        public Vector3Wide LocalHingeAxisB;
        public SpringSettingsWide SpringSettings;
    }

    public struct AngularHingeFunctions : ITwoBodyConstraintFunctions<AngularHingePrestepData, Vector2Wide>
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void GetErrorAngles(in Vector3Wide hingeAxisA, in Vector3Wide hingeAxisB, in Matrix2x3Wide jacobianA, out Vector2Wide errorAngles)
        {
            //Compute the position error and bias velocities.
            //Now we just have the slight annoyance that our error function contains inverse trigonometry.
            //We'll just use:
            //atan(dot(hingeAxisBOnPlaneX, hingeAxisA), dot(hingeAxisBOnPlaneX, constraintAxisAY)) =
            //sign(dot(hingeAxisBOnPlaneX, constraintAxisAY)) * acos(dot(hingeAxisA, hingeAxisBOnPlaneX / ||hingeAxisBOnPlaneX||))
            //TODO: You could probably speed this up a bunch with some alternative approximations if you're willing to accept more error.
            //V1 abandoned the inverse trig and just used a dot product equivalent, which... had issues, but hey it's cheap.
            Vector3Wide.Dot(hingeAxisB, jacobianA.X, out var hingeAxisBDotX);
            Vector3Wide.Dot(hingeAxisB, jacobianA.Y, out var hingeAxisBDotY);
            Vector3Wide.Scale(jacobianA.X, hingeAxisBDotX, out var toRemoveX);
            Vector3Wide.Scale(jacobianA.Y, hingeAxisBDotY, out var toRemoveY);
            Vector3Wide.Subtract(hingeAxisB, toRemoveX, out var hingeAxisBOnPlaneX);
            Vector3Wide.Subtract(hingeAxisB, toRemoveY, out var hingeAxisBOnPlaneY);
            Vector3Wide.Length(hingeAxisBOnPlaneX, out var xLength);
            Vector3Wide.Length(hingeAxisBOnPlaneY, out var yLength);
            var scaleX = Vector<float>.One / xLength;
            var scaleY = Vector<float>.One / yLength;
            Vector3Wide.Scale(hingeAxisBOnPlaneX, scaleX, out hingeAxisBOnPlaneX);
            Vector3Wide.Scale(hingeAxisBOnPlaneY, scaleY, out hingeAxisBOnPlaneY);
            //If the axis is parallel with the normal of the plane, just arbitrarily pick 0 angle.
            var epsilon = new Vector<float>(1e-7f);
            var useFallbackX = Vector.LessThan(xLength, epsilon);
            var useFallbackY = Vector.LessThan(yLength, epsilon);
            Vector3Wide.ConditionalSelect(useFallbackX, hingeAxisA, hingeAxisBOnPlaneX, out hingeAxisBOnPlaneX);
            Vector3Wide.ConditionalSelect(useFallbackY, hingeAxisA, hingeAxisBOnPlaneY, out hingeAxisBOnPlaneY);

            Vector3Wide.Dot(hingeAxisBOnPlaneX, hingeAxisA, out var hbxha);
            Vector3Wide.Dot(hingeAxisBOnPlaneY, hingeAxisA, out var hbyha);
            //We could probably get away with an acos approximation of something like (1 - x) * pi/2, but we'll do just a little more work:
            errorAngles.X = MathHelper.Acos(hbxha);
            errorAngles.Y = MathHelper.Acos(hbyha);
            Vector3Wide.Dot(hingeAxisBOnPlaneX, jacobianA.Y, out var hbxay);
            Vector3Wide.Dot(hingeAxisBOnPlaneY, jacobianA.X, out var hbyax);
            errorAngles.X = Vector.ConditionalSelect(Vector.LessThan(hbxay, Vector<float>.Zero), errorAngles.X, -errorAngles.X);
            errorAngles.Y = Vector.ConditionalSelect(Vector.LessThan(hbyax, Vector<float>.Zero), -errorAngles.Y, errorAngles.Y);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void ApplyImpulse(in Matrix2x3Wide impulseToVelocityA, in Matrix2x3Wide negatedImpulseToVelocityB, in Vector2Wide csi, ref Vector3Wide angularVelocityA, ref Vector3Wide angularVelocityB)
        {
            Matrix2x3Wide.Transform(csi, impulseToVelocityA, out var velocityChangeA);
            Vector3Wide.Add(angularVelocityA, velocityChangeA, out angularVelocityA);
            Matrix2x3Wide.Transform(csi, negatedImpulseToVelocityB, out var negatedVelocityChangeB);
            Vector3Wide.Subtract(angularVelocityB, negatedVelocityChangeB, out angularVelocityB);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void ComputeJacobians(in Vector3Wide localHingeAxisA, in QuaternionWide orientationA, out Vector3Wide hingeAxisA, out Matrix2x3Wide jacobianA)
        {
            //Note that we build the tangents in local space first to avoid inconsistencies.
            Helpers.BuildOrthonormalBasis(localHingeAxisA, out var localAX, out var localAY);
            Matrix3x3Wide.CreateFromQuaternion(orientationA, out var orientationMatrixA);
            Matrix3x3Wide.TransformWithoutOverlap(localHingeAxisA, orientationMatrixA, out hingeAxisA);
            Matrix3x3Wide.TransformWithoutOverlap(localAX, orientationMatrixA, out jacobianA.X);
            Matrix3x3Wide.TransformWithoutOverlap(localAY, orientationMatrixA, out jacobianA.Y);
        }

        public void WarmStart(in Vector3Wide positionA, in QuaternionWide orientationA, in BodyInertiaWide inertiaA, in Vector3Wide positionB, in QuaternionWide orientationB, in BodyInertiaWide inertiaB, ref AngularHingePrestepData prestep, ref Vector2Wide accumulatedImpulses, ref BodyVelocityWide wsvA, ref BodyVelocityWide wsvB)
        {
            ComputeJacobians(prestep.LocalHingeAxisA, orientationA, out _, out var jacobianA);
            Symmetric3x3Wide.MultiplyWithoutOverlap(jacobianA, inertiaA.InverseInertiaTensor, out var impulseToVelocityA);
            Symmetric3x3Wide.MultiplyWithoutOverlap(jacobianA, inertiaB.InverseInertiaTensor, out var negatedImpulseToVelocityB);
            ApplyImpulse(impulseToVelocityA, negatedImpulseToVelocityB, accumulatedImpulses, ref wsvA.Angular, ref wsvB.Angular);
        }

        public void Solve(in Vector3Wide positionA, in QuaternionWide orientationA, in BodyInertiaWide inertiaA, in Vector3Wide positionB, in QuaternionWide orientationB, in BodyInertiaWide inertiaB, float dt, float inverseDt, ref AngularHingePrestepData prestep, ref Vector2Wide accumulatedImpulses, ref BodyVelocityWide wsvA, ref BodyVelocityWide wsvB)
        {
            //Note that we build the tangents in local space first to avoid inconsistencies.
            ComputeJacobians(prestep.LocalHingeAxisA, orientationA, out var hingeAxisA, out var jacobianA);
            QuaternionWide.TransformWithoutOverlap(prestep.LocalHingeAxisB, orientationB, out var hingeAxisB);

            //We project hingeAxisB onto the planes defined by A's axis X and and axis Y, and treat them as constant with respect to A's velocity.
            //This hand waves away a bit of complexity related to the fact that A's axes have velocity too, but it works out pretty nicely in the end.
            //hingeAxisBOnPlaneX = hingeAxisB - dot(constraintAxisX, hingeAxisB) * constraintAxisX
            //hingeAxisBOnPlaneY = hingeAxisB - dot(constraintAxisY, hingeAxisB) * constraintAxisY
            //Note that we actually make use of inverse trig here. This is largely for the sake of the formulation, and the derivative will end up collapsing nicely.
            //C = [atan(dot(hingeAxisBOnPlaneX, hingeAxisA), dot(hingeAxisBOnPlaneX, constraintAxisAY))] = [0]
            //    [atan(dot(hingeAxisBOnPlaneY, hingeAxisA), dot(hingeAxisBOnPlaneY, constraintAxisAX))]   [0]
            //Focusing on the hingeAxisOnPlaneX jacobian:
            //C' = (dot(hingeAxisBOnPlaneX, hingeAxisA) * d/dt(dot(hingeAxisBOnPlaneX, constraintAxisAY)) -
            //      d/dt(dot(hingeAxisBOnPlaneX, hingeAxisA)) * dot(hingeAxisBOnPlaneX, constraintAxisAY)) * denom
            //where denom = 1f / (dot(hingeAxisBOnPlaneX, hingeAxisA)^2 + dot(hingeAxisBOnPlaneX, constraintAxisAY)^2)
            //C' = (dot(hingeAxisBOnPlaneX, hingeAxisA) * (dot(d/dt(hingeAxisBOnPlaneX), constraintAxisAY) + dot(hingeAxisBOnPlaneX, d/dt(constraintAxisAY))) -
            //     (dot(d/dt(hingeAxisBOnPlaneX), hingeAxisA) + dot(hingeAxisBOnPlaneX, d/dt(hingeAxisA))) * dot(hingeAxisBOnPlaneX, constraintAxisAY)) * denom
            //C' = (dot(hingeAxisBOnPlaneX, hingeAxisA) * (dot(wB x hingeAxisBOnPlaneX, constraintAxisAY) + dot(hingeAxisBOnPlaneX, wA x constraintAxisAY)) -
            //     (dot(wB x hingeAxisBOnPlaneX, hingeAxisA) + dot(hingeAxisBOnPlaneX, wA x hingeAxisA)) * dot(hingeAxisBOnPlaneX, constraintAxisAY)) * denom
            //C' = (dot(hingeAxisBOnPlaneX, hingeAxisA) * (dot(hingeAxisBOnPlaneX x constraintAxisAY, wB) + dot(wA, constraintAxisAY x hingeAxisBOnPlaneX)) -
            //     (dot(hingeAxisBOnPlaneX x hingeAxisA, wB) + dot(wA, hingeAxisA x hingeAxisBOnPlaneX)) * dot(hingeAxisBOnPlaneX, constraintAxisAY)) * denom
            //C' = ((dot(dot(hingeAxisBOnPlaneX, hingeAxisA) * (hingeAxisBOnPlaneX x constraintAxisAY), wB) + dot(wA, dot(hingeAxisBOnPlaneX, hingeAxisA) * (constraintAxisAY x hingeAxisBOnPlaneX))) -
            //      (dot((hingeAxisBOnPlaneX x hingeAxisA) * dot(hingeAxisBOnPlaneX, constraintAxisAY), wB) + dot(wA, (hingeAxisA x hingeAxisBOnPlaneX) * dot(hingeAxisBOnPlaneX, constraintAxisAY)))) * denom

            //C' = ((dot(dot(hingeAxisBOnPlaneX, hingeAxisA) * (hingeAxisBOnPlaneX x constraintAxisAY) - (hingeAxisBOnPlaneX x hingeAxisA) * dot(hingeAxisBOnPlaneX, constraintAxisAY), wB) +
            //       dot(wA, dot(hingeAxisBOnPlaneX, hingeAxisA) * (constraintAxisAY x hingeAxisBOnPlaneX) - (hingeAxisA x hingeAxisBOnPlaneX) * dot(hingeAxisBOnPlaneX, constraintAxisAY)))) * denom
            //C' = (dot(wB, dot(hingeAxisBOnPlaneX, hingeAxisA) * (hingeAxisBOnPlaneX x constraintAxisAY) -
            //              dot(hingeAxisBOnPlaneX, constraintAxisAY) * (hingeAxisBOnPlaneX x hingeAxisA) +
            //      dot(wA, dot(hingeAxisBOnPlaneX, hingeAxisA) * (constraintAxisAY x hingeAxisBOnPlaneX) -
            //              dot(hingeAxisBOnPlaneX, constraintAxisAY) * (hingeAxisA x hingeAxisBOnPlaneX)) * denom
            //Note that both contributing vectors of jacobian A, constraintAxisAY x hingeAxisBOnPlaneX and hingeAxisA x hingeAxisBOnPlaneX, are aligned with constraintAxisAX.
            //The only remaining question is the scale. Measure it by dotting with the constraintAxisAX.
            //(Switching notation for conciseness here: a = hingeAxisA, b = hingeAxisBOnPlaneX, x = constraintAxisAX, y = constraintAxisAY)
            //(dot(b, a) * cross(y, b) - dot(b, y) * cross(a, b)) / (dot(b, a)^2 + dot(b,y)^2)
            //scale = dot((dot(b, a) * cross(y, b) - dot(b, y) * cross(a, b)) / (dot(b, a)^2 + dot(b,y)^2), x)
            //scale = (dot(b, a) * dot(x, cross(y, b)) - dot(b, y) * dot(x, cross(a, b))) / (dot(b, a)^2 + dot(b,y)^2)
            //scale = (dot(b, a) * dot(b, cross(x, y)) - dot(b, y) * dot(b, cross(x, a))) / (dot(b, a)^2 + dot(b,y)^2)
            //scale = (dot(b, a) * dot(b, a) - dot(b, y) * dot(b, -y)) / (dot(b, a)^2 + dot(b,y)^2)
            //scale = (dot(b, a) * dot(b, a) + dot(b, y) * dot(b, y)) / (dot(b, a)^2 + dot(b,y)^2)
            //scale = 1
            //How convenient!
            //jacobianA = [constraintAxisAX]
            //            [constraintAxisAY]
            //jacobianB = -jacobianA

            //Note that JA = -JB, but for the purposes of calculating the effective mass the sign is irrelevant.
            //This computes the effective mass using the usual (J * M^-1 * JT)^-1 formulation, but we actually make use of the intermediate result J * M^-1 so we compute it directly.
            Symmetric3x3Wide.MultiplyWithoutOverlap(jacobianA, inertiaA.InverseInertiaTensor, out var impulseToVelocityA);
            //Note that we don't use -jacobianA here, so we're actually storing out the negated version of the transform. That's fine; we'll simply subtract in the iteration.
            Symmetric3x3Wide.MultiplyWithoutOverlap(jacobianA, inertiaB.InverseInertiaTensor, out var negatedImpulseToVelocityB);
            Symmetric2x2Wide.CompleteMatrixSandwich(impulseToVelocityA, jacobianA, out var angularA);
            Symmetric2x2Wide.CompleteMatrixSandwich(negatedImpulseToVelocityB, jacobianA, out var angularB);
            Symmetric2x2Wide.Add(angularA, angularB, out var inverseEffectiveMass);
            Symmetric2x2Wide.InvertWithoutOverlap(inverseEffectiveMass, out var effectiveMass);

            SpringSettingsWide.ComputeSpringiness(prestep.SpringSettings, dt, out var positionErrorToVelocity, out var effectiveMassCFMScale, out var softnessImpulseScale);
            //Note the effective mass is not scaled directly. Instead, we scale the csi to save a multiply.
            GetErrorAngles(hingeAxisA, hingeAxisB, jacobianA, out var errorAngle);
            //Note the negation: we want to oppose the separation. TODO: arguably, should bake the negation into positionErrorToVelocity, given its name.
            Vector2Wide.Scale(errorAngle, -positionErrorToVelocity, out var biasVelocity);
            Symmetric2x2Wide.TransformWithoutOverlap(biasVelocity, effectiveMass, out var biasImpulse);

            //JB = -JA. This is (angularVelocityA * JA + angularVelocityB * JB) * effectiveMass
            Vector3Wide.Subtract(wsvA.Angular, wsvB.Angular, out var difference);
            Matrix2x3Wide.TransformByTransposeWithoutOverlap(difference, jacobianA, out var csv);
            Symmetric2x2Wide.TransformWithoutOverlap(csv, effectiveMass, out var csi);
            Vector2Wide.Scale(csi, effectiveMassCFMScale, out csi);
            //csi = projection.BiasImpulse - accumulatedImpulse * projection.SoftnessImpulseScale - (csiaLinear + csiaAngular + csibLinear + csibAngular);
            Vector2Wide.Scale(accumulatedImpulses, softnessImpulseScale, out var softnessContribution);
            Vector2Wide.Add(softnessContribution, csi, out csi);
            Vector2Wide.Subtract(biasImpulse, csi, out csi);

            Vector2Wide.Add(accumulatedImpulses, csi, out accumulatedImpulses);

            ApplyImpulse(impulseToVelocityA, negatedImpulseToVelocityB, csi, ref wsvA.Angular, ref wsvB.Angular);
        }

        public bool RequiresIncrementalSubstepUpdates => false;
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void IncrementallyUpdateForSubstep(in Vector<float> dt, in BodyVelocityWide wsvA, in BodyVelocityWide wsvB, ref AngularHingePrestepData prestepData) { }
    }

    public class AngularHingeTypeProcessor : TwoBodyTypeProcessor<AngularHingePrestepData, Vector2Wide, AngularHingeFunctions, AccessOnlyAngular, AccessOnlyAngularWithoutPose, AccessOnlyAngular, AccessOnlyAngular>
    {
        public const int BatchTypeId = 23;
    }
}


text:
package com.sampythoner.lib.fun;

public class FunConstants {
	public static final String GIF_ENTRY_URL = "http://tu.duowan.com/m/bxgif";

	public static final String TUCAO_ENTRY_URL = "http://tu.duowan.com/m/tucao";

	public static final String COLD_ENTRY_URL = "http://tu.duowan.com/tag/23515.html";

	public static final String BAOZOU_ENTRY_URL = "http://tu.duowan.com/m/bzmh";

	// http://tu.duowan.com/scroll/89631.html
	// http://tu.duowan.com/scroll/89631/2.html
	public static final String PIC_URL = "http://tu.duowan.com/scroll/";
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package realworld;

import Design.Colors;
import GUIs.MainScreen;
import com.pearson.pdn.learningstudio.oauth.OAuth2PasswordService;
import com.pearson.pdn.learningstudio.oauth.OAuthServiceFactory;
import com.pearson.pdn.learningstudio.oauth.config.OAuthConfig;
import com.pearson.pdn.learningstudio.oauth.request.OAuth2Request;
import java.awt.Color;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.SwingXUtilities;
import pearson.AuthenticationData;

/**
 *
 * @author Nathan Smith
 */
public class MainLoginPanel extends JXPanel {

    /**
     * Creates new form LoginPanel
     */
    public MainLoginPanel() {

        initComponents();

        usernameTextField.setPrompt("Username");
        usernameTextField.setPromptForeground(Colors.PromptText.color());
        passwordTextField.setPrompt("Password");
        passwordTextField.setPromptForeground(Colors.PromptText.color());

        mattePainter1.setFillPaint(Color.white);
        this.setBackgroundPainter(mattePainter1);
        this.repaint();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mattePainter1 = new org.jdesktop.swingx.painter.MattePainter();
        usernameTextField = new org.jdesktop.swingx.JXTextField();
        passwordTextField = new org.jdesktop.swingx.JXTextField();
        loginButton = new org.jdesktop.swingx.JXButton();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jXLabel2 = new org.jdesktop.swingx.JXLabel();

        mattePainter1.setFillHorizontal(true);
        mattePainter1.setFillPaint(Color.white);
        mattePainter1.setFillVertical(true);

        usernameTextField.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N

        passwordTextField.setFont(new java.awt.Font("Gill Sans MT", 0, 18)); // NOI18N

        loginButton.setBackground(Colors.ButtonColorOrange.color());
        loginButton.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        loginButton.setText("Login");
        loginButton.setFont(new java.awt.Font("Gill Sans MT", 0, 24)); // NOI18N
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        jXLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/mainLogo.png"))); // NOI18N
        jXLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jXLabel1.setTextAlignment(org.jdesktop.swingx.JXLabel.TextAlignment.CENTER);

        jXLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/border.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jXLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(629, 629, 629)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jXLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(171, 171, 171)
                .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(52, 52, 52)
                .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(316, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed

        String applicationId = "15e4295d-3df5-4ae8-9727-b6a821003dd9";   // Identifies your Application
        String applicationName = "RealWorld";   // No spaces for best results (e.g., MyAppName)
        String tokenKeyMoniker = "04b11650-b3bb-41d6-91a6-c19936aaf4e5";
        String sharedSecret = "8a72063be6d0409da86a5c239e39fd10";
        String clientString = "gbtestc";
        String userName = usernameTextField.getText();
        String password = passwordTextField.getText();

        OAuthConfig config = new OAuthConfig();
        config.setApplicationId(applicationId);
        config.setApplicationName(applicationName);  	// Needed only for OAuth 2 Assertion
        config.setConsumerKey(tokenKeyMoniker);
        config.setConsumerSecret(sharedSecret);        	// Needed only for OAuth 1 & OAuth 2 Assertion
        config.setClientString(clientString);	      	// Needed only for OAuth 2

        OAuthServiceFactory oauthFactory = new OAuthServiceFactory(config);
        OAuth2PasswordService oauthService = oauthFactory.build(OAuth2PasswordService.class);

        try {
            URL apiUrl = new URL("https://api.learningstudio.com/me");
            OAuth2Request oauthRequest = oauthService.generateOAuth2PasswordRequest(userName, password);
            Map httpHeaders = oauthRequest.getHeaders();
            HttpsURLConnection httpConn = (HttpsURLConnection) apiUrl.openConnection();
            httpConn.setRequestMethod("GET");

            for (Object headerName : httpHeaders.keySet()) {
                httpConn.addRequestProperty((String) headerName, (String) httpHeaders.get(headerName));
            }

            int responseCode = httpConn.getResponseCode();
            if (responseCode == 200) {
                AuthenticationData data = new AuthenticationData(config, oauthFactory, httpHeaders, userName, password);
                MainScreen main = new MainScreen(data);
                JXFrame frame = (JXFrame) SwingXUtilities.getAncestor(JXFrame.class, getParent());
                frame.remove(MainLoginPanel.this);
                frame.revalidate();
                frame.add(main);
                frame.revalidate();
                frame.repaint();
            }
        } catch (RuntimeException rex) {
            throw rex;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Incorrect Username and/or Password");
        }

    }//GEN-LAST:event_loginButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private org.jdesktop.swingx.JXLabel jXLabel2;
    private org.jdesktop.swingx.JXButton loginButton;
    private org.jdesktop.swingx.painter.MattePainter mattePainter1;
    private org.jdesktop.swingx.JXTextField passwordTextField;
    private org.jdesktop.swingx.JXTextField usernameTextField;
    // End of variables declaration//GEN-END:variables
}


text:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //first initialize the regex object with the portion we want, and to split up what gets saved for later
    duration.setPattern("Duration: (\\d\\d):(\\d\\d):(\\d\\d).\\d\\d,");
    time.setPattern("time=(\\d\\d):(\\d\\d):(\\d\\d).\\d\\d");

    //Initialize QProcess with relevant signals and slots that respond to it
    myprocess = new QProcess();
    myprocess->setReadChannel(QProcess::ProcessChannel::StandardError);
    connect(myprocess,SIGNAL(readyRead()),this,SLOT(progress()));
    connect(myprocess,SIGNAL(finished(int)),this,SLOT(complete()));
    ffmpegPath = QDir(QCoreApplication::applicationDirPath()).filePath("ffmpeg");

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_VideoSourceButton_clicked()
{
    QStringList supportedMimeTypes;
    //Add more Mime types so you're not limited
    supportedMimeTypes << "video/mp4";

    QFileDialog fileDialog(this);
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    fileDialog.setWindowTitle(tr("Open Movie"));
    fileDialog.setMimeTypeFilters(supportedMimeTypes);

    //Sets directory in a way thats cross platform
    fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).value(0, QDir::homePath()));

    if (fileDialog.exec() == QDialog::Accepted) {

        SourceFileName = fileDialog.selectedFiles();
        //Submitted URL's are actually a list, meaning its possible to receive multiple at once. For now, you're only allowed one to convert
        ui->VideoSourceEdit->setText(SourceFileName[0]);

        QFileInfo fi(SourceFileName[0]);
        //Used later to rebuild the output name
        fullFilePath = fi.fileName();
        baseFileName = fi.baseName();
        fileExtension = fi.suffix();

        ui->VideoDestination->setEnabled(true);
    }
}

void MainWindow::on_VideoDestination_clicked()
{

    QFileDialog fileDialog(this);
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    fileDialog.setFileMode(QFileDialog::Directory);
    fileDialog.setWindowTitle(tr("Open Movie"));
    //Sets directory in a way thats cross platform
    fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).value(0, QDir::homePath()));
    if (fileDialog.exec() == QDialog::Accepted) {

        DestinationPath = fileDialog.selectedFiles();
        destDirectory = DestinationPath[0];
        ui->VideoDestinationEdit->setText(destDirectory);
        ui->ConvertButton->setEnabled(true);
    }
}

void MainWindow::on_ConvertButton_clicked()
{
    QString finalOutputPath;
    QString format;
    QStringList arguments;

    //temporarily turn off convert button until QProcess signals its completed
    ui->ConvertButton->setEnabled(false);

    //Constructs ffmpeg command line parameters based on option
    if (ui->filterOptions->currentText() == "Sepia") {
        format = "colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131"; //colormatrix way to make sepia
        finalName = baseFileName + "_sepia." + fileExtension;
        finalOutputPath = QDir(destDirectory).filePath(finalName);
        arguments<<"-i" << SourceFileName[0] << "-y" << "-vf" << format << finalOutputPath;

    } else if (ui->filterOptions->currentText() == "Black and White"){
        format = "colorchannelmixer=.3:.4:.3:0:.3:.4:.3:0:.3:.4:.3"; //colormatrix way to make gray
        finalName = baseFileName + "_BW." + fileExtension;
        finalOutputPath = QDir(destDirectory).filePath(finalName);
        arguments<<"-i" << SourceFileName[0] << "-y" << "-vf" << format << finalOutputPath;

    } else if (ui->filterOptions->currentText()=="Audio") {
        finalName = baseFileName + "_Audio." + fileExtension;
        finalOutputPath = QDir(destDirectory).filePath(finalName);
        arguments<<"-i" << SourceFileName[0] << "-y" <<"-vn" << "-acodec" << "copy"  << finalOutputPath;

    }  else if (ui->filterOptions->currentText()=="Video") {
        finalName = baseFileName + "_Video." + fileExtension;
        finalOutputPath = QDir(destDirectory).filePath(finalName);
        arguments<<"-i" << SourceFileName[0] << "-y" <<"-an" << "-acodec" << "copy" << finalOutputPath;

    } else {
        ui->ConvertResultEdit->setText("Huh, something went wrong!");
    }

    //Begin conversion process and end function. Runs in the "background." Uses Slots/Signals to notify GUI when done
    myprocess->start(ffmpegPath,arguments);
    ui->ConvertResultEdit->setText("Conversion has begun for: " + finalName);
}

void MainWindow::progress() {
    QProcessOutput = QString(myprocess->readAllStandardError());
    durResult = duration.indexIn(QProcessOutput);
    timeResult = time.indexIn(QProcessOutput);

    if (durResult > -1) {
        //enters if able to find Duration time of video. Will then convert to total seconds and adjusts progress bar
        bool ok;
        int durationHours = duration.cap(1).toInt(&ok,10);
        int durationMinutes = duration.cap(2).toInt(&ok,10);
        int durationSeconds = duration.cap(3).toInt(&ok,10);
        int totalDurationSeconds = durationHours*3600 + durationMinutes*60 + durationSeconds*1;
        ui->progressBar->setMaximum(totalDurationSeconds);

    }

    if (timeResult > -1) {
        //Entered if current time of conversion occurs. Converts to total seconds and adjusts progress bar
        bool ok;
        int timeHours = time.cap(1).toInt(&ok,10);
        int timeMinutes = time.cap(2).toInt(&ok,10);
        int timeSeconds = time.cap(3).toInt(&ok,10);
        int totalTimeSeconds = timeHours*3600 + timeMinutes*60 + timeSeconds*1;
        ui->progressBar->setValue(totalTimeSeconds);
    }
    ui->textBrowser->append(QProcessOutput);
}
void MainWindow::complete() {
    ui->ConvertButton->setEnabled(true);
    ui->progressBar->setValue(0);
    ui->ConvertResultEdit->setText("You've finished converting:  " + finalName);
}


text:
using System;
using System.Threading.Tasks;
using Remotus.Base;
using RestSharp;

namespace Remotus.API
{
    public class DeviceControllerAPI : IDeviceControllerAPI
    {
        public DeviceControllerAPI()
        {
            BaseUri = new Uri("http://localhost:9000/api/v1/");
        }

        public Uri BaseUri { get; set; }

        protected virtual IRestClient GetClient()
        {
            var jsonSerializer = new CustomJsonSerializer();
            jsonSerializer.Container.Bind(typeof(IResponseBase), typeof(DefaultResponseBase<>));
            jsonSerializer.Container.Bind(typeof(IResponseBase<>), typeof(DefaultResponseBase<>));
            jsonSerializer.Container.Bind(typeof(IError), typeof(DefaultError));
            jsonSerializer.Container.Bind(typeof(ILink), typeof(DefaultLink));
            jsonSerializer.Container.Bind(typeof(IProcessDto), typeof(ProcessDto));

            var client = new RestClient(BaseUri);
            client.AddHandler("application/json", jsonSerializer);
            client.AddHandler("text/json", jsonSerializer);
            client.AddHandler("text/x-json", jsonSerializer);
            client.AddHandler("*+json", jsonSerializer);
            client.AddHandler("*", jsonSerializer);

            //client.AddDefaultHeader("Accept", "application/json");
            return client;
        }

        protected virtual IRestRequest BuildRequest(Uri resource, Method method)
        {
            var request = new RestRequest(resource, method);
            request.AddHeader("accept", "application/json");
            return request;
        }

        protected async Task<IResponseBase<TResult>> GetResponse<TResult>(IRestRequest request)
        {
            IResponseBase<TResult> response;
            try
            {
                var client = GetClient();
                var httpResponse = await client.ExecuteTaskAsync<IResponseBase<TResult>>(request);
                response = httpResponse.Data;
            }
            catch (Exception ex)
            {
                response = new DefaultResponseBase<TResult>
                {
                    Error = DefaultError.FromException(ex),
                };
            }
            return response;
        }

        public async Task<IResponseBase<object>> TakeScreenshot()
        {
            var uri = new Uri("device/take/screenshot", UriKind.Relative);
            var request = BuildRequest(uri, Method.POST);

            var response = await GetResponse<object>(request);
            return response;
        }
    }
}


text:
package com.nanosai.gridops.codegen;

import com.nanosai.gridops.codegen.MessageDescriptor;

import java.util.ArrayList;
import java.util.List;

/**
 * A description of an IAP semantic protocol which can be used to generate Java classes for reading and writing
 * messages of that protocol.
 */
public class SemanticProtocolDescriptor {
    public String semanticProtocolName    = null;
    public byte[] semanticProtocolId      = null;
    public byte[] semanticProtocolVersion = null;

    public List<MessageDescriptor> messageDescriptors = new ArrayList<>();

    public SemanticProtocolDescriptor() {
    }

    public SemanticProtocolDescriptor(String semanticProtocolName, byte[] semanticProtocolId, byte[] semanticProtocolVersion) {
        this.semanticProtocolName = semanticProtocolName;
        this.semanticProtocolId = semanticProtocolId;
        this.semanticProtocolVersion = semanticProtocolVersion;
    }

    public void addMessageDescriptor(MessageDescriptor messageDescriptor){
        this.messageDescriptors.add(messageDescriptor);
    }

    public MessageDescriptor addMessageDescriptor(String messageName, byte[] messageType, int mepType){
        MessageDescriptor messageDescriptor = new MessageDescriptor(messageName, messageType, mepType);
        this.messageDescriptors.add(messageDescriptor);
        return messageDescriptor;
    }
}


text:
import sys

try:
    import unittest2 as unittest
except ImportError:
    import unittest
try:
    import yaml
except ImportError:
    if sys.version_info < (3, 0, 0):
        print ("[-] The yaml module is needed to read the logging configurations,"
               "\ninstall it from https://pypi.org/project/PyYAML/"
               "\n or run `pip install pyyaml.")
        raise
    else:
        sys.exit("""
                    The yaml module is needed to read the logging configurations,
                    install it from https://pypi.org/project/PyYAML/
                    or run `pip install pyyaml`.
                """)
try:
    from mock import patch, mock_open
except ImportError:
    if sys.version_info < (3, 0, 0):
        print ("[-] The mock module is needed to create mock objects,"
               "\ninstall it from https://pypi.org/project/mock/"
               "\nor run `pip install mock`.")
        raise
    else:
        sys.exit("""
                    The mock module is needed to create mock objects,
                    install it from https://pypi.org/project/mock/
                    or run `pip install mock`.
                """)

from config_manager.config_manager import ConfigManager, FileFormatError

patch.object = patch.object

class ConfigurationManagerTest(unittest.TestCase):
    @patch.object(ConfigManager, 'load_config')
    def test_str_empty_default_empty_required(self, mocked_load_config):
        # Given
        mocked_load_config.return_value = None
        config_man = ConfigManager()
        expected = "Default Configuration: Empty \n Required Configurations: Empty \n " \
                   "Configuration File Path: configs.yaml"
        # When
        actual = config_man.__str__()
        # Then
        self.assertEqual(actual, expected)

    @patch.object(ConfigManager, 'load_config')
    def test_str_non_empty_default_non_empty_required(self, mocked_load_config):
        # Given
        mocked_load_config.return_value = None
        config_man = ConfigManager(config_file_path="/path/to/config.yaml",
                                   defaults={'config_key': 'config_value'},
                                   required=['config_key'])
        expected = "Default Configuration: {'config_key': 'config_value'} \n Required Configurations: ['config_key'] " \
                   "\n Configuration File Path: /path/to/config.yaml"
        # When
        actual = config_man.__str__()
        # Then
        self.assertEqual(actual, expected)

    @staticmethod
    @patch.object(ConfigManager, 'load_yaml_file')
    def test_load_yaml_file_called_when_yaml_file_loaded(mocked_load_yaml_file):
        # Given
        config_file_path = "/path/to/config.yaml"
        # When
        ConfigManager(config_file_path=config_file_path)
        # Then
        mocked_load_yaml_file.assert_called_once_with()

    @patch.object(ConfigManager, 'load_file_data')
    def test_load_yaml_file_when_yaml_file_loaded_is_correct(self, mocked_load_file_data):
        # Given
        config_file_path = "/path/to/config.yaml"
        mocked_load_file_data.return_value = '{"config_key":"config_value", ' \
                                             ' "another_config_key":"another_config_value"}'
        # When
        config_man = ConfigManager(config_file_path=config_file_path)
        # Then
        self.assertDictEqual(config_man, {"config_key": "config_value", "another_config_key": "another_config_value"})

    @patch.object(ConfigManager, 'load_file_data')
    def test_load_yaml_file_when_yaml_file_loaded_is_faulty(self, mocked_load_file_data):
        # Given
        config_file_path = "/path/to/config.yaml"
        mocked_load_file_data.return_value = '{"incorrect_config_key""incorrect_config_value"}'
        # When - Then
        with self.assertRaises(yaml.YAMLError):
            ConfigManager(config_file_path=config_file_path)

    @staticmethod
    @patch.object(ConfigManager, 'load_json_file')
    def test_load_json_file_called_when_json_file_loaded(mocked_load_json_file):
        # Given
        config_file_path = "/path/to/config.json"
        # When
        ConfigManager(config_file_path=config_file_path)
        # Then
        mocked_load_json_file.assert_called_once_with()

    @patch.object(ConfigManager, 'load_file_data')
    def test_load_json_file_when_json_file_loaded_is_correct(self, mocked_load_file_data):
        # Given
        config_file_path = "/path/to/config.json"
        mocked_load_file_data.return_value = '{"config_key":"config_value", ' \
                                             ' "another_config_key":"another_config_value"}'
        # When
        config_man = ConfigManager(config_file_path=config_file_path)
        # Then
        self.assertDictEqual(config_man, {"config_key": "config_value", "another_config_key": "another_config_value"})

    @patch.object(ConfigManager, 'load_file_data')
    def test_load_json_file_when_json_file_loaded_is_faulty(self, mocked_load_file_data):
        # Given
        config_file_path = "/path/to/config.json"
        mocked_load_file_data.return_value = '{"config_key":}'
        # When - Then
        with self.assertRaises(ValueError):
            ConfigManager(config_file_path=config_file_path)

    @patch.object(ConfigManager, 'load_file_data')
    def test_load_json_file_when_json_file_loaded_is_faulty_2(self, mocked_load_file_data):
        # Given
        config_file_path = "/path/to/config.json"
        mocked_load_file_data.return_value = '{"config_key"}'
        # When - Then
        with self.assertRaises(ValueError):
            ConfigManager(config_file_path=config_file_path)

    def test_output_when_not_supported_format_file_loaded(self):
        # Given
        config_file_path = "/path/to/config.smth"
        # When - Then
        with self.assertRaises(FileFormatError):
            ConfigManager(config_file_path=config_file_path)

    def test_load_file_data_raise_error_when_incorrect_path(self):
        # Given
        config_file_path = "/incorrectPath/incorrectFile.json"
        # When - Then
        with self.assertRaises(IOError):
            ConfigManager(config_file_path=config_file_path)

    if sys.version_info < (3, 0, 0):
        @patch('__builtin__.open',
               mock_open(read_data="config_key: 'config_value'\nanother_config_key: 'another_config_value'"))
        def test_load_file_data_return_data(self):
            # Given
            config_man = ConfigManager()
            expected = "config_key: 'config_value'\nanother_config_key: 'another_config_value'"
            # When
            actual = config_man.load_file_data()
            # Then
            self.assertEqual(actual, expected)
    else:
        @patch('builtins.open',
               mock_open(read_data="config_key: 'config_value'\nanother_config_key: 'another_config_value'"))
        def test_load_file_data_return_data(self):
            # Given
            config_man = ConfigManager()
            expected = "config_key: 'config_value'\nanother_config_key: 'another_config_value'"
            # When
            actual = config_man.load_file_data()
            # Then
            self.assertEqual(actual, expected)

class FileFormatErrorTest(unittest.TestCase):
    def test_str(self):
        # Given
        path = "/path/to/config"
        message = "This is a test message"
        expected = repr(message)
        # When
        file_format_error = FileFormatError(path, message)
        actual = file_format_error.__str__()
        # Then
        self.assertEqual(actual, expected)


text:
package org.springframework.cloud.service.document;

import org.springframework.cloud.service.ServiceConnectorConfig;

/**
 * Class to hold configuration values for Mongo
 *
 * @author Thomas Risberg
 * @author Ramnivas Laddad
 */
public class MongoDbFactoryConfig implements ServiceConnectorConfig {
	private String writeConcern;
	private Integer connectionsPerHost;
	private Integer maxWaitTime;

	public MongoDbFactoryConfig(String writeConcern, Integer connectionsPerHost, Integer maxWaitTime) {
		this.writeConcern = writeConcern;
		this.connectionsPerHost = connectionsPerHost;
		this.maxWaitTime = maxWaitTime;
	}

	public String getWriteConcern() {
		return writeConcern;
	}

	/**
	 * Getter corresponding to the MongoOptions connectionsPerHost field
	 */
	public Integer getConnectionsPerHost() {
		return connectionsPerHost;
	}

	/**
	 * Getter corresponding to the MongoOptions maxWaitTime field
	 */
	public Integer getMaxWaitTime () {
		return maxWaitTime ;
	}
}


text:
<structures>
  <structure name="Stock">
    <field type="SizedRegexString" maxlen="8" pat="'[A-Z]+$'">name</field>
    <field type="PosInteger">shares</field>
    <field type="PosFloat">price</field>
  </structure>

  <structure name="Point">
    <field type="Integer">x</field>
    <field type="Integer">y</field>
  </structure>

 <structure name="Address">
   <field type="String">hostname</field>
   <field type="Integer">port</field>
 </structure>
</structures>