text:
#pragma once
#include <aws/networkmanager/NetworkManager_EXPORTS.h>
#include <aws/networkmanager/NetworkManagerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/networkmanager/model/AWSLocation.h>
#include <aws/networkmanager/model/Location.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/networkmanager/model/Tag.h>
#include <utility>

namespace Aws
{
namespace NetworkManager
{
namespace Model
{

  /**
   */
  class AWS_NETWORKMANAGER_API CreateDeviceRequest : public NetworkManagerRequest
  {
  public:
    CreateDeviceRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateDevice"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ID of the global network.

     */
    inline const Aws::String& GetGlobalNetworkId() const{ return m_globalNetworkId; }

    /**
     *
The ID of the global network.

     */
    inline bool GlobalNetworkIdHasBeenSet() const { return m_globalNetworkIdHasBeenSet; }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(const Aws::String& value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId = value; }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(Aws::String&& value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId = std::move(value); }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(const char* value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId.assign(value); }

    /**
     *
The ID of the global network.

     */
    inline CreateDeviceRequest& WithGlobalNetworkId(const Aws::String& value) { SetGlobalNetworkId(value); return *this;}

    /**
     *
The ID of the global network.

     */
    inline CreateDeviceRequest& WithGlobalNetworkId(Aws::String&& value) { SetGlobalNetworkId(std::move(value)); return *this;}

    /**
     *
The ID of the global network.

     */
    inline CreateDeviceRequest& WithGlobalNetworkId(const char* value) { SetGlobalNetworkId(value); return *this;}

    /**
     *
The AWS location of the device.

     */
    inline const AWSLocation& GetAWSLocation() const{ return m_aWSLocation; }

    /**
     *
The AWS location of the device.

     */
    inline bool AWSLocationHasBeenSet() const { return m_aWSLocationHasBeenSet; }

    /**
     *
The AWS location of the device.

     */
    inline void SetAWSLocation(const AWSLocation& value) { m_aWSLocationHasBeenSet = true; m_aWSLocation = value; }

    /**
     *
The AWS location of the device.

     */
    inline void SetAWSLocation(AWSLocation&& value) { m_aWSLocationHasBeenSet = true; m_aWSLocation = std::move(value); }

    /**
     *
The AWS location of the device.

     */
    inline CreateDeviceRequest& WithAWSLocation(const AWSLocation& value) { SetAWSLocation(value); return *this;}

    /**
     *
The AWS location of the device.

     */
    inline CreateDeviceRequest& WithAWSLocation(AWSLocation&& value) { SetAWSLocation(std::move(value)); return *this;}

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline CreateDeviceRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline CreateDeviceRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
A description of the device.

Length Constraints: Maximum length of 256
     * characters.

     */
    inline CreateDeviceRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The type of the device.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
The type of the device.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of the device.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of the device.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of the device.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
The type of the device.

     */
    inline CreateDeviceRequest& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
The type of the device.

     */
    inline CreateDeviceRequest& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
The type of the device.

     */
    inline CreateDeviceRequest& WithType(const char* value) { SetType(value); return *this;}

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline const Aws::String& GetVendor() const{ return m_vendor; }

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline bool VendorHasBeenSet() const { return m_vendorHasBeenSet; }

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetVendor(const Aws::String& value) { m_vendorHasBeenSet = true; m_vendor = value; }

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetVendor(Aws::String&& value) { m_vendorHasBeenSet = true; m_vendor = std::move(value); }

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetVendor(const char* value) { m_vendorHasBeenSet = true; m_vendor.assign(value); }

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithVendor(const Aws::String& value) { SetVendor(value); return *this;}

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithVendor(Aws::String&& value) { SetVendor(std::move(value)); return *this;}

    /**
     *
The vendor of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithVendor(const char* value) { SetVendor(value); return *this;}

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline const Aws::String& GetModel() const{ return m_model; }

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline bool ModelHasBeenSet() const { return m_modelHasBeenSet; }

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetModel(const Aws::String& value) { m_modelHasBeenSet = true; m_model = value; }

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetModel(Aws::String&& value) { m_modelHasBeenSet = true; m_model = std::move(value); }

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline void SetModel(const char* value) { m_modelHasBeenSet = true; m_model.assign(value); }

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithModel(const Aws::String& value) { SetModel(value); return *this;}

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithModel(Aws::String&& value) { SetModel(std::move(value)); return *this;}

    /**
     *
The model of the device.

Length Constraints: Maximum length of 128
     * characters.

     */
    inline CreateDeviceRequest& WithModel(const char* value) { SetModel(value); return *this;}

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline const Aws::String& GetSerialNumber() const{ return m_serialNumber; }

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline bool SerialNumberHasBeenSet() const { return m_serialNumberHasBeenSet; }

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline void SetSerialNumber(const Aws::String& value) { m_serialNumberHasBeenSet = true; m_serialNumber = value; }

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline void SetSerialNumber(Aws::String&& value) { m_serialNumberHasBeenSet = true; m_serialNumber = std::move(value); }

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline void SetSerialNumber(const char* value) { m_serialNumberHasBeenSet = true; m_serialNumber.assign(value); }

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline CreateDeviceRequest& WithSerialNumber(const Aws::String& value) { SetSerialNumber(value); return *this;}

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline CreateDeviceRequest& WithSerialNumber(Aws::String&& value) { SetSerialNumber(std::move(value)); return *this;}

    /**
     *
The serial number of the device.

Length Constraints: Maximum length of
     * 128 characters.

     */
    inline CreateDeviceRequest& WithSerialNumber(const char* value) { SetSerialNumber(value); return *this;}

    /**
     *
The location of the device.

     */
    inline const Location& GetLocation() const{ return m_location; }

    /**
     *
The location of the device.

     */
    inline bool LocationHasBeenSet() const { return m_locationHasBeenSet; }

    /**
     *
The location of the device.

     */
    inline void SetLocation(const Location& value) { m_locationHasBeenSet = true; m_location = value; }

    /**
     *
The location of the device.

     */
    inline void SetLocation(Location&& value) { m_locationHasBeenSet = true; m_location = std::move(value); }

    /**
     *
The location of the device.

     */
    inline CreateDeviceRequest& WithLocation(const Location& value) { SetLocation(value); return *this;}

    /**
     *
The location of the device.

     */
    inline CreateDeviceRequest& WithLocation(Location&& value) { SetLocation(std::move(value)); return *this;}

    /**
     *
The ID of the site.

     */
    inline const Aws::String& GetSiteId() const{ return m_siteId; }

    /**
     *
The ID of the site.

     */
    inline bool SiteIdHasBeenSet() const { return m_siteIdHasBeenSet; }

    /**
     *
The ID of the site.

     */
    inline void SetSiteId(const Aws::String& value) { m_siteIdHasBeenSet = true; m_siteId = value; }

    /**
     *
The ID of the site.

     */
    inline void SetSiteId(Aws::String&& value) { m_siteIdHasBeenSet = true; m_siteId = std::move(value); }

    /**
     *
The ID of the site.

     */
    inline void SetSiteId(const char* value) { m_siteIdHasBeenSet = true; m_siteId.assign(value); }

    /**
     *
The ID of the site.

     */
    inline CreateDeviceRequest& WithSiteId(const Aws::String& value) { SetSiteId(value); return *this;}

    /**
     *
The ID of the site.

     */
    inline CreateDeviceRequest& WithSiteId(Aws::String&& value) { SetSiteId(std::move(value)); return *this;}

    /**
     *
The ID of the site.

     */
    inline CreateDeviceRequest& WithSiteId(const char* value) { SetSiteId(value); return *this;}

    /**
     *
The tags to apply to the resource during creation.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
The tags to apply to the resource during creation.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
The tags to apply to the resource during creation.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The tags to apply to the resource during creation.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
The tags to apply to the resource during creation.

     */
    inline CreateDeviceRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
The tags to apply to the resource during creation.

     */
    inline CreateDeviceRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The tags to apply to the resource during creation.

     */
    inline CreateDeviceRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
The tags to apply to the resource during creation.

     */
    inline CreateDeviceRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_globalNetworkId;
    bool m_globalNetworkIdHasBeenSet;

    AWSLocation m_aWSLocation;
    bool m_aWSLocationHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;

    Aws::String m_type;
    bool m_typeHasBeenSet;

    Aws::String m_vendor;
    bool m_vendorHasBeenSet;

    Aws::String m_model;
    bool m_modelHasBeenSet;

    Aws::String m_serialNumber;
    bool m_serialNumberHasBeenSet;

    Location m_location;
    bool m_locationHasBeenSet;

    Aws::String m_siteId;
    bool m_siteIdHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;
  };

} // namespace Model
} // namespace NetworkManager
} // namespace Aws


text:
#ifndef __VDS_WEB_SERVER_WEB_SERVER_P_H_
#define __VDS_WEB_SERVER_WEB_SERVER_P_H_
#include "tcp_socket_server.h"
#include "http_router.h"
#include "http_serializer.h"
#include "http_pipeline.h"

namespace vds {
  class _ws_http_server : public std::enable_shared_from_this<_ws_http_server>
  {
  public:
    _ws_http_server(const service_provider * sp);
    ~_ws_http_server();

    vds::async_task<vds::expected<void>> start(uint16_t port);
    vds::async_task<vds::expected<void>> prepare_to_stop();

    //void add_auth_session(
    //    const std::string & id,
    //    const std::shared_ptr<auth_session> & session);

    //std::shared_ptr<auth_session> get_session(
    //
    //  const std::string & session_id) const;

    //void kill_session(const std::string& session_id);

    //async_task<expected<std::tuple<bool, std::shared_ptr<stream_output_async<uint8_t>>>>> not_found_handler(
    //  const std::shared_ptr<http_async_serializer> & output_stream,
    //  const http_message& request);

  private:
    const service_provider * sp_;
    tcp_socket_server server_;
    http_router router_;

    //mutable std::shared_mutex auth_session_mutex_;
    //std::map<std::string, std::shared_ptr<auth_session>> auth_sessions_;
    //timer update_timer_;

    //std::shared_ptr<user_manager> www_user_mng_;

    //std::shared_ptr<user_manager> get_secured_context(
    //  const std::string & session_id) const;

    struct session_data : public std::enable_shared_from_this<session_data> {
      std::shared_ptr<vds::stream_output_async<uint8_t>> target_;
      std::shared_ptr<vds::http_async_serializer> stream_;
      std::shared_ptr<vds::http_pipeline> handler_;

      session_data(
        const service_provider * sp,
        const std::shared_ptr<vds::stream_output_async<uint8_t>> & target)
        : target_(target),
          stream_(std::make_shared<vds::http_async_serializer>(sp, target)) {
      }
    };

    async_task<expected<std::shared_ptr<stream_output_async<uint8_t>>>> process_message(
      const std::shared_ptr<http_async_serializer> & output_stream,
      const std::shared_ptr<session_data> & session,
      vds::http_message request);
  };
}

#endif // __VDS_WEB_SERVER_WEB_SERVER_P_H_

redpajama_set_name: RedPajamaGithub


text:
/*******************************************************************\

Module:

Author: Daniel Kroening, kroening@kroening.com

\*******************************************************************/

#ifndef CPROVER_SIMPLIFY_EXPR_CLASS_H
#define CPROVER_SIMPLIFY_EXPR_CLASS_H

#include <hash_cont.h>
#include <map>
#include <set>

#include <expr.h>
#include <mp_arith.h>
#include <threeval.h>
#include <std_expr.h>

#define forall_value_list(it, value_list) \
  for(simplify_exprt::value_listt::const_iterator it=(value_list).begin(); \
      it!=(value_list).end(); it++)

class simplify_exprt
{
public:
  bool do_simplify_if;

  typedef enum { NORMAL, ADDRESS_OF } modet;

  bool simplify_typecast(exprt &expr, modet mode);
  bool simplify_concatenation(exprt &expr);
  bool simplify_multiplication(exprt &expr);
  bool simplify_division(exprt &expr);
  bool simplify_modulo(exprt &expr);
  bool simplify_addition_substraction(exprt &expr, modet mode);
  bool simplify_shifts(exprt &expr);
  bool simplify_bitwise(exprt &expr);
  bool simplify_if_implies(exprt &expr, const exprt &cond, bool truth, bool &new_truth);
  bool simplify_if_recursive(exprt &expr, const exprt &cond, bool truth);
  bool simplify_if_conj(exprt &expr, const exprt &cond);
  bool simplify_if_disj(exprt &expr, const exprt &cond);
  bool simplify_if_branch(exprt &trueexpr, exprt &falseexpr, const exprt &cond, modet mode);
  bool simplify_if_cond(exprt &expr, modet mode);
  bool simplify_if(exprt &expr);
  bool simplify_switch(exprt &expr);
  bool simplify_bitnot(exprt &expr);
  bool simplify_not(exprt &expr, modet mode);
  bool simplify_boolean(exprt &expr, modet mode);
  bool simplify_inequality(exprt &expr, modet mode);
  bool simplify_inequality_constant(exprt &expr, modet mode);
  bool simplify_inequality_not_constant(exprt &expr, modet mode);
  bool simplify_relation(exprt &expr, modet mode);
  bool simplify_ieee_float_relation(exprt &expr);
  bool simplify_with(exprt &expr);
  bool simplify_index(index_exprt &expr, modet mode);
  bool simplify_member(member_exprt &expr);
  bool simplify_pointer_object(exprt &expr);
  bool simplify_dynamic_size(exprt &expr);
  bool simplify_is_dynamic_object(exprt &expr);
  bool simplify_same_object(exprt &expr);
  bool simplify_valid_object(exprt &expr);
  bool simplify_object(exprt &expr);
  static tvt objects_equal(const exprt &a, const exprt &b);
  static tvt objects_equal_address_of(const exprt &a, const exprt &b);
  bool sort_and_join(exprt &expr);
  bool simplify_unary_minus(exprt &expr);
  bool simplify_dereference(exprt &expr);
  bool simplify_address_of(exprt &expr);
  bool simplify_pointer_offset(exprt &expr);
  bool eliminate_common_addends(exprt &op0, exprt &op1);
  exprt pointer_offset(const exprt &expr, const typet &type);

  virtual bool simplify_node(exprt &expr, modet mode);
  virtual bool simplify_rec(exprt &expr, modet mode);

  virtual bool simplify(exprt &expr)
  {
    return simplify_rec(expr, NORMAL);
  }

  virtual ~simplify_exprt()
  {
  }

  typedef std::set<mp_integer> value_listt;
  bool get_values(const exprt &expr, value_listt &value_list);

  simplify_exprt():do_simplify_if(true)
  {
  }

  static bool is_bitvector_type(const typet &type)
  {
    return type.id()=="unsignedbv" || type.id()=="signedbv" || type.id()=="bv";
  }
};

bool sort_and_join(const std::string &id, const std::string &type_id);

#endif


text:
package nz.co.doltech.gwtjssor.client.options;

import com.google.gwt.core.client.JavaScriptObject;

public class ThumbnailOptions extends JavaScriptObject {

    protected ThumbnailOptions() {}

    public native final void setClass(JavaScriptObject classJso) /*-{
        this.$Class = classJso;
    }-*/;

    public native final void setCols(int cols) /*-{
        this.$Cols = cols;
    }-*/;

    public native final void setSpacingX(int spacingX) /*-{
        this.$SpacingX = spacingX;
    }-*/;

    public native final void setSpacingY(int spacingY) /*-{
        this.$SpacingY = spacingY;
    }-*/;

    public native final void setAlign(int align) /*-{
        this.$Align = align;
    }-*/;

    public native final void setDefaults() /*-{
        this.$Class = $wnd.$JssorThumbnailNavigator$;
        this.$Cols = 10;
        this.$SpacingX = 8;
        this.$SpacingY = 8;
        this.$Align = 360;
    }-*/;

    public static ThumbnailOptions create() {
        ThumbnailOptions opt = JavaScriptObject.createObject().cast();
        opt.setDefaults();
        return opt;
    }
}


text:
package com.example.android.quakereport;

import java.util.Date;

/**
 * Created by tomas on 21.01.2017.
 */

public class Earthquake {

    /** Location of earthquake */
    private String mEarthquakePlace;

    /** magnitude of earthquake */
    private double  mEarthquakeMag;

    /** Image resource ID for the word */
    private String mEarthquakeDate;
    /**
     * Create a new Word object.
     *
     * @param earthquakePlace is name of location that earthquake took place
     * @param earthquakeMag magnitude of earthquake
     * @param earthquakeDate is date when  earthquake took place    */

    public Earthquake(String earthquakePlace, double earthquakeMag, String earthquakeDate) {
        mEarthquakePlace = earthquakePlace;
        mEarthquakeMag = earthquakeMag;
        mEarthquakeDate =  earthquakeDate;
    }

    /**
     * Get the place of earthquake.
     */
    public String getEarthquakePlace() {
        return mEarthquakePlace;
    }

    /**
     * Get the earthquake magnitude.
     */
    public double getEarthquakeMag() {
        return mEarthquakeMag;
    }

    /**
     * Get the date of earthquake.
     */
    public String getEarthquakeDate() {
        return mEarthquakeDate;
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Section 58</title>
  <meta id="xcode-display" name="xcode-display" content="render">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, maximum-scale=1.0">
  <link rel="stylesheet" type="text/css" href="stylesheet.css">

Structural

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Source: wikipedia.org

🔌 Adapter

The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Example:


text:
module Session
  def self.reset_session(session)
    current_user_id ||= session[:current_user_id]
    reset_session
    session[:current_user_id] ||= current_user_id
    session
  end

  def self.logged_in?(session)
    session.key?(:current_user_id) && !session[:current_user_id].nil?
  end
end


text:
package com.bruce.wechat.msg;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.bruce.wechat.msg.Resp.Article;
import com.bruce.wechat.msg.Resp.ImageMessage;
import com.bruce.wechat.msg.Resp.MusicMessage;
import com.bruce.wechat.msg.Resp.NewsMessage;
import com.bruce.wechat.msg.Resp.TextMessage;
import com.bruce.wechat.msg.Resp.VideoMessage;
import com.bruce.wechat.msg.Resp.VoiceMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * 消息工具类
 *
 * @author ivhhs
 * @date 2014.10.16
 */
public class MessageUtil {

	/**
	 * 返回消息类型:文本
	 */
	public static final String RESP_MESSAGE_TYPE_TEXT = "text";

	/**
	 * 返回消息类型:音乐
	 */
	public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

	/**
	 * 返回消息类型:图文
	 */
	public static final String RESP_MESSAGE_TYPE_NEWS = "news";

	/**
	 * 请求消息类型:文本
	 */
	public static final String REQ_MESSAGE_TYPE_TEXT = "text";

	/**
	 * 请求消息类型:图片
	 */
	public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

	/**
	 * 请求消息类型:链接
	 */
	public static final String REQ_MESSAGE_TYPE_LINK = "link";

	/**
	 * 请求消息类型:地理位置
	 */
	public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

	/**
	 * 请求消息类型:音频
	 */
	public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

	/**
	 * 请求消息类型:推送
	 */
	public static final String REQ_MESSAGE_TYPE_EVENT = "event";

	/**
	 * 事件类型:subscribe(订阅)
	 */
	public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

	/**
	 * 事件类型:unsubscribe(取消订阅)
	 */
	public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

	/**
	 * 事件类型:CLICK(自定义菜单点击事件)
	 */
	public static final String EVENT_TYPE_CLICK = "CLICK";
	/**
	 * 事件类型:视频
	 */
	public static final String REQ_MESSAGE_TYPE_VIDEO = "video";
	/**
	 * 事件类型:扫二维码
	 */
	public static final String EVENT_TYPE_SCAN = "scan";

	/**
	 * 解析微信发来的请求(XML)
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(String request) throws Exception {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();

		// 从request中取得输入流
		InputStream inputStream = new ByteArrayInputStream(request.getBytes("UTF-8"));
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();

		// 遍历所有子节点
		for (Element e : elementList)
			map.put(e.getName(), e.getText());

		// 释放资源
		inputStream.close();
		inputStream = null;

		return map;
	}

	/**
	 * 文本消息对象转换成xml
	 *
	 * @param textMessage
	 *            文本消息对象
	 * @return xml
	 */
	public static String textMessageToXml(TextMessage textMessage) {
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}

	/**
	 * 音乐消息对象转换成xml
	 *
	 * @param musicMessage
	 *            音乐消息对象
	 * @return xml
	 */
	public static String musicMessageToXml(MusicMessage musicMessage) {
		xstream.alias("xml", musicMessage.getClass());
		return xstream.toXML(musicMessage);
	}

	/**
	 * 图片消息对象转换成xml
	 *
	 * @param imageMessage
	 *            图片消息对象
	 * @return xml
	 */
	public static String imageMessageToXml(ImageMessage imageMessage) {
		xstream.alias("xml", imageMessage.getClass());
		return xstream.toXML(imageMessage);
	}

	/**
	 * 语音消息对象转换成xml
	 *
	 * @param voiceMessage
	 *            语音消息对象
	 * @return xml
	 */
	public static String voiceMessageToXml(VoiceMessage voiceMessage) {
		xstream.alias("xml", voiceMessage.getClass());
		return xstream.toXML(voiceMessage);
	}

	/**
	 * 视频消息对象转换成xml
	 *
	 * @param videoMessage
	 *            视频消息对象
	 * @return xml
	 */
	public static String videoMessageToXml(VideoMessage videoMessage) {
		xstream.alias("xml", videoMessage.getClass());
		return xstream.toXML(videoMessage);
	}

	/**
	 * 图文消息对象转换成xml
	 *
	 * @param newsMessage
	 *            图文消息对象
	 * @return xml
	 */
	public static String newsMessageToXml(NewsMessage newsMessage) {
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new Article().getClass());
		return xstream.toXML(newsMessage);
	}

	/**
	 * 扩展xstream,使其支持CDATA块
	 *
	 * @date 2013-05-19
	 */
	private static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});
}


text:
import copy
import json
from pyowm.stationsapi30.measurement import Measurement
from pyowm.utils import timestamps, formatting

class Buffer:

    station_id = None
    created_at = None
    measurements = None

    def __init__(self, station_id):
        assert station_id is not None
        self.station_id = station_id
        self.created_at = timestamps.now(timeformat='unix')
        self.measurements = []

    def creation_time(self, timeformat='unix'):
        """Returns the UTC time of creation of this aggregated measurement

        :param timeformat: the format for the time value. May be:
            '*unix*' (default) for UNIX time, '*iso*' for ISO8601-formatted
            string in the format ``YYYY-MM-DD HH:MM:SS+00`` or `date` for
            a ``datetime.datetime`` object
        :type timeformat: str
        :returns: an int or a str or a ``datetime.datetime`` object or None
        :raises: ValueError

        """
        if self.created_at is None:
            return None
        return formatting.timeformat(self.created_at, timeformat)

    def append(self, measurement):
        """
        Appends the specified ``Measurement`` object to the buffer
        :param measurement: a ``measurement.Measurement`` instance

        """
        assert isinstance(measurement, Measurement)
        assert measurement.station_id == self.station_id
        self.measurements.append(measurement)

    def append_from_dict(self, the_dict):
        """
        Creates a ``measurement.Measurement`` object from the supplied dict
        and then appends it to the buffer
        :param the_dict: dict

        """
        m = Measurement.from_dict(the_dict)
        self.append(m)

    def append_from_json(self, json_string):
        """
        Creates a ``measurement.Measurement`` object from the supplied JSON string
        and then appends it to the buffer
        :param json_string: the JSON formatted string

        """
        a_dict = json.loads(json_string)
        self.append_from_dict(a_dict)

    def empty(self):
        """
        Drops all measurements of this buffer instance

        """
        self.measurements = []

    def sort_chronologically(self):
        """
        Sorts the measurements of this buffer in chronological order

        """
        self.measurements.sort(key=lambda m: m.timestamp)

    def sort_reverse_chronologically(self):
        """
        Sorts the measurements of this buffer in reverse chronological order

        """
        self.measurements.sort(key=lambda m: m.timestamp, reverse=True)

    def __len__(self):
        return len(self.measurements)

    def __iter__(self):
        return iter(self.measurements)

    def __add__(self, other):
        assert all(i.station_id == self.station_id for i in other)
        result = copy.deepcopy(self)
        for m in other.measurements:
            result.append(m)
        return result

    def __contains__(self, measurement):
        return measurement in self.measurements

    def __repr__(self):
        return '<%s.%s - station_id=%s, n_samples=%s>' \
               % (__name__, self.__class__.__name__,
                  self.station_id, len(self))


text:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]
public class UIAnimateState : MonoBehaviour
{
    public bool startVisbile = true;
    public bool shouldTriggerOn = false;
    public bool shouldTriggerOff = false;
    private Animator animator;

    private bool isVisible = false;

    // Use this for initialization
    void Awake()
    {
        isVisible = startVisbile;
        animator = GetComponent<Animator>();
        if(animator != null)
        {
            animator.speed = float.MaxValue;
            animator.SetBool("IsVisible", isVisible);
        }
    }

    void Update()
    {
        if(shouldTriggerOn)
        {
            shouldTriggerOn = false;
            isVisible = true;
            UpdateVisibility();
        } else if (shouldTriggerOff) {
            shouldTriggerOff = false;
            isVisible = false;
            UpdateVisibility();
        }
    }

    void UpdateVisibility()
    {
        if (animator == null) return;
        animator.speed = 1;
        animator.SetBool("IsVisible", isVisible);
    }

    public bool IsVisible
    {
        get { return isVisible; }
        set { isVisible = value; UpdateVisibility(); }
    }
}


text:
from __future__ import division, unicode_literals

"""
This module contains classes to wrap Python VTK to make nice molecular plots.
"""

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Nov 27, 2011"

import os
import itertools
import math
import subprocess

import numpy as np
import vtk

from monty.serialization import loadfn

from pymatgen.util.coord_utils import in_coord_list
from pymatgen.core.periodic_table import Specie
from pymatgen.core.structure import Structure

module_dir = os.path.dirname(os.path.abspath(__file__))
EL_COLORS = loadfn(os.path.join(module_dir, "ElementColorSchemes.yaml"))

class StructureVis(object):
    """
    Provides Structure object visualization using VTK.
    """

    def __init__(self, element_color_mapping=None, show_unit_cell=True,
                 show_bonds=False, show_polyhedron=True,
                 poly_radii_tol_factor=0.5, excluded_bonding_elements=None):
        """
        Constructs a Structure Visualization.

        Args:
            element_color_mapping: Optional color mapping for the elements,
                as a dict of {symbol: rgb tuple}. For example, {"Fe": (255,
                123,0), ....} If None is specified, a default based on
                Jmol"s color scheme is used.
            show_unit_cell: Set to False to not show the unit cell
                boundaries. Defaults to True.
            show_bonds: Set to True to show bonds. Defaults to True.
            show_polyhedron: Set to True to show polyhedrons. Defaults to
                False.
            poly_radii_tol_factor: The polyhedron and bonding code uses the
                ionic radii of the elements or species to determine if two
                atoms are bonded. This specifies a tolerance scaling factor
                such that atoms which are (1 + poly_radii_tol_factor) * sum
                of ionic radii apart are still considered as bonded.
            excluded_bonding_elements: List of atom types to exclude from
                bonding determination. Defaults to an empty list. Useful
                when trying to visualize a certain atom type in the
                framework (e.g., Li in a Li-ion battery cathode material).

        Useful keyboard shortcuts implemented.
            h : Show help
            A/a : Increase/decrease cell by one unit vector in a-direction
            B/b : Increase/decrease cell by one unit vector in b-direction
            C/c : Increase/decrease cell by one unit vector in c-direction
            # : Toggle showing of polyhedrons
            - : Toggle showing of bonds
            [ : Decrease poly_radii_tol_factor by 0.05
            ] : Increase poly_radii_tol_factor by 0.05
            r : Reset camera direction
            o : Orthogonalize structure
            Up/Down : Rotate view along Up direction by 90 clock/anticlockwise
            Left/right : Rotate view along camera direction by 90
            clock/anticlockwise
        """
        # create a rendering window and renderer
        self.ren = vtk.vtkRenderer()
        self.ren_win = vtk.vtkRenderWindow()
        self.ren_win.AddRenderer(self.ren)
        self.ren.SetBackground(1, 1, 1)
        self.title = "Structure Visualizer"
        # create a renderwindowinteractor
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.ren_win)
        self.mapper_map = {}
        self.structure = None

        if element_color_mapping:
            self.el_color_mapping = element_color_mapping
        else:
            self.el_color_mapping = EL_COLORS["VESTA"]
        self.show_unit_cell = show_unit_cell
        self.show_bonds = show_bonds
        self.show_polyhedron = show_polyhedron
        self.poly_radii_tol_factor = poly_radii_tol_factor
        self.excluded_bonding_elements = excluded_bonding_elements if \
            excluded_bonding_elements else []
        self.show_help = True
        self.supercell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
        self.redraw()

        style = StructureInteractorStyle(self)
        self.iren.SetInteractorStyle(style)
        self.ren.parent = self

    def rotate_view(self, axis_ind=0, angle=0):
        """
        Rotate the camera view.

        Args:
            axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis.
            angle: Angle to rotate by. Defaults to 0.
        """
        camera = self.ren.GetActiveCamera()
        if axis_ind == 0:
            camera.Roll(angle)
        elif axis_ind == 1:
            camera.Azimuth(angle)
        else:
            camera.Pitch(angle)
        self.ren_win.Render()

    def write_image(self, filename="image.png", magnification=1,
                    image_format="png"):
        """
        Save render window to an image.

        Arguments:
            filename:
                filename to save to. Defaults to image.png.
            magnification:
                magnification. Use it to render high res images.
            image_format:
                choose between jpeg, png.  Png is the default.
        """
        render_large = vtk.vtkRenderLargeImage()
        render_large.SetInput(self.ren)
        if image_format == "jpeg":
            writer = vtk.vtkJPEGWriter()
            writer.SetQuality(80)
        else:
            writer = vtk.vtkPNGWriter()

        render_large.SetMagnification(magnification)
        writer.SetFileName(filename)

        writer.SetInputConnection(render_large.GetOutputPort())
        self.ren_win.Render()
        writer.Write()
        del render_large

    def redraw(self, reset_camera=False):
        """
        Redraw the render window.

        Args:
            reset_camera: Set to True to reset the camera to a
                pre-determined default for each structure.  Defaults to False.
        """
        self.ren.RemoveAllViewProps()
        self.picker = None
        self.add_picker_fixed()
        self.helptxt_mapper = vtk.vtkTextMapper()
        tprops = self.helptxt_mapper.GetTextProperty()
        tprops.SetFontSize(14)
        tprops.SetFontFamilyToTimes()
        tprops.SetColor(0, 0, 0)

        if self.structure is not None:
            self.set_structure(self.structure, reset_camera)

        self.ren_win.Render()

    def orthongonalize_structure(self):
        if self.structure is not None:
            self.set_structure(self.structure.copy(sanitize=True))
        self.ren_win.Render()

    def display_help(self):
        """
        Display the help for various keyboard shortcuts.
        """
        helptxt = ["h : Toggle help",
                   "A/a, B/b or C/c : Increase/decrease cell by one a,"
                   " b or c unit vector", "# : Toggle showing of polyhedrons",
                   "-: Toggle showing of bonds", "r : Reset camera direction",
                   "[/]: Decrease or increase poly_radii_tol_factor "
                   "by 0.05. Value = " + str(self.poly_radii_tol_factor),
                   "Up/Down: Rotate view along Up direction by 90 "
                   "clockwise/anticlockwise",
                   "Left/right: Rotate view along camera direction by "
                   "90 clockwise/anticlockwise", "s: Save view to image.png",
                   "o: Orthogonalize structure"]
        self.helptxt_mapper.SetInput("\n".join(helptxt))
        self.helptxt_actor.SetPosition(10, 10)
        self.helptxt_actor.VisibilityOn()

    def set_structure(self, structure, reset_camera=True):
        """
        Add a structure to the visualizer.

        Args:
            structure: structure to visualize
            reset_camera: Set to True to reset the camera to a default
                determined based on the structure.
        """
        self.ren.RemoveAllViewProps()

        has_lattice = hasattr(structure, "lattice")

        if has_lattice:
            s = Structure.from_sites(structure, to_unit_cell=True)
            s.make_supercell(self.supercell)
        else:
            s = structure

        inc_coords = []
        for site in s:
            self.add_site(site)
            inc_coords.append(site.coords)

        count = 0
        labels = ["a", "b", "c"]
        colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]

        if has_lattice:
            matrix = s.lattice.matrix

        if self.show_unit_cell and has_lattice:
            #matrix = s.lattice.matrix
            self.add_text([0, 0, 0], "o")
            for vec in matrix:
                self.add_line((0, 0, 0), vec, colors[count])
                self.add_text(vec, labels[count], colors[count])
                count += 1
            for (vec1, vec2) in itertools.permutations(matrix, 2):
                self.add_line(vec1, vec1 + vec2)
            for (vec1, vec2, vec3) in itertools.permutations(matrix, 3):
                self.add_line(vec1 + vec2, vec1 + vec2 + vec3)

        if self.show_bonds or self.show_polyhedron:
            elements = sorted(s.composition.elements, key=lambda a: a.X)
            anion = elements[-1]

            def contains_anion(site):
                for sp in site.species_and_occu.keys():
                    if sp.symbol == anion.symbol:
                        return True
                return False

            anion_radius = anion.average_ionic_radius
            for site in s:
                exclude = False
                max_radius = 0
                color = np.array([0, 0, 0])
                for sp, occu in site.species_and_occu.items():
                    if sp.symbol in self.excluded_bonding_elements \
                            or sp == anion:
                        exclude = True
                        break
                    max_radius = max(max_radius, sp.average_ionic_radius)
                    color = color + \
                        occu * np.array(self.el_color_mapping.get(sp.symbol,
                                                                  [0, 0, 0]))

                if not exclude:
                    max_radius = (1 + self.poly_radii_tol_factor) * \
                        (max_radius + anion_radius)
                    nn = structure.get_neighbors(site, max_radius)
                    nn_sites = []
                    for nnsite, dist in nn:
                        if contains_anion(nnsite):
                            nn_sites.append(nnsite)
                            if not in_coord_list(inc_coords, nnsite.coords):
                                self.add_site(nnsite)
                    if self.show_bonds:
                        self.add_bonds(nn_sites, site)
                    if self.show_polyhedron:
                        color = [i / 255 for i in color]
                        self.add_polyhedron(nn_sites, site, color)

        if self.show_help:
            self.helptxt_actor = vtk.vtkActor2D()
            self.helptxt_actor.VisibilityOn()
            self.helptxt_actor.SetMapper(self.helptxt_mapper)
            self.ren.AddActor(self.helptxt_actor)
            self.display_help()

        camera = self.ren.GetActiveCamera()
        if reset_camera:
            if has_lattice:
                #Adjust the camera for best viewing
                lengths = s.lattice.abc
                pos = (matrix[1] + matrix[2]) * 0.5 + \
                    matrix[0] * max(lengths) / lengths[0] * 3.5
                camera.SetPosition(pos)
                camera.SetViewUp(matrix[2])
                camera.SetFocalPoint((matrix[0] + matrix[1] + matrix[2]) * 0.5)
            else:
                origin = s.center_of_mass
                max_site = max(
                    s, key=lambda site: site.distance_from_point(origin))
                camera.SetPosition(origin + 5 * (max_site.coords - origin))
                camera.SetFocalPoint(s.center_of_mass)

        self.structure = structure
        self.title = s.composition.formula

    def zoom(self, factor):
        """
        Zoom the camera view by a factor.
        """
        camera = self.ren.GetActiveCamera()
        camera.Zoom(factor)
        self.ren_win.Render()

    def show(self):
        """
        Display the visualizer.
        """
        self.iren.Initialize()
        self.ren_win.SetSize(800, 800)
        self.ren_win.SetWindowName(self.title)
        self.ren_win.Render()
        self.iren.Start()

    def add_site(self, site):
        """
        Add a site to the render window. The site is displayed as a sphere, the
        color of which is determined based on the element. Partially occupied
        sites are displayed as a single element color, though the site info
        still shows the partial occupancy.

        Args:
            site: Site to add.
        """
        start_angle = 0
        radius = 0
        total_occu = 0

        for specie, occu in site.species_and_occu.items():
            radius += occu * (specie.ionic_radius
                              if isinstance(specie, Specie)
                              and specie.ionic_radius
                              else specie.average_ionic_radius)
            total_occu += occu

        for specie, occu in site.species_and_occu.items():
            if not specie:
                color = (1, 1, 1)
            elif specie.symbol in self.el_color_mapping:
                color = [i / 255 for i in self.el_color_mapping[specie.symbol]]
            mapper = self.add_partial_sphere(site.coords, radius, color,
                start_angle, start_angle + 360 * occu)
            self.mapper_map[mapper] = [site]
            start_angle += 360 * occu

        if total_occu < 1:
            mapper = self.add_partial_sphere(site.coords, radius, (1,1,1),
                start_angle, start_angle + 360 * (1 - total_occu))
            self.mapper_map[mapper] = [site]

    def add_partial_sphere(self, coords, radius, color, start=0, end=360,
                           opacity=1):
        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(coords)
        sphere.SetRadius(0.2 + 0.002 * radius)
        sphere.SetThetaResolution(18)
        sphere.SetPhiResolution(18)
        sphere.SetStartTheta(start)
        sphere.SetEndTheta(end)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(sphere.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color)
        actor.GetProperty().SetOpacity(opacity)
        self.ren.AddActor(actor)
        return mapper

    def add_text(self, coords, text, color=(0, 0, 0)):
        """
        Add text at a coordinate.

        Args:
            coords: Coordinates to add text at.
            text: Text to place.
            color: Color for text as RGB. Defaults to black.
        """
        source = vtk.vtkVectorText()
        source.SetText(text)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        follower = vtk.vtkFollower()
        follower.SetMapper(mapper)
        follower.GetProperty().SetColor(color)
        follower.SetPosition(coords)
        follower.SetScale(0.5)
        self.ren.AddActor(follower)
        follower.SetCamera(self.ren.GetActiveCamera())

    def add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1):
        """
        Adds a line.

        Args:
            start: Starting coordinates for line.
            end: Ending coordinates for line.
            color: Color for text as RGB. Defaults to grey.
            width: Width of line. Defaults to 1.
        """
        source = vtk.vtkLineSource()
        source.SetPoint1(start)
        source.SetPoint2(end)

        vertexIDs = vtk.vtkStringArray()
        vertexIDs.SetNumberOfComponents(1)
        vertexIDs.SetName("VertexIDs")
        # Set the vertex labels
        vertexIDs.InsertNextValue("a")
        vertexIDs.InsertNextValue("b")
        source.GetOutput().GetPointData().AddArray(vertexIDs)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color)
        actor.GetProperty().SetLineWidth(width)
        self.ren.AddActor(actor)

    def add_polyhedron(self, neighbors, center, color, opacity=1.0,
                       draw_edges=False, edges_color=[0.0, 0.0, 0.0],
                       edges_linewidth=2):
        """
        Adds a polyhedron.

        Args:
            neighbors: Neighbors of the polyhedron (the vertices).
            center: The atom in the center of the polyhedron.
            color: Color for text as RGB.
            opacity: Opacity of the polyhedron
            draw_edges: If set to True, the a line will be drawn at each edge
            edges_color: Color of the line for the edges
            edges_linewidth: Width of the line drawn for the edges
        """
        points = vtk.vtkPoints()
        conv = vtk.vtkConvexPointSet()
        for i in range(len(neighbors)):
            x, y, z = neighbors[i].coords
            points.InsertPoint(i, x, y, z)
            conv.GetPointIds().InsertId(i, i)
        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(conv.GetCellType(), conv.GetPointIds())
        grid.SetPoints(points)

        dsm = vtk.vtkDataSetMapper()
        polysites = [center]
        polysites.extend(neighbors)
        self.mapper_map[dsm] = polysites
        if vtk.VTK_MAJOR_VERSION <= 5:
            dsm.SetInputConnection(grid.GetProducerPort())
        else:
            dsm.SetInputData(grid)
        ac = vtk.vtkActor()
        #ac.SetMapper(mapHull)
        ac.SetMapper(dsm)
        ac.GetProperty().SetOpacity(opacity)
        if color == 'element':
            # If partial occupations are involved, the color of the specie with
            # the highest occupation is used
            myoccu = 0.0
            for specie, occu in center.species_and_occu.items():
                if occu > myoccu:
                    myspecie = specie
                    myoccu = occu
            color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]]
            ac.GetProperty().SetColor(color)
        else:
            ac.GetProperty().SetColor(color)
        if draw_edges:
            ac.GetProperty().SetEdgeColor(edges_color)
            ac.GetProperty().SetLineWidth(edges_linewidth)
            ac.GetProperty().EdgeVisibilityOn()
        self.ren.AddActor(ac)

    def add_triangle(self, neighbors, color, center=None, opacity=0.4,
                     draw_edges=False, edges_color=[0.0, 0.0, 0.0],
                     edges_linewidth=2):
        """
        Adds a triangular surface between three atoms.

        Args:
            atoms: Atoms between which a triangle will be drawn.
            color: Color for triangle as RGB.
            center: The "central atom" of the triangle
            opacity: opacity of the triangle
            draw_edges: If set to True, the a line will be  drawn at each edge
            edges_color: Color of the line for the edges
            edges_linewidth: Width of the line drawn for the edges
        """
        points = vtk.vtkPoints()
        triangle = vtk.vtkTriangle()
        for ii in range(3):
            points.InsertNextPoint(neighbors[ii].x, neighbors[ii].y,
                                   neighbors[ii].z)
            triangle.GetPointIds().SetId(ii, ii)
        triangles = vtk.vtkCellArray()
        triangles.InsertNextCell(triangle)

        # polydata object
        trianglePolyData = vtk.vtkPolyData()
        trianglePolyData.SetPoints( points )
        trianglePolyData.SetPolys( triangles )

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(trianglePolyData)

        ac = vtk.vtkActor()
        ac.SetMapper(mapper)
        ac.GetProperty().SetOpacity(opacity)
        if color == 'element':
            if center is None:
                raise ValueError(
                    'Color should be chosen according to the central atom, '
                    'and central atom is not provided')
            # If partial occupations are involved, the color of the specie with
            # the highest occupation is used
            myoccu = 0.0
            for specie, occu in center.species_and_occu.items():
                if occu > myoccu:
                    myspecie = specie
                    myoccu = occu
            color = [i / 255 for i in self.el_color_mapping[myspecie.symbol]]
            ac.GetProperty().SetColor(color)
        else:
            ac.GetProperty().SetColor(color)
        if draw_edges:
            ac.GetProperty().SetEdgeColor(edges_color)
            ac.GetProperty().SetLineWidth(edges_linewidth)
            ac.GetProperty().EdgeVisibilityOn()
        self.ren.AddActor(ac)

    def add_faces(self, faces, color, opacity=0.35):
        for face in faces:
            if len(face) == 3:
                points = vtk.vtkPoints()
                triangle = vtk.vtkTriangle()
                for ii in range(3):
                    points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
                    triangle.GetPointIds().SetId(ii, ii)
                triangles = vtk.vtkCellArray()
                triangles.InsertNextCell(triangle)
                trianglePolyData = vtk.vtkPolyData()
                trianglePolyData.SetPoints(points)
                trianglePolyData.SetPolys(triangles)
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(trianglePolyData)
                ac = vtk.vtkActor()
                ac.SetMapper(mapper)
                ac.GetProperty().SetOpacity(opacity)
                ac.GetProperty().SetColor(color)
                self.ren.AddActor(ac)
            elif False and len(face) == 4:
                points = vtk.vtkPoints()
                for ii in range(4):
                    points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
                line1 = vtk.vtkLine()
                line1.GetPointIds().SetId(0, 0)
                line1.GetPointIds().SetId(1, 2)
                line2 = vtk.vtkLine()
                line2.GetPointIds().SetId(0, 3)
                line2.GetPointIds().SetId(1, 1)
                lines = vtk.vtkCellArray()
                lines.InsertNextCell(line1)
                lines.InsertNextCell(line2)
                polydata = vtk.vtkPolyData()
                polydata.SetPoints(points)
                polydata.SetLines(lines)
                ruledSurfaceFilter = vtk.vtkRuledSurfaceFilter()
                ruledSurfaceFilter.SetInput(polydata)
                ruledSurfaceFilter.SetResolution(15, 15)
                ruledSurfaceFilter.SetRuledModeToResample()
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(ruledSurfaceFilter.GetOutput())
                ac = vtk.vtkActor()
                ac.SetMapper(mapper)
                ac.GetProperty().SetOpacity(opacity)
                ac.GetProperty().SetColor(color)
                self.ren.AddActor(ac)
            elif len(face) > 3:
                center = np.zeros(3, np.float)
                for site in face:
                    center += site
                center /= np.float(len(face))
                for ii in range(len(face)):
                    points = vtk.vtkPoints()
                    triangle = vtk.vtkTriangle()
                    points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
                    ii2 = np.mod(ii+1, len(face))
                    points.InsertNextPoint(face[ii2][0], face[ii2][1], face[ii2][2])
                    points.InsertNextPoint(center[0], center[1], center[2])
                    for ii in range(3):
                        triangle.GetPointIds().SetId(ii, ii)
                    triangles = vtk.vtkCellArray()
                    triangles.InsertNextCell(triangle)
                    trianglePolyData = vtk.vtkPolyData()
                    trianglePolyData.SetPoints(points)
                    trianglePolyData.SetPolys(triangles)
                    mapper = vtk.vtkPolyDataMapper()
                    mapper.SetInput(trianglePolyData)
                    ac = vtk.vtkActor()
                    ac.SetMapper(mapper)
                    ac.GetProperty().SetOpacity(opacity)
                    ac.GetProperty().SetColor(color)
                    self.ren.AddActor(ac)
            else:
                raise ValueError("Number of points for a face should be >= 3")

    def add_edges(self, edges, type='line', linewidth=2, color=[0.0, 0.0, 0.0]):
        points = vtk.vtkPoints()
        lines = vtk.vtkCellArray()
        for iedge, edge in enumerate(edges):
            points.InsertPoint(2*iedge, edge[0])
            points.InsertPoint(2*iedge + 1, edge[1])
            lines.InsertNextCell(2)
            lines.InsertCellPoint(2*iedge)
            lines.InsertCellPoint(2*iedge + 1)
        polydata = vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.SetLines(lines)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(polydata)
        ac = vtk.vtkActor()
        ac.SetMapper(mapper)
        ac.GetProperty().SetColor(color)
        ac.GetProperty().SetLineWidth(linewidth)
        self.ren.AddActor(ac)

    def add_bonds(self, neighbors, center, color=None, opacity=None,
                  radius=0.1):
        """
        Adds bonds for a site.

        Args:
            neighbors: Neighbors of the site.
            center: The site in the center for all bonds.
            color: Color of the tubes representing the bonds
            opacity: Opacity of the tubes representing the bonds
            radius: Radius of tube s representing the bonds
        """
        points = vtk.vtkPoints()
        points.InsertPoint(0, center.x, center.y, center.z)
        n = len(neighbors)
        lines = vtk.vtkCellArray()
        for i in range(n):
            points.InsertPoint(i + 1, neighbors[i].coords)
            lines.InsertNextCell(2)
            lines.InsertCellPoint(0)
            lines.InsertCellPoint(i + 1)
        pd = vtk.vtkPolyData()
        pd.SetPoints(points)
        pd.SetLines(lines)

        tube = vtk.vtkTubeFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            tube.SetInputConnection(pd.GetProducerPort())
        else:
            tube.SetInputData(pd)
        tube.SetRadius(radius)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(tube.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        if opacity is not None:
            actor.GetProperty().SetOpacity(opacity)
        if color is not None:
            actor.GetProperty().SetColor(color)
        self.ren.AddActor(actor)

    def add_picker_fixed(self):
        # Create a cell picker.
        picker = vtk.vtkCellPicker()
        # Create a Python function to create the text for the text mapper used
        # to display the results of picking.

        def annotate_pick(obj, event):
            if picker.GetCellId() < 0 and not self.show_help:
                self.helptxt_actor.VisibilityOff()
            else:
                mapper = picker.GetMapper()
                if mapper in self.mapper_map:
                    output = []
                    for site in self.mapper_map[mapper]:
                        row = ["{} - ".format(site.species_string),
                               ", ".join(["{:.3f}".format(c)
                                          for c in site.frac_coords]),
                               "[" + ", ".join(["{:.3f}".format(c)
                                                for c in site.coords]) +
                               "]"]
                        output.append("".join(row))
                    self.helptxt_mapper.SetInput("\n".join(output))
                    self.helptxt_actor.SetPosition(10, 10)
                    self.helptxt_actor.VisibilityOn()
                    self.show_help = False
        self.picker = picker
        picker.AddObserver("EndPickEvent", annotate_pick)
        self.iren.SetPicker(picker)

    def add_picker(self):
        # Create a cell picker.
        picker = vtk.vtkCellPicker()
        # Create a Python function to create the text for the text mapper used
        # to display the results of picking.
        source = vtk.vtkVectorText()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        follower = vtk.vtkFollower()
        follower.SetMapper(mapper)
        follower.GetProperty().SetColor((0, 0, 0))
        follower.SetScale(0.2)
        self.ren.AddActor(follower)
        follower.SetCamera(self.ren.GetActiveCamera())
        follower.VisibilityOff()

        def annotate_pick(obj, event):
            if picker.GetCellId() < 0:
                follower.VisibilityOff()
            else:
                pick_pos = picker.GetPickPosition()
                mapper = picker.GetMapper()
                if mapper in self.mapper_map:
                    site = self.mapper_map[mapper]
                    output = [site.species_string, "Frac. coords: " +
                                                   " ".join(["{:.4f}".format(c)
                                                             for c in
                                                             site.frac_coords])]
                    source.SetText("\n".join(output))
                    follower.SetPosition(pick_pos)
                    follower.VisibilityOn()
        picker.AddObserver("EndPickEvent", annotate_pick)
        self.picker = picker
        self.iren.SetPicker(picker)

class StructureInteractorStyle(vtk.vtkInteractorStyleTrackballCamera):
    """
    A custom interactor style for visualizing structures.
    """

    def __init__(self, parent):
        self.parent = parent
        self.AddObserver("LeftButtonPressEvent", self.leftButtonPressEvent)
        self.AddObserver("MouseMoveEvent", self.mouseMoveEvent)
        self.AddObserver("LeftButtonReleaseEvent", self.leftButtonReleaseEvent)
        self.AddObserver("KeyPressEvent", self.keyPressEvent)

    def leftButtonPressEvent(self, obj, event):
        self.mouse_motion = 0
        self.OnLeftButtonDown()
        return

    def mouseMoveEvent(self, obj, event):
        self.mouse_motion = 1
        self.OnMouseMove()
        return

    def leftButtonReleaseEvent(self, obj, event):
        ren = obj.GetCurrentRenderer()
        iren = ren.GetRenderWindow().GetInteractor()
        if self.mouse_motion == 0:
            pos = iren.GetEventPosition()
            iren.GetPicker().Pick(pos[0], pos[1], 0, ren)
        self.OnLeftButtonUp()
        return

    def keyPressEvent(self, obj, event):
        parent = obj.GetCurrentRenderer().parent
        sym = parent.iren.GetKeySym()

        if sym in "ABCabc":
            if sym == "A":
                parent.supercell[0][0] += 1
            elif sym == "B":
                parent.supercell[1][1] += 1
            elif sym == "C":
                parent.supercell[2][2] += 1
            elif sym == "a":
                parent.supercell[0][0] = max(parent.supercell[0][0] - 1, 1)
            elif sym == "b":
                parent.supercell[1][1] = max(parent.supercell[1][1] - 1, 1)
            elif sym == "c":
                parent.supercell[2][2] = max(parent.supercell[2][2] - 1, 1)
            parent.redraw()
        elif sym == "numbersign":
            parent.show_polyhedron = not parent.show_polyhedron
            parent.redraw()
        elif sym == "minus":
            parent.show_bonds = not parent.show_bonds
            parent.redraw()
        elif sym == "bracketleft":
            parent.poly_radii_tol_factor -= 0.05 \
                if parent.poly_radii_tol_factor > 0 else 0
            parent.redraw()
        elif sym == "bracketright":
            parent.poly_radii_tol_factor += 0.05
            parent.redraw()
        elif sym == "h":
            parent.show_help = not parent.show_help
            parent.redraw()
        elif sym == "r":
            parent.redraw(True)
        elif sym == "s":
            parent.write_image("image.png")
        elif sym == "Up":
            parent.rotate_view(1, 90)
        elif sym == "Down":
            parent.rotate_view(1, -90)
        elif sym == "Left":
            parent.rotate_view(0, -90)
        elif sym == "Right":
            parent.rotate_view(0, 90)
        elif sym == "o":
            parent.orthongonalize_structure()
            parent.redraw()

        self.OnKeyPress()

def make_movie(structures, output_filename="movie.mp4", zoom=1.0, fps=20,
               bitrate="10000k", quality=1, **kwargs):
    """
    Generate a movie from a sequence of structures using vtk and ffmpeg.

    Args:
        structures ([Structure]): sequence of structures
        output_filename (str): filename for structure output. defaults to
            movie.mp4
        zoom (float): A zoom to be applied to the visualizer. Defaults to 1.0.
        fps (int): Frames per second for the movie. Defaults to 20.
        bitrate (str): Video bitate.  Defaults to "10000k" (fairly high
            quality).
        quality (int): A quality scale. Defaults to 1.
        \*\*kwargs: Any kwargs supported by StructureVis to modify the images
            generated.
    """
    vis = StructureVis(**kwargs)
    vis.show_help = False
    vis.redraw()
    vis.zoom(zoom)
    sigfig = int(math.floor(math.log10(len(structures))) + 1)
    filename = "image{0:0" + str(sigfig) + "d}.png"
    for i, s in enumerate(structures):
        vis.set_structure(s)
        vis.write_image(filename.format(i), 3)
    filename = "image%0" + str(sigfig) + "d.png"
    args = ["ffmpeg", "-y", "-i", filename,
            "-q:v", str(quality), "-r", str(fps), "-b:v", str(bitrate),
            output_filename]
    subprocess.Popen(args)


text:
NS_ASSUME_NONNULL_BEGIN

@class LNKClasses, LNKMatrix;

/// Abstract
/// Models probability distributions for use with LNKClassifiers.
@interface LNKClassProbabilityDistribution : NSObject

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

- (instancetype)initWithClasses:(LNKClasses *)classes featureCount:(LNKSize)featureCount NS_DESIGNATED_INITIALIZER;

@property (nonatomic, retain, nonnull, readonly) LNKClasses *classes;
@property (nonatomic, readonly) LNKSize featureCount;

- (LNKFloat)priorForClassAtIndex:(LNKSize)index;
- (LNKFloat)probabilityLogForClassAtIndex:(LNKSize)classIndex featureAtIndex:(LNKSize)featureIndex value:(LNKFloat)value;

// Subclasses must override this method to build a probability distribution.
- (void)buildWithMatrix:(LNKMatrix *)matrix;

@end

NS_ASSUME_NONNULL_END


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Region.ScriptEngine.Interfaces;

namespace OpenSim.Region.ScriptEngine.Shared.Api
{
    public class ApiManager
    {
        private Dictionary<string,Type> m_Apis = new Dictionary<string,Type>();

        public string[] GetApis()
        {
            if (m_Apis.Count > 0)
            {
                List<string> l = new List<string>(m_Apis.Keys);
                return l.ToArray();
            }

            Assembly a = Assembly.GetExecutingAssembly();

            Type[] types = a.GetExportedTypes();

            foreach (Type t in types)
            {
                string name = t.ToString();
                int idx = name.LastIndexOf('.');
                if (idx != -1)
                    name = name.Substring(idx+1);

                if (name.EndsWith("_Api"))
                {
                    name = name.Substring(0, name.Length - 4);
                    m_Apis[name] = t;
                }
            }

            List<string> ret = new List<string>(m_Apis.Keys);
            return ret.ToArray();
        }

        public IScriptApi CreateApi(string api)
        {
            if (!m_Apis.ContainsKey(api))
                return null;

            IScriptApi ret = (IScriptApi)(Activator.CreateInstance(m_Apis[api]));
            return ret;
        }
    }
}


text:
var proxyquire = require('proxyquireify')(require);
var mockComponent = require('../mock');var _ = require('lodash');

describe('Auth Error Component: ', function () {

  var AuthError,
    element,
    spies,
    proxies;

  var React, TestUtils;

  beforeEach(function () {
    React = require('react/addons');
    TestUtils = React.addons.TestUtils;
  });

  beforeEach(function () {
    AuthError = require('./auth.error');
    element = TestUtils.renderIntoDocument(<AuthError authError="none" />);
  });

  it('should instantiate the AuthError', function () {
    expect(TestUtils.isCompositeComponent(element)).to.be.true;
  });
});


text:
require 'net/http'
require 'uri'

Dir[Rails.root.join("lib", "gnite", "*.rb")].each {|f| require f}

module Gnite
end


text:
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using System.Windows.Media;

namespace CodeNav.Helpers
{
    public static class ColorHelper
    {
        public static SolidColorBrush ToBrush(Color color)
        {
            var brush = new SolidColorBrush(color);
            brush.Freeze();
            return brush;
        }

        /// <summary>
        /// Convert from VSTheme EnvironmentColor to a XAML SolidColorBrush
        /// </summary>
        /// <param name="key">VSTheme EnvironmentColor key</param>
        /// <returns>XAML SolidColorBrush</returns>
        public static SolidColorBrush ToBrush(ThemeResourceKey key)
            => new SolidColorBrush(ToMediaColor(VSColorTheme.GetThemedColor(key)));

        public static SolidColorBrush ToBrush(System.Drawing.Color color)
            => new SolidColorBrush(ToMediaColor(color));

        public static Color ToMediaColor(System.Drawing.Color drawingColor)
            => Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G, drawingColor.B);

        public static Color ToMediaColor(ThemeResourceKey key)
            => ToMediaColor(VSColorTheme.GetThemedColor(key));

        public static System.Drawing.Color ToDrawingColor(Color color)
            => System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);

        public static System.Drawing.Color ToDrawingColor(SolidColorBrush solidColorBrush)
            => ToDrawingColor(solidColorBrush.Color);

        public static System.Drawing.Color Transparent()
            => ToDrawingColor(Brushes.Transparent);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<declare-styleable name="CompoundButton">
		<attr name="android:button"/>
	</declare-styleable>
	<declare-styleable name="ColorPickerItem">
		<attr name="color_filter" format="color"/>
	</declare-styleable>

</resources>