text:
import itertools
import logging
from collections import namedtuple
from functools import lru_cache

import cv2
import networkx as nx
import numpy as np
import scipy.spatial as spatial
from networkx.algorithms import bipartite
from opensfm import align
from opensfm import context
from opensfm import dataset
from opensfm import geo
from opensfm import multiview
from opensfm import pybundle
from opensfm import reconstruction

logger = logging.getLogger(__name__)

PartialReconstruction = namedtuple("PartialReconstruction", ["submodel_path", "index"])

def kmeans(samples, nclusters, max_iter=100, attempts=20):
    criteria = (cv2.TERM_CRITERIA_MAX_ITER, max_iter, 1.0)
    flags = cv2.KMEANS_PP_CENTERS

    if context.OPENCV3:
        return cv2.kmeans(samples, nclusters, None, criteria, attempts, flags)
    else:
        return cv2.kmeans(samples, nclusters, criteria, attempts, flags)

def add_cluster_neighbors(positions, labels, centers, max_distance):
    reflla = np.mean(positions, 0)
    reference = geo.TopocentricConverter(reflla[0], reflla[1], 0)

    topocentrics = []
    for position in positions:
        x, y, z = reference.to_topocentric(position[0], position[1], 0)
        topocentrics.append([x, y])

    topocentrics = np.array(topocentrics)
    topo_tree = spatial.cKDTree(topocentrics)

    clusters = []
    for label in np.arange(centers.shape[0]):
        cluster_indices = np.where(labels == label)[0]

        neighbors = []
        for i in cluster_indices:
            neighbors.extend(topo_tree.query_ball_point(topocentrics[i], max_distance))

        cluster = list(np.union1d(cluster_indices, neighbors))
        clusters.append(cluster)

    return clusters

def connected_reconstructions(reconstruction_shots):
    g = nx.Graph()
    for r in reconstruction_shots:
        g.add_node(r, bipartite=0)
        for shot_id in reconstruction_shots[r]:
            g.add_node(shot_id, bipartite=1)
            g.add_edge(r, shot_id)

    p = bipartite.projected_graph(g, reconstruction_shots.keys())

    return p.edges()

def scale_matrix(covariance):
    try:
        L = np.linalg.cholesky(covariance)
    except Exception as e:
        logger.error(
            "Could not compute Cholesky of covariance matrix {}".format(covariance)
        )

        d = np.diag(np.diag(covariance).clip(1e-8, None))
        L = np.linalg.cholesky(d)

    return np.linalg.inv(L)

def invert_similarity(s, A, b):
    s_inv = 1 / s
    A_inv = A.T
    b_inv = -s_inv * A_inv.dot(b)

    return s_inv, A_inv, b_inv

def partial_reconstruction_name(key):
    return str(key.submodel_path) + "_index" + str(key.index)

def add_camera_constraints_soft(ra, reconstruction_shots, reconstruction_name):
    added_shots = set()
    for key in reconstruction_shots:
        shots = reconstruction_shots[key]
        rec_name = reconstruction_name(key)
        ra.add_reconstruction(rec_name, 0, 0, 0, 0, 0, 0, 1, False)
        for shot_id in shots:
            shot = shots[shot_id]
            shot_name = str(shot_id)

            R = shot.pose.rotation
            t = shot.pose.translation

            if shot_id not in added_shots:
                ra.add_shot(shot_name, R[0], R[1], R[2], t[0], t[1], t[2], False)

                gps = shot.metadata.gps_position.value
                gps_sd = shot.metadata.gps_accuracy.value

                ra.add_absolute_position_constraint(
                    shot_name, gps[0], gps[1], gps[2], gps_sd
                )

                added_shots.add(shot_id)

            covariance = np.diag([1e-5, 1e-5, 1e-5, 1e-2, 1e-2, 1e-2])
            sm = scale_matrix(covariance)
            rmc = pybundle.RARelativeMotionConstraint(
                rec_name, shot_name, R[0], R[1], R[2], t[0], t[1], t[2]
            )

            for i in range(6):
                for j in range(6):
                    rmc.set_scale_matrix(i, j, sm[i, j])

            ra.add_relative_motion_constraint(rmc)

def add_camera_constraints_hard(
    ra, reconstruction_shots, reconstruction_name, add_common_camera_constraint
):
    for key in reconstruction_shots:
        shots = reconstruction_shots[key]
        rec_name = reconstruction_name(key)
        ra.add_reconstruction(rec_name, 0, 0, 0, 0, 0, 0, 1, False)
        for shot_id in shots:
            shot = shots[shot_id]
            shot_name = rec_name + str(shot_id)

            R = shot.pose.rotation
            t = shot.pose.translation
            ra.add_shot(shot_name, R[0], R[1], R[2], t[0], t[1], t[2], True)

            gps = shot.metadata.gps_position.value
            gps_sd = shot.metadata.gps_accuracy.value
            ra.add_relative_absolute_position_constraint(
                rec_name, shot_name, gps[0], gps[1], gps[2], gps_sd
            )

    if add_common_camera_constraint:
        connections = connected_reconstructions(reconstruction_shots)
        for connection in connections:
            rec_name1 = reconstruction_name(connection[0])
            rec_name2 = reconstruction_name(connection[1])

            shots1 = reconstruction_shots[connection[0]]
            shots2 = reconstruction_shots[connection[1]]

            common_images = set(shots1.keys()).intersection(shots2.keys())
            for image in common_images:
                ra.add_common_camera_constraint(
                    rec_name1,
                    rec_name1 + str(image),
                    rec_name2,
                    rec_name2 + str(image),
                    1,
                    0.1,
                )

@lru_cache(25)
def load_reconstruction(path, index):
    d1 = dataset.DataSet(path)
    r1 = d1.load_reconstruction()[index]
    g1 = d1.load_tracks_manager()
    return (path + ("_%s" % index)), (r1, g1)

def add_point_constraints(ra, reconstruction_shots, reconstruction_name):
    connections = connected_reconstructions(reconstruction_shots)
    for connection in connections:

        i1, (r1, g1) = load_reconstruction(
            connection[0].submodel_path, connection[0].index
        )
        i2, (r2, g2) = load_reconstruction(
            connection[1].submodel_path, connection[1].index
        )

        rec_name1 = reconstruction_name(connection[0])
        rec_name2 = reconstruction_name(connection[1])

        scale_treshold = 1.3
        treshold_in_meter = 0.3
        minimum_inliers = 20
        status, T, inliers = reconstruction.resect_reconstruction(
            r1, r2, g1, g2, treshold_in_meter, minimum_inliers
        )
        if not status:
            continue

        s, R, t = multiview.decompose_similarity_transform(T)
        if (
            s > scale_treshold
            or s < (1.0 / scale_treshold)
            or len(inliers) < minimum_inliers
        ):
            continue

        for t1, t2 in inliers:
            c1 = r1.points[t1].coordinates
            c2 = r2.points[t2].coordinates

            ra.add_common_point_constraint(
                rec_name1, c1[0], c1[1], c1[2], rec_name2, c2[0], c2[1], c2[2], 1e-1
            )

def load_reconstruction_shots(meta_data):
    reconstruction_shots = {}
    for submodel_path in meta_data.get_submodel_paths():
        data = dataset.DataSet(submodel_path)
        if not data.reconstruction_exists():
            continue

        reconstruction = data.load_reconstruction()
        for index, partial_reconstruction in enumerate(reconstruction):
            key = PartialReconstruction(submodel_path, index)
            reconstruction_shots[key] = partial_reconstruction.shots

    return reconstruction_shots

def align_reconstructions(
    reconstruction_shots,
    reconstruction_name,
    use_points_constraints,
    camera_constraint_type="soft_camera_constraint",
):
    ra = pybundle.ReconstructionAlignment()

    if camera_constraint_type == "soft_camera_constraint":
        add_camera_constraints_soft(ra, reconstruction_shots, reconstruction_name)
    if camera_constraint_type == "hard_camera_constraint":
        add_camera_constraints_hard(ra, reconstruction_shots, reconstruction_name, True)
    if use_points_constraints:
        add_point_constraints(ra, reconstruction_shots, reconstruction_name)

    logger.info("Running alignment")
    ra.run()
    logger.info(ra.brief_report())

    transformations = {}
    for key in reconstruction_shots:
        rec_name = reconstruction_name(key)
        r = ra.get_reconstruction(rec_name)
        s = r.scale
        A = cv2.Rodrigues(np.array([r.rx, r.ry, r.rz]))[0]
        b = np.array([r.tx, r.ty, r.tz])
        transformations[key] = invert_similarity(s, A, b)

    return transformations

def apply_transformations(transformations):
    submodels = itertools.groupby(
        sorted(transformations.keys(), key=lambda key: key.submodel_path),
        lambda key: key.submodel_path,
    )
    for submodel_path, keys in submodels:
        data = dataset.DataSet(submodel_path)
        if not data.reconstruction_exists():
            continue

        reconstruction = data.load_reconstruction()
        for key in keys:
            partial_reconstruction = reconstruction[key.index]
            s, A, b = transformations[key]
            align.apply_similarity(partial_reconstruction, s, A, b)

        data.save_reconstruction(reconstruction, "reconstruction.aligned.json")


text:
{ \
    static type inst(__VA_ARGS__); \
    return inst; \
}

#define NOARG_SINGLETON(name, type) Property &name() \
{ \
    static type inst; \
    return inst; \
}

#define UNDEFINED_SINGLETON(name) NOARG_SINGLETON(name, UndefinedProperty)

using namespace std;

class UndefinedProperty : public Property
{
public:
    virtual bool is_available() {return false;}
    virtual string get_string_value() {return "";}
};

class FirmwareVersionProperty : public Property
{
public:
    virtual bool is_available();
    virtual string get_string_value();
};

bool FirmwareVersionProperty::is_available()
{
    try {
        get_string_value();
        return true;
    } catch (const runtime_error &) {
        return false;
    }
}

string FirmwareVersionProperty::get_string_value()
{
    int fd = open("/setting/updater/dat4", O_RDONLY);
    if (fd < 0)
        throw runtime_error(string_format("Open failed: %d", fd));

    unsigned char version[2];
    if (read(fd, version, sizeof(version)) != sizeof(version))
        throw runtime_error("Read failed");

    if (close(fd))
        throw runtime_error("Close failed");

    return string_format("%x.%02x", version[1], version[0]);
}

NOARG_SINGLETON(prop_firmware_version, FirmwareVersionProperty)

#ifdef API_backup

class BkProperty : public Property
{
protected:
    BackupProperty &property;
public:
    BkProperty(BackupProperty &property) : property(property) {}
    virtual bool is_available();
};

class StringBkProperty : public BkProperty
{
public:
    StringBkProperty(BackupProperty &property) : BkProperty(property) {}
    virtual string get_string_value();
};

class HexBkProperty : public BkProperty
{
public:
    HexBkProperty(BackupProperty &property) : BkProperty(property) {}
    virtual string get_string_value();
};

class BackupRegionProperty : public Property
{
public:
    virtual bool is_available();
    virtual string get_string_value();
};

bool BkProperty::is_available()
{
    return property.is_valid();
}

string StringBkProperty::get_string_value()
{
    return string(&property.read()[0]);
}

string HexBkProperty::get_string_value()
{
    vector<char> value = property.read();
    string str;
    str.reserve(2 * value.size());
    for (vector<char>::iterator it = value.begin(); it != value.end(); it++)
        str += string_format("%02x", *it);
    const char *p = str.c_str();
    while (*p == '0')
        p++;
    return string(p);
}

bool BackupRegionProperty::is_available()
{
    try {
        get_string_value();
        return true;
    } catch (const backup_error &) {
        return false;
    }
}

string BackupRegionProperty::get_string_value()
{
    return Backup_get_region();
}

SINGLETON(prop_android_platform_version, StringBkProperty, bkprop_android_platform_version())
NOARG_SINGLETON(prop_backup_region, BackupRegionProperty)
SINGLETON(prop_model_code, HexBkProperty, bkprop_model_code())
SINGLETON(prop_model_name, StringBkProperty, bkprop_model_name())
SINGLETON(prop_serial_number, HexBkProperty, bkprop_serial_number())

#else

UNDEFINED_SINGLETON(prop_android_platform_version)
UNDEFINED_SINGLETON(prop_backup_region)
UNDEFINED_SINGLETON(prop_model_code)
UNDEFINED_SINGLETON(prop_model_name)
UNDEFINED_SINGLETON(prop_serial_number)

#endif

redpajama_set_name: RedPajamaGithub


text:
package io.scaledml.core.inputformats;

import io.scaledml.core.SparseItem;
import io.scaledml.core.util.LineBytesBuffer;

public class BinaryInputFormat implements InputFormat {

    @Override
    public void parse(LineBytesBuffer line, SparseItem item, long lineNo) {
        item.read(line);
    }
}


text:
using safe_browsing::ClientDownloadResponse;
using safe_browsing::ClientSafeBrowsingReportRequest;

namespace {

const char kDownloadDangerPromptPrefix[] = "Download.DownloadDangerPrompt";

// Converts DownloadDangerType into their corresponding string.
const char* GetDangerTypeString(
    const content::DownloadDangerType& danger_type) {
  switch (danger_type) {
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE:
      return "DangerousFile";
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
      return "DangerousURL";
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
      return "DangerousContent";
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
      return "DangerousHost";
    case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
      return "UncommonContent";
    case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
      return "PotentiallyUnwanted";
    case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS:
    case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT:
    case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED:
    case content::DOWNLOAD_DANGER_TYPE_MAX:
      break;
  }
  NOTREACHED();
  return nullptr;
}

}  // namespace

void DownloadDangerPrompt::SendSafeBrowsingDownloadRecoveryReport(
    bool did_proceed,
    const content::DownloadItem& download) {
  safe_browsing::SafeBrowsingService* sb_service =
      g_browser_process->safe_browsing_service();
  ClientSafeBrowsingReportRequest report;
  report.set_type(ClientSafeBrowsingReportRequest::DANGEROUS_DOWNLOAD_RECOVERY);
  switch (download.GetDangerType()) {
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL:
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT:
      report.set_download_verdict(ClientDownloadResponse::DANGEROUS);
      break;
    case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT:
      report.set_download_verdict(ClientDownloadResponse::UNCOMMON);
      break;
    case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED:
      report.set_download_verdict(ClientDownloadResponse::POTENTIALLY_UNWANTED);
      break;
    case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST:
      report.set_download_verdict(ClientDownloadResponse::DANGEROUS_HOST);
      break;
    default:
      break;
  }
  report.set_url(download.GetURL().spec());
  report.set_did_proceed(did_proceed);

  std::string serialized_report;
  if (report.SerializeToString(&serialized_report))
    sb_service->SendSerializedDownloadReport(serialized_report);
  else
    DLOG(ERROR) << "Unable to serialize the threat report.";
}

void DownloadDangerPrompt::RecordDownloadDangerPrompt(
    bool did_proceed,
    const content::DownloadItem& download) {
  int64_t file_type_uma_value =
      safe_browsing::FileTypePolicies::GetInstance()->UmaValueForFile(
          download.GetTargetFilePath());
  content::DownloadDangerType danger_type = download.GetDangerType();

  UMA_HISTOGRAM_SPARSE_SLOWLY(
      base::StringPrintf("%s.%s.Shown", kDownloadDangerPromptPrefix,
                         GetDangerTypeString(danger_type)),
      file_type_uma_value);
  if (did_proceed) {
    UMA_HISTOGRAM_SPARSE_SLOWLY(
        base::StringPrintf("%s.%s.Proceed", kDownloadDangerPromptPrefix,
                           GetDangerTypeString(danger_type)),
        file_type_uma_value);
  }
}


text:
package com.mainmethod.premofm.helper.opml;

import android.util.Log;

import com.mainmethod.premofm.helper.TextHelper;
import com.mainmethod.premofm.object.Channel;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.Reader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

/** Reads OPML documents. */
public class OpmlReader {
    private static final String TAG = "OpmlReader";

    private boolean isInOpml = false;

    /**
     * Reads an Opml document and returns a list of all OPML elements it can
     * find
     *
     * @throws IOException
     * @throws XmlPullParserException
     */
    public ArrayList<Channel> readDocument(Reader reader)
            throws XmlPullParserException, IOException, NoSuchAlgorithmException {
        ArrayList<Channel> elementList = new ArrayList<>();
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(reader);
        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {

            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:

                    if (xpp.getName().equals(OpmlSymbols.OPML)) {
                        isInOpml = true;
                    } else if (isInOpml && xpp.getName().equals(OpmlSymbols.OUTLINE)) {
                        Channel element = new Channel();

                        final String title = xpp.getAttributeValue(null, OpmlSymbols.TITLE);

                        if (title != null) {
                            Log.i(TAG, "Using title: " + title);
                            element.setTitle(title);
                        } else {
                            Log.i(TAG, "Title not found, using text");
                            element.setTitle(xpp.getAttributeValue(null, OpmlSymbols.TEXT));
                        }
                        element.setFeedUrl(xpp.getAttributeValue(null, OpmlSymbols.XMLURL));
                        element.setSiteUrl(xpp.getAttributeValue(null, OpmlSymbols.HTMLURL));
                        element.setGeneratedId(TextHelper.generateMD5(element.getFeedUrl()));
                        element.setSubscribed(true);

                        if (element.getFeedUrl() != null) {

                            if (element.getTitle() == null) {
                                Log.i(TAG, "Opml element has no text attribute.");
                                element.setTitle(element.getFeedUrl());
                            }
                            elementList.add(element);
                        }
                    }
                    break;
            }
            eventType = xpp.next();
        }
        return elementList;
    }
}


text:
{% load filters %}

        {% if analysis.status == "error" %}

        {% elif analysis.status == "started" %}

        {% elif not analysis.results %}

        {% else %}

        {% endif %}
        {{ analysis.service_name }} (v.{{ analysis.version}})

    Info
    | Log
    | Results
    {% if admin %}
    | Delete
    {% endif %}

Information

Start: {{ analysis.start_date }}

Finish: {{ analysis.finish_date }}

Analyst: {{ analysis.analyst }}

Configuration

{% if analysis.config %}

    {% with config=analysis.config|to_dict %}
        {% for key, value in config.items %}

 {{ key }} : {{ value }}

        {% endfor %}
    {% endwith %}

{% else %}
    No configuration information available.
{% endif %}

Analysis Log

            Level
            Date/Time
            Message

    {% for l in analysis.log %}

            {{ l.level }}
            {{ l.datetime }}
            {{ l.message|linebreaksbr }}

    {% endfor %}

Results

    {% if analysis.template %}
        {% if analysis.template|template_exists %}
            {% include analysis.template %}
        {% else %}

ERROR: Requested custom analysis template {{ analysis.template }} does not exist.

        {% endif %}
    {% else %}
        {% include 'services_results_default.html' %}
    {% endif %}

{% comment %}
{# This will show the raw JSON stored in the database (for debugging) #}
{# Remove comment/endcomment tags to show. #}

{{ analysis|pprint }}

{% endcomment %}


text:
title: Swift 类型转换
author: 但江
avatar: danjiang
location: 成都
category: programming
tag: swift
---

从这篇文章,你将学习到 Swift 的类型转换,类型转换是类独有的特性,让我们开始吧。

![Swift Type Casting](/images/swift-type-casting.jpg)

## 用于类型转换的类层次结构

{% highlight swift %}
class MediaItem {
  var name: String
  init(name: String) {
    self.name = name
  }
}

class Movie: MediaItem {
  var director: String
  init(name: String, director: String) {
    self.director = director
    super.init(name: name)
  }
}

class Song: MediaItem {
  var artist: String
  init(name: String, artist: String) {
    self.artist = artist
    super.init(name: name)
  }
}

let library = [
  Movie(name: "Casablance", director: "Michael Curtiz"),
  Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
  Movie(name: "Citizen Kane", director: "Orson Welles")
]
{% endhighlight %}

## 类型检查

通过 **is** 来检查一个实例是不是确定的子类类型:

{% highlight swift %}
var movieCount = 0
var songCount = 0

for item in library {
  if item is Movie {
    movieCount += 1
  } else if item is Song {
    songCount += 1
  }
}
{% endhighlight %}

## 向下转换

通过 **as?** 或 **as** 来将实例转换为确定的子类实例:

{% highlight swift %}
for item in library {
  if let movie = item as? Movie {
    print("Movie: \(movie.name), dir. \(movie.director)")
  } else if let song = item as? Song {
    print("Song: \(song.name), by \(song.artist)")
  }
}
{% endhighlight %}

## Any 和 AnyObject

* **Any** 代表任何类型的实例,包括函数类型;
* **AnyObject** 代表任何类的实例。

一个 **Any** 的例子:

{% highlight swift %}
var things = [Any]()

things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })

for thing in things {
  switch thing {
  case 0 as Int:
    print("zero as an Int")
  case 0 as Double:
    print("zero as a Double")
  case let someInt as Int:
    print("an integer value of \(someInt)")
  case let someDouble as Double where someDouble > 0:
    print("a positive double value of \(someDouble)")
  case is Double:
    print("some other double value that I don`t want to print")
  case let someString as String:
    print("a string value of \"\(someString)\"")
  case let (x, y) as (Double, Double):
    print("an (x, y) point at \(x), \(y)")
  case let movie as Movie:
    print("a movie called \(movie.name), dir. \(movie.director)")
  case let stringConverter as (String) -> String:
    print(stringConverter("Michael"))
  default:
    print("something else")
  }
}
{% endhighlight %}


text:
package com.consol.citrus.ws.interceptor;

import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.EndpointInterceptor;

/**
 * Endpoint interceptor implementation logging incoming WebService requests and respective responses to
 * the logger in their complete nature (e.g. complete SOAP envelope).
 *
 * For SOAP messages the SOAP envelope content is logged with transformer instance. For
 * WebService requests (other than SOAP) the content is logged via {@link java.io.ByteArrayOutputStream}
 * which is much more expensive as whole message is loaded to internal memory.
 *
 * @author Christoph Deppisch
 */
public class LoggingEndpointInterceptor extends LoggingInterceptorSupport implements EndpointInterceptor {

    /**
     * Write request message to logger.
     */
    public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
        logRequest("Received SOAP request", messageContext, true);

        return true;
    }

    /**
     * Write response message to logger.
     */
    public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
        logResponse("Sending SOAP response", messageContext, false);

        return true;
    }

    /**
     * Write fault message to logger.
     */
    public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
        logResponse("Endpoint sending SOAP fault", messageContext, false);

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
    }
}


text:
package org.opencv.features2d;

import org.opencv.core.Algorithm;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.utils.Converters;

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

// C++: class DescriptorMatcher
//javadoc: DescriptorMatcher
public class DescriptorMatcher extends Algorithm {

    protected DescriptorMatcher(long addr) {
        super(addr);
    }

    public static final int
            FLANNBASED = 1,
            BRUTEFORCE = 2,
            BRUTEFORCE_L1 = 3,
            BRUTEFORCE_HAMMING = 4,
            BRUTEFORCE_HAMMINGLUT = 5,
            BRUTEFORCE_SL2 = 6;

    //
    // C++:  Ptr_DescriptorMatcher clone(bool emptyTrainData = false)
    //

    //javadoc: DescriptorMatcher::clone(emptyTrainData)
    public DescriptorMatcher clone(boolean emptyTrainData) {

        DescriptorMatcher retVal = new DescriptorMatcher(clone_0(nativeObj, emptyTrainData));

        return retVal;
    }

    //javadoc: DescriptorMatcher::clone()
    public DescriptorMatcher clone() {

        DescriptorMatcher retVal = new DescriptorMatcher(clone_1(nativeObj));

        return retVal;
    }

    //
    // C++: static Ptr_DescriptorMatcher create(String descriptorMatcherType)
    //

    //javadoc: DescriptorMatcher::create(descriptorMatcherType)
    public static DescriptorMatcher create(String descriptorMatcherType) {

        DescriptorMatcher retVal = new DescriptorMatcher(create_0(descriptorMatcherType));

        return retVal;
    }

    //
    // C++: static Ptr_DescriptorMatcher create(int matcherType)
    //

    //javadoc: DescriptorMatcher::create(matcherType)
    public static DescriptorMatcher create(int matcherType) {

        DescriptorMatcher retVal = new DescriptorMatcher(create_1(matcherType));

        return retVal;
    }

    //
    // C++:  bool empty()
    //

    //javadoc: DescriptorMatcher::empty()
    public boolean empty() {

        boolean retVal = empty_0(nativeObj);

        return retVal;
    }

    //
    // C++:  bool isMaskSupported()
    //

    //javadoc: DescriptorMatcher::isMaskSupported()
    public boolean isMaskSupported() {

        boolean retVal = isMaskSupported_0(nativeObj);

        return retVal;
    }

    //
    // C++:  vector_Mat getTrainDescriptors()
    //

    //javadoc: DescriptorMatcher::getTrainDescriptors()
    public List<Mat> getTrainDescriptors() {
        List<Mat> retVal = new ArrayList<Mat>();
        Mat retValMat = new Mat(getTrainDescriptors_0(nativeObj));
        Converters.Mat_to_vector_Mat(retValMat, retVal);
        return retVal;
    }

    //
    // C++:  void add(vector_Mat descriptors)
    //

    //javadoc: DescriptorMatcher::add(descriptors)
    public void add(List<Mat> descriptors) {
        Mat descriptors_mat = Converters.vector_Mat_to_Mat(descriptors);
        add_0(nativeObj, descriptors_mat.nativeObj);

        return;
    }

    //
    // C++:  void clear()
    //

    //javadoc: DescriptorMatcher::clear()
    public void clear() {

        clear_0(nativeObj);

        return;
    }

    //
    // C++:  void knnMatch(Mat queryDescriptors, Mat trainDescriptors, vector_vector_DMatch& matches, int k, Mat mask = Mat(), bool compactResult = false)
    //

    //javadoc: DescriptorMatcher::knnMatch(queryDescriptors, trainDescriptors, matches, k, mask, compactResult)
    public void knnMatch(Mat queryDescriptors, Mat trainDescriptors, List<MatOfDMatch> matches, int k, Mat mask, boolean compactResult) {
        Mat matches_mat = new Mat();
        knnMatch_0(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj, k, mask.nativeObj, compactResult);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //javadoc: DescriptorMatcher::knnMatch(queryDescriptors, trainDescriptors, matches, k)
    public void knnMatch(Mat queryDescriptors, Mat trainDescriptors, List<MatOfDMatch> matches, int k) {
        Mat matches_mat = new Mat();
        knnMatch_1(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj, k);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //
    // C++:  void knnMatch(Mat queryDescriptors, vector_vector_DMatch& matches, int k, vector_Mat masks = vector_Mat(), bool compactResult = false)
    //

    //javadoc: DescriptorMatcher::knnMatch(queryDescriptors, matches, k, masks, compactResult)
    public void knnMatch(Mat queryDescriptors, List<MatOfDMatch> matches, int k, List<Mat> masks, boolean compactResult) {
        Mat matches_mat = new Mat();
        Mat masks_mat = Converters.vector_Mat_to_Mat(masks);
        knnMatch_2(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj, k, masks_mat.nativeObj, compactResult);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //javadoc: DescriptorMatcher::knnMatch(queryDescriptors, matches, k)
    public void knnMatch(Mat queryDescriptors, List<MatOfDMatch> matches, int k) {
        Mat matches_mat = new Mat();
        knnMatch_3(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj, k);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //
    // C++:  void match(Mat queryDescriptors, Mat trainDescriptors, vector_DMatch& matches, Mat mask = Mat())
    //

    //javadoc: DescriptorMatcher::match(queryDescriptors, trainDescriptors, matches, mask)
    public void match(Mat queryDescriptors, Mat trainDescriptors, MatOfDMatch matches, Mat mask) {
        Mat matches_mat = matches;
        match_0(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj, mask.nativeObj);

        return;
    }

    //javadoc: DescriptorMatcher::match(queryDescriptors, trainDescriptors, matches)
    public void match(Mat queryDescriptors, Mat trainDescriptors, MatOfDMatch matches) {
        Mat matches_mat = matches;
        match_1(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj);

        return;
    }

    //
    // C++:  void match(Mat queryDescriptors, vector_DMatch& matches, vector_Mat masks = vector_Mat())
    //

    //javadoc: DescriptorMatcher::match(queryDescriptors, matches, masks)
    public void match(Mat queryDescriptors, MatOfDMatch matches, List<Mat> masks) {
        Mat matches_mat = matches;
        Mat masks_mat = Converters.vector_Mat_to_Mat(masks);
        match_2(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj, masks_mat.nativeObj);

        return;
    }

    //javadoc: DescriptorMatcher::match(queryDescriptors, matches)
    public void match(Mat queryDescriptors, MatOfDMatch matches) {
        Mat matches_mat = matches;
        match_3(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj);

        return;
    }

    //
    // C++:  void radiusMatch(Mat queryDescriptors, Mat trainDescriptors, vector_vector_DMatch& matches, float maxDistance, Mat mask = Mat(), bool compactResult = false)
    //

    //javadoc: DescriptorMatcher::radiusMatch(queryDescriptors, trainDescriptors, matches, maxDistance, mask, compactResult)
    public void radiusMatch(Mat queryDescriptors, Mat trainDescriptors, List<MatOfDMatch> matches, float maxDistance, Mat mask, boolean compactResult) {
        Mat matches_mat = new Mat();
        radiusMatch_0(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj, maxDistance, mask.nativeObj, compactResult);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //javadoc: DescriptorMatcher::radiusMatch(queryDescriptors, trainDescriptors, matches, maxDistance)
    public void radiusMatch(Mat queryDescriptors, Mat trainDescriptors, List<MatOfDMatch> matches, float maxDistance) {
        Mat matches_mat = new Mat();
        radiusMatch_1(nativeObj, queryDescriptors.nativeObj, trainDescriptors.nativeObj, matches_mat.nativeObj, maxDistance);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //
    // C++:  void radiusMatch(Mat queryDescriptors, vector_vector_DMatch& matches, float maxDistance, vector_Mat masks = vector_Mat(), bool compactResult = false)
    //

    //javadoc: DescriptorMatcher::radiusMatch(queryDescriptors, matches, maxDistance, masks, compactResult)
    public void radiusMatch(Mat queryDescriptors, List<MatOfDMatch> matches, float maxDistance, List<Mat> masks, boolean compactResult) {
        Mat matches_mat = new Mat();
        Mat masks_mat = Converters.vector_Mat_to_Mat(masks);
        radiusMatch_2(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj, maxDistance, masks_mat.nativeObj, compactResult);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //javadoc: DescriptorMatcher::radiusMatch(queryDescriptors, matches, maxDistance)
    public void radiusMatch(Mat queryDescriptors, List<MatOfDMatch> matches, float maxDistance) {
        Mat matches_mat = new Mat();
        radiusMatch_3(nativeObj, queryDescriptors.nativeObj, matches_mat.nativeObj, maxDistance);
        Converters.Mat_to_vector_vector_DMatch(matches_mat, matches);
        matches_mat.release();
        return;
    }

    //
    // C++:  void read(String fileName)
    //

    //javadoc: DescriptorMatcher::read(fileName)
    public void read(String fileName) {

        read_0(nativeObj, fileName);

        return;
    }

    //
    // C++:  void train()
    //

    //javadoc: DescriptorMatcher::train()
    public void train() {

        train_0(nativeObj);

        return;
    }

    //
    // C++:  void write(String fileName)
    //

    //javadoc: DescriptorMatcher::write(fileName)
    public void write(String fileName) {

        write_0(nativeObj, fileName);

        return;
    }

    @Override
    protected void finalize() throws Throwable {
        delete(nativeObj);
    }

    // C++:  Ptr_DescriptorMatcher clone(bool emptyTrainData = false)
    private static native long clone_0(long nativeObj, boolean emptyTrainData);

    private static native long clone_1(long nativeObj);

    // C++: static Ptr_DescriptorMatcher create(String descriptorMatcherType)
    private static native long create_0(String descriptorMatcherType);

    // C++: static Ptr_DescriptorMatcher create(int matcherType)
    private static native long create_1(int matcherType);

    // C++:  bool empty()
    private static native boolean empty_0(long nativeObj);

    // C++:  bool isMaskSupported()
    private static native boolean isMaskSupported_0(long nativeObj);

    // C++:  vector_Mat getTrainDescriptors()
    private static native long getTrainDescriptors_0(long nativeObj);

    // C++:  void add(vector_Mat descriptors)
    private static native void add_0(long nativeObj, long descriptors_mat_nativeObj);

    // C++:  void clear()
    private static native void clear_0(long nativeObj);

    // C++:  void knnMatch(Mat queryDescriptors, Mat trainDescriptors, vector_vector_DMatch& matches, int k, Mat mask = Mat(), bool compactResult = false)
    private static native void knnMatch_0(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj, int k, long mask_nativeObj, boolean compactResult);

    private static native void knnMatch_1(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj, int k);

    // C++:  void knnMatch(Mat queryDescriptors, vector_vector_DMatch& matches, int k, vector_Mat masks = vector_Mat(), bool compactResult = false)
    private static native void knnMatch_2(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj, int k, long masks_mat_nativeObj, boolean compactResult);

    private static native void knnMatch_3(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj, int k);

    // C++:  void match(Mat queryDescriptors, Mat trainDescriptors, vector_DMatch& matches, Mat mask = Mat())
    private static native void match_0(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj, long mask_nativeObj);

    private static native void match_1(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj);

    // C++:  void match(Mat queryDescriptors, vector_DMatch& matches, vector_Mat masks = vector_Mat())
    private static native void match_2(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj, long masks_mat_nativeObj);

    private static native void match_3(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj);

    // C++:  void radiusMatch(Mat queryDescriptors, Mat trainDescriptors, vector_vector_DMatch& matches, float maxDistance, Mat mask = Mat(), bool compactResult = false)
    private static native void radiusMatch_0(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj, float maxDistance, long mask_nativeObj, boolean compactResult);

    private static native void radiusMatch_1(long nativeObj, long queryDescriptors_nativeObj, long trainDescriptors_nativeObj, long matches_mat_nativeObj, float maxDistance);

    // C++:  void radiusMatch(Mat queryDescriptors, vector_vector_DMatch& matches, float maxDistance, vector_Mat masks = vector_Mat(), bool compactResult = false)
    private static native void radiusMatch_2(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj, float maxDistance, long masks_mat_nativeObj, boolean compactResult);

    private static native void radiusMatch_3(long nativeObj, long queryDescriptors_nativeObj, long matches_mat_nativeObj, float maxDistance);

    // C++:  void read(String fileName)
    private static native void read_0(long nativeObj, String fileName);

    // C++:  void train()
    private static native void train_0(long nativeObj);

    // C++:  void write(String fileName)
    private static native void write_0(long nativeObj, String fileName);

    // native support for java finalize()
    private static native void delete(long nativeObj);

}


text:
use prelude::v1::*;

use ffi::CString;
use io::{self, Error, ErrorKind};
use libc::{self, c_int, c_char, c_void, socklen_t};
use mem;
use net::{IpAddr, SocketAddr, Shutdown};
use num::Int;
use sys::c;
use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
use sys_common::{AsInner, FromInner, IntoInner};

////////////////////////////////////////////////////////////////////////////////
// sockaddr and misc bindings
////////////////////////////////////////////////////////////////////////////////

fn hton<I: Int>(i: I) -> I { i.to_be() }
fn ntoh<I: Int>(i: I) -> I { Int::from_be(i) }

fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
                     payload: T) -> io::Result<()> {
    unsafe {
        let payload = &payload as *const T as *const c_void;
        try!(cvt(libc::setsockopt(*sock.as_inner(), opt, val, payload,
                                  mem::size_of::<T>() as socklen_t)));
        Ok(())
    }
}

#[allow(dead_code)]
fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
                           val: c_int) -> io::Result<T> {
    unsafe {
        let mut slot: T = mem::zeroed();
        let mut len = mem::size_of::<T>() as socklen_t;
        let ret = try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
                                         &mut slot as *mut _ as *mut _,
                                         &mut len)));
        assert_eq!(ret as usize, mem::size_of::<T>());
        Ok(slot)
    }
}

fn sockname<F>(f: F) -> io::Result<SocketAddr>
    where F: FnOnce(*mut libc::sockaddr, *mut socklen_t) -> c_int
{
    unsafe {
        let mut storage: libc::sockaddr_storage = mem::zeroed();
        let mut len = mem::size_of_val(&storage) as socklen_t;
        try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
        sockaddr_to_addr(&storage, len as usize)
    }
}

fn sockaddr_to_addr(storage: &libc::sockaddr_storage,
                    len: usize) -> io::Result<SocketAddr> {
    match storage.ss_family as libc::c_int {
        libc::AF_INET => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in>());
            Ok(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in)
            }))
        }
        libc::AF_INET6 => {
            assert!(len as usize >= mem::size_of::<libc::sockaddr_in6>());
            Ok(FromInner::from_inner(unsafe {
                *(storage as *const _ as *const libc::sockaddr_in6)
            }))
        }
        _ => {
            Err(Error::new(ErrorKind::InvalidInput, "invalid argument", None))
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// get_host_addresses
////////////////////////////////////////////////////////////////////////////////

extern "system" {
    fn getaddrinfo(node: *const c_char, service: *const c_char,
                   hints: *const libc::addrinfo,
                   res: *mut *mut libc::addrinfo) -> c_int;
    fn freeaddrinfo(res: *mut libc::addrinfo);
}

pub struct LookupHost {
    original: *mut libc::addrinfo,
    cur: *mut libc::addrinfo,
}

impl Iterator for LookupHost {
    type Item = io::Result<SocketAddr>;
    fn next(&mut self) -> Option<io::Result<SocketAddr>> {
        unsafe {
            if self.cur.is_null() { return None }
            let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
                                       (*self.cur).ai_addrlen as usize);
            self.cur = (*self.cur).ai_next as *mut libc::addrinfo;
            Some(ret)
        }
    }
}

impl Drop for LookupHost {
    fn drop(&mut self) {
        unsafe { freeaddrinfo(self.original) }
    }
}

pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
    init();

    let c_host = CString::from_slice(host.as_bytes());
    let mut res = 0 as *mut _;
    unsafe {
        try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _,
                                 &mut res)));
        Ok(LookupHost { original: res, cur: res })
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP streams
////////////////////////////////////////////////////////////////////////////////

pub struct TcpStream {
    inner: Socket,
}

impl TcpStream {
    pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        let (addrp, len) = addr.into_inner();
        try!(cvt_r(|| unsafe { libc::connect(*sock.as_inner(), addrp, len) }));
        Ok(TcpStream { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_NODELAY,
                   nodelay as c_int)
    }

    pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> {
        let ret = setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_KEEPALIVE,
                             seconds.is_some() as c_int);
        match seconds {
            Some(n) => ret.and_then(|()| self.set_tcp_keepalive(n)),
            None => ret,
        }
    }

    #[cfg(any(target_os = "macos", target_os = "ios"))]
    fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE,
                   seconds as c_int)
    }
    #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
    fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE,
                   seconds as c_int)
    }
    #[cfg(not(any(target_os = "macos",
                  target_os = "ios",
                  target_os = "freebsd",
                  target_os = "dragonfly")))]
    fn set_tcp_keepalive(&self, _seconds: u32) -> io::Result<()> {
        Ok(())
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let ret = try!(cvt(unsafe {
            libc::send(*self.inner.as_inner(),
                       buf.as_ptr() as *const c_void,
                       buf.len() as wrlen_t,
                       0)
        }));
        Ok(ret as usize)
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getpeername(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        use libc::consts::os::bsd44::SHUT_RDWR;

        let how = match how {
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Both => SHUT_RDWR,
        };
        try!(cvt(unsafe { libc::shutdown(*self.inner.as_inner(), how) }));
        Ok(())
    }

    pub fn duplicate(&self) -> io::Result<TcpStream> {
        self.inner.duplicate().map(|s| TcpStream { inner: s })
    }
}

////////////////////////////////////////////////////////////////////////////////
// TCP listeners
////////////////////////////////////////////////////////////////////////////////

pub struct TcpListener {
    inner: Socket,
}

impl TcpListener {
    pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_STREAM));

        // On platforms with Berkeley-derived sockets, this allows
        // to quickly rebind a socket, without needing to wait for
        // the OS to clean up the previous one.
        if !cfg!(windows) {
            try!(setsockopt(&sock, libc::SOL_SOCKET, libc::SO_REUSEADDR,
                            1 as c_int));
        }

        // Bind our new socket
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));

        // Start listening
        try!(cvt(unsafe { libc::listen(*sock.as_inner(), 128) }));
        Ok(TcpListener { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut len = mem::size_of_val(&storage) as socklen_t;
        let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
                                          &mut len));
        let addr = try!(sockaddr_to_addr(&storage, len as usize));
        Ok((TcpStream { inner: sock, }, addr))
    }

    pub fn duplicate(&self) -> io::Result<TcpListener> {
        self.inner.duplicate().map(|s| TcpListener { inner: s })
    }
}

////////////////////////////////////////////////////////////////////////////////
// UDP
////////////////////////////////////////////////////////////////////////////////

pub struct UdpSocket {
    inner: Socket,
}

impl UdpSocket {
    pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
        init();

        let sock = try!(Socket::new(addr, libc::SOCK_DGRAM));
        let (addrp, len) = addr.into_inner();
        try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) }));
        Ok(UdpSocket { inner: sock })
    }

    pub fn socket(&self) -> &Socket { &self.inner }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        sockname(|buf, len| unsafe {
            libc::getsockname(*self.inner.as_inner(), buf, len)
        })
    }

    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
        let mut addrlen = mem::size_of_val(&storage) as socklen_t;

        let n = try!(cvt(unsafe {
            libc::recvfrom(*self.inner.as_inner(),
                           buf.as_mut_ptr() as *mut c_void,
                           buf.len() as wrlen_t, 0,
                           &mut storage as *mut _ as *mut _, &mut addrlen)
        }));
        Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
    }

    pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
        let (dstp, dstlen) = dst.into_inner();
        let ret = try!(cvt(unsafe {
            libc::sendto(*self.inner.as_inner(),
                         buf.as_ptr() as *const c_void, buf.len() as wrlen_t,
                         0, dstp, dstlen)
        }));
        Ok(ret as usize)
    }

    pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
        setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_BROADCAST,
                   on as c_int)
    }

    pub fn set_multicast_loop(&self, on: bool) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_IP,
                   libc::IP_MULTICAST_LOOP, on as c_int)
    }

    pub fn join_multicast(&self, multi: &IpAddr) -> io::Result<()> {
        match *multi {
            IpAddr::V4(..) => {
                self.set_membership(multi, libc::IP_ADD_MEMBERSHIP)
            }
            IpAddr::V6(..) => {
                self.set_membership(multi, libc::IPV6_ADD_MEMBERSHIP)
            }
        }
    }
    pub fn leave_multicast(&self, multi: &IpAddr) -> io::Result<()> {
        match *multi {
            IpAddr::V4(..) => {
                self.set_membership(multi, libc::IP_DROP_MEMBERSHIP)
            }
            IpAddr::V6(..) => {
                self.set_membership(multi, libc::IPV6_DROP_MEMBERSHIP)
            }
        }
    }
    fn set_membership(&self, addr: &IpAddr, opt: c_int) -> io::Result<()> {
        match *addr {
            IpAddr::V4(ref addr) => {
                let mreq = libc::ip_mreq {
                    imr_multiaddr: *addr.as_inner(),
                    // interface == INADDR_ANY
                    imr_interface: libc::in_addr { s_addr: 0x0 },
                };
                setsockopt(&self.inner, libc::IPPROTO_IP, opt, mreq)
            }
            IpAddr::V6(ref addr) => {
                let mreq = libc::ip6_mreq {
                    ipv6mr_multiaddr: *addr.as_inner(),
                    ipv6mr_interface: 0,
                };
                setsockopt(&self.inner, libc::IPPROTO_IPV6, opt, mreq)
            }
        }
    }

    pub fn multicast_time_to_live(&self, ttl: i32) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_MULTICAST_TTL,
                   ttl as c_int)
    }

    pub fn time_to_live(&self, ttl: i32) -> io::Result<()> {
        setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
    }

    pub fn duplicate(&self) -> io::Result<UdpSocket> {
        self.inner.duplicate().map(|s| UdpSocket { inner: s })
    }
}


text:
package com.johnson.CommonWechatFrontAPi.service;

import com.johnson.CommonWechatFrontAPi.model.compontent.ThemeColor;
import com.johnson.CommonWechatFrontAPi.model.user.UserData;

import java.util.List;

/**
 * Created by johnson on 8/15/2017.
 */
public interface ThemeService {

    List<ThemeColor> list() throws Exception;

    void save(ThemeColor theme) throws Exception;

    void delete(int id) throws Exception;

    ThemeColor findUserTheme(String uuid)throws Exception;

    void saveUserData(UserData userData)throws Exception;

}


text:
#pragma once

namespace stm32plus {
  namespace net {

    /**
     * Application layer feature to provide DNS client functionality
     * for IP name resolution
     */

    template<class TTransportLayer>
    class Dns : public virtual TTransportLayer {

      public:
        struct Parameters {

          uint32_t dns_timeout;               ///< 10000ms is the default. don't go less than 5000 according to RFC 1123
          uint32_t dns_cacheSize;             ///< DNS cache size (default is 20)
          uint8_t dns_retries;                ///< number of times to retry all servers (default is 5)

          Parameters() {
            dns_timeout=10000;
            dns_cacheSize=20;
            dns_retries=5;
          }
        };

        /**
         * error codes
         */

        enum {
          E_TIMEOUT = 1,                      ///< timed out waiting for a response
          E_UNCONFIGURED,                     ///< we haven't been given a DNS server
          E_TIMED_OUT,                        ///< timed out waiting for a response
          E_TRUNCATED_REPLY,                  ///< reply was truncated, which it should not be
          E_SERVER_RECURSION_NOT_SUPPORTED,   ///< the server could not recursively resolve the query
          E_SERVER_ERROR,                     ///< the server returned an error (cause is set)
          E_NO_ANSWERS,                       ///< the server did not return an answer
          E_NO_A_RECORD_IN_ANSWERS,           ///< server did not return an A record in the answers
          E_OUT_OF_MEMORY                     ///< memory allocation failure
        };

      protected:
        Parameters _params;
        uint16_t _queryId;
        uint16_t _replyPort;
        IpAddress _dnsServers[3];
        DnsCache _cache;

        volatile bool _awaitingReply;
        DnsReplyPacket volatile *_replyPacket;

      protected:
        void onNotification(NetEventDescriptor& ned);
        void onReceive(UdpDatagramEvent& ned);
        bool queryServer(const IpAddress& dnsServer,const DnsQueryPacket& packet,uint16_t querySize,IpAddress& ipAddress,uint32_t& ttl);
        bool processQueryResponse(IpAddress& ipAddress,uint32_t& ttl);
        void freeReplyPacket();

      public:
        Dns();
        ~Dns();

        bool initialise(const Parameters& params);
        bool startup();

        bool dnsHostnameQuery(const char *hostname,IpAddress& ipAddress);
    };

    /**
     * Constructor
     */

    template<class TTransportLayer>
    inline Dns<TTransportLayer>::Dns() {

      uint32_t randomNumber;

      _dnsServers[0]=nullptr;
      _replyPacket=nullptr;
      _awaitingReply=false;

      this->nextRandom(randomNumber);
      _queryId=randomNumber;
    }

    /**
     * Destructor
     */

    template<class TTransportLayer>
    inline Dns<TTransportLayer>::~Dns() {
      freeReplyPacket();
    }

    /**
     * Initialise the class
     * @param params The parameters
     * @return true if it worked
     */

    template<class TTransportLayer>
    inline bool Dns<TTransportLayer>::initialise(const Parameters& params) {

      // remember params

      _params=params;

      // create the cache

      if(!_cache.initialise(_params.dns_cacheSize,this->_rtc))
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_OUT_OF_MEMORY);

      // subscribe to notifications and receive events

      this->NetworkNotificationEventSender.insertSubscriber(NetworkNotificationEventSourceSlot::bind(this,&Dns<TTransportLayer>::onNotification));
      this->UdpReceiveEventSender.insertSubscriber(UdpReceiveEventSourceSlot::bind(this,&Dns<TTransportLayer>::onReceive));
      return true;
    }

    /**
     * Startup the feature
     * @return true
     */

    template<class TTransportLayer>
    inline bool Dns<TTransportLayer>::startup() {
      return true;
    }

    /**
     * Notification event notification from the stack
     * @param ned The network event descriptor
     */

    template<class TTransportLayer>
    __attribute__((noinline)) inline void Dns<TTransportLayer>::onNotification(NetEventDescriptor& ned) {

      uint8_t i;

      // only concerned with DNS servers

      if(ned.eventType!=NetEventDescriptor::NetEventType::DNS_SERVERS_ANNOUNCEMENT)
        return;

      IpDnsServersAnnouncementEvent& dnsevent(static_cast<IpDnsServersAnnouncementEvent&>(ned));

      // copy out the valid servers from the event

      for(i=0;i<3;i++)
        if(dnsevent.ipDnsServers[i]!=nullptr && dnsevent.ipDnsServers[i].isValid())
          _dnsServers[i]=*dnsevent.ipDnsServers;

      // invalidate the others

      while(i!=3)
        _dnsServers[i++].invalidate();
    }

    /**
     * This is the basic host namet to IP address lookup functionality
     * @param hostname The host to lookup
     * @param[out] ipAddress The IP address of the host
     * @return true if it worked
     */

    template<class TTransportLayer>
    inline bool Dns<TTransportLayer>::dnsHostnameQuery(const char *hostname,IpAddress& ipAddress) {

      uint16_t querySize;
      uint32_t ttl;
      uint8_t i,retry;

      // special case for localhost

      if(!strcasecmp(hostname,"localhost")) {
        ipAddress.setLocalhost();
        return true;
      }

      // is the association cached?

      if(_cache.lookup(hostname,ipAddress))
        return true;

      // must have at least one server

      if(_dnsServers[0]==nullptr)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_UNCONFIGURED);

      // the size of the query is the hostname+2+header+4

      querySize=DnsPacketHeader::getPacketHeaderSize()+
                strlen(hostname)+2+
                4;

      // allocate the query

      scoped_array<uint8_t> packetData(new uint8_t[querySize]);
      if(packetData.get()==nullptr)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_OUT_OF_MEMORY);

      // create the header and data

      DnsQueryPacket& packet=reinterpret_cast<DnsQueryPacket&>(*(packetData.get()));

      freeReplyPacket();
      _queryId++;
      packet.createQuery(hostname,_queryId);

      // retry for the configured number of times

      for(retry=0;retry<_params.dns_retries;retry++) {

        // run through the list of servers

        for(i=0;i<3 && _dnsServers[i].isValid();i++) {
          if(queryServer(_dnsServers[i],packet,querySize,ipAddress,ttl)) {
            _cache.add(hostname,ipAddress,ttl);
            return true;
          }
        }
      }

      // they all failed, preserve error returned by the last one

      return false;
    }

    /**
     * Query the server and wait for a response
     * @param packet The packet to send
     * @param querySize The size of the packet
     * @param[out] ipAddress The returned IP address mapping
     * @param[out] ttl The time-to-live of the entry in seconds
     * @return true if it worked
     */

    template<class TTransportLayer>
    inline bool Dns<TTransportLayer>::queryServer(const IpAddress& dnsServer,
                                                   const DnsQueryPacket& packet,
                                                   uint16_t querySize,
                                                   IpAddress& ipAddress,
                                                   uint32_t& ttl) {

      uint32_t now;
      bool retval;

      // claim an ephemeral port for the reply

      if(!this->ip_acquireEphemeralPort(_replyPort))
        return false;

      // send the packet asynchronously over UDP to the DHCP server

      _awaitingReply=true;

      if(!this->udpSend(dnsServer,                                  // server to send to
                        _replyPort,                                 // source port
                        IpPorts::PORT_DNS_REQUEST,                  // destination port,
                        reinterpret_cast<const uint8_t *>(&packet), // data
                        querySize,                                  // data size
                        true,                                       // asynchronous flag
                        0)) {                                       // n/a for async
        this->ip_releaseEphemeralPort(_replyPort);
        return false;         // should not happen, async always returns true
      }

      // await a response

      now=MillisecondTimer::millis();
      while(_awaitingReply) {
        if(MillisecondTimer::hasTimedOut(now,_params.dns_timeout)) {
          this->ip_releaseEphemeralPort(_replyPort);
          return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_TIMED_OUT);
        }
      }

      retval=processQueryResponse(ipAddress,ttl);

      freeReplyPacket();
      this->ip_releaseEphemeralPort(_replyPort);
      return retval;
    }

    /**
     * Process the response from the server
     * @param[out] ipAddress The response IP address
     * @param[out] ttl The time-to-live of the entry in seconds
     * @return true if it worked
     */

    template<class TTransportLayer>
    inline bool Dns<TTransportLayer>::processQueryResponse(IpAddress& ipAddress,uint32_t& ttl) {

      uint16_t flags=NetUtil::ntohs(_replyPacket->dns_flags);
      uint8_t *answers,*record;

      // the flags must not have an error (unknown host is picked up here as cause=3)

      if((flags & 0xf)!=0)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_SERVER_ERROR,flags & 0xf);

      // the flags must not indicate truncation

      if((flags & DnsPacketHeader::TRUNCATED)!=0)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_TRUNCATED_REPLY);

      // there must be at least one answer

      if(NetUtil::ntohs(_replyPacket->dns_numberOfAnswerRrs)==0)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_NO_ANSWERS);

      // find the answers

      DnsReplyPacket *packet(const_cast<DnsReplyPacket *>(_replyPacket));
      answers=packet->findAnswers();

      // find the first A record

      if((record=packet->findRecord(answers,DnsPacketHeader::RecordType::A))==nullptr)
        return this->setError(ErrorProvider::ERROR_PROVIDER_NET_DNS,E_NO_A_RECORD_IN_ANSWERS);

      // step over the name (should possibly verify that it's the answer to our question here)

      record=packet->stepOverName(record);

      // pull out the IP address and ttl from the record

      ipAddress.ipAddress=*reinterpret_cast<uint32_t *>(record+10);
      ttl=NetUtil::ntohl(*reinterpret_cast<uint32_t *>(record+4));

      return true;
    }

    /**
     * Receive event notification from the stack
     * @param upe The UDP packet event descriptor
     */

    template<class TTransportLayer>
    __attribute__((noinline)) inline void Dns<TTransportLayer>::onReceive(UdpDatagramEvent& upe) {

      // must be for our reply port

      if(NetUtil::ntohs(upe.udpDatagram.udp_destinationPort)!=_replyPort)
        return;

      // it's considered handled now

      upe.handled=true;

      // handle UDP packets when we're waiting

      if(!_awaitingReply || _replyPacket!=nullptr)
        return;

      // must be a valid packet on the DNS port

      if(NetUtil::ntohs(upe.udpDatagram.udp_sourcePort)!=IpPorts::PORT_DNS_REQUEST ||
         NetUtil::ntohs(upe.udpDatagram.udp_length)<DnsPacketHeader::getPacketHeaderSize())
        return;

      DnsQueryPacket *reply(reinterpret_cast<DnsQueryPacket *>(upe.udpDatagram.udp_data));

      // must be our DNS packet. there is no fixed magic number to indicate that this packet is
      // a DNS response. we only have our ID to go on

      if(NetUtil::ntohs(reply->dns_identification)!=_queryId)
        return;

      // it's for us

      _replyPacket=(DnsReplyPacket *)malloc(upe.udpDatagram.udp_length);
      memcpy(const_cast<DnsReplyPacket *>(_replyPacket),upe.udpDatagram.udp_data,upe.udpDatagram.udp_length);

      // wake up the caller

      _awaitingReply=false;
    }

    /**
     * Free the reply packet
     */

    template<class TTransportLayer>
    inline void Dns<TTransportLayer>::freeReplyPacket() {

      if(_replyPacket) {
        free((void *)_replyPacket);
        _replyPacket=nullptr;
        _awaitingReply=false;
      }
    }
  }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../chat.scss';
import getTimeStamp from '../../utils/getTimeStamp.js';
import MdAccessTime from 'react-icons/lib/md/access-time';
import MdReply from 'react-icons/lib/md/reply';

export default class MessageFooter extends Component {
  reply = () => {
    this.props.updateInputValue(inputValue => `${this.props.message.user.name}, ${inputValue}`);
  };

  render() {
    const { message, isMine } = this.props;
    return (

        {!isMine &&

              {message.user.name}
              <MdAccessTime className={styles.timeIcon} />
              <MdReply className={styles.replyIcon} />

        }

{getTimeStamp(message.createdAt)}

    );
  }
}

MessageFooter.propTypes = {
  message: PropTypes.object,
  isMine: PropTypes.bool,
  updateInputValue: PropTypes.func
};


text:
module Fastlane
  module Actions
    module SharedValues
      HOCKEY_DOWNLOAD_LINK = :HOCKEY_DOWNLOAD_LINK
      HOCKEY_BUILD_INFORMATION = :HOCKEY_BUILD_INFORMATION # contains all keys/values from the HockeyApp API, like :title, :bundle_identifier
    end

    class HockeyAction < Action
      def self.connection(options)
        require 'faraday'
        require 'faraday_middleware'

        base_url = options.delete(:bypass_cdn) ? "https://rink.hockeyapp.net" : "https://upload.hockeyapp.net"
        foptions = {
          url: base_url
        }
        Faraday.new(foptions) do |builder|
          builder.request(:multipart)
          builder.request(:url_encoded)
          builder.response(:json, content_type: /\bjson$/)
          builder.use(FaradayMiddleware::FollowRedirects)
          builder.adapter(:net_http)
        end
      end

      def self.upload(api_token, ipa, options)
        create_update = options.delete(:create_update)

        if create_update
          self.create_and_update_build(api_token, ipa, options)
        else
          self.upload_build(api_token, ipa, options)
        end
      end

      # Uses https://support.hockeyapp.net/kb/api/api-versions#upload-version if a `public_identifier` was specified
      # otherwise https://support.hockeyapp.net/kb/api/api-apps#upload-app
      def self.upload_build(api_token, ipa, options)
        connection = self.connection(options)

        options[:ipa] = Faraday::UploadIO.new(ipa, 'application/octet-stream') if ipa and File.exist?(ipa)

        dsym_filename = options.delete(:dsym_filename)
        if dsym_filename
          options[:dsym] = Faraday::UploadIO.new(dsym_filename, 'application/octet-stream')
        end

        connection.post do |req|
          req.options.timeout = options.delete(:timeout)
          if options[:public_identifier].nil?
            req.url("/api/2/apps/upload")
          else
            req.url("/api/2/apps/#{options.delete(:public_identifier)}/app_versions/upload")
          end
          req.headers['X-HockeyAppToken'] = api_token
          req.body = options
        end
      end

      # Uses https://support.hockeyapp.net/kb/api/api-versions#create-version
      # and https://support.hockeyapp.net/kb/api/api-versions#update-version
      # to upload a build
      def self.create_and_update_build(api_token, ipa, options)
        [:public_identifier, :bundle_short_version, :bundle_version].each do |key|
          UI.user_error!("To use the 'create_update' upload mechanism you need to pass the '#{key.to_sym}' option.") unless options[key]
        end
        # https://support.hockeyapp.net/discussions/problems/33355-is-uploadhockeyappnet-available-for-general-use
        # GET requests are cached on CDN, so bypass it
        options[:bypass_cdn] = true
        connection = self.connection(options)

        options.delete(:ipa)
        options.delete(:apk)
        app_id = options.delete(:public_identifier)

        ipaio = Faraday::UploadIO.new(ipa, 'application/octet-stream') if ipa and File.exist?(ipa)
        dsym = options.delete(:dsym)

        if dsym
          dsym_io = Faraday::UploadIO.new(dsym, 'application/octet-stream') if dsym and File.exist?(dsym)
        end

        # https://support.hockeyapp.net/discussions/problems/83559
        # Should not set status to "2" (downloadable) until after the app is uploaded, so allow the caller
        # to specify a different status for the `create` step
        update_status = options[:status]
        options[:status] = options[:create_status]

        response = connection.get do |req|
          req.url("/api/2/apps/#{app_id}/app_versions/new")
          req.headers['X-HockeyAppToken'] = api_token
          req.body = options
        end

        case response.status
        when 200...300
          app_version_id = response.body['id']
          UI.message("successfully created version with id #{app_version_id}")
        else
          UI.user_error!("Error trying to create app version:  #{response.status} - #{response.body}")
        end

        options[:ipa] = ipaio

        if dsym
          options[:dsym] = dsym_io
        end

        options[:status] = update_status

        connection.put do |req|
          req.options.timeout = options.delete(:timeout)
          req.url("/api/2/apps/#{app_id}/app_versions/#{app_version_id}")
          req.headers['X-HockeyAppToken'] = api_token
          req.body = options
        end
      end

      def self.run(options)
        build_file = [
          options[:ipa],
          options[:apk]
        ].detect { |e| !e.to_s.empty? }

        if options[:dsym]
          dsym_filename = options[:dsym]
        else

          if build_file.nil?
            UI.user_error!("You have to provide a build file (params 'apk' or 'ipa')")
          end

          if options[:ipa].to_s.end_with?(".ipa")
            dsym_path = options[:ipa].to_s.gsub('.ipa', '.app.dSYM.zip')
            if File.exist?(dsym_path)
              dsym_filename = dsym_path
            else
              UI.important("Symbols not found on path #{File.expand_path(dsym_path)}. Crashes won't be symbolicated properly")
              dsym_filename = nil
            end
          end
        end

        UI.user_error!("Symbols on path '#{File.expand_path(dsym_filename)}' not found") if dsym_filename && !File.exist?(dsym_filename)

        if options[:upload_dsym_only]
          UI.success('Starting with dSYM upload to HockeyApp... this could take some time.')
        else
          UI.success('Starting with file(s) upload to HockeyApp... this could take some time.')
        end

        values = options.values
        values[:dsym_filename] = dsym_filename
        values[:notes_type] = options[:notes_type]

        api_token = values.delete(:api_token)

        values.delete_if { |k, v| v.nil? }

        return values if Helper.test?

        ipa_filename = build_file
        ipa_filename = nil if options[:upload_dsym_only]

        response = self.upload(api_token, ipa_filename, values)
        case response.status
        when 200...300
          url = response.body['public_url']

          Actions.lane_context[SharedValues::HOCKEY_DOWNLOAD_LINK] = url
          Actions.lane_context[SharedValues::HOCKEY_BUILD_INFORMATION] = response.body

          UI.message("Public Download URL: #{url}") if url
          UI.success('Build successfully uploaded to HockeyApp!')
        else
          if response.body.to_s.include?("App could not be created")
            UI.user_error!("Hockey has an issue processing this app. Please confirm that an app in Hockey matches this IPA's bundle ID or that you are using the correct API upload token. If error persists, please provide the :public_identifier option from the HockeyApp website. More information https://github.com/fastlane/fastlane/issues/400")
          else
            UI.user_error!("Error when trying to upload file(s) to HockeyApp: #{response.status} - #{response.body}")
          end
        end
      end

      def self.description
        "Upload a new build to HockeyApp"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :apk,
                                       env_name: "FL_HOCKEY_APK",
                                       description: "Path to your APK file",
                                       default_value: Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH],
                                       optional: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Couldn't find apk file at path '#{value}'") unless File.exist?(value)
                                       end,
                                       conflicting_options: [:ipa],
                                       conflict_block: proc do |value|
                                         UI.user_error!("You can't use 'apk' and '#{value.key}' options in one run")
                                       end),
          FastlaneCore::ConfigItem.new(key: :api_token,
                                       env_name: "FL_HOCKEY_API_TOKEN",
                                       sensitive: true,
                                       description: "API Token for Hockey Access",
                                       verify_block: proc do |value|
                                         UI.user_error!("No API token for Hockey given, pass using `api_token: 'token'`") unless value and !value.empty?
                                       end),
          FastlaneCore::ConfigItem.new(key: :ipa,
                                       env_name: "FL_HOCKEY_IPA",
                                       description: "Path to your IPA file. Optional if you use the _gym_ or _xcodebuild_ action. For Mac zip the .app. For Android provide path to .apk file. In addition you could use this to upload .msi, .zip, .pkg, etc if you use the 'create_update' mechanism",
                                       default_value: Actions.lane_context[SharedValues::IPA_OUTPUT_PATH],
                                       optional: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Couldn't find ipa file at path '#{value}'") unless File.exist?(value)
                                       end,
                                       conflicting_options: [:apk],
                                       conflict_block: proc do |value|
                                         UI.user_error!("You can't use 'ipa' and '#{value.key}' options in one run")
                                       end),
          FastlaneCore::ConfigItem.new(key: :dsym,
                                       env_name: "FL_HOCKEY_DSYM",
                                       description: "Path to your symbols file. For iOS and Mac provide path to app.dSYM.zip. For Android provide path to mappings.txt file",
                                       default_value: Actions.lane_context[SharedValues::DSYM_OUTPUT_PATH],
                                       optional: true,
                                       verify_block: proc do |value|
                                         # validation is done in the action
                                       end),
          FastlaneCore::ConfigItem.new(key: :create_update,
                                       env_name: "FL_HOCKEY_CREATE_UPDATE",
                                       description: "Set true if you want to create then update your app as opposed to just upload it."\
                                         " You will need the 'public_identifier', 'bundle_version' and 'bundle_short_version'",
                                       is_string: false,
                                       default_value: false,
                                       verify_block: proc do |value|
                                         # validation is done in the action
                                       end),
          FastlaneCore::ConfigItem.new(key: :notes,
                                       env_name: "FL_HOCKEY_NOTES",
                                       description: "Beta Notes",
                                       default_value: Actions.lane_context[SharedValues::FL_CHANGELOG] || "No changelog given"),
          FastlaneCore::ConfigItem.new(key: :notify,
                                       env_name: "FL_HOCKEY_NOTIFY",
                                       description: "Notify testers? \"1\" for yes",
                                       default_value: "1"),
          FastlaneCore::ConfigItem.new(key: :status,
                                       env_name: "FL_HOCKEY_STATUS",
                                       description: "Download status: \"1\" = No user can download; \"2\" = Available for download (only possible with full-access token)",
                                       default_value: "2"),
          FastlaneCore::ConfigItem.new(key: :create_status,
                                       env_name: "FL_HOCKEY_CREATE_STATUS",
                                       description: "Download status for initial version creation when create_update is true: \"1\" = No user can download; \"2\" = Available for download (only possible with full-access token)",
                                       default_value: "2"),
          FastlaneCore::ConfigItem.new(key: :notes_type,
                                      env_name: "FL_HOCKEY_NOTES_TYPE",
                                      description: "Notes type for your :notes, \"0\" = Textile, \"1\" = Markdown (default)",
                                      default_value: "1"),
          FastlaneCore::ConfigItem.new(key: :release_type,
                                      env_name: "FL_HOCKEY_RELEASE_TYPE",
                                      description: "Release type of the app: \"0\" = Beta (default), \"1\" = Store, \"2\" = Alpha, \"3\" = Enterprise",
                                      default_value: "0"),
          FastlaneCore::ConfigItem.new(key: :mandatory,
                                      env_name: "FL_HOCKEY_MANDATORY",
                                      description: "Set to \"1\" to make this update mandatory",
                                      default_value: "0"),
          FastlaneCore::ConfigItem.new(key: :teams,
                                      env_name: "FL_HOCKEY_TEAMS",
                                      description: "Comma separated list of team ID numbers to which this build will be restricted",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :users,
                                      env_name: "FL_HOCKEY_USERS",
                                      description: "Comma separated list of user ID numbers to which this build will be restricted",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :tags,
                                      env_name: "FL_HOCKEY_TAGS",
                                      description: "Comma separated list of tags which will receive access to the build",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :bundle_short_version,
                                      env_name: "FL_HOCKEY_BUNDLE_SHORT_VERSION",
                                      description: "The bundle_short_version of your application, required when using `create_update`",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :bundle_version,
                                      env_name: "FL_HOCKEY_BUNDLE_VERSION",
                                      description: "The bundle_version of your application, required when using `create_update`",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :public_identifier,
                                      env_name: "FL_HOCKEY_PUBLIC_IDENTIFIER",
                                      description: "App id of the app you are targeting, usually you won't need this value. Required, if `upload_dsym_only` set to `true`",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :commit_sha,
                                      env_name: "FL_HOCKEY_COMMIT_SHA",
                                      description: "The Git commit SHA for this build",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :repository_url,
                                      env_name: "FL_HOCKEY_REPOSITORY_URL",
                                      description: "The URL of your source repository",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :build_server_url,
                                      env_name: "FL_HOCKEY_BUILD_SERVER_URL",
                                      description: "The URL of the build job on your build server",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :upload_dsym_only,
                                      env_name: "FL_HOCKEY_UPLOAD_DSYM_ONLY",
                                      description: "Flag to upload only the dSYM file to hockey app",
                                      is_string: false,
                                      default_value: false),
          FastlaneCore::ConfigItem.new(key: :owner_id,
                                      env_name: "FL_HOCKEY_OWNER_ID",
                                      description: "ID for the owner of the app",
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :strategy,
                                       env_name: "FL_HOCKEY_STRATEGY",
                                       description: "Strategy: 'add' = to add the build as a new build even if it has the same build number (default); 'replace' = to replace a build with the same build number",
                                       default_value: "add",
                                       verify_block: proc do |value|
                                         UI.user_error!("Invalid value '#{value}' for key 'strategy'. Allowed values are 'add', 'replace'.") unless ['add', 'replace'].include?(value)
                                       end),
          FastlaneCore::ConfigItem.new(key: :timeout,
                                      env_name: "FL_HOCKEY_TIMEOUT",
                                      description: "Request timeout in seconds",
                                      is_string: false,
                                      optional: true),
          FastlaneCore::ConfigItem.new(key: :bypass_cdn,
                                      env_name: "FL_HOCKEY_BYPASS_CDN",
                                      description: "Flag to bypass Hockey CDN when it uploads successfully but reports error",
                                      is_string: false,
                                      default_value: false),
          FastlaneCore::ConfigItem.new(key: :dsa_signature,
                                      env_name: "FL_HOCKEY_DSA_SIGNATURE",
                                      description: "DSA signature for sparkle updates for macOS",
                                      is_string: true,
                                      default_value: "",
                                      optional: true)
        ]
      end

      def self.output
        [
          ['HOCKEY_DOWNLOAD_LINK', 'The newly generated download link for this build'],
          ['HOCKEY_BUILD_INFORMATION', 'contains all keys/values from the HockeyApp API, like :title, :bundle_identifier']
        ]
      end

      def self.author
        ["KrauseFx", "modzelewski", "lacostej"]
      end

      def self.is_supported?(platform)
        true
      end

      def self.details
        [
          "Symbols will also be uploaded automatically if a `app.dSYM.zip` file is found next to `app.ipa`. In case it is located in a different place you can specify the path explicitly in `:dsym` parameter.",
          "More information about the available options can be found in the [HockeyApp Docs](http://support.hockeyapp.net/kb/api/api-versions#upload-version)."
        ].join("\n")
      end

      def self.example_code
        [
          'hockey(
            api_token: "...",
            ipa: "./app.ipa",
            notes: "Changelog"
          )',
          'hockey(
            api_token: "...",
            create_update: true,
            public_identifier: "....",
            bundle_short_version: "1.0.2",
            bundle_version: "1.0.2.145",
            ipa: "./my.msi",
            notes: "Changelog"
          )'
        ]
      end

      def self.category
        :beta
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<item>
<userName>shieldwatch</userName>
<passWord>test123</passWord>
<dataProcessFor>1</dataProcessFor>
<Company FormType='W2'>
<PayerInfo>
<TIN>56679988</TIN>
<Year>2015</Year>
<TypeOfTIN>4</TypeOfTIN>
<TransferAgentIndicator>0</TransferAgentIndicator>
<CompanyName>ABC Company</CompanyName>
<CompanyNameLine2>ABC Company</CompanyNameLine2>
<CompanyAddress>123 Some Street</CompanyAddress>
<City>Some City</City>
<State>ST</State>
<Zipcode>123445</Zipcode>
<Phone>8152264352</Phone>
</PayerInfo>
<Recipient id="11">
<PayeeTIN>374476543</PayeeTIN>
<PayeeTypeOfTIN>1</PayeeTypeOfTIN>
<PayeeName>RONALDO TRUEDOE</PayeeName>
<PayeeName2>RE</PayeeName2>
<PayeeAddr>111 S PALMTREE CT</PayeeAddr>
<PayeeCity>SOMECITY</PayeeCity>
<PayeeState>OK</PayeeState>
<PayeeZipcode>743451111</PayeeZipcode>
<Box1>452.67</Box1>
<Box2>125.51</Box2>
<AcctNumber>0245896005</AcctNumber>
<EmploymentType>R</EmploymentType>
<StateNameOne>KY</StateNameOne>
<StateIdOne>822963</StateIdOne>
<Box14TextOne>KJDA 289.23</Box14TextOne>
<Code_a>S</Code_a>
<Amt_a>1825.00</Amt_a>
<StatutoryInd>false</StatutoryInd>
<RetirementPlanInd>true</RetirementPlanInd>
<ThirdPartySickPayInd>false</ThirdPartySickPayInd>
<W2ControlNumber>255-8B</W2ControlNumber>
<FITWithh>3459.00</FITWithh>
<MedicareWithh>623.16</MedicareWithh>
<MedWagesAndTips>42976.25</MedWagesAndTips>
<SocSecWages>42976.25</SocSecWages>
<SocSecWithh>2664.53</SocSecWithh>
<StateTaxWithhOne>1663.00</StateTaxWithhOne>
<StateWagesTipsEtcOne>41151.25</StateWagesTipsEtcOne>
<WagesTipsOtherComp>41151.25</WagesTipsOtherComp>
</Recipient>
</Company>
</item>
</gwx:DataPacket>