text:
<!doctype html>

	<title>Remove Dups Properties</title>
	<link rel="stylesheet" type="text/css" href="../../css/style.css">

Remove Dups Properties

Properties for the Remove Dups component can be viewed by Double click->component on canvas. The properties contain only the 'General' tab since Remove Dups falls under the Straight Pull category in the component palette.

General Properties

Display

Name - The identifier for the component. This is a mandatory property. This property is pre-populated with the component name, i.e. 'Removedups' followed by an incremental number. It can be changed to any custom name. The name property has following restrictions:

Must be specified and should not be blank.

Must be unique across the job.

Accepts only alphabets (a-z), numerals (0-9) and 4 special characters: "_", "-", ",", " " (space)<./span>

ID - ID field will specify unique id for every component.

Type - Type defines the type of component within the category. This typically is the name of the component. This is a non editable field.

Configuration

Key Fields - The key field grid accepts the key fields that will be used to determine the duplicate records in the input data. The component uses the key fields to group the data fields before performing the operation.

Secondary Keys - Secondary keys accepts the columns which will further groups the data fields. Here, user can specify the sort order which can be either Ascending or Descending. By default the sort order is Ascending(Asc).

Runtime Properties - Runtime properties are used to override the Hadoop configurations specific to Remove Dups component at run time. User is required to enter the property name and value in the runtime properties grid.

Check  How to pass Hadoop properties to component

Retain - Retain has three options -

First  - Retains first occurrence of specified duplicate field and removes other duplicate records.

Last   - Retains last occurrence of specified duplicate field and removes other duplicate records.

Unique - Retains any unique record from duplicate records.

Batch - Batch simply accepts a numeric number starting from 0 to 99 and signifies the batch this component will execute in. By default this is 0.

Validations

The Remove_Dups components applies validations to the mandatory fields as described above. Upon placing the Remove_Dups component on job canvas for the first time (from component palette), the component shows up a warning icon as mandatory properties are not provided.

The properties window displays error icon on mandatory fields if it has an incorrect value. The error icon is displayed on the tab as well, if any of the field within the tab has some error.

If the properties window has some error even after user visit's it once, then the error icon appears on RemoveDups component. This error icon is removed only when all the mandatory fields are supplied with correct values.


text:
import eventlet
import mock
import os

from networking_vsphere.drivers import dvs_driver
from networking_vsphere.drivers import manager
from networking_vsphere.drivers import vc_driver
from networking_vsphere.tests import base
from networking_vsphere.tests.unit.drivers import fake_driver
from networking_vsphere.tests.unit.utils import stubs
from networking_vsphere.utils import vim_session

class TestVcenterManager(base.TestCase):

    def setUp(self):
        super(TestVcenterManager, self).setUp()
        self.callback = fake_driver.MockCallback()
        self.manager = manager.VcenterManager(self.callback)
        self.useFixture(stubs.FakeVmware())
        self.LOG = manager.LOG

    def test_parse_mapping(self):
        cluster_dvs_list = self.manager._parse_mapping("abc:123")
        self.assertEqual(len(cluster_dvs_list), 1)

    def test_parse_mapping_multiple(self):
        cluster_dvs_list = self.manager._parse_mapping("abc:123,def:456")
        self.assertEqual(len(cluster_dvs_list), 2)

    def test_initialize_driver_noconf(self):
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(self.LOG, "error") as mock_log_error:
            self.manager.initialize_driver()
            self.assertIsNone(self.manager.driver)
            self.assertTrue(mock_log_error.called)

    def test_initialize_driver(self):
        fake_tuple = ["dc/host/cluster1:dvs1"]
        self.flags(vcenter_ip="vcenter.test.com", group='VMWARE')
        self.flags(vcenter_username="fake_user", group='VMWARE')
        self.flags(vcenter_password="fake_pass", group='VMWARE')
        self.flags(vcenter_api_retry_count="1", group='VMWARE')
        self.flags(wsdl_location="http://fake.test.com", group='VMWARE')
        self.flags(cluster_dvs_mapping=fake_tuple, group='VMWARE')
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(eventlet, "spawn"), \
                mock.patch.object(vc_driver.VCNetworkDriver, "add_cluster",
                                  return_value=True):
            self.assertEqual(len(self.manager.cluster_switch_mapping), 0)
            self.manager.initialize_driver()
            self.assertIsNotNone(self.manager.driver)
            self.assertEqual(len(self.manager.cluster_switch_mapping), 1)

    def test_initialize_driver_with_cert_check_and_cert_path(self):
        fake_tuple = ["dc/host/cluster1:dvs1"]
        ca_path = "/etc/ssl/certs/certs.pem"
        self.flags(vcenter_ip="vcenter.test.com", group='VMWARE')
        self.flags(vcenter_username="fake_user", group='VMWARE')
        self.flags(vcenter_password="fake_pass", group='VMWARE')
        self.flags(vcenter_api_retry_count="1", group='VMWARE')
        self.flags(wsdl_location="http://fake.test.com", group='VMWARE')
        self.flags(cert_check=True, group='VMWARE')
        self.flags(cert_path=ca_path, group='VMWARE')
        self.flags(cluster_dvs_mapping=fake_tuple, group='VMWARE')
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(eventlet, "spawn"), \
                mock.patch.object(vc_driver.VCNetworkDriver, "add_cluster",
                                  return_value=True), \
                mock.patch.object(os.path, "isfile", return_value=True):
            self.assertEqual(len(self.manager.cluster_switch_mapping), 0)
            self.manager.initialize_driver()
            self.assertIsNotNone(self.manager.driver)
            self.assertEqual(len(self.manager.cluster_switch_mapping), 1)
            self.assertEqual(self.manager.ca_path, ca_path)

    def test_initialize_driver_with_cert_check_false_and_cert_path(self):
        fake_tuple = ["dc/host/cluster1:dvs1"]
        self.flags(vcenter_ip="vcenter.test.com", group='VMWARE')
        self.flags(vcenter_username="fake_user", group='VMWARE')
        self.flags(vcenter_password="fake_pass", group='VMWARE')
        self.flags(vcenter_api_retry_count="1", group='VMWARE')
        self.flags(wsdl_location="http://fake.test.com", group='VMWARE')
        self.flags(cert_check=False, group='VMWARE')
        self.flags(cert_path="/etc/ssl/certs/certs.pem", group='VMWARE')
        self.flags(cluster_dvs_mapping=fake_tuple, group='VMWARE')
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(eventlet, "spawn"), \
                mock.patch.object(vc_driver.VCNetworkDriver, "add_cluster",
                                  return_value=True), \
                mock.patch.object(os.path, "isfile", return_value=True):
            self.assertEqual(len(self.manager.cluster_switch_mapping), 0)
            self.manager.initialize_driver()
            self.assertIsNotNone(self.manager.driver)
            self.assertEqual(len(self.manager.cluster_switch_mapping), 1)
            self.assertIsNone(self.manager.ca_path)

    def test_initialize_driver_without_cert_path_exception(self):
        fake_tuple = ["dc/host/cluster1:dvs1"]
        self.flags(vcenter_ip="vcenter.test.com", group='VMWARE')
        self.flags(vcenter_username="fake_user", group='VMWARE')
        self.flags(vcenter_password="fake_pass", group='VMWARE')
        self.flags(vcenter_api_retry_count="1", group='VMWARE')
        self.flags(wsdl_location="http://fake.test.com", group='VMWARE')
        self.flags(cert_check=True, group='VMWARE')
        self.flags(cert_path=None, group='VMWARE')
        self.flags(cluster_dvs_mapping=fake_tuple, group='VMWARE')
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(self.LOG, "error") as mock_log_error:
            self.assertEqual(len(self.manager.cluster_switch_mapping), 0)
            self.assertRaises(SystemExit, self.manager.initialize_driver)
            self.assertTrue(mock_log_error.called)

    def test_initialize_driver_invalid_cert_path_exception(self):
        fake_tuple = ["dc/host/cluster1:dvs1"]
        self.flags(vcenter_ip="vcenter.test.com", group='VMWARE')
        self.flags(vcenter_username="fake_user", group='VMWARE')
        self.flags(vcenter_password="fake_pass", group='VMWARE')
        self.flags(vcenter_api_retry_count="1", group='VMWARE')
        self.flags(wsdl_location="http://fake.test.com", group='VMWARE')
        self.flags(cert_check=True, group='VMWARE')
        self.flags(cert_path="/etc/ssl/certs/certs.pem", group='VMWARE')
        self.flags(cluster_dvs_mapping=fake_tuple, group='VMWARE')
        with mock.patch.object(vim_session.ConnectionHandler, "stop",
                               return_value=None), \
                mock.patch.object(self.LOG, "error") as mock_log_error, \
                mock.patch.object(os.path, "isfile", return_value=False):
            self.assertEqual(len(self.manager.cluster_switch_mapping), 0)
            self.assertRaises(SystemExit, self.manager.initialize_driver)
            self.assertTrue(mock_log_error.called)

    def test_start(self):
        self.manager.driver = None
        self.assertIsNone(self.manager.start())

    def test_pause(self):
        with mock.patch.object(dvs_driver.DvsNetworkDriver, "pause") as pause:
            self.manager.driver = dvs_driver.DvsNetworkDriver()
            self.manager.pause()
            self.assertTrue(pause.called)

    def test_pause_none_driver(self):
        self.manager.driver = None
        self.assertIsNone(self.manager.pause())

    @mock.patch.object(vim_session.ConnectionHandler, "stop")
    def test_stop(self, mock_conn_stop):
        mock_conn_stop.return_value = None
        with mock.patch.object(dvs_driver.DvsNetworkDriver, "stop"
                               ) as mock_dvs_stop:
            self.manager.driver = dvs_driver.DvsNetworkDriver()
            self.manager.stop()
            self.assertTrue(mock_dvs_stop.called)

redpajama_set_name: RedPajamaGithub


text:
ReportGenerator converts XML reports generated by OpenCover, PartCover, Visual Studio  or NCover into human readable reports in various formats.

The reports do not only show the coverage quota, but also include the source code and visualize which lines have been covered.

ReportGenerator supports merging several reports into one.
It is also possible to pass one XML file containing several reports to ReportGenerator (e.g. a build log file).

The following output formats are supported by ReportGenerator:
* HTML, HTMLSummary
* XML, XMLSummary
* Latex, LatexSummary
* TextSummary
* [Custom reports](https://github.com/danielpalme/ReportGenerator/wiki/Custom-reports)

**Compatibility:**
* [OpenCover](https://github.com/OpenCover/opencover)
* [PartCover](https://github.com/sawilde/partcover.net4) (4.0)
* [PartCover](http://sourceforge.net/projects/partcover/) (2.2, 2.3)
* Visual Studio ([vstest.console.exe](https://github.com/danielpalme/ReportGenerator/wiki/Visual-Studio-Coverage-Tools#vstestconsoleexe), [CodeCoverage.exe](https://github.com/danielpalme/ReportGenerator/wiki/Visual-Studio-Coverage-Tools#codecoverageexe))
* [NCover](http://www.ncover.com/download/current) (tested version 1.5.8, other versions may not work)

Also available as **NuGet** package: http://www.nuget.org/packages/ReportGenerator

Additional information about ReportGenerator can be found under [Resources](#resources).

Author: Daniel Palme
Blog: [www.palmmedia.de](http://www.palmmedia.de)
Twitter: [@danielpalme](http://twitter.com/danielpalme)

## Screenshots
The screenshots show two snippets of the generated reports:
![Screenshot 1](http://danielpalme.github.io/ReportGenerator/resources/screenshot1.png)
![Screenshot 2](http://danielpalme.github.io/ReportGenerator/resources/screenshot2.png)

## Usage
ReportGenerator is a commandline tool which requires the following parameters:

```
Parameters:
    ["]-reports:<report>[;<report>][;<report>]["]
    ["]-targetdir:<target directory>["]
    [["]-reporttypes:<None|Html|HtmlSummary|...>[;<None|Html|HtmlSummary|...>]["]]
    [["]-sourcedirs:<directory>[;<directory>][;<directory>]["]]
    [["]-historydir:<history directory>["]]
    [["]-filters:<(+|-)filter>[;<(+|-)filter>][;<(+|-)filter>]["]]
    [["]-verbosity:<Verbose|Info|Error>["]]

Explanations:
   Reports:           The coverage reports that should be parsed (separated by
                      semicolon). Wildcards are allowed.
   Targetdirectory:   The directory where the generated report should be saved.
   Reporttypes:       The output formats and scope (separated by semicolon).
                      Values: None, Html, HtmlSummary, Xml, XmlSummary, Latex,
                              LatexSummary
   SourceDirectories: Optional directories which contain the corresponding source code
                      (separated by semicolon).
                      The source files are used if coverage report contains classes
                      without path information.
   History directory: Optional directory for storing persistent coverage information.
                      Can be used in future reports to show coverage evolution.
   Filters:           Optional list of assemblies that should be included or excluded
                      in the report. Exclusion filters take precedence over inclusion
                      filters. Wildcards are allowed.
   Verbosity:         The verbosity level of the log messages.
                      Values: Verbose, Info, Error

Default values:
   -reporttypes:Html
   -filters:+*
   -verbosity:Verbose

Examples:
   "-reports:coverage.xml" "-targetdir:C:\report"
   "-reports:target\*\*.xml" "-targetdir:C:\report" -reporttypes:Latex;HtmlSummary
   "-reports:coverage1.xml;coverage2.xml" "-targetdir:report"
   "-reports:coverage.xml" "-targetdir:C:\report" -reporttypes:Latex "-sourcedirs:C:\MyProject"
   "-reports:coverage.xml" "-targetdir:C:\report" "-sourcedirs:C:\MyProject1;C:\MyProject2" "-filters:+Included;-Exclude
d.*"
```

A MSBuild task also exists:

```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Coverage" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <UsingTask TaskName="ReportGenerator" AssemblyFile="ReportGenerator.exe" />
  <ItemGroup>
    <CoverageFiles Include="partcover.xml" />
    <SourceDirectories Include="C:\MyProject1" />
    <SourceDirectories Include="C:\MyProject2" />
  </ItemGroup>
  <Target Name="Coverage">
    <ReportGenerator ReportFiles="@(CoverageFiles)" TargetDirectory="report" ReportTypes="Html;Latex" SourceDirectories="@(SourceDirectories)" HistoryDirectory="history" Filters="+Include;-Excluded" VerbosityLevel="Verbose" />
  </Target>
</Project>
```

## Resources

* http://www.palmmedia.de/Blog/2015/1/27/reportgenerator-new-beta-with-historytrend-charts
* http://www.palmmedia.de/Blog/2012/4/29/reportgenerator-new-release-with-more-advanced-report-preprocessing
* http://www.palmmedia.de/Blog/2009/10/30/msbuild-code-coverage-analysis-with-partcover-and-reportgenerator
* http://www.palmmedia.de/Blog/2010/2/15/partcover-coverage-of-unexecuted-methods
* http://www.palmmedia.de/Blog/2010/5/2/partcover-coverage-of-unexecuted-methods-part-2
* http://www.mellekoning.nl/index.php/2010/02/13/unit-testing-coverage-with-partcover-and-reportgenerator


text:
package ru.job4j.io.filemanager;

public interface Message {
    Type type();

    enum Type {
        LS,
        UP,
        CD,
        DOWNLOAD,
        UPLOAD;

        public static boolean contains(String type) {
            boolean result = false;
            for (Type t : Message.Type.values()) {
                if (t.name().equalsIgnoreCase(type)) {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
}


text:
package com.matthewtamlin.mixtape.example.data;

import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Environment;

import com.matthewtamlin.java_utilities.file.FileFinder;
import com.matthewtamlin.mixtape.example.util.Id3Util;
import com.matthewtamlin.mixtape.library.data.ListDataSourceHelper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.os.Environment.getExternalStoragePublicDirectory;
import static com.matthewtamlin.mixtape.example.util.Id3Util.MetadataField.ALBUM;

public class Mp3AlbumDataSource extends ListDataSourceHelper<Mp3Album> {
	private final Resources resources;

	private List<Mp3Album> albums = null;

	public Mp3AlbumDataSource(final Resources resources) {
		this.resources = resources;
	}

	@Override
	public void loadData(final boolean forceRefresh,
			final DataLoadedListener<List<Mp3Album>> callback) {
		final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(final Void... params) {
				if (albums == null || forceRefresh) {
					final List<Mp3Song> songs = loadMp3SongsFromMusicDirectory();
					albums = sortSongsByAlbum(songs);
				}

				return null;
			}

			@Override
			protected void onPostExecute(final Void aVoid) {
				if (callback != null) {
					callback.onDataLoaded(Mp3AlbumDataSource.this, albums);
				}
			}
		};

		task.execute();
	}

	public void deleteItem(final Mp3Album item) {
		if (albums.contains(item)) {
			final int index = albums.indexOf(item);

			albums.remove(item);

			for (final ItemRemovedListener<Mp3Album> listener : getItemRemovedListeners()) {
				listener.onDataRemoved(this, item, index);
			}
		}
	}

	private List<Mp3Song> loadMp3SongsFromMusicDirectory() {
		final List<Mp3Song> mp3Songs = new ArrayList<>();

		final File musicDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);

		final Set<File> filesInMusicDir = FileFinder.searchDownTreeFrom(musicDir);

		for (final File file : filesInMusicDir) {
			final String[] splitName = file.getName().split("\\.");

			if (splitName[splitName.length - 1].toLowerCase().equals("mp3")) {
				mp3Songs.add(new Mp3Song(file, resources));
			}
		}

		return mp3Songs;
	}

	private List<Mp3Album> sortSongsByAlbum(final List<Mp3Song> songs) {
		final Map<String, Mp3Album> albumMap = new HashMap<>();

		for (final Mp3Song song : songs) {
			try {
				final String key = Id3Util.getMetadataFromId3Tag(song.getMp3File(), ALBUM);

				if (!albumMap.containsKey(key)) {
					albumMap.put(key, new Mp3Album());
				}

				albumMap.get(key).add(song);
			} catch (final IOException e) {
				// In production, this should be logged as a warning/error
			}
		}

		return new ArrayList<>(albumMap.values());
	}
}


text:
"""Auth models."""
from datetime import datetime, timedelta
import secrets
from typing import Dict, List, NamedTuple, Optional
import uuid

import attr

from homeassistant.util import dt as dt_util

from . import permissions as perm_mdl
from .const import GROUP_ID_ADMIN

TOKEN_TYPE_NORMAL = "normal"
TOKEN_TYPE_SYSTEM = "system"
TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token"

@attr.s(slots=True)
class Group:
    """A group."""

    name = attr.ib(type=Optional[str])
    policy = attr.ib(type=perm_mdl.PolicyType)
    id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
    system_generated = attr.ib(type=bool, default=False)

@attr.s(slots=True)
class User:
    """A user."""

    name = attr.ib(type=Optional[str])
    perm_lookup = attr.ib(type=perm_mdl.PermissionLookup, eq=False, order=False)
    id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
    is_owner = attr.ib(type=bool, default=False)
    is_active = attr.ib(type=bool, default=False)
    system_generated = attr.ib(type=bool, default=False)

    groups = attr.ib(type=List[Group], factory=list, eq=False, order=False)

    # List of credentials of a user.
    credentials = attr.ib(type=List["Credentials"], factory=list, eq=False, order=False)

    # Tokens associated with a user.
    refresh_tokens = attr.ib(
        type=Dict[str, "RefreshToken"], factory=dict, eq=False, order=False
    )

    _permissions = attr.ib(
        type=Optional[perm_mdl.PolicyPermissions],
        init=False,
        eq=False,
        order=False,
        default=None,
    )

    @property
    def permissions(self) -> perm_mdl.AbstractPermissions:
        """Return permissions object for user."""
        if self.is_owner:
            return perm_mdl.OwnerPermissions

        if self._permissions is not None:
            return self._permissions

        self._permissions = perm_mdl.PolicyPermissions(
            perm_mdl.merge_policies([group.policy for group in self.groups]),
            self.perm_lookup,
        )

        return self._permissions

    @property
    def is_admin(self) -> bool:
        """Return if user is part of the admin group."""
        if self.is_owner:
            return True

        return self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups)

    def invalidate_permission_cache(self) -> None:
        """Invalidate permission cache."""
        self._permissions = None

@attr.s(slots=True)
class RefreshToken:
    """RefreshToken for a user to grant new access tokens."""

    user = attr.ib(type=User)
    client_id = attr.ib(type=Optional[str])
    access_token_expiration = attr.ib(type=timedelta)
    client_name = attr.ib(type=Optional[str], default=None)
    client_icon = attr.ib(type=Optional[str], default=None)
    token_type = attr.ib(
        type=str,
        default=TOKEN_TYPE_NORMAL,
        validator=attr.validators.in_(
            (TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN)
        ),
    )
    id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
    created_at = attr.ib(type=datetime, factory=dt_util.utcnow)
    token = attr.ib(type=str, factory=lambda: secrets.token_hex(64))
    jwt_key = attr.ib(type=str, factory=lambda: secrets.token_hex(64))

    last_used_at = attr.ib(type=Optional[datetime], default=None)
    last_used_ip = attr.ib(type=Optional[str], default=None)

@attr.s(slots=True)
class Credentials:
    """Credentials for a user on an auth provider."""

    auth_provider_type = attr.ib(type=str)
    auth_provider_id = attr.ib(type=Optional[str])

    # Allow the auth provider to store data to represent their auth.
    data = attr.ib(type=dict)

    id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
    is_new = attr.ib(type=bool, default=True)

class UserMeta(NamedTuple):
    """User metadata."""

    name: Optional[str]
    is_active: bool


text:
package org.keycloak.adapters.saml.config.parsers;

import org.keycloak.adapters.saml.config.IDP.HttpClientConfig;
import org.keycloak.saml.common.exceptions.ParsingException;
import org.keycloak.saml.common.util.StaxParserUtil;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.StartElement;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class HttpClientParser extends AbstractKeycloakSamlAdapterV1Parser<HttpClientConfig> {

    private static final HttpClientParser INSTANCE = new HttpClientParser();

    private HttpClientParser() {
        super(KeycloakSamlAdapterV1QNames.HTTP_CLIENT);
    }

    public static HttpClientParser getInstance() {
        return INSTANCE;
    }

    @Override
    protected HttpClientConfig instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
        final HttpClientConfig config = new HttpClientConfig();

        final Boolean allowAnyHostname = StaxParserUtil.getBooleanAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_ALLOW_ANY_HOSTNAME);
        config.setAllowAnyHostname(allowAnyHostname == null ? false : allowAnyHostname);
        config.setClientKeystore(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CLIENT_KEYSTORE));
        config.setClientKeystorePassword(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CLIENT_KEYSTORE_PASSWORD));
        final Integer connPoolSize = StaxParserUtil.getIntegerAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CONNECTION_POOL_SIZE);
        config.setConnectionPoolSize(connPoolSize == null ? 0 : connPoolSize);
        final Boolean disableTrustManager = StaxParserUtil.getBooleanAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_DISABLE_TRUST_MANAGER);
        config.setDisableTrustManager(disableTrustManager == null ? false : disableTrustManager);
        config.setProxyUrl(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_PROXY_URL));
        config.setTruststore(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_TRUSTSTORE));
        config.setTruststorePassword(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_TRUSTSTORE_PASSWORD));

        final Long socketTimeout = StaxParserUtil.getLongAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_SOCKET_TIMEOUT);
        config.setSocketTimeout(socketTimeout == null ? -1 : socketTimeout);
        final Long connectionTimeout = StaxParserUtil.getLongAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CONNECTION_TIMEOUT);
        config.setConnectionTimeout(connectionTimeout == null ? -1 : connectionTimeout);
        final Long connectionTTL = StaxParserUtil.getLongAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CONNECTION_TTL);
        config.setConnectionTTL(connectionTTL == null ? -1 : connectionTTL);

        return config;
    }

    @Override
    protected void processSubElement(XMLEventReader xmlEventReader, HttpClientConfig target, KeycloakSamlAdapterV1QNames element, StartElement elementDetail) throws ParsingException {
    }
}


text:
<!--
# Copyright:: Copyright (c) 2008-2017 Shadow-Soft, Inc.
#
# 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.
#
-->
<!-- .slide: data-background="images/consulting-background.jpg" -->
# Spider Graph
<img src="/images/ssoftlogo.png" class="absolute" height="30%" width="30%">

## Introduction
<canvas data-chart="radar" data-chart-src="data/devops-phase-report.csv" width="500" height="300">
<!--
{
"options": { "scale": {
               "gridLines": { "color": "#FFF", "zeroLineColor": "#FF0" },
               "ticks": { "display": false},
               "pointLabels": { "fontSize": "20", "fontColor": "#99F" }
             }
}
}
-->
</canvas>

### Results
<!-- Show a completed DOJO sample spider graph -->
<canvas data-chart="horizontalBar" data-chart-src="data/question-report.csv" width="600" height="300">
<!--
{
"options": {
  "responsive": true,
  "scales": {
    "xAxes": [{ "stacked": false }], "yAxes": [{ "stacked": true }]
  }
}
}
-->
</canvas>


text:
import cn from 'classnames';
import { bind } from 'decko';
import * as React from 'react';

import {
  getDiffValueBorderClassname,
  getDiffValueBgClassname,
} from '../../../shared/DiffHighlight/DiffHighlight';
import { IAttribute } from 'shared/models/Attribute';
import { Icon } from 'shared/view/elements/Icon/Icon';
import Popup from 'shared/view/elements/Popup/Popup';
import { IAttributeDiff, checkAttributeIsDiff, IPrimitiveAttributeDiff, IListAttributeDiff } from '../../../../../store/compareModels/compareModels';

import styles from './ComparableAttributeButton.module.css';
import { PopupComparedEntities } from '../../../shared/PopupComparedEntities/PopupComparedEntities';

interface ILocalProps {
  currentAttribute: IModelAttributeByKey;
  modelsAttributesByKey: IModelsAttributesByKey;
}

export type IModelsAttributesByKey = Array<IModelAttributeByKey | undefined>; // todo rename
export type IModelAttributeByKey = { modelNumber: number; diff: IAttributeDiff; attribute: IAttribute; };

interface ILocalState {
  isModalOpen: boolean;
}

class ComparableAttributeButton extends React.PureComponent<
  ILocalProps,
  ILocalState
> {
  public state: ILocalState = {
    isModalOpen: false,
  };

  public render() {
    const {
      currentAttribute,
      modelsAttributesByKey,
    } = this.props;
    const iconType = 'cube';

    const buttonAdditionClassName = getDiffValueBorderClassname(
      currentAttribute.modelNumber,
      checkAttributeIsDiff(currentAttribute.diff),
    );

    return (

        <Popup
          title="Comparing attributes"
          titleIcon={iconType}
          contentLabel="attribute-action"
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleCloseModal}
        >

            <PopupComparedEntities entities={modelsAttributesByKey}>
              {(modelAttributesByKey) => (
                this.renderAttribute(modelAttributesByKey)
              )}
            </PopupComparedEntities>

        </Popup>

              <Icon className={styles.notif_icon} type={iconType} />

              {currentAttribute.attribute.key}

    );
  }

  @bind
  private renderAttribute({ modelNumber, attribute, diff }: IModelAttributeByKey) {
    return (

        <this.RenderField keystr="Key" value={attribute.key} />
        {typeof attribute.value === 'object' ? (
          Array.isArray(attribute.value) ? (
            <this.RenderFieldList
              keystr="Value"
              value={attribute.value}
              getAdditionalValueClassName={value =>
                getDiffValueBgClassname(modelNumber, (diff as IListAttributeDiff).diffInfo[value])
              }
            />
          ) : (
            <this.RenderFieldObject keystr="Value" value={attribute.value} />
          )
        ) : (
          <this.RenderField
            keystr="Value"
            value={attribute.value}
            additionalClassName={getDiffValueBgClassname(
              modelNumber,
              (diff as IPrimitiveAttributeDiff).isDiff
            )}
          />
        )}

    );
  }

  @bind
  private handleCloseModal() {
    this.setState({ isModalOpen: false });
  }

  @bind
  private showModal() {
    this.setState({ isModalOpen: true });
  }

  private RenderField(props: {
    keystr?: string;
    value?: string | number;
    additionalClassName?: string;
  }) {
    const { keystr, value } = props;
    return (

{keystr}

        {value ? (

            {String(value)}

        ) : (
          '-'
        )}

    );
  }

  private RenderFieldList(props: {
    keystr?: string;
    value?: Array<string | number>;
    getAdditionalValueClassName: (value: string | number) => string | undefined;
  }) {
    const { keystr, value, getAdditionalValueClassName } = props;
    return (

{keystr}

          {value && value.length > 0
            ? value.map(item => {
                return (

                    {String(item)}

                );
              })
            : '-'}

    );
  }

  private RenderFieldObject(props: { keystr?: string; value?: object }) {
    const { keystr, value } = props;
    return (

{keystr}

          {value ? (

{JSON.stringify(value, null, 2)}

          ) : (
            '-'
          )}

    );
  }
}

export default ComparableAttributeButton;


text:
<component name="CopyrightManager">
  <copyright>
    <option name="myName" value="Basis.js" />
    <option name="notice" value="Copyright &#36;today.year Basis.js framework
http://basisjs.com" />
  </copyright>
</component>


text:
package org.apache.sysds.test.functions.builtin.part1;

import org.apache.sysds.common.Types.ExecMode;
import org.apache.sysds.common.Types.ExecType;
import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysds.test.AutomatedTestBase;
import org.apache.sysds.test.TestConfiguration;
import org.apache.sysds.test.TestUtils;
import org.junit.Test;

import java.util.HashMap;

public class BuiltinCorrelationMatrixTest extends AutomatedTestBase
{
	private final static String TEST_NAME = "correlationMatrix";
	private final static String TEST_DIR = "functions/builtin/";
	private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinCorrelationMatrixTest.class.getSimpleName() + "/";

	private final static double eps = 1e-3;
	private final static int rows = 1765;
	private final static double spDense = 0.99;

	@Override
	public void setUp() {
		addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{"B"}));
	}

	@Test
	public void testCorrelationMatrixDefaultCP() {
		runCorrelationMatrix(true, ExecType.CP);
	}

	@Test
	public void testCorrelationMatrixDefaultSP() {
		runCorrelationMatrix(true, ExecType.SPARK);
	}

	private void runCorrelationMatrix(boolean defaultProb, ExecType instType)
	{
		ExecMode platformOld = setExecMode(instType);

		try
		{
			loadTestConfiguration(getTestConfiguration(TEST_NAME));

			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-args", input("A"), output("B") };
			fullRScriptName = HOME + TEST_NAME + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + expectedDir();

			//generate actual dataset
			double[][] A = getRandomMatrix(rows, 10, -1, 1, spDense, 7);
			writeInputMatrixWithMTD("A", A, true);

			runTest(true, false, null, -1);
			runRScript(true);

			//compare matrices
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromOutputDir("B");
			HashMap<CellIndex, Double> rfile  = readRMatrixFromExpectedDir("B");
			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
		}
		finally {
			rtplatform = platformOld;
		}
	}
}


text:
import Ember from 'ember';
import Cattle from 'ui/utils/cattle';

var ExternalServiceController = Cattle.LegacyTransitioningResourceController.extend({
  needs: ['environment'],
  environment: Ember.computed.alias('controllers.environment'),

  actions: {
    activate: function() {
      return this.doAction('activate');
    },

    deactivate: function() {
      return this.doAction('deactivate');
    },

    edit: function() {
      this.transitionToRoute('service.edit', this.get('environmentId'), this.get('id'));
    },
  },

  scaleTimer: null,
  saveScale: function() {
    if ( this.get('scaleTimer') )
    {
      Ember.run.cancel(this.get('scaleTimer'));
    }

    var timer = Ember.run.later(this, function() {
      this.save();
    }, 500);

    this.set('scaleTimer', timer);
  },

  availableActions: function() {
    var a = this.get('actions');

    var choices = [
      { label: 'Start',         icon: 'icon icon-play',         action: 'activate',     enabled: !!a.activate,    color: 'text-success'},
      { label: 'Stop',          icon: 'icon icon-pause',        action: 'deactivate',   enabled: !!a.deactivate,  color: 'text-danger'},
      { label: 'Delete',        icon: 'icon icon-trash',        action: 'promptDelete', enabled: !!a.remove, altAction: 'delete', color: 'text-warning' },
      { label: 'Purge',         icon: '',                       action: 'purge',        enabled: !!a.purge },
      { divider: true },
      { label: 'View in API',   icon: 'icon icon-externallink', action: 'goToApi',      enabled: true },
      { label: 'Clone',         icon: 'icon icon-copy',         action: 'clone',        enabled: true },
      { label: 'Edit',          icon: 'icon icon-edit',         action: 'edit',         enabled: !!a.update },
    ];

    return choices;
  }.property('actions.{activate,deactivate,update,remove,purge}'),

  state: Ember.computed.alias('model.combinedState'),
});

ExternalServiceController.reopenClass({
  stateMap: {
    'active':           {icon: 'icon icon-cloud',          color: 'text-success'},
  }
});

export default ExternalServiceController;


text:
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices

' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.

' Review the values of the assembly attributes

<Assembly: AssemblyTitle("InternetModem")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("BoycoT")>
<Assembly: AssemblyProduct("InternetModem")>
<Assembly: AssemblyCopyright("Copyright @ BoycoT 2005 - 2016")>
<Assembly: AssemblyTrademark("")>

<Assembly: ComVisible(False)>

'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("655e65ae-7c7f-4221-8c38-4b50b6a74f91")>

' Version information for an assembly consists of the following four values:
'
'      Major Version
'      Minor Version
'      Build Number
'      Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>

<Assembly: AssemblyVersion("17.8.13.1")>
<Assembly: AssemblyFileVersion("17.8.13.1")>


text:
package tools.xor.util;

import java.util.Stack;

public class IdentityStack<T> extends Stack<T>
{
	/**
	 *
	 */
	private static final long serialVersionUID = -7633241118173209011L;

	/**
	 * Returns the index of the first occurrence of the specified element in
	 * this vector, searching forwards from {@code index}, or returns -1 if
	 * the element is not found.
	 * More formally, returns the lowest index {@code i} such that
	 * <tt>(i >= index && (o==null ? get(i)==null : o == get(i)))</tt>,
	 * or -1 if there is no such index.
	 *
	 * @param o element to search for
	 * @param index index to start searching from
	 * @return the index of the first occurrence of the element in
	 *         this vector at position {@code index} or later in the vector;
	 *         {@code -1} if the element is not found.
	 * @throws IndexOutOfBoundsException if the specified index is negative
	 */
	@Override
	public synchronized int indexOf(Object o, int index) {
		for (int i = index ; i < elementCount ; i++)
			if (elementData[i]==o)
				return i;
		return -1;
	}
}


text:
@interface ASTexture : NSObject
{
  GLuint name;
  CGSize size;
  Quad2D vertices;
  Quad2D coordinates;
}

- (id)initWithImagePath:(NSString*)path;

- (void)drawAtPoint:(CGPoint)point withRect:(CGRect)rect;

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mag. 16: t. 564. 1802

#### Original name
null

### Remarks
null


text:
namespace {

#define INIT_GUMBO_STRING(varname, literal) \
  GumboStringPiece varname = {literal, sizeof(literal) - 1}

class GumboStringBufferTest : public GumboTest {
 protected:
  GumboStringBufferTest() { gumbo_string_buffer_init(&buffer_); }

  ~GumboStringBufferTest() { gumbo_string_buffer_destroy(&buffer_); }

  void NullTerminateBuffer() { buffer_.data[buffer_.length++] = 0; }

  GumboStringBuffer buffer_;
};

TEST_F(GumboStringBufferTest, Reserve) {
  gumbo_string_buffer_reserve(21, &buffer_);
  EXPECT_EQ(40, buffer_.capacity);
  strcpy(buffer_.data, "01234567890123456789");
  buffer_.length = 20;
  NullTerminateBuffer();
  EXPECT_EQ(21, buffer_.length);
  EXPECT_STREQ("01234567890123456789", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendString) {
  INIT_GUMBO_STRING(str, "01234567");
  gumbo_string_buffer_append_string(&str, &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("01234567", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendStringWithResize) {
  INIT_GUMBO_STRING(str, "01234567");
  gumbo_string_buffer_append_string(&str, &buffer_);
  gumbo_string_buffer_append_string(&str, &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("0123456701234567", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendCodepoint_1Byte) {
  gumbo_string_buffer_append_codepoint('a', &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("a", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendCodepoint_2Bytes) {
  gumbo_string_buffer_append_codepoint(0xE5, &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("\xC3\xA5", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendCodepoint_3Bytes) {
  gumbo_string_buffer_append_codepoint(0x39E7, &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("\xE3\xA7\xA7", buffer_.data);
}

TEST_F(GumboStringBufferTest, AppendCodepoint_4Bytes) {
  gumbo_string_buffer_append_codepoint(0x679E7, &buffer_);
  NullTerminateBuffer();
  EXPECT_STREQ("\xF1\xA7\xA7\xA7", buffer_.data);
}

TEST_F(GumboStringBufferTest, ToString) {
  gumbo_string_buffer_reserve(8, &buffer_);
  strcpy(buffer_.data, "012345");
  buffer_.length = 7;

  char* dest = gumbo_string_buffer_to_string(&buffer_);
  EXPECT_STREQ("012345", dest);
  gumbo_free(dest);
}

}  // namespace


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameCntrl : MonoBehaviour {

	float 			score;
	GameObject [] 	colorObjects = new GameObject[4];

	public GameObject   ColorObjectPref;
	public Vector3 []   Positions;
	public Text 		ScoreText;
	public Button 		RestartBtn;

	void Start ()
	{
		score = 0;
		ScoreText.text = "Match the color";

		InitColorObj ();

		RestartBtn.GetComponent<Button>().onClick.AddListener(Restart);

		RestartBtn.gameObject.SetActive(false);
	}

	void InitColorObj ()
	{
		for (int i = 0; i < Positions.Length; i++)
		{
			colorObjects [i] = Instantiate (ColorObjectPref, Positions[i], Quaternion.identity) as GameObject;
		}

		RandomizeColors ();
	}

	void RandomizeColors ()
	{
		Color randColor = Random.ColorHSV (0f, 1f,
										   0.2f, 1f,
										   0.2f, 1f);

		float randRange = -.005f*score + 1f;

		GameObject.Find ("MainColorObject").GetComponent <ColorObject> ().SetColor (randColor, randRange);

		SetRandomRight ();

		for (int i = 0; i < Positions.Length; i++)
		{
			colorObjects[i].GetComponent <ColorObject> ().SetColor (randColor, randRange);
		}
	}

	void SetRandomRight ()
	{
		int right = Random.Range (0, Positions.Length);

		for (int i = 0; i < Positions.Length; i++)
		{
			if (i == right)
				{ colorObjects[i].GetComponent <ColorObject> ().isRight = true; }
			else
				{ colorObjects[i].GetComponent <ColorObject> ().isRight = false; }
		}
	}

	public void GameOver ()
	{
		ScoreText.text = "Game over\nYour score is: " + score.ToString ();

		for (int i = 0; i < Positions.Length; i++)
		{
			colorObjects[i].GetComponent <ColorObject> ().isEnable = false;
		}

		RestartBtn.gameObject.SetActive(true);
	}

	public void NextLevel ()
	{
		score++;
		ScoreText.text = score.ToString ();

		RandomizeColors ();
	}

	void Restart ()
	{
		RestartBtn.gameObject.SetActive(false);

		score = 0;
		ScoreText.text = score.ToString ();

		for (int i = 0; i < Positions.Length; i++)
		{
			colorObjects[i].GetComponent <ColorObject> ().isEnable = true;
		}

		RandomizeColors ();
	}
}


text:
package demos.applets;

import java.applet.*;
import java.awt.Container;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.KeyListener;

import javax.media.opengl.*;
import com.jogamp.newt.awt.NewtCanvasAWT;
import com.jogamp.newt.opengl.GLWindow;
import java.awt.BorderLayout;

/** Shows how to deploy an applet using JOGL. This demo must be
    referenced from a web page via an <applet> tag. */

public class JOGLNewtApplet1Run extends Applet {
    GLWindow glWindow;
    NewtCanvasAWT newtCanvasAWT;
    JOGLNewtAppletBase base;

    public void init() {
        if(!(this instanceof Container)) {
            throw new RuntimeException("This Applet is not a AWT Container");
        }
        Container container = (Container) this; // have to think about that, we may use a Container

        String glEventListenerClazzName=null;
        String glProfileName=null;
        int glSwapInterval=0;
        boolean glDebug=false;
        boolean glTrace=false;
        String tmp;
        try {
            glEventListenerClazzName = getParameter("gl_event_listener_class");
            glProfileName = getParameter("gl_profile");
            glSwapInterval = JOGLNewtAppletBase.str2Int(getParameter("gl_swap_interval"), glSwapInterval);
            glDebug = JOGLNewtAppletBase.str2Bool(getParameter("gl_debug"), glDebug);
            glTrace = JOGLNewtAppletBase.str2Bool(getParameter("gl_trace"), glTrace);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(null==glEventListenerClazzName) {
            throw new RuntimeException("No applet parameter 'gl_event_listener_class'");
        }
        base = new JOGLNewtAppletBase(glEventListenerClazzName,
                                      glSwapInterval,
                                      glDebug,
                                      glTrace);

        try {
            GLProfile.initSingleton();
            GLCapabilities caps = new GLCapabilities(GLProfile.get(glProfileName));
            glWindow = GLWindow.create(caps);
            newtCanvasAWT = new NewtCanvasAWT(glWindow);
            container.setLayout(new BorderLayout());
            container.add(newtCanvasAWT, BorderLayout.CENTER);
            base.init(glWindow);
            if(base.isValid()) {
                GLEventListener glEventListener = base.getGLEventListener();

                if(glEventListener instanceof MouseListener) {
                    addMouseListener((MouseListener)glEventListener);
                }
                if(glEventListener instanceof MouseMotionListener) {
                    addMouseMotionListener((MouseMotionListener)glEventListener);
                }
                if(glEventListener instanceof KeyListener) {
                    addKeyListener((KeyListener)glEventListener);
                }
            }
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public void start() {
        base.start();
    }

    public void stop() {
        base.stop();
    }

    public void destroy() {
        glWindow.setVisible(false); // hide 1st
        glWindow.reparentWindow(null); // get out of newtCanvasAWT
        this.remove(newtCanvasAWT); // remove newtCanvasAWT
        base.destroy(true); // destroy glWindow unrecoverable
        base=null;
    }
}


text:
#ifndef __CAP_FFMPEG_IMPL_H__
#define __CAP_FFMPEG_IMPL_H__

#include "ffmpeg_api.hpp"
#include <assert.h>
#include <algorithm>
#include <limits>

#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4244 4510 4512 4610 )
#endif

#ifdef __cplusplus
extern "C" {
#endif

#include "ffmpeg_codecs.hpp"

#include <libavutil/mathematics.h>

#ifdef WIN32
  #define HAVE_FFMPEG_SWSCALE 1
  #include <libavcodec/avcodec.h>
  #include <libswscale/swscale.h>
#else

#ifndef HAVE_FFMPEG_SWSCALE
    #error "libswscale is necessary to build the newer OpenCV ffmpeg wrapper"
#endif

// if the header path is not specified explicitly, let's deduce it
#if !defined HAVE_FFMPEG_AVCODEC_H && !defined HAVE_LIBAVCODEC_AVCODEC_H

#if defined(HAVE_GENTOO_FFMPEG)
  #define HAVE_LIBAVCODEC_AVCODEC_H 1
  #if defined(HAVE_FFMPEG_SWSCALE)
    #define HAVE_LIBSWSCALE_SWSCALE_H 1
  #endif
#elif defined HAVE_FFMPEG
  #define HAVE_FFMPEG_AVCODEC_H 1
  #if defined(HAVE_FFMPEG_SWSCALE)
    #define HAVE_FFMPEG_SWSCALE_H 1
  #endif
#endif

#endif

#if defined(HAVE_FFMPEG_AVCODEC_H)
  #include <ffmpeg/avcodec.h>
#endif
#if defined(HAVE_FFMPEG_SWSCALE_H)
  #include <ffmpeg/swscale.h>
#endif

#if defined(HAVE_LIBAVCODEC_AVCODEC_H)
  #include <libavcodec/avcodec.h>
#endif
#if defined(HAVE_LIBSWSCALE_SWSCALE_H)
  #include <libswscale/swscale.h>
#endif

#endif

#ifdef __cplusplus
}
#endif

#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( default: 4244 4510 4512 4610 )
#endif

#ifdef NDEBUG
#define CV_WARN(message)
#else
#define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
#endif

/* PIX_FMT_RGBA32 macro changed in newer ffmpeg versions */
#ifndef PIX_FMT_RGBA32
#define PIX_FMT_RGBA32 PIX_FMT_RGB32
#endif

#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

#if defined WIN32 || defined _WIN32
    #include <windows.h>
#elif defined __linux__ || defined __APPLE__
    #include <unistd.h>
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/sysctl.h>
#endif

typedef long long s64;

#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif

#if defined(__APPLE__)
#define AV_NOPTS_VALUE_ ((s64)0x8000000000000000LL)
#else
#define AV_NOPTS_VALUE_ ((s64)0x8000000000000000LL)
#endif

static int get_number_of_cpus(void)
{
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(52, 111, 0)
    return 1;
#elif defined WIN32 || defined _WIN32
    SYSTEM_INFO sysinfo;
    GetSystemInfo( &sysinfo );

	//return 1;
    return (int)sysinfo.dwNumberOfProcessors;
#elif defined __linux__
    return (int)sysconf( _SC_NPROCESSORS_ONLN );
#elif defined __APPLE__
    int numCPU=0;
    int mib[4];
    size_t len = sizeof(numCPU);

    // set the mib for hw.ncpu
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;

    // get the number of CPUs from the system
    sysctl(mib, 2, &numCPU, &len, NULL, 0);

    if( numCPU < 1 )
    {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );

        if( numCPU < 1 )
            numCPU = 1;
    }

    return (int)numCPU;
#else
    return 1;
#endif
}

struct Image_FFMPEG
{
    unsigned char* data;
    int step;
    int width;
    int height;
    int cn;
};

inline void _opencv_ffmpeg_free(void** ptr)
{
    if(*ptr) free(*ptr);
    *ptr = 0;
}

static int interrupt_cb(void *ctx)
{
    static int i = 0;
    i ++;
    printf("%s----%d %d \n", __FILE__, __LINE__, i);
    return 0;
}

class CvCapture_FFMPEG
{
public:
    CvCapture_FFMPEG();
    ~CvCapture_FFMPEG(){}
    bool open( const char* filename );
    void close();
    bool setSize(int w, int h);

    double getProperty(int);
    bool setProperty(int, double);
    bool grabFrame();
    bool grabFrame(unsigned char** dataRGB, int* step, int* width, int* height, int* cn,
            unsigned char** data, int *size);
    bool retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn);

    void init();

    void    seek(s64 frame_number);
    void    seek(double sec);
    bool    slowSeek( int framenumber );

    s64 get_total_frames();
    double  get_duration_sec();
    double  get_fps();
    int     get_bitrate();

    double  r2d(AVRational r);
    s64 dts_to_frame_number(s64 dts);
    double  dts_to_sec(s64 dts);

private:
    AVFormatContext * ic;
    AVCodec         * avcodec;
    int               video_stream;
    AVStream        * video_st;
    AVFrame         * picture;
    AVFrame           rgb_picture;
    s64           picture_pts;

    AVPacket          packet;
    Image_FFMPEG      frame;
    struct SwsContext *img_convert_ctx;

    s64 frame_number, first_frame_number;

    double eps_zero;
/*
   'filename' contains the filename of the videosource,
   'filename==NULL' indicates that ffmpeg's seek support works
   for the particular file.
   'filename!=NULL' indicates that the slow fallback function is used for seeking,
   and so the filename is needed to reopen the file on backward seeking.
*/
    char              * filename;

    /* Data for av_read_frame */
    unsigned char* pData;
    int nDataSize;
};

inline CvCapture_FFMPEG::CvCapture_FFMPEG()
{
	init();
}

inline void CvCapture_FFMPEG::init()
{
    ic = 0;
    video_stream = -1;
    video_st = 0;
    picture = 0;
    picture_pts = AV_NOPTS_VALUE_;
    first_frame_number = -1;
    memset( &rgb_picture, 0, sizeof(rgb_picture) );
    memset( &frame, 0, sizeof(frame) );
    filename = 0;
    memset(&packet, 0, sizeof(packet));
    av_init_packet(&packet);
    img_convert_ctx = 0;
    nDataSize = 1024 * 1024;
    pData = (unsigned char*)malloc(1024 * 1024);

    avcodec = 0;
    frame_number = 0;
    eps_zero = 0.000025;
}

inline void CvCapture_FFMPEG::close()
{
    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }

    if( picture )
        av_free(picture);

    if(video_st)
    {
#if LIBAVFORMAT_BUILD > 4628
        avcodec_close( video_st->codec );

#else
        avcodec_close( &(video_st->codec) );

#endif
        video_st = NULL;
    }

    if( ic )
    {
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 24, 2)
        av_close_input_file(ic);
#else
        avformat_close_input(&ic);
#endif

        ic = NULL;
    }

    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }

    // free last packet if exist
    if (packet.data) {
        av_free_packet (&packet);
        packet.data = NULL;
    }

    if (pData)
    {
        free(pData);
    }

    init();
}

#ifndef AVSEEK_FLAG_FRAME
#define AVSEEK_FLAG_FRAME 0
#endif
#ifndef AVSEEK_FLAG_ANY
#define AVSEEK_FLAG_ANY 1
#endif

inline  void icvInitFFMPEG_internal()
{
    static volatile bool initialized = false;
    if( !initialized )
    {
        avcodec_register_all();
        av_register_all();
    #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 13, 0)
        avformat_network_init();
    #endif

        /* register all codecs, demux and protocols */

        av_log_set_level(AV_LOG_DEBUG);

        initialized = true;
    }
}

inline bool CvCapture_FFMPEG::setSize(int w, int h)
{
    if( rgb_picture.data[0] )
    {
        free( rgb_picture.data[0] );
        rgb_picture.data[0] = 0;
    }
    rgb_picture.data[0] = (uint8_t*)malloc(
            avpicture_get_size( PIX_FMT_RGB24,
                                w, h));
    avpicture_fill( (AVPicture*)&rgb_picture, rgb_picture.data[0],
                    PIX_FMT_RGB24, w, h );

    frame.width = w;
    frame.height = h;
    frame.cn = 3;
    frame.step = rgb_picture.linesize[0];
    frame.data = rgb_picture.data[0];
    return true;
}

inline bool CvCapture_FFMPEG::open( const char* _filename )
{
    icvInitFFMPEG_internal();

    unsigned i;
    bool valid = false;

    close();

	AVDictionary *opts = 0;
	av_dict_set(&opts, "rtsp_transport", "tcp", 0);
	//av_dict_set(&opts, "reorder_queue_size", "500", 0);
	//av_dict_set(&opts, "buffer_size", "1024000", 0);

       ic = avformat_alloc_context();
       ic->interrupt_callback.callback = interrupt_cb;
       ic->interrupt_callback.opaque = this;
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    int err = avformat_open_input(&ic, _filename, NULL, &opts);
#else
    int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
#endif

    if (err < 0) {
        CV_WARN("Error opening file");
        goto exit_func;
    }
    err =
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 3, 0)
    avformat_find_stream_info(ic, NULL);
#else
    av_find_stream_info(ic);
#endif
    if (err < 0) {
        CV_WARN("Could not find codec parameters");
        goto exit_func;
    }
    for(i = 0; i < ic->nb_streams; i++)
    {
#if LIBAVFORMAT_BUILD > 4628
        AVCodecContext *enc = ic->streams[i]->codec;
#else
        AVCodecContext *enc = &ic->streams[i]->codec;
#endif

#ifdef FF_API_THREAD_INIT
        avcodec_thread_init(enc, get_number_of_cpus());
#else
        enc->thread_count = get_number_of_cpus();
#endif

#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
#define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
#endif

        if( AVMEDIA_TYPE_VIDEO == enc->codec_type && video_stream < 0) {
            AVCodec *codec = avcodec_find_decoder(enc->codec_id);
            if (!codec ||
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
                avcodec_open2(enc, codec, NULL)
#else
                avcodec_open(enc, codec)
#endif
                < 0) goto exit_func;

            video_stream = i;
            video_st = ic->streams[i];
            picture = avcodec_alloc_frame();

            rgb_picture.data[0] = (uint8_t*)malloc(
                    avpicture_get_size( PIX_FMT_RGB24,
                                        enc->width, enc->height ));
            avpicture_fill( (AVPicture*)&rgb_picture, rgb_picture.data[0],
                            PIX_FMT_RGB24, enc->width, enc->height );

            frame.width = enc->width;
            frame.height = enc->height;
            frame.cn = 3;
            frame.step = rgb_picture.linesize[0];
            frame.data = rgb_picture.data[0];
            break;
        }
    }

    if(video_stream >= 0) valid = true;

exit_func:

    if( !valid )
        close();

    return valid;
}

void inline DumpHex(char * pBuff, int nSize)
{
    for (int i = 0; i < nSize; i ++)
    {
         printf("0x%x ", pBuff[i]);
    }
    printf("\n");
}

inline bool CvCapture_FFMPEG::grabFrame(unsigned char** dataRGB, int* step, int* width, int* height, int* cn,
        unsigned char** data, int *size)
{
    bool valid = false;
    int got_picture;

    int count_errs = 0;
    const int max_number_of_attempts = 1 << 16;

    if( !ic || !video_st )  return false;

    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;

    av_free_packet (&packet);

    picture_pts = AV_NOPTS_VALUE_;

    unsigned long start;
    unsigned long end;

    // get the next frame
    while (!valid)
    {
        start = GetTickCount();
		//while (1){
        int ret = av_read_frame(ic, &packet);

        //printf("(%s,%d) Size %d ret %d %d\n", __FUNCTION__, __LINE__, packet.size, ret,
	//		GetTickCount() - start);

        //DumpHex((char *)(packet.data), 20);
        if (ret == AVERROR(-1)) continue;

	//	}

        /* else if (ret < 0) break; */

        if( packet.stream_index != video_stream )
        {
	     //printf("(%s,%d)\n", __FUNCTION__, __LINE__);
            av_free_packet (&packet);
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
            continue;
        }

        start = GetTickCount();
        // Decode video frame
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
            avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
        #elif LIBAVFORMAT_BUILD > 4628
                avcodec_decode_video(video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #else
                avcodec_decode_video(&video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #endif
        //printf("(%s,%d) avcodec_decode_video2  %d\n", __FUNCTION__, __LINE__,
	//		GetTickCount() - start);
        // Did we get a video frame?
        if(got_picture)
        {
         //printf("(%s,%d) got_picture  %d\n", __FUNCTION__, __LINE__,
	//		GetTickCount() - start);
            //picture_pts = picture->best_effort_timestamp;
            if( picture_pts == AV_NOPTS_VALUE_ )
                picture_pts = packet.pts != AV_NOPTS_VALUE_ && packet.pts != 0 ? packet.pts : packet.dts;
            frame_number++;
            valid = true;

            break;
        }
        else
        {
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
        }

        av_free_packet (&packet);
    }

    if( valid && first_frame_number < 0 )
        first_frame_number = dts_to_frame_number(picture_pts);
    *size = 0;
    *data = NULL;
    if (valid == true)
    {
        retrieveFrame(0, dataRGB, step, width, height, cn);
        *size = packet.size;
        *data = pData;
        memcpy(pData, packet.data, packet.size);

        av_free_packet (&packet);
    }

    // return if we have a new picture or not
    return valid;
}

inline bool CvCapture_FFMPEG::grabFrame()
{
    bool valid = false;
    int got_picture;

    int count_errs = 0;
    const int max_number_of_attempts = 1 << 16;

    if( !ic || !video_st )  return false;

    if( ic->streams[video_stream]->nb_frames > 0 &&
        frame_number > ic->streams[video_stream]->nb_frames )
        return false;

    av_free_packet (&packet);

    picture_pts = AV_NOPTS_VALUE_;

    unsigned long start;
    unsigned long end;

    // get the next frame
    while (!valid)
    {
        start = GetTickCount();
        //while (1){
        int ret = av_read_frame(ic, &packet);

        //printf("(%s,%d) Size %d ret %d %d\n", __FUNCTION__, __LINE__, packet.size, ret,
    //      GetTickCount() - start);

        //DumpHex((char *)(packet.data), 20);
        if (ret == AVERROR(-1)) continue;

    //  }

        /* else if (ret < 0) break; */

        if( packet.stream_index != video_stream )
        {
         //printf("(%s,%d)\n", __FUNCTION__, __LINE__);
            av_free_packet (&packet);
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
            continue;
        }

        start = GetTickCount();
        // Decode video frame
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
            avcodec_decode_video2(video_st->codec, picture, &got_picture, &packet);
        #elif LIBAVFORMAT_BUILD > 4628
                avcodec_decode_video(video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #else
                avcodec_decode_video(&video_st->codec,
                                     picture, &got_picture,
                                     packet.data, packet.size);
        #endif
        //printf("(%s,%d) avcodec_decode_video2  %d\n", __FUNCTION__, __LINE__,
    //      GetTickCount() - start);
        // Did we get a video frame?
        if(got_picture)
        {
         //printf("(%s,%d) got_picture  %d\n", __FUNCTION__, __LINE__,
    //      GetTickCount() - start);
            //picture_pts = picture->best_effort_timestamp;
            if( picture_pts == AV_NOPTS_VALUE_ )
                picture_pts = packet.pts != AV_NOPTS_VALUE_ && packet.pts != 0 ? packet.pts : packet.dts;
            frame_number++;
            valid = true;
        }
        else
        {
            count_errs++;
            if (count_errs > max_number_of_attempts)
                break;
        }

        av_free_packet (&packet);
    }

    if( valid && first_frame_number < 0 )
        first_frame_number = dts_to_frame_number(picture_pts);

    // return if we have a new picture or not
    return valid;
}

inline bool CvCapture_FFMPEG::retrieveFrame(int, unsigned char** data, int* step, int* width, int* height, int* cn)
{
    if( !video_st || !picture->data[0] )
        return false;

    avpicture_fill((AVPicture*)&rgb_picture, rgb_picture.data[0], PIX_FMT_RGB24,
                   frame.width, frame.height);

    if( img_convert_ctx == NULL ||
        frame.width != video_st->codec->width ||
        frame.height != video_st->codec->height )
    {
        if( img_convert_ctx )
            sws_freeContext(img_convert_ctx);

        img_convert_ctx = sws_getCachedContext(
                NULL,
                video_st->codec->width, video_st->codec->height,
                video_st->codec->pix_fmt,
                frame.width , frame.height ,
                PIX_FMT_RGB24,
                SWS_BICUBIC,
                NULL, NULL, NULL
                );

        if (img_convert_ctx == NULL)
            return false;//CV_Error(0, "Cannot initialize the conversion context!");
    }

    sws_scale(
            img_convert_ctx,
            picture->data,
            picture->linesize,
            0, video_st->codec->height,
            rgb_picture.data,
            rgb_picture.linesize
            );

    *data = frame.data;
    *step = frame.step;
    *width = frame.width;
    *height = frame.height;
    *cn = frame.cn;

    return true;
}

inline double CvCapture_FFMPEG::getProperty( int property_id )
{
    if( !video_st ) return 0;

    switch( property_id )
    {
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
        return 1000.0*(double)frame_number/get_fps();
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
        return (double)frame_number;
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
        return r2d(ic->streams[video_stream]->time_base);
    case CV_FFMPEG_CAP_PROP_FRAME_COUNT:
        return (double)get_total_frames();
    case CV_FFMPEG_CAP_PROP_FRAME_WIDTH:
        return (double)frame.width;
    case CV_FFMPEG_CAP_PROP_FRAME_HEIGHT:
        return (double)frame.height;
    case CV_FFMPEG_CAP_PROP_FPS:
#if LIBAVCODEC_BUILD > 4753
        return av_q2d(video_st->r_frame_rate);
#else
        return (double)video_st->codec.frame_rate
                / (double)video_st->codec.frame_rate_base;
#endif
    case CV_FFMPEG_CAP_PROP_FOURCC:
#if LIBAVFORMAT_BUILD > 4628
        return (double)video_st->codec->codec_tag;
#else
        return (double)video_st->codec.codec_tag;
#endif
    default:
        break;
    }

    return 0;
}

inline double CvCapture_FFMPEG::r2d(AVRational r)
{
    return r.num == 0 || r.den == 0 ? 0. : (double)r.num / (double)r.den;
}

inline double CvCapture_FFMPEG::get_duration_sec()
{
    double sec = (double)ic->duration / (double)AV_TIME_BASE;

    if (sec < eps_zero)
    {
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
    }

    if (sec < eps_zero)
    {
        sec = (double)ic->streams[video_stream]->duration * r2d(ic->streams[video_stream]->time_base);
    }

    return sec;
}

inline int CvCapture_FFMPEG::get_bitrate()
{
    return ic->bit_rate;
}

inline double CvCapture_FFMPEG::get_fps()
{
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
    }
#endif

    if (fps < eps_zero)
    {
        fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
    }

    return fps;
}

inline s64 CvCapture_FFMPEG::get_total_frames()
{
    s64 nbf = ic->streams[video_stream]->nb_frames;

    if (nbf == 0)
    {
        nbf = (s64)floor(get_duration_sec() * get_fps() + 0.5);
    }
    return nbf;
}

inline s64 CvCapture_FFMPEG::dts_to_frame_number(s64 dts)
{
    double sec = dts_to_sec(dts);
    return (s64)(get_fps() * sec + 0.5);
}

inline double CvCapture_FFMPEG::dts_to_sec(s64 dts)
{
    return (double)(dts - ic->streams[video_stream]->start_time) *
        r2d(ic->streams[video_stream]->time_base);
}

inline void CvCapture_FFMPEG::seek(s64 _frame_number)
{
    _frame_number = std::min(_frame_number, get_total_frames());
    int delta = 16;

    // if we have not grabbed a single frame before first seek, let's read the first frame
    // and get some valuable information during the process
    if( first_frame_number < 0 && get_total_frames() > 1 )
        grabFrame();

    for(;;)
    {
        s64 _frame_number_temp = std::max(_frame_number-delta, (s64)0);
        double sec = (double)_frame_number_temp / get_fps();
        s64 time_stamp = ic->streams[video_stream]->start_time;
        double  time_base  = r2d(ic->streams[video_stream]->time_base);
        time_stamp += (s64)(sec / time_base + 0.5);
        if (get_total_frames() > 1) av_seek_frame(ic, video_stream, time_stamp, AVSEEK_FLAG_BACKWARD);
        avcodec_flush_buffers(ic->streams[video_stream]->codec);
        if( _frame_number > 0 )
        {
            grabFrame();

            if( _frame_number > 1 )
            {
                frame_number = dts_to_frame_number(picture_pts) - first_frame_number;
                //printf("_frame_number = %d, frame_number = %d, delta = %d\n",
                //       (int)_frame_number, (int)frame_number, delta);

                if( frame_number < 0 || frame_number > _frame_number-1 )
                {
                    if( _frame_number_temp == 0 || delta >= INT_MAX/4 )
                        break;
                    delta = delta < 16 ? delta*2 : delta*3/2;
                    continue;
                }
                while( frame_number < _frame_number-1 )
                {
                    if(!grabFrame())
                        break;
                }
                frame_number++;
                break;
            }
            else
            {
                frame_number = 1;
                break;
            }
        }
        else
        {
            frame_number = 0;
            break;
        }
    }
}

inline void CvCapture_FFMPEG::seek(double sec)
{
    seek((s64)(sec * get_fps() + 0.5));
}

inline bool CvCapture_FFMPEG::setProperty( int property_id, double value )
{
    if( !video_st ) return false;

    switch( property_id )
    {
    case CV_FFMPEG_CAP_PROP_POS_MSEC:
    case CV_FFMPEG_CAP_PROP_POS_FRAMES:
    case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
        {
            switch( property_id )
            {
            case CV_FFMPEG_CAP_PROP_POS_FRAMES:
                seek((s64)value);
                break;

            case CV_FFMPEG_CAP_PROP_POS_MSEC:
                seek(value/1000.0);
                break;

            case CV_FFMPEG_CAP_PROP_POS_AVI_RATIO:
                seek((s64)(value*ic->duration));
                break;
            }

            picture_pts=(s64)value;
        }
        break;
    default:
        return false;
    }

    return true;
}

///////////////// FFMPEG CvVideoWriter implementation //////////////////////////
class CvVideoWriter_FFMPEG
{
public:
    bool open( const char* filename, int fourcc,
               double fps, int width, int height, bool isColor );
    void close();
    bool writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin );

    void init();
private:
    AVOutputFormat  * fmt;
    AVFormatContext * oc;
    uint8_t         * outbuf;
    uint32_t          outbuf_size;
    FILE            * outfile;
    AVFrame         * picture;
    AVFrame         * input_picture;
    uint8_t         * picbuf;
    AVStream        * video_st;
    int               input_pix_fmt;
    Image_FFMPEG      temp_image;
    int               frame_width, frame_height;
    bool              ok;
    struct SwsContext *img_convert_ctx;
};

inline  const char * icvFFMPEGErrStr(int err)
{
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
    switch(err) {
    case AVERROR_BSF_NOT_FOUND:
        return "Bitstream filter not found";
    case AVERROR_DECODER_NOT_FOUND:
        return "Decoder not found";
    case AVERROR_DEMUXER_NOT_FOUND:
        return "Demuxer not found";
    case AVERROR_ENCODER_NOT_FOUND:
        return "Encoder not found";
    case AVERROR_EOF:
        return "End of file";
    case AVERROR_EXIT:
        return "Immediate exit was requested; the called function should not be restarted";
    case AVERROR_FILTER_NOT_FOUND:
        return "Filter not found";
    case AVERROR_INVALIDDATA:
        return "Invalid data found when processing input";
    case AVERROR_MUXER_NOT_FOUND:
        return "Muxer not found";
    case AVERROR_OPTION_NOT_FOUND:
        return "Option not found";
    case AVERROR_PATCHWELCOME:
        return "Not yet implemented in FFmpeg, patches welcome";
    case AVERROR_PROTOCOL_NOT_FOUND:
        return "Protocol not found";
    case AVERROR_STREAM_NOT_FOUND:
        return "Stream not found";
    default:
        break;
    }
#else
    switch(err) {
    case AVERROR_NUMEXPECTED:
        return "Incorrect filename syntax";
    case AVERROR_INVALIDDATA:
        return "Invalid data in header";
    case AVERROR_NOFMT:
        return "Unknown format";
    case AVERROR_IO:
        return "I/O error occurred";
    case AVERROR_NOMEM:
        return "Memory allocation error";
    default:
        break;
    }
#endif

    return "Unspecified error";
}

/* function internal to FFMPEG (libavformat/riff.c) to lookup codec id by fourcc tag*/
extern "C" {
    enum CodecID codec_get_bmp_id(unsigned int tag);
}

inline void CvVideoWriter_FFMPEG::init()
{
    fmt = 0;
    oc = 0;
    outbuf = 0;
    outbuf_size = 0;
    outfile = 0;
    picture = 0;
    input_picture = 0;
    picbuf = 0;
    video_st = 0;
    input_pix_fmt = 0;
    memset(&temp_image, 0, sizeof(temp_image));
    img_convert_ctx = 0;
    frame_width = frame_height = 0;
    ok = false;
}

/**
 * the following function is a modified version of code
 * found in ffmpeg-0.4.9-pre1/output_example.c
 */
inline  AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc)
{
    AVFrame * picture;
    uint8_t * picture_buf;
    int size;

    picture = avcodec_alloc_frame();
    if (!picture)
        return NULL;
    size = avpicture_get_size( (PixelFormat) pix_fmt, width, height);
    if(alloc){
        picture_buf = (uint8_t *) malloc(size);
        if (!picture_buf)
        {
            av_free(picture);
            return NULL;
        }
        avpicture_fill((AVPicture *)picture, picture_buf,
                       (PixelFormat) pix_fmt, width, height);
    }
    else {
    }
    return picture;
}

/* add a video output stream to the container */
inline  AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc,
                                             CodecID codec_id,
                                             int w, int h, int bitrate,
                                             double fps, int pixel_format)
{
    AVCodecContext *c;
    AVStream *st;
    int frame_rate, frame_rate_base;
    AVCodec *codec;

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 10, 0)
    st = avformat_new_stream(oc, 0);
#else
    st = av_new_stream(oc, 0);
#endif

    if (!st) {
        CV_WARN("Could not allocate stream");
        return NULL;
    }

#if LIBAVFORMAT_BUILD > 4628
    c = st->codec;
#else
    c = &(st->codec);
#endif

#if LIBAVFORMAT_BUILD > 4621
    c->codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
#else
    c->codec_id = oc->oformat->video_codec;
#endif

    if(codec_id != CODEC_ID_NONE){
        c->codec_id = codec_id;
    }

    //if(codec_tag) c->codec_tag=codec_tag;
    codec = avcodec_find_encoder(c->codec_id);

    c->codec_type = AVMEDIA_TYPE_VIDEO;

    /* put sample parameters */
    s64 lbit_rate = (s64)bitrate;
    lbit_rate += (bitrate / 2);
    lbit_rate = std::min(lbit_rate, (s64)INT_MAX);
    c->bit_rate = lbit_rate;

    // took advice from
    // http://ffmpeg-users.933282.n4.nabble.com/warning-clipping-1-dct-coefficients-to-127-127-td934297.html
    c->qmin = 3;

    /* resolution must be a multiple of two */
    c->width = w;
    c->height = h;

    /* time base: this is the fundamental unit of time (in seconds) in terms
       of which frame timestamps are represented. for fixed-fps content,
       timebase should be 1/framerate and timestamp increments should be
       identically 1. */
    frame_rate=(int)(fps+0.5);
    frame_rate_base=1;
    while (fabs((double)frame_rate/frame_rate_base) - fps > 0.001){
        frame_rate_base*=10;
        frame_rate=(int)(fps*frame_rate_base + 0.5);
    }
#if LIBAVFORMAT_BUILD > 4752
    c->time_base.den = frame_rate;
    c->time_base.num = frame_rate_base;
    /* adjust time base for supported framerates */
    if(codec && codec->supported_framerates){
        const AVRational *p= codec->supported_framerates;
        AVRational req = {frame_rate, frame_rate_base};
        const AVRational *best=NULL;
        AVRational best_error= {INT_MAX, 1};
        for(; p->den!=0; p++){
            AVRational error= av_sub_q(req, *p);
            if(error.num <0) error.num *= -1;
            if(av_cmp_q(error, best_error) < 0){
                best_error= error;
                best= p;
            }
        }
        c->time_base.den= best->num;
        c->time_base.num= best->den;
    }
#else
    c->frame_rate = frame_rate;
    c->frame_rate_base = frame_rate_base;
#endif

    c->gop_size = 12; /* emit one intra frame every twelve frames at most */
    c->pix_fmt = (PixelFormat) pixel_format;

    if (c->codec_id == CODEC_ID_MPEG2VIDEO) {
        c->max_b_frames = 2;
    }
    if (c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MSMPEG4V3){
        /* needed to avoid using macroblocks in which some coeffs overflow
           this doesnt happen with normal video, it just happens here as the
           motion of the chroma plane doesnt match the luma plane */
        /* avoid FFMPEG warning 'clipping 1 dct coefficients...' */
        c->mb_decision=2;
    }
#if LIBAVCODEC_VERSION_INT>0x000409
    // some formats want stream headers to be seperate
    if(oc->oformat->flags & AVFMT_GLOBALHEADER)
    {
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
#endif

    return st;
}

static const int OPENCV_NO_FRAMES_WRITTEN_CODE = 1000;

inline  int icv_av_write_frame_FFMPEG( AVFormatContext * oc, AVStream * video_st, uint8_t * outbuf, uint32_t outbuf_size, AVFrame * picture )
{
#if LIBAVFORMAT_BUILD > 4628
    AVCodecContext * c = video_st->codec;
#else
    AVCodecContext * c = &(video_st->codec);
#endif
    int out_size;
    int ret = 0;

    if (oc->oformat->flags & AVFMT_RAWPICTURE) {
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

#ifndef PKT_FLAG_KEY
#define PKT_FLAG_KEY AV_PKT_FLAG_KEY
#endif

        pkt.flags |= PKT_FLAG_KEY;
        pkt.stream_index= video_st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_write_frame(oc, &pkt);
    } else {
        /* encode the image */
        out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
        /* if zero size, it means the image was buffered */
        if (out_size > 0) {
            AVPacket pkt;
            av_init_packet(&pkt);

#if LIBAVFORMAT_BUILD > 4752
            if(c->coded_frame->pts != (s64)AV_NOPTS_VALUE_)
                pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st->time_base);
#else
            pkt.pts = c->coded_frame->pts;
#endif
            if(c->coded_frame->key_frame)
                pkt.flags |= PKT_FLAG_KEY;
            pkt.stream_index= video_st->index;
            pkt.data= outbuf;
            pkt.size= out_size;

            /* write the compressed frame in the media file */
            ret = av_write_frame(oc, &pkt);
        } else {
            ret = OPENCV_NO_FRAMES_WRITTEN_CODE;
        }
    }
    return ret;
}

/// write a frame with FFMPEG
inline bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int width, int height, int cn, int origin )
{
    bool ret = false;

    if( (width & -2) != frame_width || (height & -2) != frame_height || !data )
        return false;
    width = frame_width;
    height = frame_height;

    // typecast from opaque data type to implemented struct
#if LIBAVFORMAT_BUILD > 4628
    AVCodecContext *c = video_st->codec;
#else
    AVCodecContext *c = &(video_st->codec);
#endif

#if LIBAVFORMAT_BUILD < 5231
    // It is not needed in the latest versions of the ffmpeg
    if( c->codec_id == CODEC_ID_RAWVIDEO && origin != 1 )
    {
        if( !temp_image.data )
        {
            temp_image.step = (width*cn + 3) & -4;
            temp_image.width = width;
            temp_image.height = height;
            temp_image.cn = cn;
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
        }
        for( int y = 0; y < height; y++ )
            memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, width*cn);
        data = temp_image.data;
        step = temp_image.step;
    }
#else
    if( width*cn != step )
    {
        if( !temp_image.data )
        {
            temp_image.step = width*cn;
            temp_image.width = width;
            temp_image.height = height;
            temp_image.cn = cn;
            temp_image.data = (unsigned char*)malloc(temp_image.step*temp_image.height);
        }
        if (origin == 1)
            for( int y = 0; y < height; y++ )
                memcpy(temp_image.data + y*temp_image.step, data + (height-1-y)*step, temp_image.step);
        else
            for( int y = 0; y < height; y++ )
                memcpy(temp_image.data + y*temp_image.step, data + y*step, temp_image.step);
        data = temp_image.data;
        step = temp_image.step;
    }
#endif

    // check parameters
    if (input_pix_fmt == PIX_FMT_BGR24) {
        if (cn != 3) {
            return false;
        }
    }
    else if (input_pix_fmt == PIX_FMT_GRAY8) {
        if (cn != 1) {
            return false;
        }
    }
    else {
        assert(false);
    }

    if ( c->pix_fmt != input_pix_fmt ) {
        assert( input_picture );
        // let input_picture point to the raw data buffer of 'image'
        avpicture_fill((AVPicture *)input_picture, (uint8_t *) data,
                       (PixelFormat)input_pix_fmt, width, height);

        if( !img_convert_ctx )
        {
            img_convert_ctx = sws_getContext(width,
                                             height,
                                             (PixelFormat)input_pix_fmt,
                                             c->width,
                                             c->height,
                                             c->pix_fmt,
                                             SWS_BICUBIC,
                                             NULL, NULL, NULL);
            if( !img_convert_ctx )
                return false;
        }

        if ( sws_scale(img_convert_ctx, input_picture->data,
                       input_picture->linesize, 0,
                       height,
                       picture->data, picture->linesize) < 0 )
            return false;
    }
    else{
        avpicture_fill((AVPicture *)picture, (uint8_t *) data,
                       (PixelFormat)input_pix_fmt, width, height);
    }

    ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, picture) >= 0;

    return ret;
}

/// close video output stream and free associated memory
inline void CvVideoWriter_FFMPEG::close()
{
    unsigned i;

    // nothing to do if already released
    if ( !picture )
        return;

    /* no more frame to compress. The codec has a latency of a few
       frames if using B frames, so we get the last frames by
       passing the same picture again */
    // TODO -- do we need to account for latency here?

    /* write the trailer, if any */
    if(ok && oc)
    {
        if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
        {
            for(;;)
            {
                int ret = icv_av_write_frame_FFMPEG( oc, video_st, outbuf, outbuf_size, NULL);
                if( ret == OPENCV_NO_FRAMES_WRITTEN_CODE || ret < 0 )
                    break;
            }
        }
        av_write_trailer(oc);
    }

    if( img_convert_ctx )
    {
        sws_freeContext(img_convert_ctx);
        img_convert_ctx = 0;
    }

    // free pictures
#if LIBAVFORMAT_BUILD > 4628
    if( video_st->codec->pix_fmt != input_pix_fmt)
#else
    if( video_st->codec.pix_fmt != input_pix_fmt)
#endif
    {
        if(picture->data[0])
            free(picture->data[0]);
        picture->data[0] = 0;
    }
    av_free(picture);

    if (input_picture)
        av_free(input_picture);

    /* close codec */
#if LIBAVFORMAT_BUILD > 4628
    avcodec_close(video_st->codec);
#else
    avcodec_close(&(video_st->codec));
#endif

    av_free(outbuf);

    /* free the streams */
    for(i = 0; i < oc->nb_streams; i++)
    {
        av_freep(&oc->streams[i]->codec);
        av_freep(&oc->streams[i]);
    }

    if (!(fmt->flags & AVFMT_NOFILE))
    {
        /* close the output file */

#if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0)
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0)
        url_fclose(oc->pb);
#else
        url_fclose(&oc->pb);
#endif
#else
        avio_close(oc->pb);
#endif

    }

    /* free the stream */
    av_free(oc);

    if( temp_image.data )
    {
        free(temp_image.data);
        temp_image.data = 0;
    }

    init();
}

/// Create a video writer object that uses FFMPEG
inline bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc,
                                 double fps, int width, int height, bool is_color )
{
    icvInitFFMPEG_internal();

    CodecID codec_id = CODEC_ID_NONE;
    int err, codec_pix_fmt;
    double bitrate_scale = 1;

    close();

    // check arguments
    if( !filename )
        return false;
    if(fps <= 0)
        return false;

    // we allow frames of odd width or height, but in this case we truncate
    // the rightmost column/the bottom row. Probably, this should be handled more elegantly,
    // but some internal functions inside FFMPEG swscale require even width/height.
    width &= -2;
    height &= -2;
    if( width <= 0 || height <= 0 )
        return false;

    /* auto detect the output format from the name and fourcc code. */

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
    fmt = av_guess_format(NULL, filename, NULL);
#else
    fmt = guess_format(NULL, filename, NULL);
#endif

    if (!fmt)
        return false;

    /* determine optimal pixel format */
    if (is_color) {
        input_pix_fmt = PIX_FMT_BGR24;
    }
    else {
        input_pix_fmt = PIX_FMT_GRAY8;
    }

    /* Lookup codec_id for given fourcc */
#if LIBAVCODEC_VERSION_INT<((51<<16)+(49<<8)+0)
    if( (codec_id = codec_get_bmp_id( fourcc )) == CODEC_ID_NONE )
        return false;
#else
    const struct AVCodecTag * tags[] = { codec_bmp_tags, NULL};
    if( (codec_id = av_codec_get_id(tags, fourcc)) == CODEC_ID_NONE )
        return false;
#endif

    // alloc memory for context
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
    oc = avformat_alloc_context();
#else
    oc = av_alloc_format_context();
#endif
    assert (oc);

    /* set file name */
    oc->oformat = fmt;
    _snprintf(oc->filename, sizeof(oc->filename), "%s", filename);

    /* set some options */
    oc->max_delay = (int)(0.7*AV_TIME_BASE);  /* This reduces buffer underrun warnings with MPEG */

    // set a few optimal pixel formats for lossless codecs of interest..
    switch (codec_id) {
#if LIBAVCODEC_VERSION_INT>((50<<16)+(1<<8)+0)
    case CODEC_ID_JPEGLS:
        // BGR24 or GRAY8 depending on is_color...
        codec_pix_fmt = input_pix_fmt;
        break;
#endif
    case CODEC_ID_HUFFYUV:
        codec_pix_fmt = PIX_FMT_YUV422P;
        break;
    case CODEC_ID_MJPEG:
    case CODEC_ID_LJPEG:
        codec_pix_fmt = PIX_FMT_YUVJ420P;
        bitrate_scale = 3;
        break;
    case CODEC_ID_RAWVIDEO:
        codec_pix_fmt = input_pix_fmt == PIX_FMT_GRAY8 ||
                        input_pix_fmt == PIX_FMT_GRAY16LE ||
                        input_pix_fmt == PIX_FMT_GRAY16BE ? input_pix_fmt : PIX_FMT_YUV420P;
        break;
    default:
        // good for lossy formats, MPEG, etc.
        codec_pix_fmt = PIX_FMT_YUV420P;
        break;
    }

    double bitrate = MIN(bitrate_scale*fps*width*height, (double)INT_MAX/2);

    // TODO -- safe to ignore output audio stream?
    video_st = icv_add_video_stream_FFMPEG(oc, codec_id,
                                           width, height, (int)(bitrate + 0.5),
                                           fps, codec_pix_fmt);

    /* set the output parameters (must be done even if no
   parameters). */
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
    if (av_set_parameters(oc, NULL) < 0) {
        return false;
    }
#endif

#if 0
#if FF_API_DUMP_FORMAT
    dump_format(oc, 0, filename, 1);
#else
    av_dump_format(oc, 0, filename, 1);
#endif
#endif

    /* now that all the parameters are set, we can open the audio and
     video codecs and allocate the necessary encode buffers */
    if (!video_st){
        return false;
    }

    AVCodec *codec;
    AVCodecContext *c;

#if LIBAVFORMAT_BUILD > 4628
    c = (video_st->codec);
#else
    c = &(video_st->codec);
#endif

    c->codec_tag = fourcc;
    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
        fprintf(stderr, "Could not find encoder for codec id %d: %s", c->codec_id, icvFFMPEGErrStr(
        #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(53, 2, 0)
                AVERROR_ENCODER_NOT_FOUND
        #else
                -1
        #endif
                ));
        return false;
    }

    s64 lbit_rate = (s64)c->bit_rate;
    lbit_rate += (bitrate / 2);
    lbit_rate = std::min(lbit_rate, (s64)INT_MAX);
    c->bit_rate_tolerance = (int)lbit_rate;
    c->bit_rate = (int)lbit_rate;

    /* open the codec */
    if ((err=
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
         avcodec_open2(c, codec, NULL)
#else
         avcodec_open(c, codec)
#endif
         ) < 0) {
        fprintf(stderr, "Could not open codec '%s': %s", codec->name, icvFFMPEGErrStr(err));
        return false;
    }

    outbuf = NULL;

    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
        /* allocate output buffer */
        /* assume we will never get codec output with more than 4 bytes per pixel... */
        outbuf_size = width*height*4;
        outbuf = (uint8_t *) av_malloc(outbuf_size);
    }

    bool need_color_convert;
    need_color_convert = (c->pix_fmt != input_pix_fmt);

    /* allocate the encoded raw picture */
    picture = icv_alloc_picture_FFMPEG(c->pix_fmt, c->width, c->height, need_color_convert);
    if (!picture) {
        return false;
    }

    /* if the output format is not our input format, then a temporary
   picture of the input format is needed too. It is then converted
   to the required output format */
    input_picture = NULL;
    if ( need_color_convert ) {
        input_picture = icv_alloc_picture_FFMPEG(input_pix_fmt, c->width, c->height, false);
        if (!input_picture) {
            return false;
        }
    }

    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
#if LIBAVFORMAT_BUILD < CALC_FFMPEG_VERSION(53, 2, 0)
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
#else
            if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0)
#endif
            {
            return false;
        }
    }

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    /* write the stream header, if any */
    err=avformat_write_header(oc, NULL);
#else
    err=av_write_header( oc );
#endif

    if(err < 0)
    {
        close();
        remove(filename);
        return false;
    }
    frame_width = width;
    frame_height = height;
    ok = true;
    return true;
}

#endif /* __CAP_FFMPEG_IMPL_H__ */


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocalMBTiles</string>
    <string name="offline_message">No available network found.  Only local MBTiles will be loaded.</string>
</resources>


text:
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using NUnit.Framework;

namespace MongoDB.Bson.Tests.Serialization
{
    [TestFixture]
    public class TestIdGenerators
    {
        private struct S : IEquatable<S>
        {
            public int I;
            public bool Equals(S other)
            {
                return this.I == other.I;
            }
        };

        [Test]
        public void TestGuidIdChecker()
        {
            var idChecker = BsonSerializer.LookupIdGenerator(typeof(Guid));
            Assert.IsTrue(idChecker.IsEmpty(Guid.Empty));
            Assert.IsFalse(idChecker.IsEmpty(Guid.NewGuid()));
        }

        [Test]
        public void TestIntZeroIdChecker()
        {
            var idChecker = new ZeroIdChecker<int>();
            Assert.IsTrue(idChecker.IsEmpty(0));
            Assert.IsFalse(idChecker.IsEmpty(1));
        }

        [Test]
        public void TestNullIdChecker()
        {
            var idChecker = new NullIdChecker();
            Assert.IsTrue(idChecker.IsEmpty(null));
            Assert.IsFalse(idChecker.IsEmpty(new object()));
        }

        [Test]
        public void TestObjectIdChecker()
        {
            var idChecker = BsonSerializer.LookupIdGenerator(typeof(ObjectId));
            Assert.IsTrue(idChecker.IsEmpty(ObjectId.Empty));
            Assert.IsFalse(idChecker.IsEmpty(ObjectId.GenerateNewId()));
        }

        [Test]
        public void TestStructZeroIdChecker()
        {
            var idChecker = new ZeroIdChecker<S>();
            Assert.IsTrue(idChecker.IsEmpty(default(S)));
            Assert.IsTrue(idChecker.IsEmpty(new S()));
            Assert.IsTrue(idChecker.IsEmpty(new S { I = 0 }));
            Assert.IsFalse(idChecker.IsEmpty(new S { I = 1 }));
        }
    }
}


text:
<ns0:DryadDataFile xmlns:ns0="http://purl.org/dryad/schema/terms/v3.1" xmlns:ns2="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://purl.org/dryad/schema/terms/v3.1 http://datadryad.org/profile/v3.1/dryad.xsd">
  <ns2:type>file</ns2:type>
  <ns2:creator>Tur, Cristina</ns2:creator>
  <ns2:creator>Traveset, Anna</ns2:creator>
  <ns2:title>Pollen-transport networks</ns2:title>
  <ns2:identifier>http://dx.doi.org/10.5061/dryad.63fp5/1</ns2:identifier>
  <ns2:rights>http://creativecommons.org/publicdomain/zero/1.0/</ns2:rights>
  <ns2:description>Quantitative matrices of interactions among insect pollinators and plant pollen types for species-species and individuals-species networks at two study sites.</ns2:description>
  <ns2:subject>species-based networks</ns2:subject>
  <ns2:subject>individual-based networks</ns2:subject>
  <ns2:subject>pollen-load analysis</ns2:subject>
  <ns2:subject>pollination networks</ns2:subject>
  <ns2:subject>plant-pollinator interactions</ns2:subject>
  <ns2:spatial>Mallorca</ns2:spatial>
  <ns2:spatial>Balearic Islands (Spain)</ns2:spatial>
  <ns2:dateSubmitted>2013-08-01T16:16:41Z</ns2:dateSubmitted>
  <ns2:available>2013-08-01T16:16:41Z</ns2:available>
  <ns2:provenance>Step: registerPendingPublicationStep - action:registerPendingPublicationAction Entered publication blackout by Dryad Queue(dryad.queue@gmail.com), on 2013-08-01T16:09:11Z (GMT)</ns2:provenance>
  <ns2:provenance>Made available in DSpace on 2013-08-01T16:16:41Z (GMT). No. of bitstreams: 2
weighted_webs.rar: 10394 bytes, checksum: 58ca2f7580bc07b18565cc4bfa27d231 (MD5)
README.txt: 2415 bytes, checksum: f6576d2495b65c04f067961dd8094bf6 (MD5)</ns2:provenance>
  <ns2:isPartOf>http://dx.doi.org/10.5061/dryad.63fp5</ns2:isPartOf>
</ns0:DryadDataFile>


text:
package com.google.acre.javascript.DOM;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.w3c.dom.NodeList;

import com.google.acre.javascript.JSObject;

public class JSNodeList extends JSObject {

    private static final long serialVersionUID = -6538188524200220002L;

    private Object _wrapped;

    public JSNodeList() { }

    public JSNodeList(NodeList nodelist, Scriptable scope) {
        _wrapped = nodelist;
        _scope = scope;
    }

    public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) {
        Scriptable scope = ScriptableObject.getTopLevelScope(ctorObj);
        NodeList nodelist = ((JSNodeList)args[0]).getWrapped();
        return new JSNodeList(nodelist, scope);
    }

    public String getClassName() {
        return "NodeList";
    }

    public int jsGet_length() {
        return ((NodeList)_wrapped).getLength();
    }

    public Scriptable jsFunction_item(int index) {
        return JSNode.makeByNodeType(((NodeList)_wrapped).item(index), _scope);
    }

    public Object get(int index, Scriptable start) {
        return jsFunction_item(index);
    }

    public NodeList getWrapped() {
        return ((NodeList)_wrapped);
    }
}


text:
namespace Machete.X12.Segments
{
    using System;
    using Exceptions;

    public class MissingSegment<TSegment> :
        Segment<TSegment>
        where TSegment : X12Segment
    {
        public Type EntityType => typeof(TSegment);
        public bool IsPresent => false;
        public bool HasValue => false;

        public TSegment Value
        {
            get { throw new SegmentMissingException("The segment is missing."); }
        }
    }
}