text:
import unittest

import command
import config
import mesh_cop
import thread_cert
from pktverify.consts import MLE_DATA_RESPONSE, LEAD_PET_URI, LEAD_KA_URI, MGMT_COMMISSIONER_SET_URI, NM_CHANNEL_TLV, NM_COMMISSIONER_ID_TLV, NM_COMMISSIONER_SESSION_ID_TLV, NM_STATE_TLV, NM_STEERING_DATA_TLV, NM_BORDER_AGENT_LOCATOR_TLV, LEADER_DATA_TLV, NETWORK_DATA_TLV, ACTIVE_TIMESTAMP_TLV, SOURCE_ADDRESS_TLV, NWD_COMMISSIONING_DATA_TLV, MESHCOP_ACCEPT, MESHCOP_REJECT, LEADER_ALOC
from pktverify.packet_verifier import PacketVerifier
from pktverify.bytes import Bytes

COMMISSIONER = 1
LEADER = 2

# Test Purpose and Description:
# -----------------------------
# The purpose of this test case is to verify Leader's and active Commissioner's behavior via
# MGMT_COMMISSIONER_SET request and response
#
# Test Topology:
# -------------
# Commissioner
#    |
#  Leader
#
# DUT Types:
# ----------
#  Leader
#  Commissioner

class Cert_9_2_02_MGMTCommissionerSet(thread_cert.TestCase):
    SUPPORT_NCP = False

    TOPOLOGY = {
        COMMISSIONER: {
            'name': 'COMMISSIONER',
            'mode': 'rdn',
            'allowlist': [LEADER]
        },
        LEADER: {
            'name': 'LEADER',
            'mode': 'rdn',
            'allowlist': [COMMISSIONER]
        },
    }

    def test(self):
        self.nodes[LEADER].start()
        self.simulator.go(config.LEADER_STARTUP_DELAY)
        self.assertEqual(self.nodes[LEADER].get_state(), 'leader')

        self.nodes[COMMISSIONER].start()
        self.simulator.go(config.ROUTER_STARTUP_DELAY)
        self.assertEqual(self.nodes[COMMISSIONER].get_state(), 'router')
        self.simulator.get_messages_sent_by(LEADER)

        self.collect_rlocs()
        self.collect_rloc16s()

        self.nodes[COMMISSIONER].commissioner_start()
        self.simulator.go(3)

        leader_messages = self.simulator.get_messages_sent_by(LEADER)
        msg = leader_messages.next_coap_message('2.04', assert_enabled=True)
        commissioner_session_id_tlv = command.get_sub_tlv(msg.coap.payload, mesh_cop.CommissionerSessionId)

        steering_data_tlv = mesh_cop.SteeringData(bytes([0xff]))
        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([steering_data_tlv])
        self.simulator.go(5)

        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([steering_data_tlv, commissioner_session_id_tlv])
        self.simulator.go(5)

        border_agent_locator_tlv = mesh_cop.BorderAgentLocator(0x0400)
        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs(
            [commissioner_session_id_tlv, border_agent_locator_tlv])
        self.simulator.go(5)

        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([
            steering_data_tlv,
            commissioner_session_id_tlv,
            border_agent_locator_tlv,
        ])
        self.simulator.go(5)

        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs(
            [mesh_cop.CommissionerSessionId(0xffff), steering_data_tlv])
        self.simulator.go(5)

        self.nodes[COMMISSIONER].commissioner_mgmtset_with_tlvs([
            commissioner_session_id_tlv,
            steering_data_tlv,
            mesh_cop.Channel(0x0, 0x0),
        ])
        self.simulator.go(5)

        leader_rloc = self.nodes[LEADER].get_rloc()
        commissioner_rloc = self.nodes[COMMISSIONER].get_rloc()
        self.assertTrue(self.nodes[COMMISSIONER].ping(leader_rloc))
        self.simulator.go(1)
        self.assertTrue(self.nodes[LEADER].ping(commissioner_rloc))

    def verify(self, pv):
        pkts = pv.pkts
        pv.summary.show()

        LEADER = pv.vars['LEADER']
        LEADER_RLOC = pv.vars['LEADER_RLOC']
        LEADER_RLOC16 = pv.vars['LEADER_RLOC16']
        COMMISSIONER = pv.vars['COMMISSIONER']
        COMMISSIONER_RLOC = pv.vars['COMMISSIONER_RLOC']

        # Step 1: Ensure topology is formed correctly
        pv.verify_attached('COMMISSIONER', 'LEADER')

        # Step 2: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             (missing Commissioner Session ID TLV)
        #             Steering Data TLV (0xFF)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STEERING_DATA_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.steering_data == Bytes('ff')
                   ).\
           must_next()

        # Step 3: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Reject)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_REJECT
                   ).\
           must_next()

        # Step 4: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             Commissioner Session ID TLV
        #             Steering Data TLV (0xFF)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p: {
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_STEERING_DATA_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_meshcop.tlv.steering_data == Bytes('ff')
                   ).\
           must_next()

        # Step 5: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Accept)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_ACCEPT
                   ).\
           must_next()

        # Step 6: Leader sends a MLE Data Response to the network with the
        #         following TLVs:
        #             - Active Timestamp TLV
        #             - Leader Data TLV
        #             - Network Data TLV
        #             - Source Address TLV
        pkts.filter_wpan_src64(LEADER).\
            filter_LLANMA().\
            filter_mle_cmd(MLE_DATA_RESPONSE).\
            filter(lambda p: {
                              NETWORK_DATA_TLV,
                              SOURCE_ADDRESS_TLV,
                              ACTIVE_TIMESTAMP_TLV,
                              LEADER_DATA_TLV
                             } == set(p.mle.tlv.type) and\
                             {
                              NWD_COMMISSIONING_DATA_TLV
                             } == set(p.thread_nwd.tlv.type) and\
                             {
                              NM_BORDER_AGENT_LOCATOR_TLV,
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_STEERING_DATA_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_nwd.tlv.stable == [0]
                   ).\
            must_next()

        # Step 7: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             Commissioner Session ID TLV
        #             Border Agent Locator TLV (0x0400) (not allowed TLV)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p: {
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_BORDER_AGENT_LOCATOR_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_meshcop.tlv.ba_locator == 0x0400
                   ).\
           must_next()

        # Step 8: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Reject)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_REJECT
                   ).\
           must_next()

        # Step 9: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             Commissioner Session ID TLV
        #             Steering Data TLV (0xFF)
        #             Border Agent Locator TLV (0x0400) (not allowed TLV)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p: {
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_STEERING_DATA_TLV,
                              NM_BORDER_AGENT_LOCATOR_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_meshcop.tlv.ba_locator == 0x0400 and\
                   p.thread_meshcop.tlv.steering_data == Bytes('ff')
                   ).\
           must_next()

        # Step 10: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Reject)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_REJECT
                   ).\
           must_next()

        # Step 11: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             Commissioner Session ID TLV (0xFFFF) (invalid value)
        #             Steering Data TLV (0xFF)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p: {
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_STEERING_DATA_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_meshcop.tlv.commissioner_sess_id == 0xFFFF and\
                   p.thread_meshcop.tlv.steering_data == Bytes('ff')
                   ).\
           must_next()

        # Step 12: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Reject)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_REJECT
                   ).\
           must_next()

        # Step 13: Commissioner sends a Set Commissioner Dataset Request (MGMT_COMMISSIONER_SET.req)
        #         to Leader Anycast or Routing Locator:
        #         CoAP Request URI
        #             CON POST coap://<L>:MM/c/cs
        #         CoAP Payload
        #             Commissioner Session ID TLV
        #             Steering Data TLV (0xFF)
        #             Channel TLV (not allowed TLV)
        _mgmt_set_pkt = pkts.filter_wpan_src64(COMMISSIONER).\
            filter_ipv6_2dsts(LEADER_ALOC, LEADER_RLOC).\
            filter_coap_request(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p: {
                              NM_COMMISSIONER_SESSION_ID_TLV,
                              NM_STEERING_DATA_TLV,
                              NM_CHANNEL_TLV
                             } == set(p.thread_meshcop.tlv.type) and\
                   p.thread_meshcop.tlv.steering_data == Bytes('ff')
                   ).\
           must_next()

        # Step 14: Leader sends a Set Commissioner Dataset Response (MGMT_COMMISSIONER_SET.rsp) to
        #         Commissioner:
        #         CoAP Response Code
        #             2.04 Changed
        #         CoAP Payload
        #             State TLV (value = Accept)
        pkts.filter_ipv6_src_dst(_mgmt_set_pkt.ipv6.dst, COMMISSIONER_RLOC).\
            filter_coap_ack(MGMT_COMMISSIONER_SET_URI).\
            filter(lambda p:
                   [NM_STATE_TLV] == p.coap.tlv.type and\
                   p.thread_meshcop.tlv.state == MESHCOP_ACCEPT
                   ).\
           must_next()

        # Step 15: Verify connectivity by sending an ICMPv6 Echo Request to the DUT mesh local address
        _pkt = pkts.filter_ping_request().\
            filter_ipv6_src_dst(COMMISSIONER_RLOC, LEADER_RLOC).\
            must_next()
        pkts.filter_ping_reply(identifier=_pkt.icmpv6.echo.identifier).\
            filter_ipv6_src_dst(LEADER_RLOC, COMMISSIONER_RLOC).\
            must_next()

        _pkt = pkts.filter_ping_request().\
            filter_ipv6_src_dst(LEADER_RLOC, COMMISSIONER_RLOC).\
            must_next()
        pkts.filter_ping_reply(identifier=_pkt.icmpv6.echo.identifier).\
            filter_ipv6_src_dst(COMMISSIONER_RLOC, LEADER_RLOC).\
            must_next()

if __name__ == '__main__':
    unittest.main()


text:
package slb

import (
	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

type AddressType string

const (
	InternetAddressType = AddressType("internet")
	IntranetAddressType = AddressType("intranet")
)

type InternetChargeType string

const (
	PayByBandwidth = InternetChargeType("paybybandwidth")
	PayByTraffic   = InternetChargeType("paybytraffic")
)

type CreateLoadBalancerArgs struct {
	RegionId           common.Region
	LoadBalancerName   string
	AddressType        AddressType
	VSwitchId          string
	InternetChargeType InternetChargeType
	Bandwidth          int
	ClientToken        string
}

type CreateLoadBalancerResponse struct {
	common.Response
	LoadBalancerId   string
	Address          string
	NetworkType      string
	VpcId            string
	VSwitchId        string
	LoadBalancerName string
}

// CreateLoadBalancer create loadbalancer
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&CreateLoadBalancer
func (client *Client) CreateLoadBalancer(args *CreateLoadBalancerArgs) (response *CreateLoadBalancerResponse, err error) {
	response = &CreateLoadBalancerResponse{}
	err = client.Invoke("CreateLoadBalancer", args, response)
	if err != nil {
		return nil, err
	}
	return response, err
}

type DeleteLoadBalancerArgs struct {
	LoadBalancerId string
}

type DeleteLoadBalancerResponse struct {
	common.Response
}

// DeleteLoadBalancer delete loadbalancer
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DeleteLoadBalancer
func (client *Client) DeleteLoadBalancer(loadBalancerId string) (err error) {
	args := &DeleteLoadBalancerArgs{
		LoadBalancerId: loadBalancerId,
	}
	response := &DeleteLoadBalancerResponse{}
	err = client.Invoke("DeleteLoadBalancer", args, response)
	return err
}

type ModifyLoadBalancerInternetSpecArgs struct {
	LoadBalancerId     string
	InternetChargeType InternetChargeType
	Bandwidth          int
}

type ModifyLoadBalancerInternetSpecResponse struct {
	common.Response
}

// ModifyLoadBalancerInternetSpec Modify loadbalancer internet spec
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&ModifyLoadBalancerInternetSpec

func (client *Client) ModifyLoadBalancerInternetSpec(args *ModifyLoadBalancerInternetSpecArgs) (err error) {
	response := &ModifyLoadBalancerInternetSpecResponse{}
	err = client.Invoke("ModifyLoadBalancerInternetSpec", args, response)
	return err
}

type Status string

const InactiveStatus = Status("inactive")
const ActiveStatus = Status("active")
const LockedStatus = Status("locked")

type SetLoadBalancerStatusArgs struct {
	LoadBalancerId     string
	LoadBalancerStatus Status
}

type SetLoadBalancerStatusResponse struct {
	common.Response
}

// SetLoadBalancerStatus Set loadbalancer status
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&SetLoadBalancerStatus

func (client *Client) SetLoadBalancerStatus(loadBalancerId string, status Status) (err error) {
	args := &SetLoadBalancerStatusArgs{
		LoadBalancerId:     loadBalancerId,
		LoadBalancerStatus: status,
	}
	response := &SetLoadBalancerStatusResponse{}
	err = client.Invoke("SetLoadBalancerStatus", args, response)
	return err
}

type SetLoadBalancerNameArgs struct {
	LoadBalancerId   string
	LoadBalancerName string
}

type SetLoadBalancerNameResponse struct {
	common.Response
}

// SetLoadBalancerName Set loadbalancer name
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&SetLoadBalancerName

func (client *Client) SetLoadBalancerName(loadBalancerId string, name string) (err error) {
	args := &SetLoadBalancerNameArgs{
		LoadBalancerId:   loadBalancerId,
		LoadBalancerName: name,
	}
	response := &SetLoadBalancerNameResponse{}
	err = client.Invoke("SetLoadBalancerName", args, response)
	return err
}

type DescribeLoadBalancersArgs struct {
	RegionId           common.Region
	LoadBalancerId     string
	LoadBalancerName   string
	AddressType        AddressType
	NetworkType        string
	VpcId              string
	VSwitchId          string
	Address            string
	InternetChargeType InternetChargeType
	ServerId           string
}

type ListenerPortAndProtocolType struct {
	ListenerPort     int
	ListenerProtocol string
}

type BackendServerType struct {
	ServerId string
	Weight   int
}

type LoadBalancerType struct {
	LoadBalancerId     string
	LoadBalancerName   string
	LoadBalancerStatus string
	Address            string
	RegionId           common.Region
	RegionIdAlias      string
	AddressType        AddressType
	VSwitchId          string
	VpcId              string
	NetworkType        string
	Bandwidth          int
	InternetChargeType InternetChargeType
	CreateTime         string //Why not ISO 6801
	CreateTimeStamp    util.ISO6801Time
	ListenerPorts      struct {
		ListenerPort []int
	}
	ListenerPortsAndProtocol struct {
		ListenerPortAndProtocol []ListenerPortAndProtocolType
	}
	BackendServers struct {
		BackendServer []BackendServerType
	}
}

type DescribeLoadBalancersResponse struct {
	common.Response
	LoadBalancers struct {
		LoadBalancer []LoadBalancerType
	}
}

// DescribeLoadBalancers Describe loadbalancers
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DescribeLoadBalancers

func (client *Client) DescribeLoadBalancers(args *DescribeLoadBalancersArgs) (loadBalancers []LoadBalancerType, err error) {
	response := &DescribeLoadBalancersResponse{}
	err = client.Invoke("DescribeLoadBalancers", args, response)
	if err != nil {
		return nil, err
	}
	return response.LoadBalancers.LoadBalancer, err
}

type DescribeLoadBalancerAttributeArgs struct {
	LoadBalancerId string
}

type DescribeLoadBalancerAttributeResponse struct {
	common.Response
	LoadBalancerType
}

// DescribeLoadBalancerAttribute Describe loadbalancer attribute
//
// You can read doc at http://docs.aliyun.com/#/pub/slb/api-reference/api-related-loadbalancer&DescribeLoadBalancerAttribute

func (client *Client) DescribeLoadBalancerAttribute(loadBalancerId string) (loadBalancer *LoadBalancerType, err error) {
	args := &DescribeLoadBalancersArgs{
		LoadBalancerId: loadBalancerId,
	}
	response := &DescribeLoadBalancerAttributeResponse{}
	err = client.Invoke("DescribeLoadBalancerAttribute", args, response)
	if err != nil {
		return nil, err
	}
	return &response.LoadBalancerType, err
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import React, {
  Component
} from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Image,
  Dimensions,
  TouchableHighlight,
  ScrollView,
  AsyncStorage,
} from 'react-native';

const {width, height} = Dimensions.get('window');

import Video from 'react-native-video';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';

export default class Home extends Component {

  componentDidMount() {
    this.getData();
    this.randomUsers();
  }

  getData() {
    AsyncStorage.multiGet(['userId', 'userName', 'userAvatar']).then((data) => {
      console.log(data)
      let userName = data[1][1];
      let userId = data[0][1];
      let userAvatar = data[2][1];
      if (userId != null) {
        this.props.navigator.replace({id: 'welcome'});
      }
    }).done();
  }

  randomUsers() {
    fetch("http://www.amkwebsolutions.com/trades/random-protraders/", {
      method: "GET",
    }).then((response) => response.json())
    .then((responseData) => {
      this.state.user1 = responseData.randomusers_image[0],
      this.state.user2 = responseData.randomusers_image[1],
      this.state.user3 = responseData.randomusers_image[2],
      this.state.user4 = responseData.randomusers_image[3]
    }).done();
  }

  state = {
    rate: 1,
    volume: 1,
    muted: false,
    resizeMode: 'contain',
    duration: 0.0,
    currentTime: 0.0,
    paused: true,
  };

  video: Video;

  onLoad = (data) => {
    this.setState({ duration: data.duration });
  };

  onProgress = (data) => {
    this.setState({ currentTime: data.currentTime });
  };

  onEnd = () => {
    this.setState({ paused: true })
    this.video.seek(0)
  };

  onAudioBecomingNoisy = () => {
    this.setState({ paused: true })
  };

  onAudioFocusChanged = (event: { hasAudioFocus: boolean }) => {
    this.setState({ paused: !event.hasAudioFocus })
  };

  getCurrentTimePercentage() {
    if (this.state.currentTime > 0) {
      return parseFloat(this.state.currentTime) / parseFloat(this.state.duration);
    }
    return 0;
  };

  renderRateControl(rate) {
    const isSelected = (this.state.rate === rate);

    return (
      <TouchableOpacity onPress={() => { this.setState({ rate }) }}>
        <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
          {rate}x
        </Text>
      </TouchableOpacity>
    );
  }

  renderResizeModeControl(resizeMode) {
    const isSelected = (this.state.resizeMode === resizeMode);

    return (
      <TouchableOpacity onPress={() => { this.setState({ resizeMode }) }}>
        <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
          {resizeMode}
        </Text>
      </TouchableOpacity>
    )
  }

  renderVolumeControl(volume) {
    const isSelected = (this.state.volume === volume);

    return (
      <TouchableOpacity onPress={() => { this.setState({ volume }) }}>
        <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
          {volume * 100}%
        </Text>
      </TouchableOpacity>
    )
  }

  render() {
    const flexCompleted = this.getCurrentTimePercentage() * 100;
    const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100;

    return (
      <View style={styles.container}>
        <View style={styles.header_main} >
            <Image source={{uri: 'http://res.cloudinary.com/vowelweb/image/upload/v1498114115/Logo_mqzlgt.png'}}   style={styles.header_logo}/>
        </View>
        <TouchableOpacity
          style={styles.fullScreen}
          onPress={() => this.setState({ paused: !this.state.paused })}
        >
          <Video
            ref={(ref: Video) => { this.video = ref }}
            source={require('../video/mov_bbb.mp4')}
            style={{width: width, height: width / (16/9)}}
            rate={this.state.rate}
            paused={this.state.paused}
            volume={this.state.volume}
            muted={this.state.muted}
            resizeMode={this.state.resizeMode}
            onLoad={this.onLoad}
            onProgress={this.onProgress}
            onEnd={this.onEnd}
            onAudioBecomingNoisy={this.onAudioBecomingNoisy}
            onAudioFocusChanged={this.onAudioFocusChanged}
            repeat={false}
          />
        </TouchableOpacity>
        <ScrollView>
        <View style={{flex: 0.5, flexDirection: 'row', paddingBottom: 10, paddingTop: 5,}}>
            <TouchableHighlight style={styles.buttonLogin} onPress={() => this.props.navigator.push({id: 'login'})} underlayColor='#99d9f4'>
              <Text style={styles.buttonTextLogin}>LOGIN</Text>
            </TouchableHighlight>
            <TouchableHighlight style={styles.buttonRegister} onPress={() => this.props.navigator.push({id: 'register'})} underlayColor='#99d9f4'>
              <Text style={styles.buttonTextRegister}>REGISTER</Text>
            </TouchableHighlight>
        </View>
        <View style={{flex: 0.2, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingBottom: 10,}}>
          <Text style={styles.heading}>The Coin TradePros Traders</Text>
          <Text style={styles.heading}>Here Can Help!</Text>
        </View>
        <View style={{flex: 0.5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
          <Image source={{uri: this.state.user1 }} style={{width: 120, height: 120, marginRight: 50, marginBottom: 10, borderRadius: 150,}} />
          <Image source={{uri: this.state.user2 }} style={{width: 120, height: 120, marginBottom: 10, borderRadius: 150,}} />
        </View>
        <View style={{flex: 0.5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
          <Image source={{uri: this.state.user3 }} style={{width: 120, height: 120, marginRight: 50, marginBottom: 10, borderRadius: 150,}} />
          <Image source={{uri: this.state.user4 }} style={{width: 120, height: 120, marginBottom: 10, borderRadius: 150,}} />
        </View>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#efeff2',
  },
  fullScreen: {
    flex: 0.6,
    backgroundColor: 'black',
    justifyContent: 'center',
    borderBottomWidth:2,
    borderColor: 'black',
  },
  header_main: {
    flex: 0.25,
    backgroundColor: 'white',
    justifyContent: 'center',
    flexDirection: 'row',
    paddingLeft: 30,
    paddingRight: 30,
    borderBottomWidth:1,
  },
  header_logo: {
    flex:1,
    width:null,
    height:null,
    resizeMode:'contain'
  },
    buttonTextLogin: {
    fontSize: 18,
    color: '#d40000',
    alignSelf: 'center',
    fontFamily: 'Montserrat-SemiBold',
  },
  buttonLogin: {
    height: 40,
    backgroundColor: '#fff',
    borderColor: '#d40000',
    borderWidth: 2,
    marginTop: 10,
    marginBottom: 0,
    alignSelf: 'stretch',
    justifyContent: 'center',
    marginLeft: 20,
    marginRight: 10,
    width: responsiveWidth(41.5),
  },
    buttonTextRegister: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center',
    fontFamily: 'Montserrat-SemiBold',
  },
  buttonRegister: {
    height: 40,
    backgroundColor: '#217821',
    borderColor: '#217821',
    borderWidth: 2,
    marginTop: 10,
    marginBottom: 0,
    alignSelf: 'stretch',
    justifyContent: 'center',
    marginLeft: 10,
    marginRight: 20,
    width: responsiveWidth(41.5),
  },
  heading: {
    fontFamily: 'Montserrat-SemiBold',
    color: 'black',
    fontSize: 22,
  }
});


text:
/**
 *    @file
 *      This file defines types and objects for reading and writing
 *      Abstract Syntax Notation One (ASN.1) encoded data.
 *
 */

#pragma once

#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include <asn1/ASN1OID.h>
#endif

#include <lib/asn1/ASN1Error.h>
#include <lib/support/DLLUtil.h>
#include <lib/support/Span.h>

namespace chip {
namespace TLV {
class TLVReader;
}
} // namespace chip

/**
 *   @namespace chip::ASN1
 *
 *   @brief
 *     This namespace includes all interfaces within CHIP for
 *     working with Abstract Syntax Notation One (ASN.1).
 */

namespace chip {
namespace ASN1 {

static constexpr size_t kMaxConstructedAndEncapsulatedTypesDepth = 10;

enum ASN1TagClasses
{
    kASN1TagClass_Universal       = 0x00,
    kASN1TagClass_Application     = 0x40,
    kASN1TagClass_ContextSpecific = 0x80,
    kASN1TagClass_Private         = 0xC0
};

enum ASN1UniversalTags : uint8_t
{
    kASN1UniversalTag_Boolean         = 1,
    kASN1UniversalTag_Integer         = 2,
    kASN1UniversalTag_BitString       = 3,
    kASN1UniversalTag_OctetString     = 4,
    kASN1UniversalTag_Null            = 5,
    kASN1UniversalTag_ObjectId        = 6,
    kASN1UniversalTag_ObjectDesc      = 7,
    kASN1UniversalTag_External        = 8,
    kASN1UniversalTag_Real            = 9,
    kASN1UniversalTag_Enumerated      = 10,
    kASN1UniversalTag_UTF8String      = 12,
    kASN1UniversalTag_Sequence        = 16,
    kASN1UniversalTag_Set             = 17,
    kASN1UniversalTag_NumericString   = 18,
    kASN1UniversalTag_PrintableString = 19,
    kASN1UniversalTag_T61String       = 20,
    kASN1UniversalTag_VideotexString  = 21,
    kASN1UniversalTag_IA5String       = 22,
    kASN1UniversalTag_UTCTime         = 23,
    kASN1UniversalTag_GeneralizedTime = 24,
    kASN1UniversalTag_GraphicString   = 25,
    kASN1UniversalTag_VisibleString   = 26,
    kASN1UniversalTag_GeneralString   = 27,
    kASN1UniversalTag_UniversalString = 28
};

/**
 *  @struct ASN1UniversalTime
 *
 *  @brief
 *    A data structure representing ASN1 universal time in a calendar format.
 */
struct ASN1UniversalTime
{
    uint16_t Year;  /**< Year component. Legal interval is 0..9999. */
    uint8_t Month;  /**< Month component. Legal interval is 1..12. */
    uint8_t Day;    /**< Day of month component. Legal interval is 1..31. */
    uint8_t Hour;   /**< Hour component. Legal interval is 0..23. */
    uint8_t Minute; /**< Minute component. Legal interval is 0..59. */
    uint8_t Second; /**< Second component. Legal interval is 0..59. */

    static constexpr size_t kASN1UTCTimeStringLength         = 13;
    static constexpr size_t kASN1GeneralizedTimeStringLength = 15;
    static constexpr size_t kASN1TimeStringMaxLength         = 15;

    /**
     * @brief Set time from ASN1_TIME string.
     *        Two string formats are supported:
     *            YYMMDDHHMMSSZ - for years in the range 1950 - 2049
     *          YYYYMMDDHHMMSSZ - other years
     **/
    CHIP_ERROR ImportFrom_ASN1_TIME_string(const CharSpan & asn1_time);

    /**
     * @brief Encode time as an ASN1_TIME string.
     *        Two string formats are supported:
     *            YYMMDDHHMMSSZ - for years in the range 1950 - 2049
     *          YYYYMMDDHHMMSSZ - other years
     **/
    CHIP_ERROR ExportTo_ASN1_TIME_string(MutableCharSpan & asn1_time) const;

    /**
     * @brief Encode time as Unix epoch time.
     **/
    bool ExportTo_UnixTime(uint32_t & unixEpoch);
};

class DLL_EXPORT ASN1Reader
{
public:
    void Init(const uint8_t * buf, size_t len);
    void Init(const ByteSpan & data) { Init(data.data(), data.size()); }
    template <size_t N>
    void Init(const uint8_t (&data)[N])
    {
        Init(data, N);
    }

    uint8_t GetClass(void) const { return Class; };
    uint8_t GetTag(void) const { return Tag; };
    const uint8_t * GetValue(void) const { return Value; };
    uint32_t GetValueLen(void) const { return ValueLen; };
    bool IsConstructed(void) const { return Constructed; };
    bool IsIndefiniteLen(void) const { return IndefiniteLen; };
    bool IsEndOfContents(void) const { return EndOfContents; };

    CHIP_ERROR Next(void);
    CHIP_ERROR EnterConstructedType(void);
    CHIP_ERROR ExitConstructedType(void);
    CHIP_ERROR GetConstructedType(const uint8_t *& val, uint32_t & valLen);
    CHIP_ERROR EnterEncapsulatedType(void);
    CHIP_ERROR ExitEncapsulatedType(void);
    bool IsContained(void) const;
    CHIP_ERROR GetInteger(int64_t & val);
    CHIP_ERROR GetBoolean(bool & val);
    CHIP_ERROR GetObjectId(OID & oid);
    CHIP_ERROR GetUTCTime(ASN1UniversalTime & outTime);
    CHIP_ERROR GetGeneralizedTime(ASN1UniversalTime & outTime);
    CHIP_ERROR GetBitString(uint32_t & outVal);

private:
    static constexpr size_t kMaxContextDepth = kMaxConstructedAndEncapsulatedTypesDepth;

    struct ASN1ParseContext
    {
        const uint8_t * ElemStart;
        uint32_t HeadLen;
        uint32_t ValueLen;
        bool IndefiniteLen;
        const uint8_t * ContainerEnd;
    };

    uint8_t Class;
    uint8_t Tag;
    const uint8_t * Value;
    uint32_t ValueLen;
    bool Constructed;
    bool IndefiniteLen;
    bool EndOfContents;

    const uint8_t * mBuf;
    const uint8_t * mBufEnd;
    const uint8_t * mElemStart;
    const uint8_t * mContainerEnd;
    uint32_t mHeadLen;
    ASN1ParseContext mSavedContexts[kMaxContextDepth];
    uint32_t mNumSavedContexts;

    CHIP_ERROR DecodeHead(void);
    void ResetElementState(void);
    CHIP_ERROR EnterContainer(uint32_t offset);
    CHIP_ERROR ExitContainer(void);
};

class DLL_EXPORT ASN1Writer
{
public:
    void Init(uint8_t * buf, size_t maxLen);
    void Init(const MutableByteSpan & data) { Init(data.data(), data.size()); }
    template <size_t N>
    void Init(uint8_t (&data)[N])
    {
        Init(data, N);
    }
    void InitNullWriter(void);
    size_t GetLengthWritten(void) const;

    CHIP_ERROR PutInteger(int64_t val);
    CHIP_ERROR PutBoolean(bool val);
    CHIP_ERROR PutObjectId(const uint8_t * val, uint16_t valLen);
    CHIP_ERROR PutObjectId(OID oid);
    CHIP_ERROR PutString(uint8_t tag, const char * val, uint16_t valLen);
    CHIP_ERROR PutOctetString(const uint8_t * val, uint16_t valLen);
    CHIP_ERROR PutOctetString(uint8_t cls, uint8_t tag, const uint8_t * val, uint16_t valLen);
    CHIP_ERROR PutOctetString(uint8_t cls, uint8_t tag, chip::TLV::TLVReader & tlvReader);
    CHIP_ERROR PutBitString(uint32_t val);
    CHIP_ERROR PutBitString(uint8_t unusedBits, const uint8_t * val, uint16_t valLen);
    CHIP_ERROR PutBitString(uint8_t unusedBits, chip::TLV::TLVReader & tlvReader);
    CHIP_ERROR PutTime(const ASN1UniversalTime & val);
    CHIP_ERROR PutNull(void);
    CHIP_ERROR PutConstructedType(const uint8_t * val, uint16_t valLen);
    CHIP_ERROR StartConstructedType(uint8_t cls, uint8_t tag);
    CHIP_ERROR EndConstructedType(void);
    CHIP_ERROR StartEncapsulatedType(uint8_t cls, uint8_t tag, bool bitStringEncoding);
    CHIP_ERROR EndEncapsulatedType(void);
    CHIP_ERROR PutValue(uint8_t cls, uint8_t tag, bool isConstructed, const uint8_t * val, uint16_t valLen);
    CHIP_ERROR PutValue(uint8_t cls, uint8_t tag, bool isConstructed, chip::TLV::TLVReader & tlvReader);

private:
    static constexpr size_t kMaxDeferredLengthDepth = kMaxConstructedAndEncapsulatedTypesDepth;

    uint8_t * mBuf;
    uint8_t * mBufEnd;
    uint8_t * mWritePoint;
    uint8_t * mDeferredLengthLocations[kMaxDeferredLengthDepth];
    uint8_t mDeferredLengthCount;

    CHIP_ERROR EncodeHead(uint8_t cls, uint8_t tag, bool isConstructed, int32_t len);
    CHIP_ERROR WriteDeferredLength(void);
    static uint8_t BytesForLength(int32_t len);
    static void EncodeLength(uint8_t * buf, uint8_t bytesForLen, int32_t lenToEncode);
    void WriteData(const uint8_t * p, size_t len);
};

OID ParseObjectID(const uint8_t * encodedOID, uint16_t encodedOIDLen);
bool GetEncodedObjectID(OID oid, const uint8_t *& encodedOID, uint16_t & encodedOIDLen);

OIDCategory GetOIDCategory(OID oid);

const char * GetOIDName(OID oid);

CHIP_ERROR DumpASN1(ASN1Reader & reader, const char * prefix, const char * indent);

inline OID GetOID(OIDCategory category, uint8_t id)
{
    return static_cast<OID>(category | id);
}

inline uint8_t GetOIDEnum(OID oid)
{
    return static_cast<uint8_t>(oid & kOID_EnumMask);
}

} // namespace ASN1
} // namespace chip


text:
import { login } from 'requests/passport'
import { routerRedux } from 'dva/router'
import showOpsNotification from 'utils/notification'

export default {
  namespace: 'passport',
  state: {
    loginLoading: false,
  },

  effects: {
    *login ({
      payload,
    }, { put, call }) {
      yield put({ type: 'showLoginLoading' })
      const data = yield call(login, payload)
      yield put({ type: 'hideLoginLoading' })
      data.notice = true
      showOpsNotification(data, 'Login')
      if (data.success) {
        yield put({ type: 'app/init' })
      }
    },
  },
  reducers: {
    showLoginLoading (state) {
      return {
        ...state,
        loginLoading: true,
      }
    },
    hideLoginLoading (state) {
      return {
        ...state,
        loginLoading: false,
      }
    },
  },
}


text:
'use strict';

import React from 'react';
import {Router, Route, Link} from 'react-router'
import Reflux from 'reflux';
import classNames from 'classnames';

import Store from './store';
import Actions from './actions';
import CurrencyForm from './components';

var CurrencyHandler = React.createClass({
  mixins: [
    Reflux.listenTo(Store, 'onStoreUpdate')
  ],

  componentDidMount() {
    Actions.load(this.props.params.id);
  },

  getInitialState() {
    var storeData = Store.getDefaultData();
    return {
      currency: storeData.currency,
      currencies: storeData.currencies,
    };
  },

  onStoreUpdate(storeData) {
    if (storeData.loaded !== undefined) {
      this.setState({loaded: storeData.loaded});
    }

    if (storeData.currency !== undefined) {
      this.setState({currency: storeData.currency});
    }

    if (storeData.currencies !== undefined) {
      this.setState({currencies: storeData.currencies});
    }
  },

  renderForm() {
    if (this.props.params.id && !this.state.currency.id) {
      return

;
    }

    if (!this.state.loaded) {
      return

;
    }

    return <CurrencyForm currency={this.state.currency}
                        currencies={this.state.currencies} />
  },

  render() {
    return (

            Currency

              <Link to="/p/dashboard"> Home</Link>

              <Link to="/p/currencies"> Currencies</Link>

Currency

          {this.renderForm()}

    );
  }
});

export default CurrencyHandler;


text:
package org.ligi.axt.listeners;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class ActivityFinishingOnClickListener implements OnClickListener {

	private final Activity activity2finish;

	public ActivityFinishingOnClickListener(
            Activity activity2finish) {
		this.activity2finish=activity2finish;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		activity2finish.finish();
	}

}


text:
package com.bigstark.video;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;

import java.io.IOException;

/**
 * Created by bigstark on 16. 1. 6..
 */
public class BigstarVideoView extends TextureView {
    private static final String TAG = BigstarVideoView.class.getSimpleName();

    public static final int STATE_PLAYING = 0;
    public static final int STATE_PAUSE = 1;
    public static final int STATE_STOPPED = 2;
    public static final int STATE_RELEASED = 3;

    private boolean startImmediately = false;
    private boolean isRetainPlayerInstance = false;

    private Uri uri;
    private MediaPlayer player;
    private PlaybackEventListenerImpl playbackEventListenerImpl;
    private PlayStateChangedListenerImpl playStateChangedListenerImpl;

    private PositionHandler positionHandler = new PositionHandler();

    public BigstarVideoView(Context context) {
        this(context, null);
    }

    public BigstarVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BigstarVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initSurface();
    }

    private void initSurface() {
        // set surface texture listener.
        SurfaceTextureListenerImpl surfaceTextureListener = new SurfaceTextureListenerImpl();
        super.setSurfaceTextureListener(surfaceTextureListener);
    }

    private void initPlayer() {
        // initialize media player.
        playbackEventListenerImpl = new PlaybackEventListenerImpl();
        playStateChangedListenerImpl = new PlayStateChangedListenerImpl();

        player = new MediaPlayer();
        player.setOnPreparedListener(playStateChangedListenerImpl);
        player.setOnErrorListener(playStateChangedListenerImpl);
        player.setOnCompletionListener(playStateChangedListenerImpl);
        player.setOnBufferingUpdateListener(playbackEventListenerImpl);
        player.setOnSeekCompleteListener(playbackEventListenerImpl);
    }

    /**
     * Prepare video from uri.
     *
     * @param uri
     */
    public void setVideoURI(Uri uri) {
        setVideoURI(uri, false);
    }

    /**
     * Prepare video from uri.
     *

     * When prepare complete, start video immediately or not.
     *
     * @param uri
     * @param startImmediately
     */
    public void setVideoURI(Uri uri, boolean startImmediately) {
        this.uri = uri;
        this.startImmediately = startImmediately;

        // player is released. reinitialize
        synchronized (BigstarVideoView.class) {
            if (player == null) {
                initPlayer();
            }
        }

        try {
            player.setDataSource(getContext(), uri);
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private SurfaceTextureListener listener;

    @Override
    public void setSurfaceTextureListener(SurfaceTextureListener listener) {
        this.listener = listener;
    }

    private class SurfaceTextureListenerImpl implements SurfaceTextureListener {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
            Log.v(TAG, String.format("Surface now available - width : %d, height : %d", width, height));
            synchronized (BigstarVideoView.class) {
                if (player == null) {
                    initPlayer();

                    if (uri != null) {
                        setVideoURI(uri, startImmediately);
                    }
                }
            }

            Surface surface = new Surface(surfaceTexture);
            player.setSurface(surface);

            if (listener != null) {
                listener.onSurfaceTextureAvailable(surfaceTexture, width, height);
            }
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            Log.v(TAG, String.format("Surface size changed - width : %d, height : %d", width, height));

            if (listener != null) {
                listener.onSurfaceTextureSizeChanged(surface, width, height);
            }
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            Log.v(TAG, "Surface is destroyed");

            if (!isRetainPlayerInstance) {
                release();
            }

            if (listener != null) {
                return listener.onSurfaceTextureDestroyed(surface);
            }

            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
            if (listener != null) {
                listener.onSurfaceTextureUpdated(surface);
            }
        }
    }

    /**
     * set Retain MediaPlayer instance.
     *
     * @param isRetain
     */
    public void setRetainPlayerInstance(boolean isRetain) {
        this.isRetainPlayerInstance = isRetain;
    }

    /**
     * @return video's width
     */
    public int getVideoWidth() {
        return isReleased() ? 0 : player.getVideoWidth();
    }

    /**
     * @return video's height
     */
    public int getVideoHeight() {
        return isReleased() ? 0 : player.getVideoHeight();
    }

    /**
     * Start video.
     *

     * If uri is null, not working.
     */
    public void start() {
        // player is released.
        if (isReleased()) {
            throw new IllegalStateException("BigstarVideoView is released. Set video uri again.");
        }

        if (uri == null) {
            return;
        }

        player.start();
        positionHandler.sendMessage(positionHandler.obtainMessage(STATE_PLAYING));
        playbackEventListenerImpl.onPlaying();
    }

    /**
     * Pause video.
     *

     * If uri is null, not working.
     */
    public void pause() {
        // player is released.
        if (isReleased()) {
            throw new IllegalStateException("BigstarVideoView is released. Set video uri again.");
        }

        if (uri == null) {
            return;
        }

        player.pause();
        positionHandler.sendMessage(positionHandler.obtainMessage(STATE_PAUSE));
        playbackEventListenerImpl.onPaused();
    }

    /**
     * Stop video.
     *

     * If uri is null, not working.
     */
    public void stop() {
        // player is released.
        if (isReleased()) {
            throw new IllegalStateException("BigstarVideoView is released. Set video uri again.");
        }

        if (uri == null) {
            return;
        }

        player.stop();
        positionHandler.sendMessage(positionHandler.obtainMessage(STATE_STOPPED));
        playbackEventListenerImpl.onStopped();
    }

    /**
     * Release media player.
     *

     * It releases all listener, so After releases, re initialize.
     */
    public void release() {
        // already released
        if (player == null) {
            return;
        }

        Log.v(TAG, "VideoView is released");

        positionHandler.sendMessage(positionHandler.obtainMessage(STATE_STOPPED));
        player.release();

        player = null;
        uri = null;
        startImmediately = false;

        if (playStateChangedListenerImpl != null) {
            playStateChangedListenerImpl.onReleased();
        }
    }

    /**
     * @return player released or not.
     */
    public boolean isReleased() {
        return player == null;
    }

    /**
     * @return video is playing or not.
     */
    public boolean isPlaying() {
        return player != null && uri != null && player.isPlaying();
    }

    /**
     * @return current position of media player
     */
    public int getCurrentPosition() {
        return player == null ? 0 : player.getCurrentPosition();
    }

    /**
     * @return duration of media player
     */
    public int getDuration() {
        return player == null ? 0 : player.getDuration();
    }

    /**
     * seek to position
     *
     * @param msec : micro seconds.
     */
    public void seekTo(int msec) {
        if (player == null) {
            throw new IllegalStateException("BigstarVideoView is released. Set video uri again.");
        }

        player.seekTo(msec);
    }

    private OnPlaybackEventListener onPlaybackEventListener;
    private OnPlayStateChangedListener onPlayStateChangedListener;

    /**
     * It works only video screen is alive state.
     *
     * @param listener
     */
    public void setOnPlaybackEventListener(OnPlaybackEventListener listener) {
        this.onPlaybackEventListener = listener;
    }

    /**
     * When player released, it works.
     *
     * @param listener
     */
    public void setOnPlayStateChangedListener(OnPlayStateChangedListener listener) {
        this.onPlayStateChangedListener = listener;
    }

    private class PlaybackEventListenerImpl implements OnPlaybackEventListener, MediaPlayer.OnBufferingUpdateListener,
            MediaPlayer.OnSeekCompleteListener {

        @Override
        public void onPlaying() {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onPlaying();
            }
        }

        @Override
        public void onPaused() {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onPaused();
            }
        }

        @Override
        public void onStopped() {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onStopped();
            }
        }

        @Override
        public void onPositionChanged(int position) {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onPositionChanged(position);
            }
        }

        private int buffering = 0;
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            if (buffering == percent) {
                return;
            }

            buffering = percent;
            onBufferingUpdate(buffering);
        }

        @Override
        public void onBufferingUpdate(int buffering) {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onBufferingUpdate(buffering);
            }
        }

        @Override
        public void onSeekComplete(MediaPlayer mp) {
            onSeekComplete();
        }

        @Override
        public void onSeekComplete() {
            if (onPlaybackEventListener != null) {
                onPlaybackEventListener.onSeekComplete();
            }
        }
    }

    private class PlayStateChangedListenerImpl implements OnPlayStateChangedListener, MediaPlayer.OnPreparedListener,
            MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            onPrepared();

            if (startImmediately) {
                start();
            }
        }

        @Override
        public void onPrepared() {
            if (onPlayStateChangedListener != null) {
                onPlayStateChangedListener.onPrepared();
            }
        }

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            onError(ErrorReason.NETWORK);
            return false;
        }

        @Override
        public void onError(ErrorReason reason) {
            if (onPlayStateChangedListener != null) {
                onPlayStateChangedListener.onError(reason);
            }
        }

        @Override
        public void onCompletion(MediaPlayer mp) {
            onCompletion();
        }

        @Override
        public void onCompletion() {
            if (onPlayStateChangedListener != null) {
                onPlayStateChangedListener.onCompletion();
            }
        }

        @Override
        public void onReleased() {
            if (onPlayStateChangedListener != null) {
                onPlayStateChangedListener.onReleased();
            }
        }
    }

    /**
     * It is used to check position changed.
     *
     * It runs every 128ms when state is playing.
     */
    private class PositionHandler extends Handler {
        private static final int INTERVAL_TIME = 128;

        private int previousPosition = 0;

        public PositionHandler() {
            super(Looper.myLooper());
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case STATE_PLAYING:
                    schedulePlaying();
                    break;
                case STATE_STOPPED:
                case STATE_RELEASED:
                case STATE_PAUSE:
                    removeMessages(STATE_PLAYING);

            }
        }

        private void schedulePlaying() {
            removeMessages(STATE_PLAYING);
            if (player == null || isReleased()) {
                Log.e(TAG, "player is not initialized or released.");
                return;
            }

            if (!player.isPlaying()) {
                Log.v("BigstarVideoView", "player is not playing so start again");
                start();
                return;
            }

            Message msg = obtainMessage();
            msg.what = STATE_PLAYING;
            sendMessageDelayed(msg, INTERVAL_TIME);

            int offset = player.getCurrentPosition();
            if (this.previousPosition == offset) {
                return;
            }

            this.previousPosition = offset;
            playbackEventListenerImpl.onPositionChanged(offset);
        }
    }
}


text:
import string

import requests
from bs4 import BeautifulSoup

from app import db

from app.models import Set, LetterScore

def tidy_name(raw_name):
    # Only use first line
    result = raw_name.split('<')[0]

    # Remove anything past "(" or "#"
    result = result.split('(')[0].split('#')[0]

    # Remove 'letter', 'distribution' and 'Scrabble'
    for word in ['letter', 'distribution', 'Scrabble']:
        result = result.replace(word, '')

    return result.strip()

class PointsTable():
    def __init__(self, soup_table):
        # print(soup_table)
        self.name = tidy_name(soup_table.find('caption').text)
        self.soup_table = soup_table

    def parse_table(self):
        result = {}
        # First row contains the header - distribution, skip this
        for table_row in self.soup_table.findAll('tr')[1:]:
            row_value = int(table_row.find('th').text)
            for table_cell in table_row.findAll('td'):
                letters = table_cell.text.upper()
                letters = letters.replace('BLANK', '').replace(' ', '')
                for letter in letters:
                    if letter in string.ascii_uppercase:
                        result[letter] = row_value
        self.points = result

def extract_points(soup):
    languages_found = []
    result = []

    for soup_table in soup.findAll('table')[1:]:
        points_table = PointsTable(soup_table)

        # Only use first table for each language
        if not points_table.name in languages_found:
            points_table.parse_table()

            if points_table.points.keys():
                languages_found.append(points_table.name)
                result.append(points_table)

    return result

def store_points(points):
    for points_table in points:
        # Skip the 'Super' set, as it is not a separate language
        if points_table.name == 'Super':
            continue

        # Skip tables with an unprintable name
        try:
            print(points_table.name)
        except:
            continue

        set_record = Set(name=points_table.name)
        db.session.add(set_record)
        db.session.commit()

        for letter, score in points_table.points.iteritems():
            score_record = LetterScore(set_id=set_record.id, letter=letter, score=score)
            db.session.add(score_record)
            db.session.commit()

db.create_all()

print("Deleting any previous data")
db.session.query(LetterScore).delete()
db.session.query(Set).delete()
db.session.commit()
print("Done")

r = requests.get('https://en.wikipedia.org/wiki/Scrabble_letter_distributions')
soup = BeautifulSoup(r.text)

points = extract_points(soup)

store_points(points)


text:
import Eventer from "../Eventer";
import { ToolMenuGroup, ToolMenuItem, CheckMenuItem, ZoomMenuItem } from "../tool_menu/BoardTools";
import { ToolRenderer } from "./ToolRenderer";
import { CopyTool, PasteTool } from "./CopyPaste";
import { Eraser, Pen } from "./Drawing";
import { AddFogPen, RemoveFogPen, AddFogShape, RemoveFogShape } from "./Fog";
import { GlobalShortCuts } from "./GlobalShortcuts";
import { InsertImageTool } from "./InsertImage";
import { LabelTool } from "./Label";
import { OverlandMeasureTemplateTool } from "./OverlandTemplates";
import { PingTool } from "./Ping";
import { Pointer } from "./Pointer";
import { ReachTemplateTool } from "./ReachTemplates";
import { ShapeTool } from "./Shape";
import { ConeTemplate, LineTemplate, Measure, RadiusTemplate, RectangleTemplate } from "./Templates";
import { TokenTool } from "./Tokens";
import { TokensFromTool } from "./TokensFromTool";
import { generateActionId } from "../Actions";
import {LevelTool} from "./LevelTool";
import { LevelHole } from "./LevelHole";
import { SavageWorldsBurstTemplateTool, SavageWorldsConeTemplateTool} from "./SavageWorldsTemplates";

export class ToolManager extends Eventer {

  constructor(board) {
    super();

    this.board = board;
    this.currentTool = null;

    var self = this;

    this.sharedToolOptions = {
      pingColor: ({type: "color", label: "Color", name: "color", value: "#EE204D"}),
      drawingColor: ({type: "color", label: "Color", name: "color", value: "#000000"}),
      drawingBackgroundColor: ({type: "color", label: "Background Color", name: "backgroundColor", includeClear: true, value: null}),
      drawingWidth: ({type: "size", name: "width", label: "Width", sizes: [5, 7, 10, 15, 20, 30], value: 7 }),
      fogWidth: ({type: "size", name: "width", label: "Width", sizes: [25, 75, 100, 200, 500], value: 75 }),
      templateColor: ({type: "color", name: "color", label: "Color", value: "#EE204D"}),
      copiedImage: ({type: "copiedImage", url: this.board.copiedArea, name: 'copiedImage'})
    };

    this.toolMap = {
      "pointer": new Pointer(this),
      "pen": new Pen(this),
      "shape": new ShapeTool(this),
      "eraser": new Eraser(this),
      "measure_template": new Measure(this),
      "line_template": new LineTemplate(this),
      "rectangle_template": new RectangleTemplate(this),
      "radius_template": new RadiusTemplate(this),
      "cone_template": new ConeTemplate(this),
      "reach_template": new ReachTemplateTool(this),
      "overland_measure_template": new OverlandMeasureTemplateTool(this),
      "savage_worlds_burst_template": new SavageWorldsBurstTemplateTool(this),
      "savage_worlds_cone_template": new SavageWorldsConeTemplateTool(this),
      "ping": new PingTool(this),
      "add_fog": new AddFogPen(this),
      "add_fog_shape": new AddFogShape(this),
      "remove_fog": new RemoveFogPen(this),
      "remove_fog_shape": new RemoveFogShape(this),
      "label": new LabelTool(this),
      "copy": new CopyTool(this),
      "paste": new PasteTool(this),
      "insert_image": new InsertImageTool(this),
      "tokens": new TokenTool(this),
      "tokens_from": new TokensFromTool(this),
      "levels": new LevelTool(this),
      "level_hole": new LevelHole(this)
    };

    this.templateGroups = {
      pathfinder: "pathfinder_template_group",
      overland: "overland_template_group",
      savage_worlds: "savage_worlds_template_group"
    };

    this.toolSet = [
      new ToolMenuGroup("pointer_group", [
        new ToolMenuItem("pointer", {
          label: "Pointer",
          glyph: ["fas", "mouse-pointer"],
          handler: function() { self.setTool("pointer"); }
        }),

        new ToolMenuItem("ping", {
          label: "Ping",
          glyph: ["fas", "bullseye"],
          handler: function() { self.setTool("ping"); }
        })
      ]),

      new ToolMenuGroup("view_group", {noClickthrough: true}, [
        new ZoomMenuItem("zoom", {
          label: "Zoom",
          glyph: ["fas", "search-plus"],
          handler: function(zoom) { self.changeZoom(zoom); }
        }),

        new ToolMenuItem("levels", {
          label: "Levels",
          glyph: ["fas", "layer-group"],
          handler: () => this.setTool("levels")
        }),

        new ToolMenuItem("tokens", {
          label: "Tokens",
          glyph: ["fas", "user-circle"],
          handler: function() { self.setTool("tokens"); }
        }),

        new ToolMenuItem("tokens_from", {
          label: "Tokens From",
          glyph: ["fas", "users"],
          handler: function() { self.setTool("tokens_from"); }
        }),

        new ToolMenuItem("fullscreen", {
          label: "Fullscreen",
          glyph: ["fas", "tv"],
          handler: function() {
            self.board.toggleFullscreen();
          }
        }),

        new ToolMenuItem("save_viewport", {
          label: "Save View",
          glyph: ["fas", "plus"],
          handler: function() {
            self.board.saveViewPort();
          }
        }),

        new ToolMenuItem("restore_viewport", {
          label: "Restore View",
          glyph: ["fas", "minus"],
          visible: false,
          handler: function() {
            self.board.restoreViewPort();
          }
        }),

        new CheckMenuItem("view_port_sync", {
          label: "Sync View",
          glyph: ["fas", "sync-alt"],
          handler: function() {
            self.board.viewPortManager.toggleSynced();
          }
        }),

        new ToolMenuItem("beckon", {
          label: "Beckon",
          tooltip: "Beckon PCs to current view",
          glyph: ["fas", "compress-arrows-alt"],
          handler: function() { self.board.beckon(); }
        }),
      ]),

      new ToolMenuGroup("draw_group", [
        new ToolMenuItem("pen", {
          label: "Pen",
          glyph: ["fas", "pen"],
          handler: function() { self.setTool("pen"); }
        }),

        new ToolMenuItem("eraser", {
          label: "Eraser",
          glyph: ["fas", "eraser"],
          handler: function() { self.setTool("eraser"); }
        }),

        new ToolMenuItem("shape", {
          label: "Shapes",
          tooltip: "Draw lines, circles, and rectangles",
          glyph: ["fas", "shapes"],
          handler: function() { self.setTool("shape"); }
        }),

        new ToolMenuItem("label", {
          label: "Label",
          tooltip: "Create a text label",
          glyph: ["fas", "font"],
          handler: function() { self.setTool("label"); }
        }),

        new ToolMenuItem("insert_image", {
          label: "Image",
          tooltip: "Insert an image",
          glyph: ["far", "image"],
          handler: function() { self.setTool("insert_image"); }
        }),

        new ToolMenuItem("level_hole", {
          label: "Level Hole",
          tooltip: "Create a translucent hole in this level",
          glyph: ["fas", "border-style"],
          handler: function() { self.setTool("level_hole") }
        }),

        new ToolMenuItem("copy", {
          label: "Copy",
          tooltip: "Copy a section of the drawing layer",
          glyph: ["fas", "copy"],
          handler: function() { self.setTool("copy"); }
        }),

        new ToolMenuItem("paste", {
          label: "Paste",
          tooltip: "Paste copied region",
          glyph: ["fas", "paste"],
          visible: false,
          handler: function() { self.setTool("paste"); }
        })
      ]),

      new ToolMenuGroup("pathfinder_template_group", [
        new ToolMenuItem("measure_template", {
          label: "Measure",
          tooltip: "Measures movement distance in a straight line",
          glyph: ["fas", "ruler"],
          handler: function() { self.setTool("measure_template"); }
        }),

        new ToolMenuItem("line_template", {
          label: "Line",
          tooltip: "Creates a line template (ie: Lightning Bolt)",
          glyph: ["fas", "bolt"],
          handler: function() { self.setTool("line_template"); }
        }),

        new ToolMenuItem("rectangle_template", {
          label: "Rectangle",
          tooltip: "Creates a rectangle template",
          glyph: ["far", "square"],
          handler: function() { self.setTool("rectangle_template"); }
        }),

        new ToolMenuItem("radius_template", {
          label: "Radius",
          tooltip: "Creates a circular radius template",
          glyph: ["far", "circle"],
          handler: function() { self.setTool("radius_template"); }
        }),

        new ToolMenuItem("cone_template", {
          label: "Cone",
          tooltip: "Creates a cone template",
          glyph: ["fas", "play"],
          handler: function() { self.setTool("cone_template"); }
        }),

        new ToolMenuItem("reach_template", {
          label: "Reach",
          tooltip: "Creates creature reach template",
          glyph: ["fas", "dharmachakra"],
          handler: function() { self.setTool("reach_template"); }
        })
      ]),

      new ToolMenuGroup("overland_template_group", [
        new ToolMenuItem("overland_measure_template", {
          label: "Measure",
          tooltip: "Measure distances",
          glyph: ["fas", "ruler"],
          handler: function() { self.setTool("overland_measure_template"); }
        })
      ]),

      new ToolMenuGroup("savage_worlds_template_group", [
        new ToolMenuItem("overland_measure_template", {
          label: "Measure",
          tooltip: "Measure distances",
          glyph: ["fas", "ruler"],
          handler: function() { self.setTool("overland_measure_template"); }
        }),

        new ToolMenuItem("savage_worlds_burst_template", {
          label: "Burst",
          tooltip: "Small, Medium, and Large Burst Templates",
          glyph: ["far", "circle"],
          handler: function() { self.setTool("savage_worlds_burst_template"); }
        }),

        new ToolMenuItem("savage_worlds_cone_template", {
          label: "Cone",
          tooltip: "Standard Cone Template",
          glyph: ["fas", "play"],
          handler: function() { self.setTool("savage_worlds_cone_template"); }
        })
      ]),

      new ToolMenuGroup("fog_group", [
        new ToolMenuItem("add_fog", {
          label: "Add Fog",
          tooltip: "Draw to add fog",
          glyph: ["fas", "cloud"],
          handler: function() { self.setTool("add_fog"); }
        }),

        new ToolMenuItem("add_fog_shape", {
          label: "Add Shape",
          tooltip: "Draw shapes to add fog",
          glyph: ["fas", "square"],
          handler: function() { self.setTool("add_fog_shape"); }
        }),

        new ToolMenuItem("remove_fog", {
          label: "Remove Fog",
          tooltip: "Draw to remove fog",
          glyph: ["fas", "eye"],
          handler: function() { self.setTool("remove_fog"); }
        }),

        new ToolMenuItem("remove_fog_shape", {
          label: "Remove Shape",
          tooltip: "Draw shapes to remove fog",
          glyph: ["fas", "minus-square"],
          handler: function() { self.setTool("remove_fog_shape"); }
        }),

        new ToolMenuItem("fog_all", {
          label: "Fog Everything",
          tooltip: "Covers entire map in fog",
          glyph: ["fas", "square"],
          handler: function() {
            if (confirm("Are you sure?  This cannot be undone")) {
              var action = {actionType: "fogEverythingAction", uid: generateActionId(), version: 1, level: self.board.getLevel().id};
              self.board.addAction(action, null, true);
            }
          }
        }),

        new ToolMenuItem("fog_none", {
          label: "Clear Fog",
          tooltip: "Removes fog from entire map",
          glyph: ["far", "lightbulb"],
          handler: function() {
            if (confirm("Are you sure?  This cannot be undone")) {
              var action = {actionType: "fogNothingAction", uid: generateActionId(), version: 1, level: self.board.getLevel().id};
              self.board.addAction(action, null, true);
            }
          }
        })
      ]),

      new ToolMenuItem("toggle_pc_mode", {
        label: "Toggle Pc Mode",
        tooltip: "Toggles GM Mode",
        glyph: ["fas", "binoculars"],
        handler: function() {
          self.board.setPcMode(!self.board.pcMode);
        }
      }),

      new ToolMenuItem("undo", {
        label: "Undo",
        tooltip: "Undo",
        glyph: ["fa", "undo"],
        handler: function() { self.board.undo(); }
      }),

      new ToolMenuItem("connection_warning", {
        label: "Connection Error",
        tooltip: "Connection Error",
        glyph: ["fas", "bolt"],
        visible: true,
        active: true,
        handler: () => {}
      })
    ];

    this.globalShortcutTool = new GlobalShortCuts(this);
  }

  // Draws the current tool onto the board
  draw() {
    if (this.currentTool) {
      this.currentTool.draw();
    }
  }

  // Builds and/or updates the HTML tool menu
  render() {
    if (!this.renderer) {
      this.renderer = new ToolRenderer(this.toolSet, this.board.drawingSettings);
    }
    this.renderer.render();
  }

  initialize() {
    // Ensure a current tool:
    if (!this.currentTool) {
      this.setTool("pointer");
    }

    this.globalShortcutTool.disable();
    this.globalShortcutTool.enable();

    this.render();
  }

  setTool(name) {
    var tool = this.toolMap[name];

    if (tool) {
      if (this.currentTool) {
        this.currentTool.disable();
      }
      this.currentTool = tool;
      this.currentTool.enable();
      this.setOptions();
      this.currentTool.optionsChanged();

      var menuItem = this.getMenuItem(name);

      if (menuItem) {
        this.toolSet.forEach(t => t.unselect());
        menuItem.select();
      }

      this.render();

      return tool;

    } else {
      throw "No such tool";
    }
  }

  setOptions() {
    if (this.currentTool) {
      this.renderer.updateOptions(this.currentTool.getOptions());
    }
  }

  // Updates the menu UI
  updateZoom(zoom) {
    this.getMenuItem("zoom").value = zoom;
    this.render();
  }

  updateViewPortSync(vpSync) {
    this.getMenuItem("view_port_sync").value = vpSync;
    this.render();
  }

  toggleDisplay() {
    this.renderer.toggleDisplay();
  }

  undo() {
    this.board.undo();
  }

  clearTokens() {
    this.board.clearTokens();
  }

  // Changes the board's zoom, which will call updateZoom and update the UI
  changeZoom(zoom) {
    this.board.setZoom(zoom);
  }

  showPasteTool() {
    this.getMenuItem("paste").visible = true;
    this.render();
  }

  hideFogTools() {
    this.getMenuItem("fog_group").visible = false;
    this.render();
  }

  hideImageTool() {
    this.getMenuItem("insert_image").visible = false;
    this.render();
  }

  hidePcModeTool() {
    this.getMenuItem("toggle_pc_mode").visible = false;
    this.render();
  }

  hideBeckonTool() {
    this.getMenuItem("beckon").visible = false;
    this.render();
  }

  hideTokensFromTool() {
    this.getMenuItem("tokens_from").visible = false;
    this.render();
  }

  setPcModeActiveState(state) {
    this.getMenuItem("toggle_pc_mode").active = state;
    this.render();
  }

  setErrorState(enabled, msg) {
    let i = this.getMenuItem("connection_warning");
    i.visible = enabled;
    i.label = msg;
    i.tooltip = msg;
  }

  setTemplateSet(type) {
    for (let t in this.templateGroups) {
      let groupItem = this.getMenuItem(this.templateGroups[t]);
      groupItem.visible = t === type;
    }
  }

  hideCameraButton() {

  }

  showCameraButton() {

  }

  showSaveViewPort() {
    this.getMenuItem("save_viewport").visible = true;
    this.render();
  }

  hideSaveViewPort() {
    this.getMenuItem("save_viewport").visible = false;
    this.render();
  }

  showRestoreViewPort() {
    this.getMenuItem("restore_viewport").visible = true;
    this.render();
  }

  hideRestoreViewPort() {
    this.getMenuItem("restore_viewport").visible = false;
    this.render();
  }

  getMenuItem(name) {
    var recur = function(items, name) {
      var found = null;
      items.find(i => {
        if (i.name == name) {
          found = i;
          return true;
        }
        if (i.children) {
          found = recur(i.children, name);
        }
        return found != null;
      });

      return found;
    };

    return recur(this.toolSet, name);
  }

  sharedTool(name) {
    return this.sharedToolOptions[name];
  }
}


text:
<!DOCTYPE html>

		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>MShugars Portfolio</title>
		<meta name="generator" content="Bootply" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link href="css/styles.css" rel="stylesheet">

        Miranda Shugars | Online Repository

		<object data="shugars_portfolio.pdf#toolbar=0?navpanes=0?scrollbar=0" type="application/pdf" width="100%" height="1040">
		</object>

        	Viewing Problems? Try

            	     | Direct Link |

Copyright © Shugars 2016


text:
from .endpoint import Endpoint, LocaleAwareEndpoint

class PvpSeasonLeaderboardEndpoint(Endpoint):
    default_page_size = 50

class PvpSeasonEndpoint(LocaleAwareEndpoint):
    def get_leaderboards(self, season_id):
        name = "%s/%s/leaderboards" % (self.name, season_id)
        cache_name = "%s.%s.leaderboards.json" % (self.name, season_id)
        return self.get_cached(name, cache_name)

    def get_leaderboard_endpoint(self, season_id, board, region=None):
        name = "%s/%s/leaderboards/%s" % (self.name, season_id, board)
        if region:
            name += "/" + region
        return PvpSeasonLeaderboardEndpoint(name)

    def get_leaderboard(self, season_id, board, region=None, page=0, page_size=None):
        endpoint = self.get_leaderboard_endpoint(season_id, board, region)
        return endpoint.page(page, page_size)


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ClusterExtensions.cs" company="KlusterKite">
//   All rights reserved
// </copyright>
// <summary>
//   Bundle of extension methods to fake cluster internal messages
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace KlusterKite.Core.TestKit
{
    using System.Collections.Immutable;
    using System.Linq;
    using System.Reflection;

    using Akka.Cluster;

    /// <summary>
    /// Bundle of extension methods to fake cluster internal messages
    /// </summary>
    public static class ClusterExtensions
    {
        /// <summary>
        /// Creates a member from internal Akka method
        /// </summary>
        /// <param name="uniqueAddress">
        /// The unique Address.
        /// </param>
        /// <param name="upNumber">
        /// The up number of gossip message.
        /// </param>
        /// <param name="status">
        /// The member status.
        /// </param>
        /// <param name="roles">
        /// The list of roles.
        /// </param>
        /// <returns>
        /// The new member
        /// </returns>
        // ReSharper disable once StyleCop.SA1305
        public static Member MemberCreate(UniqueAddress uniqueAddress, int upNumber, MemberStatus status, ImmutableHashSet<string> roles)
        {
            var createMethod =
                typeof(Member).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
                .First(m => m.Name == "Create" && m.GetParameters().Length == 4);

            return (Member)createMethod.Invoke(null, new object[] { uniqueAddress, upNumber, status, roles });
        }
    }
}


text:
package com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.database;

import com.bitdubai.fermat_api.DealsWithPluginIdentity;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabase;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTableRecord;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperObjectFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_wpd_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.exceptions.CantInitializeWalletPublisherMiddlewareDatabaseException;

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

/**
 * The Class com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_publisher.developer.bitdubai.version_1.database.WalletPublisherMiddlewareDeveloperDatabaseFactory have
 * contains the methods that the Developer Database Tools uses to show the information.
 *

 *
 * Created by Roberto Requena - (rart3001@gmail.com) on 04/08/15.
 *
 * @version 1.0
 * @since Java JDK 1.7
 */

public class WalletPublisherMiddlewareDeveloperDatabaseFactory implements DealsWithPluginDatabaseSystem, DealsWithPluginIdentity {

    /**
     * DealsWithPluginDatabaseSystem Interface member variables.
     */
    PluginDatabaseSystem pluginDatabaseSystem;

    /**
     * DealsWithPluginIdentity Interface member variables.
     */
    UUID pluginId;

    Database database;

    /**
     * Constructor
     *
     * @param pluginDatabaseSystem
     * @param pluginId
     */
    public WalletPublisherMiddlewareDeveloperDatabaseFactory(PluginDatabaseSystem pluginDatabaseSystem, UUID pluginId) {
        this.pluginDatabaseSystem = pluginDatabaseSystem;
        this.pluginId = pluginId;
    }

    /**
     * This method open or creates the database i'll be working with
     *
     * @throws CantInitializeWalletPublisherMiddlewareDatabaseException
     */
    public void initializeDatabase() throws CantInitializeWalletPublisherMiddlewareDatabaseException {
        try {

             /*
              * Open new database connection
              */
            database = this.pluginDatabaseSystem.openDatabase(pluginId, WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);
            database.closeDatabase();

        } catch (CantOpenDatabaseException cantOpenDatabaseException) {

             /*
              * The database exists but cannot be open. I can not handle this situation.
              */
            throw new CantInitializeWalletPublisherMiddlewareDatabaseException(cantOpenDatabaseException.getMessage());

        } catch (DatabaseNotFoundException e) {

             /*
              * The database no exist may be the first time the plugin is running on this device,
              * We need to create the new database
              */
            WalletPublisherMiddlewareDatabaseFactory walletPublisherMiddlewareDatabaseFactory = new WalletPublisherMiddlewareDatabaseFactory(pluginDatabaseSystem);

            try {
                  /*
                   * We create the new database
                   */
                database = walletPublisherMiddlewareDatabaseFactory.createDatabase(pluginId, WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME);
                database.closeDatabase();
            } catch (CantCreateDatabaseException cantCreateDatabaseException) {
                  /*
                   * The database cannot be created. I can not handle this situation.
                   */
                throw new CantInitializeWalletPublisherMiddlewareDatabaseException(cantCreateDatabaseException.getMessage());
            }
        }
    }

    public List<DeveloperDatabase> getDatabaseList(DeveloperObjectFactory developerObjectFactory) {
        /**
         * I only have one database on my plugin. I will return its name.
         */
        List<DeveloperDatabase> databases = new ArrayList<DeveloperDatabase>();
        databases.add(developerObjectFactory.getNewDeveloperDatabase(WalletPublisherMiddlewareDatabaseConstants.DATA_BASE_NAME, this.pluginId.toString()));
        return databases;
    }

    public List<DeveloperDatabaseTable> getDatabaseTableList(DeveloperObjectFactory developerObjectFactory) {
        List<DeveloperDatabaseTable> tables = new ArrayList<DeveloperDatabaseTable>();

        /**
         * Table INFORMATION PUBLISHED COMPONENTS columns.
         */
        List<String> InformationPublishedComponentsColumns = new ArrayList<String>();

        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_ID_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_WFP_ID_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_WFP_NAME_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_COMPONENT_TYPE_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_DESCRIPTIONS_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_ICON_IMG_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_MAIN_SCREEN_SHOT_IMG_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_VIDEO_URL_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_STATUS_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_STATUS_TIMESTAMP_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_PUBLICATION_TIMESTAMP_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_PUBLISHER_IDENTITY_PUBLIC_KEY_COLUMN_NAME);
        InformationPublishedComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_SIGNATURE_COLUMN_NAME);
        /**
         * Table INFORMATION PUBLISHED COMPONENTS addition.
         */
        DeveloperDatabaseTable iNFORMATIONPUBLISHEDCOMPONENTSTable = developerObjectFactory.getNewDeveloperDatabaseTable(WalletPublisherMiddlewareDatabaseConstants.INFORMATION_PUBLISHED_COMPONENTS_TABLE_NAME, InformationPublishedComponentsColumns);
        tables.add(iNFORMATIONPUBLISHEDCOMPONENTSTable);

        /**
         * Table COMPONENT VERSIONS DETAILS columns.
         */
        List<String> componentVersionsDetailsColumns = new ArrayList<String>();

        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_ID_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_SCREEN_SIZE_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_VERSION_TIMESTAMP_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_WALLET_VERSION_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_WALLET_VERSION_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_INITIAL_PLATFORM_VERSION_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_FINAL_PLATFORM_VERSION_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_OBSERVATIONS_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_CATALOG_ID_COLUMN_NAME);
        componentVersionsDetailsColumns.add(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_COMPONENT_ID_COLUMN_NAME);
        /**
         * Table COMPONENT VERSIONS DETAILS addition.
         */
        DeveloperDatabaseTable cOMPONENTVERSIONSDETAILSTable = developerObjectFactory.getNewDeveloperDatabaseTable(WalletPublisherMiddlewareDatabaseConstants.COMPONENT_VERSIONS_DETAILS_TABLE_NAME, componentVersionsDetailsColumns);
        tables.add(cOMPONENTVERSIONSDETAILSTable);

        /**
         * Table SCREENS SHOTS COMPONENTS columns.
         */
        List<String> screensShotsComponentsColumns = new ArrayList<String>();

        screensShotsComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.SCREENS_SHOTS_COMPONENTS_FILE_ID_COLUMN_NAME);
        screensShotsComponentsColumns.add(WalletPublisherMiddlewareDatabaseConstants.SCREENS_SHOTS_COMPONENTS_COMPONENT_ID_COLUMN_NAME);
        /**
         * Table SCREENS SHOTS COMPONENTS addition.
         */
        DeveloperDatabaseTable sCREENSSHOTSCOMPONENTSTable = developerObjectFactory.getNewDeveloperDatabaseTable(WalletPublisherMiddlewareDatabaseConstants.SCREENS_SHOTS_COMPONENTS_TABLE_NAME, screensShotsComponentsColumns);
        tables.add(sCREENSSHOTSCOMPONENTSTable);

        return tables;
    }

    public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(DeveloperObjectFactory developerObjectFactory, DeveloperDatabaseTable developerDatabaseTable) {
        /**
         * Will get the records for the given table
         */
        List<DeveloperDatabaseTableRecord> returnedRecords = new ArrayList<DeveloperDatabaseTableRecord>();

        /**
         * I load the passed table name from the SQLite database.
         */
        DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());
        try {
            selectedTable.loadToMemory();
            database.closeDatabase();
        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {

            /**
             * if there was an error, I will returned an empty list.
             */
            database.closeDatabase();
            return returnedRecords;
        }

        List<DatabaseTableRecord> records = selectedTable.getRecords();
        List<String> developerRow = new ArrayList<String>();
        for (DatabaseTableRecord row : records) {
            /**
             * for each row in the table list
             */
            for (DatabaseRecord field : row.getValues()) {
                /**
                 * I get each row and save them into a List<String>
                 */
                developerRow.add(field.getValue());
            }
            /**
             * I create the Developer Database record
             */
            returnedRecords.add(developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
        }

        /**
         * return the list of DeveloperRecords for the passed table.
         */
        return returnedRecords;
    }

    @Override
    public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
        this.pluginDatabaseSystem = pluginDatabaseSystem;
    }

    @Override
    public void setPluginId(UUID pluginId) {
        this.pluginId = pluginId;
    }
}