text:
<?php
if (!defined('EVENT_ESPRESSO_VERSION') )
	exit('NO direct script access allowed');

class Registration_Overview_Help_Tour extends EE_Help_Tour {

	protected function _set_tour_properties() {
		$this->_label = __('Registrations Overview Tour', 'event_espresso');
		if ( isset( $this->_req_data['event_id'] ) )
			$this->_slug = 'registration-per-event-overview-joyride';
		else
			$this->_slug = 'registration-overview-joyride';
	}

	protected function _set_tour_stops() {
		$this->_stops = array(
			10 => array(
				'content' => $this->_start(),
				),
			20 => array(
				'id' => '_REG_ID',
				'content' => $this->_reg_id_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => -20,
					'tipAdjustmentY' => -30
					)
				),
			30 => array(
				'id' => '_REG_count',
				'content' => $this->_reg_count_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => -5,
					'tipAdjustmentY' => -30
					)
				),
			40 => array(
				'id' => 'ATT_fname',
				'content' => $this->_attendee_name_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => -5,
					'tipAdjustmentY' => -30
					)
				),
			50 => array(
				'id' => '_REG_date',
				'content' => $this->_reg_date_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => 5,
					'tipAdjustmentY' => -30
					)
				),
			60 => array(
				'id' => 'event_name',
				'content' => $this->_event_name_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => -5,
					'tipAdjustmentY' => -30
					)
				),
			70 => array(
				'id' => 'DTT_EVT_start',
				'content' => $this->_dtt_evt_start_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => 5,
					'tipAdjustmentY' => -30
					)
				),
			80 => array(
				'id' => '_REG_code',
				'content' => $this->_reg_code_stop(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentX' => 0,
					'tipAdjustmentY' => -30
					)
				),
			90 => array(
				'id' => '_REG_final_price',
				'content' => $this->_txn_total_stop(),
				'options' => array(
					'tipLocation' => 'left',
					'tipAdjustmentX' => 5,
					'tipAdjustmentY' => -50
					)
				),
			100 => array(
				'id' => 'actions',
				'content' => $this->_actions_stop(),
				'options' => array(
					'tipLocation' => 'left',
					'tipAdjustmentX' => 0,
					'tipAdjustmentY' => -50
					)
				),
			110 => array(
				'class' => 'ee-list-table-legend-container',
				'content' => $this->_legend_stop(),
				'options' => array(
					'tipLocation' => 'right',
					'tipAdjustmentX' => 15,
					'tipAdjustmentY' => -40
					)
				),
			120 => array(
				'class' => 'subsubsub',
				'content' => $this->_views_stop(),
				'options' => array(
					'tipLocation' => 'right',
					'tipAdjustmentY' => -50,
					'tipAdjustmentX' => 15
					)
				),
			130 => array(
				'class' => 'bulkactions',
				'content' => $this->_bulkactions_stop(),
				'options' => array(
					'tipLocation' => 'bottom',
					'tipAdjustmentY' => -30,
					'tipAdjustmentX' => 15
					)
				),
			140 => array(
				'id' => 'EVT_CAT',
				'content' => $this->_stop_about_filters(),
				'options' => array(
					'tipLocation' => 'top',
					'tipAdjustmentY' => -40,
					'tipAdjustmentX' => 25
					)
				),
			150 => array(
				'id' => 'event-espresso_page_espresso_registrations-search-input',
				'content' => $this->_search_stop(),
				'options' => array(
					'tipLocation' => 'left',
					'tipAdjustmentY' => -50,
					'tipAdjustmentX' => -15
					)
				),
			);
	}

	protected function _start() {
		$content = '
' . __('Registration Overview', 'event_espresso') . '
';
		if ( isset( $this->_req_data['event_id'] ) ) {
			$content .= '
' . __('An introduction to the Registration Overview page for a single event. This view is pretty much the same as the default overview registration page except you are only seeing registrations for a specific event.  There are also some changes to the available columns in this view.', 'event_espresso') . '
';
		} else {
			$content .= '
' . __('This tour of the Registration Overview page will go over different areas of the screen to help you understand what they are used for.', 'event_espresso') . '
';
		}
		return $content;
	}

	protected function _reg_id_stop() {
		return '
' . __('View the registration ID. Can be sorted in ascending or descending order.', 'event_espresso') . '
';
	}

	protected function _reg_count_stop() {
		return '
' . __('View registration number.', 'event_espresso') . '
';
	}

	protected function _attendee_name_stop() {
		return '
' . __('View the name of the registrant. Can be sorted in ascending or descending order.', 'event_espresso') . '
';
	}

	protected function _reg_date_stop() {
		return '
' . __('View registration date. Can be sorted in ascending or descending order.', 'event_espresso') . '
';
	}

	protected function _event_name_stop() {
		return '
' . __('View the name of the event. Can be sorted in ascending or descending order.', 'event_espresso') . '
';
	}

	protected function _dtt_evt_start_stop() {
		return '
' . __('View the date of the event. Can be sorted in ascending or descending order.', 'event_espresso') . '
';
	}

	protected function _reg_code_stop() {
		return '
' . __('View registration code for a registrant.', 'event_espresso') . '
';
	}

	protected function _txn_total_stop() {
		return '
' . __('View price of registration.', 'event_espresso') . '
';
	}

	protected function _actions_stop() {
		return '
' . __('Perform an action to a registration. See legend in bottom left corner.', 'event_espresso') . '
';
	}

	protected function _legend_stop() {
		return '
' . __('This is the legend that describes the actions available in the actions column. Also shows available statuses for a registration.', 'event_espresso') . '
';
	}

	protected function _views_stop() {
		return '
' . __('You can select different views by time period or look at registrations which have been moved to the trash.') . '
';
	}

	protected function _bulkactions_stop() {
		return '
' . __('Perform a bulk action to multiple registrations.', 'event_espresso') . '
';
	}

	protected function _stop_about_filters() {
		return '
' . __('Registrations can be filtered by date, categories, or status.', 'event_espresso') . '
';
	}

	protected function _search_stop() {
		return '
' . __('Search through registrations. The following sources will be searched: Event Name, Event Description, First Name, Last Name, Biography, Email Address, Address, Comments, Notes, Registration Final Price, Registration Code, Registration Group Size, Ticket Name, and Ticket Description.', 'event_espresso') . '
';
	}

}


text:
package cs263.cs263;

public class Place {
	public double lat=0;
	public double lng=0;

}

redpajama_set_name: RedPajamaGithub


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=end

require 'rubygems'
require 'net/ldap'
require 'net/ldap/dn'
require 'date'
require 'duckpunch-netldap'

class InvalidPasswordException < StandardError
end

class LDAPStorage
  ####################################################################
  # Description of LDAP related data model
  # The following should fully describe how we interact with LDAP
  # no specifics shouldbe in the implementation code below
  ####################################################################
  # set the objectClasses for user objects
  OBJECT_CLASS = ["inetOrgPerson", "posixAccount", "top"]

  # group object classes
  GROUP_OBJECT_CLASSES = ["posixGroup", "top"]
  GROUP_MEMBER_ATTRIBUTE = :memberUid

  CONST_GROUPID_NUM = "113"
  CONST_USERID_NUM  = "500"

  DEFAULT_GROUP_ATTRIBUTES = {
      :gidNumber => CONST_GROUPID_NUM
  }

  LDAP_ATTR_MAPPING = {
      :givenname            => :first,
      :sn                   => :last,
      :uid                  => :email,
      :userPassword         => :password,
      :o                    => :vendor,
      :displayName          => :emailtoken,
      :destinationIndicator => :status,
      :homeDirectory        => :homedir,
      :uidNumber            => :uidnumber,
      :gidNumber            => :gidnumber,
      :mail                 => :emailAddress,
      :gecos                => :resetKey
  }
  ENTITY_ATTR_MAPPING = LDAP_ATTR_MAPPING.invert

  REQUIRED_FIELDS = [
      :first,
      :last,
      :email,
      :password,
      :emailtoken,
      :homedir,
      :status,
      :emailAddress
  ]

  LDAP_WO_CONSTANTS = {
      :loginShell           =>  "/sbin/nologin"
  }

  # some fields are stored in the description field as
  # key/value pairs
  # WARNING: Modifying these values will not work unless the unpacking logic in search_map_user_fields is also updated
  PACKED_ENTITY_FIELD_MAPPING = {
      :tenant => "tenant",
      :edorg  => "edOrg"
  }

  # Additional fiels (see above) are packed into this field as key/value pairs
  LDAP_DESCRIPTION_FIELD = :description

  # READ-ONLY FIELDS
  RO_LDAP_ATTR_MAPPING = {
      :createTimestamp => :created,
      :modifyTimestamp => :updated,
      :cn              => :cn
  }

  # these values are injected when the user is created
  ENTITY_CONSTANTS = {
      :emailtoken => "-",
      :uidnumber  => CONST_USERID_NUM,
      :gidnumber  => CONST_GROUPID_NUM,
      :vendor     => "none",
      :homedir    => "/dev/null",
      :resetKey   => ""
  }

  # List of fields to fetch from LDAP for user
  COMBINED_LDAP_ATTR_MAPPING = LDAP_ATTR_MAPPING.merge(RO_LDAP_ATTR_MAPPING)

  ALLOW_UPDATING = [
      :first,
      :last,
      :password,
      :vendor,
      :emailtoken,
      :homedir,
      :tenant,
      :edorg,
      :emailAddress,
      :resetKey
  ]

  LDAP_DATETIME_FIELDS = Set.new [
                                     :createTimestamp,
                                     :modifyTimestamp
                                 ]

  ################################################################
  # Implementation
  ################################################################

  # Initialize the module
  def initialize(host, port, base, username, password, use_ssl)
    @people_base = "ou=people,#{base}"
    @group_base  = "ou=groups,#{base}"
    @ldap_conf = {
        :host => host,
        :port => port,
        :base => @people_base,
        :auth => {
            :method => :simple,
            :username => username,
            :password => password
        }
    }

    # enable SSL if n
    if use_ssl.is_a? String then use_ssl = use_ssl.downcase == 'true' ? true : false end
    if use_ssl
      @ldap_conf[:encryption] = {    :method => :simple_tls    }
    end

    # test whether it can bind
    #test_ldap = Net::LDAP.new @ldap_conf
    #raise ldap_ex(test_ldap, "Could not bind to ldap server.") if !test_ldap.bind
  end

  def get_ldap_config
    return @ldap_conf.clone
  end

  # user_info = {
  #     :first => "John",
  #     :last => "Doe",
  #     :email => "jdoe@example.com",
  #     :password => "secret",
  #     :vendor => "Acme Inc."
  #     :emailtoken ... hash string
  #     :tenant
  #     :edorg
  #     :status  ... "submitted"
  # }
  def create_user(user_info)
    cn = user_info[:email]
    dn = get_DN(cn)
    attributes = {
        :cn => cn,
        :objectclass => OBJECT_CLASS,
    }

    # inject the constant values into the user info
    e_user_info = ENTITY_CONSTANTS.merge(user_info)

    # make sure the required features are there
    REQUIRED_FIELDS.each do |k|
      if !e_user_info[k] || (e_user_info[k].strip == "")
        raise "The following attributes #{REQUIRED_FIELDS} need to be set. These were provided: #{e_user_info}"
      end
    end

    LDAP_ATTR_MAPPING.each do |ldap_k, rec_k|
      value = e_user_info[rec_k]
      attributes[ldap_k] = value
    end

    # add all the required LDAP constants. These are write-only
    attributes.merge!(LDAP_WO_CONSTANTS)

    # pack additional fields into the description field
    packed_fields = pack_fields(e_user_info)
    if packed_fields.strip != ""
      attributes[LDAP_DESCRIPTION_FIELD] = packed_fields
    end

    # make the ldap call
    Net::LDAP.open(@ldap_conf) do |ldap|
      if !(ldap.add(:dn => dn, :attributes => attributes))
        raise ldap_ex(ldap, "Unable to create user in LDAP: #{attributes}.")
      end
    end
  end

  def authenticate(uid, password)
    # retrieve the raw user record
    filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:email].to_s, uid)
    user = search_map_user_fields(filter, 1, true)[0]
    return false if !user

    local_conf = @ldap_conf.clone
    local_conf[:auth] = {
        :method => :simple,
        :username => user[:dn],
        :password => password
    }
    ldap = Net::LDAP.new local_conf
    return ldap.bind
  end

  # returns extended user_info
  def read_user(email_address)
    filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:email].to_s, email_address)
    return search_map_user_fields(filter, 1)[0]
  end

  # returns extended user_info for the given emailtoken (see create_user) or nil
  def read_user_emailtoken(emailtoken)
    filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:emailtoken].to_s, emailtoken)
    return search_map_user_fields(filter, 1)[0]
  end

  # returns extended user_info for the given resetKey (see create_user) or nil
  def read_user_resetkey(resetKey)
    filter = Net::LDAP::Filter.begins(ENTITY_ATTR_MAPPING[:resetKey].to_s, resetKey + "@")
    return search_map_user_fields(filter, 1)[0]
  end
  # returns array of extended user_info for all users or all users with given status
  # use constants in approval.rb
  def read_users(status=nil)
    # if a filter is provided for the status then set it otherwise just search for people
    # Note: The filter will not capture users that do not have their status set.
    if status
      filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:status].to_s, status ? status : "*")
    else
      filter = Net::LDAP::Filter.eq(:objectClass, "inetOrgPerson")
    end
    return search_map_user_fields(filter)
  end

  # returns array of extended user_info for all users or all users with given status
  # use constants in approval.rb
  def search_users(wildcard_email_address)
    filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:email].to_s, wildcard_email_address)
    return search_map_user_fields(filter)
  end

  def search_users_raw(wildcard_email_address)
    filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:email].to_s, wildcard_email_address)
    return search_map_user_fields(filter, nil, true)
  end

  # updates the user status from an extended user_info
  def update_status(user)
    if user_exists?(user[:email])
      found_user = read_user(user[:email])
      raise "Could not update user #{user[:email]}. User does not exist." if !found_user

      dn = get_DN(found_user[:cn])
      Net::LDAP.open(@ldap_conf) do |ldap|

        if !ldap.replace_attribute(dn, ENTITY_ATTR_MAPPING[:status], user[:status])
          raise ldap_ex(ldap, "Could not update user status for user #{user[:email]}")
        end
      end
    end
  end

  # enable login and update the status
  # This means the user is added to the LDAP group that corresponds to the given role
  def add_user_group(email_address, group_id)
    user_dn  = email_address
    group_dn = get_group_DN(group_id)

    filter = Net::LDAP::Filter.eq( "cn", group_id)

    Net::LDAP.open(@ldap_conf) do |ldap|
      group_found = ldap.search(:base => @group_base, :filter => filter).to_a()[0]
      if !group_found
        group_attrib = DEFAULT_GROUP_ATTRIBUTES.clone
        group_attrib.update({
                                :cn => group_id,
                                :objectclass => GROUP_OBJECT_CLASSES,
                                GROUP_MEMBER_ATTRIBUTE => user_dn
                            })

        if !ldap.add(:dn => group_dn, :attributes => group_attrib)
          raise ldap_ex(ldap, "Could not add #{email_address} to new group #{group_id} using attributes: #{group_attrib}")
        end
      else
        if !group_found[GROUP_MEMBER_ATTRIBUTE].index(user_dn)
          if !ldap.modify(:dn => group_dn, :operations => [[:add, GROUP_MEMBER_ATTRIBUTE, user_dn]])
            raise ldap_ex(ldap, "Could not add #{email_address} to existing  group #{group_id} using attributed '#{GROUP_MEMBER_ATTRIBUTE}' with LDAP base '#{@group_base}'")
          end
        end
      end
    end
  end

  # disable login and update the status
  def remove_user_group(email_address, group_id)
    # note the user is stored in the group via uid only
    user_dn = email_address
    group_dn = get_group_DN(group_id)

    filter = Net::LDAP::Filter.eq( "cn", group_id)
    Net::LDAP.open(@ldap_conf) do |ldap|
      group_found = ldap.search(:base => @group_base, :filter => filter).to_a()[0]

      if group_found
        removed = group_found[GROUP_MEMBER_ATTRIBUTE].delete(user_dn)
        if removed
          if group_found[GROUP_MEMBER_ATTRIBUTE].empty?
            if !ldap.delete(:dn => group_dn)
              raise ldap_ex(ldap, "Could not remove user #{user_dn} for group #{group_id}")
            end
          else
            if !ldap.replace_attribute(group_dn, GROUP_MEMBER_ATTRIBUTE, group_found[GROUP_MEMBER_ATTRIBUTE])
              raise ldap_ex(ldap, "Could not remove user #{user_dn} for group #{group_id}")
            end
          end
        end
      end
    end
  end

  def get_user_groups(email_address)
    user_dn = email_address
    filter = Net::LDAP::Filter.eq( GROUP_MEMBER_ATTRIBUTE, user_dn)

    Net::LDAP.open(@ldap_conf) do |ldap|
      ldap.search(:base => @group_base, :filter => filter).to_a().map do |group|
        group[:cn][0]
      end
    end
  end

  # returns true if the user exists
  def user_exists?(email_address)
    !!read_user(email_address)
  end

  # updates the user_info except for the user status
  # user_info is the same input as for create_user
  def update_user_info(user_info)
    return if !user_info || user_info.empty?

    # get the current user entry
    curr_user_info = read_user(user_info[:email])
    if curr_user_info
      dn = get_DN(curr_user_info[:cn])

      Net::LDAP.open(@ldap_conf) do |ldap|
        #update the ldap attributes
        desc_attributes = {}
        ALLOW_UPDATING.each do |attribute|
          if user_info && !!user_info[attribute] && (curr_user_info[attribute] != user_info[attribute])
            if PACKED_ENTITY_FIELD_MAPPING.include?(attribute)
              desc_attributes[attribute] = user_info[attribute]
            else
              if !(ldap.replace_attribute(dn, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]))
                if !curr_user_info[attribute]
                  if !(ldap.add_attribute(dn, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]))
                    puts curr_user_info
                    puts user_info

                    ops = [[:add, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]]]
                    ldap.modify :dn => dn, :operations => ops

                    raise ldap_ex(ldap, "Unable to add new attribute '#{ENTITY_ATTR_MAPPING[attribute]}' with value '#{user_info[attribute]}'.")
                  end
                else
                  raise ldap_ex(ldap, "Unable to update attribute '#{ENTITY_ATTR_MAPPING[attribute]}' with value '#{user_info[attribute]}'.")
                end
              end
            end
          end
        end

        # updat the attributes that are encoded in description
        if !desc_attributes.empty?
          temp = (curr_user_info.clone).merge(desc_attributes)
          packed = pack_fields(temp)
          ldap.replace_attribute(dn, LDAP_DESCRIPTION_FIELD, packed)
        end
      end
    end
  end

  # deletes the user entirely
  def delete_user(email_address)
    found_user = read_user(email_address)
    if found_user
      Net::LDAP.open(@ldap_conf) do |ldap|
        ldap.delete(:dn => get_DN(found_user[:cn]))
      end
    end
  end

  # delete attribute for a user
  def delete_user_attribute(email_address, attribute)
    found_user = read_user(email_address)
    if found_user
      dn = get_DN(found_user[:cn])
      Net::LDAP.open(@ldap_conf) do |ldap|
        ldap.delete_attribute(dn, ENTITY_ATTR_MAPPING[attribute])
      end
    end
  end

  # retrieve one group from ldap
  def get_group(group_id)
    group_found = nil
    filter = Net::LDAP::Filter.eq( "cn", group_id)
    Net::LDAP.open(@ldap_conf) do |ldap|
      group_found = ldap.search(:base => @group_base, :filter => filter).to_a()[0]
    end
    group_found
  end

  #############################################################################
  # PRIVATE methods
  #############################################################################
  private

  # returns the LDAP DN
  def get_DN(cn)
    return "cn=#{escape_seg(cn)},#{@people_base}"
  end

  def get_group_DN(group_id)
    return "cn=#{group_id},#{@group_base}"
  end

  def escape_seg(value)
    return Net::LDAP::DN.escape(value)
  end

  # extract the user from the ldap record
  def search_map_user_fields(filter, max_recs=nil, raw=false)
    # search for all fields plus the description field
    Net::LDAP.open(@ldap_conf) do |ldap|
      attributes = COMBINED_LDAP_ATTR_MAPPING.keys + [LDAP_DESCRIPTION_FIELD] + (raw ? LDAP_WO_CONSTANTS.keys : [])
      arr = ldap.search(:filter => filter, :attributes => attributes).to_a()
      if !max_recs
        max_recs = arr.length
      end

      # if the raw ldap records were requested then return them
      return arr if raw

      # process them into records
      return arr[0..(max_recs-1)].map do |entry|
        user_rec = {}
        COMBINED_LDAP_ATTR_MAPPING.each do |ldap_k, rec_k|
          attr_val = entry[ldap_k].is_a?(Array) ?  entry[ldap_k][0] : entry[ldap_k]
          user_rec[rec_k] = LDAP_DATETIME_FIELDS.include?(ldap_k) ? DateTime.iso8601(attr_val) : attr_val
        end

        # unpack the fields that are stored in the description field
        desc = (entry[LDAP_DESCRIPTION_FIELD] ? entry[LDAP_DESCRIPTION_FIELD] : [])[0]
        # handle packed fields deliminated by carriage return, newline, comma, or space
        desc = desc.gsub(/tenant=([^\s,]+)[,\s]+/, "tenant=\\1\n") unless desc == nil
        unpacked_fields = if desc && (desc.strip != "")
                            mapping = desc.strip().split("\n").map {|x| x.strip}
                            mapping = mapping.map do |x|
                              x.split("=").map {|y| y.strip }
                            end
                            mapping = Hash[mapping]
                          else
                            {}
                          end
        PACKED_ENTITY_FIELD_MAPPING.each do |rec_k, packed_k|
          if unpacked_fields.include?(packed_k)
            user_rec[rec_k] = unpacked_fields[packed_k]
          end
        end

        user_rec
      end
    end
  end

  def pack_fields(user_info)
    packed_fields = Hash[ PACKED_ENTITY_FIELD_MAPPING.map { |k,v| [v, user_info[k]] } ]
    ((packed_fields.select {|k,v| !!v}).map { |k,v|  "#{k}=#{v}" }).join("\n")
  end

  def ldap_ex(ldap, msg, check_password_error=false)
    op = ldap.get_operation_result
    if op.code == 19   # indicates a password that does not comply with policy
      raise InvalidPasswordException
    else
      "#{msg} (#{op.code}) #{op.message}"
    end
  end

end


text:
package rationals.transformations;

import java.util.Arrays;

import org.junit.Test;

import junit.framework.TestCase;
import rationals.Automaton;
import rationals.State;
import rationals.Transition;
import rationals.TransitionBuilder;
import rationals.properties.ContainsEpsilon;

public class EpsilonTransitionRemoverTest extends TestCase {

    private Automaton<String, Transition<String>, TransitionBuilder<String>> automaton;

    protected void setUp() throws Exception {
        super.setUp();
        automaton = new Automaton<>();
        State s1 = automaton.addState(true, true);
        State s2 = automaton.addState(false, false);
        State s3 = automaton.addState(false, true);
        State e1 = automaton.addState(false, false);
        State e2 = automaton.addState(false, false);
        State e3 = automaton.addState(false, false);
        String epsilon = null;
        automaton.addTransition(new Transition<>(e1, "c", e1));
        automaton.addTransition(new Transition<>(s1, epsilon, e1));
        automaton.addTransition(new Transition<>(e1, epsilon, s1));
        automaton.addTransition(new Transition<>(s1, "a", s2));
        automaton.addTransition(new Transition<>(s2, epsilon, e2));
        automaton.addTransition(new Transition<>(e2, epsilon, e3));
        automaton.addTransition(new Transition<>(e3, "b", s3));
        automaton.addTransition(new Transition<>(s3, "a", s2));
        automaton.addTransition(new Transition<>(e2, "b", s1));
    }

    public EpsilonTransitionRemoverTest(String arg0) {
        super(arg0);
    }

    @Test
    public void test1() {
    	EpsilonTransitionRemover<String, Transition<String>, TransitionBuilder<String>> norm = new EpsilonTransitionRemover<>();
        Automaton<String, Transition<String>, TransitionBuilder<String>> b = norm.transform(automaton);
        assertTrue(new ContainsEpsilon<String, Transition<String>, TransitionBuilder<String>>().test(b));
        String[] word = new String[] { "a", "b", "a", "b" };
        assertTrue(b.accept(Arrays.asList(word)));
    }

    @Test
    public void test2() {
    	EpsilonTransitionRemover<String, Transition<String>, TransitionBuilder<String>> norm = new EpsilonTransitionRemover<>();
        Automaton<String, Transition<String>, TransitionBuilder<String>> b = norm.transform(automaton);
        assertTrue(new ContainsEpsilon<String, Transition<String>, TransitionBuilder<String>>().test(b));
        String[] word3 = new String[] { };
        assertTrue(b.accept(Arrays.asList(word3)));
    }

    @Test
    public void test3() {
    	EpsilonTransitionRemover<String, Transition<String>, TransitionBuilder<String>> norm = new EpsilonTransitionRemover<>();
        Automaton<String, Transition<String>, TransitionBuilder<String>> b = norm.transform(automaton);
        assertTrue(new ContainsEpsilon<String, Transition<String>, TransitionBuilder<String>>().test(b));
        String[] word2 = new String[] { "c","c","a", "b", "a", "b", "a", "b" };
        assertTrue(b.accept(Arrays.asList(word2)));
    }

    @Test
    public void test4() {
    	EpsilonTransitionRemover<String, Transition<String>, TransitionBuilder<String>> norm = new EpsilonTransitionRemover<>();
        Automaton<String, Transition<String>, TransitionBuilder<String>> b = norm.transform(automaton);
        assertTrue(new ContainsEpsilon<String, Transition<String>, TransitionBuilder<String>>().test(b));
        String[] word1 = new String[] { "a", "b", "a", "b", "a" };
        assertTrue(!b.accept(Arrays.asList(word1)));
    }

    @Test
    public void test5() {
    	EpsilonTransitionRemover<String, Transition<String>, TransitionBuilder<String>> norm = new EpsilonTransitionRemover<>();
        Automaton<String, Transition<String>, TransitionBuilder<String>> b = norm.transform(automaton);
        assertTrue(new ContainsEpsilon<String, Transition<String>, TransitionBuilder<String>>().test(b));
        String[] word2 = new String[] { "c","c","c"};
        assertTrue(b.accept(Arrays.asList(word2)));
    }
}


text:
import { isArray } from '@ember/array';
import Component from '@ember/component';
import {
  computed, get, observer, set, setProperties
} from '@ember/object';
import { alias, equal, union } from '@ember/object/computed';
import { on } from '@ember/object/evented';
import { inject as service } from '@ember/service';
import { isEmpty } from '@ember/utils';
import ipaddr from 'ipaddr.js';
import { hash } from 'rsvp';
import Semver from 'semver';
import ClusterDriver from 'shared/mixins/cluster-driver';
import C from 'shared/utils/constants';
import { addQueryParams } from 'shared/utils/util';
import { DEFAULT_AKS_CONFIG, DEFAULT_AKS_NODE_POOL_CONFIG } from 'ui/models/cluster';
import { regionsWithAZs } from 'ui/utils/azure-choices';
import layout from './template';
import { satisfies, coerceVersion } from 'shared/utils/parse-version';

const NETWORK_POLICY = [
  {
    label: 'None',
    value: null
  },
  {
    label: 'Calico',
    value: 'calico'
  },
  {
    label:    'Azure (requires Azure CNI)',
    value:    'azure',
    disabled: true
  }
];
const CHINA_REGION_API_URL = 'https://management.chinacloudapi.cn/';
const CHINA_REGION_AUTH_URL = 'https://login.chinacloudapi.cn/';
const NETWORK_PLUGINS = [
  {
    label: 'Kubenet',
    value: 'kubenet'
  },
  {
    label: 'Azure CNI',
    value: 'azure'
  }
];
const LB_SKUS = [
  {
    label: 'Standard',
    value: 'Standard'
  },
  {
    label: 'Basic',
    value: 'Basic'
  }
];

// Because aks just put out 1.25.0 as a preview we're releasing
// it as experimental until we can adequately test it.
// https://github.com/rancher/dashboard/issues/7217
const EXPERIMENTAL_RANGE = '>= 1.25.0'
const MINIMUM_VERSION = '>= 1.23.0'

export default Component.extend(ClusterDriver, {
  globalStore:          service(),
  intl:                 service(),
  settings:             service(),
  versionChoiceService: service('version-choices'),
  layout,

  configField: 'aksConfig',

  clusterAdvanced:           false,
  clusterErrors:             null,
  clusterLocationSaved:      false,
  clusterLocationSaving:     false,
  disableAzs:                false,
  enabledAuthorizedIpRanges: false,
  errors:                    null,
  lbSkus:                    LB_SKUS,
  loadBalancerImmutable:     false,
  monitoringRegionConent:    [],
  networkPlugins:            NETWORK_PLUGINS,
  otherErrors:               null,
  regions:                   null,
  step:                      1,
  versions:                  null,
  vmSizes:                   null,
  originalSecret:            null,
  regionsWithAZs,

  defaultNodePoolConfig: DEFAULT_AKS_NODE_POOL_CONFIG,
  defaultAksConfig:      DEFAULT_AKS_CONFIG,

  defaultK8sVersionRange: alias(`settings.${ C.SETTING.VERSION_SYSTEM_K8S_DEFAULT_RANGE }`),
  editing:                equal('mode', 'edit'),
  isNew:                  equal('mode', 'new'),
  allErrors:              union('errors', 'otherErrors', 'clusterErrors'),

  init() {
    this._super(...arguments);

    let config = get(this, 'cluster.aksConfig');

    if ( !config ) {
      config = this.globalStore.createRecord(JSON.parse(JSON.stringify(this.defaultAksConfig)));
      const defNodePool = this.globalStore.createRecord(JSON.parse(JSON.stringify(this.defaultNodePoolConfig)))

      setProperties(defNodePool, {
        isNew: true,
        name:  'agentpool',
      });
      set(config, 'nodePools', [defNodePool]);

      setProperties(this, {
        'cluster.aksConfig': config,
        'loadBalancerSku':   'Standard',
      });
    } else {
      if ( this.editing && this.importedClusterIsPending || (this.clusterIsPending && config?.privateCluster) ) {
        set(this, 'step', 4);
      } else {
        this.syncUpstreamConfig();

        const tags = { ...( config.tags || {} ) };

        set(this, 'tags', tags);

        if (!isEmpty(config?.authorizedIpRanges)) {
          set(this, 'enabledAuthorizedIpRanges', true);
        }
      }
    }

    let cur = config?.azureCredentialSecret;

    if ( cur && !cur.startsWith('cattle-global-data:') ) {
      cur = `cattle-global-data:${ cur }`;
    }

    set(this, 'originalSecret', cur);
  },

  actions: {
    addNodePool() {
      const config = get(this, `primaryResource.aksConfig`);
      const kubernetesVersion = get(config, 'kubernetesVersion');
      let nodePools = (get(config, 'nodePools') || []).slice();
      const npConfig = JSON.parse(JSON.stringify(this.defaultNodePoolConfig));

      if (!isArray(nodePools)) {
        nodePools = [];
      }

      const nodePool = this.globalStore.createRecord(npConfig);

      set(nodePool, 'mode', 'User')

      setProperties(nodePool, {
        orchestratorVersion: kubernetesVersion,
        isNew:               true,
      });

      nodePools.pushObject(nodePool);

      set(this, 'config.nodePools', nodePools);
    },

    removeNodePool(nodePool) {
      let { config: { nodePools = [] } } = this;

      if (!isEmpty(nodePools)) {
        nodePools.removeObject(nodePool);
      }

      set(this, 'config.nodePools', nodePools);
    },
    updateAuthorizedIpRanges(ipRanges) {
      set(this, 'config.authorizedIpRanges', ipRanges);
    },
    async finishAndSelectCloudCredential(cred) {
      // Workaround for when embedding in the dashboard UI
      // Need to go and fetch the cloud credentials again
      try {
        const store = get(this, 'globalStore');
        const creds = await store.findAll('cloudcredential', { forceReload: true });

        if (creds?.content) {
          set(this, 'cloudCredentials', creds.content);
        }
      } catch (err) {
        console.warn('Unable to fetch cloud credentials', err); // eslint-disable-line
      }

      if (cred) {
        set(this, 'config.azureCredentialSecret', get(cred, 'id'));
        this.send('loadRegions', (ok, error) => {
          if (!ok) {
            this.send('errorHandler', error);
          }
        });
      }
    },
    async loadRegions(cb) {
      const store = get(this, 'globalStore')
      const selectedCloudCredential = this.selectedCloudCredential;
      const regionsWithAZs = this.regionsWithAZs
      const data = {
        cloudCredentialId: get(selectedCloudCredential, 'id'),
        // tenantId:          get(this, 'config.tenantId'),
      };
      const url = addQueryParams('/meta/aksLocations', data);

      try {
        const regions = await store.rawRequest({
          url,
          method: 'GET',
        });

        const filteredRegions = (regions?.body ?? []).map((reg) => {
          if (regionsWithAZs.includes(reg?.displayName || '')) {
            return {
              ...reg,
              ...{ group: 'High Availablity' }
            }
          } else {
            return {
              ...reg,
              ...{ group: 'Other' }
            };
          }
        });

        set(this, 'regions', filteredRegions);

        cb(true);

        set(this, 'step', 2);

        if (this.editing) {
          set(this, 'clusterLocationSaving', true);
          this.send('authenticate', (ok, error) => {
            if (!ok) {
              this.send('errorHandler', error);
            }
            set(this, 'clusterLocationSaving', false);
          })
        }
      } catch (error) {
        this.send('errorHandler', error);
        cb(false);
      }
    },

    authenticate(cb) {
      const store = get(this, 'globalStore')
      const { selectedCloudCredential } = this;
      const data = {
        cloudCredentialId: get(selectedCloudCredential, 'id'),
        // tenantId:          get(this, 'config.tenantId'),
        region:            get(this, 'config.resourceLocation'),
        clusterId:         get(this, 'cluster.id')
      };

      if ( get(this, 'isChinaRegion') ) {
        setProperties(data, {
          baseUrl:     CHINA_REGION_API_URL,
          authBaseUrl: CHINA_REGION_AUTH_URL
        })
      }

      const versionsUrl = addQueryParams('/meta/aksVersions', data);
      const upgradesUrl = addQueryParams('/meta/aksUpgrades', data);
      const vNetsUrl = addQueryParams('/meta/aksVirtualNetworks', data);
      const vmSizes = addQueryParams('/meta/aksVMSizes', data);

      const aksRequest = {
        versions: store.rawRequest({
          url:    versionsUrl,
          method: 'GET',
        }),
        upgradeVersions: data.clusterId ? store.rawRequest({
          url:    upgradesUrl,
          method: 'GET'
        }) : Promise.resolve({}),
        virtualNetworks: store.rawRequest({
          url:    vNetsUrl,
          method: 'GET',
        }),
        vmSizes: store.rawRequest({
          url:    vmSizes,
          method: 'GET',
        }),
      }

      return hash(aksRequest).then((resp) => {
        const { mode }                      = this;
        const {
          versions, upgradeVersions, virtualNetworks, vmSizes
        } = resp;

        const isEdit                        = mode === 'edit';
        const versionz                      = (get(versions, 'body') || []);
        const upgradeVersionz               = (get(upgradeVersions, 'body.upgrades') || []);
        const nonExperimentalVersions       = versionz.filter((v) =>  !satisfies(coerceVersion(v), EXPERIMENTAL_RANGE));
        const initialVersion                = isEdit ? this.config.kubernetesVersion : Semver.maxSatisfying(nonExperimentalVersions, this.defaultK8sVersionRange); // default in azure ui

        if (!isEdit && initialVersion) {
          set(this, 'cluster.aksConfig.kubernetesVersion', initialVersion);
        }

        const enabledVersions = upgradeVersionz
          .filter((upgrade) => upgrade.enabled)
          .map((upgrade) => upgrade.version);

        setProperties(this, {
          step:            3,
          versions:        enabledVersions.length > 0 ? [initialVersion, ...enabledVersions] : versionz,
          virtualNetworks: (get(virtualNetworks, 'body') || []),
          vmSizes:         vmSizes?.body || [],
        });

        cb(true);
      }).catch((xhr) => {
        const err = xhr.body.message || xhr.body.code || xhr.body.error;

        setProperties(this, { errors: [err], });

        cb(false, [err]);
      });
    },

    setTags(section) {
      set(this, 'config.tags', section);
    },
  },

  resetNetworkPolicy: observer('config.{networkPolicy,networkPlugin}', function() {
    const { networkPolicy, networkPlugin } = this.config;

    if (networkPlugin === 'kubenet' && networkPolicy === 'azure') {
      set(this, 'config.networkPolicy', null);
    }

    if (this.config.networkPolicy === null) {
      set(this, 'cluster.enableNetworkPolicy', false)
    }
  }),

  resetIpRanges: observer('config.privateCluster', 'loadBalancerSku', function() {
    if (( this.config?.privateCluster || this.loadBalancerSku === 'Basic' ) && !isEmpty(this.config?.authorizedIpRanges)) {
      setProperties(this, {
        'config.authorizedIpRanges': [],
        enabledAuthorizedIpRanges:   false,
      });
    }
  }),

  resourceLocationChanged: observer('config.resourceLocation', function() {
    const { regions, config: { resourceLocation } } = this;
    const match = regions.findBy('name', resourceLocation);

    const regionHasAz = this.regionsWithAZs.includes(match?.displayName || '');

    if (regionHasAz) {
      set(this, 'disableAzs', false);
    } else {
      set(this, 'disableAzs', true);
    }
  }),

  postSaveChanged: observer('isPostSave', function() {
    const {
      isNew,
      isPostSave,
      config: { privateCluster },
      importedClusterIsPending,
    } = this;

    if ((privateCluster || importedClusterIsPending) && isPostSave) {
      if (isNew) {
        set(this, 'step', 4);
      } else {
        this.close();
      }
    } else {
      this.close();
    }
  }),

  availablityZonesChanged: on('init', observer('config.nodePools.[]', function() {
    const nodePools = get(this, 'config.nodePools') || [];
    const azs = [];

    nodePools.forEach((np) => {
      if (np?.availabilityZones && np.availabilityZones.length > 0) {
        azs.pushObjects(np.availabilityZones);
      }
    });
    const anySet = azs.uniq().any((az) => az);

    if (anySet) {
      setProperties(this, {
        'loadBalancerSku':       'Standard',
        'loadBalancerImmutable': true,
      });
    } else {
      set(this, 'loadBalancerImmutable', false);
    }
  })),

  resetAdvancedOptions: on('init', observer('config.networkPlugin', function() {
    if (get(this, 'isNew') && get(this, 'config.networkPlugin') === 'azure') {
      const config = get(this, 'config');
      const defaultConfigOptions = {
        dnsServiceIp:                '10.0.0.10',
        dockerBridgeCidr:            '172.17.0.1/16',
        podCidr:                     '172.244.0.0/16',
        serviceCidr:                 '10.0.0.0/16',
        subnet:                      '',
        virtualNetwork:              '',
        virtualNetworkResourceGroup: '',
      };
      const {
        subnet,
        virtualNetwork,
        virtualNetworkResourceGroup,
        serviceCidr,
        dnsServiceIp,
        dockerBridgeCidr
      } = defaultConfigOptions;

      setProperties(config, {
        subnet,
        virtualNetwork,
        virtualNetworkResourceGroup,
        serviceCidr,
        dnsServiceIp,
        dockerBridgeCidr
      });
    }
  })),

  monitoringConfigDisabled: computed('model.originalCluster.aksStatus.upstreamSpec.monitoring', 'isNewOrEditable', 'editing', function(){
    const { isNewOrEditable, editing } = this;
    const upstreamMonitoringEnabled = get(this, 'model.originalCluster.aksStatus.upstreamSpec.monitoring') ?? false;

    if (isNewOrEditable) {
      return false;
    }

    if (editing && !upstreamMonitoringEnabled) {
      return false;
    }

    return true;
  }),

  importedClusterIsPending: computed('clusterIsPending', 'model.originalCluster', function() {
    const { clusterIsPending } = this;
    const originalCluster = get(this, 'model.originalCluster');
    const ourClusterSpec = get(( originalCluster ?? {} ), 'aksConfig');
    const upstreamSpec = get(( originalCluster ?? {} ), 'aksStatus.upstreamSpec');

    return clusterIsPending && get(ourClusterSpec, 'imported') && !isEmpty(upstreamSpec);
  }),

  clusterIsPending: computed('clusterState', function() {
    const { clusterState } = this;

    return ['pending', 'provisioning', 'waiting'].includes(clusterState);
  }),

  anyWindowsNodes: computed('config.nodePools.@each.osType', function() {
    const nodePools = this?.config?.nodePools ?? [];

    if (isEmpty(nodePools)) {
      return false;
    }

    return nodePools.any((np) => np?.osType === 'Windows');
  }),

  hasProvisioned: computed('model.cluster', function() {
    const cluster = get(this, 'model.cluster');
    const { state = '', isError = false } = cluster;
    let clusterHasProvisioned = true;

    if (isError && state === 'provisioning') {
      if (isEmpty(cluster?.aksStatus?.upstreamSpec)) {
        clusterHasProvisioned = false;
      }
    }

    return clusterHasProvisioned;
  }),

  isNewOrEditable:   computed('hasProvisioned', 'isNew', 'mode', function() {
    const isNew = get(this, 'isNew');

    if (isNew) {
      return true;
    }

    return this.mode === 'edit' && !this.hasProvisioned;
  }),

  cloudCredentials: computed('model.cloudCredentials', 'originalSecret', function() {
    const out = this.model.cloudCredentials.filter((cc) => {
      const isAzure = Object.prototype.hasOwnProperty.call(cc, 'azurecredentialConfig');

      if (isAzure) {
        return true;
      }

      return false;
    });

    if ( this.originalSecret && !out.find((x) => x.id === this.originalSecret ) ) {
      const obj = this.globalStore.createRecord({
        name:                  `${ this.originalSecret.replace(/^cattle-global-data:/, '') } (current)`,
        id:                    this.originalSecret,
        type:                  'cloudCredential',
        azurecredentialConfig: {},
      });

      out.push(obj);
    }

    return out;
  }),

  selectedCloudCredential: computed('cloudCredentials.@each.id', 'config.azureCredentialSecret', function() {
    const cur = this.config?.azureCredentialSecret;
    const  cloudCredentials = this.cloudCredentials;

    if (isEmpty(cloudCredentials) && isEmpty(cur)) {
      return null;
    } else {
      return cloudCredentials.findBy('id', cur.includes('cattle-global-data:') ? cur : `cattle-global-data:${ cur }`);
    }
  }),

  versionChoices: computed('versions', function() {
    const {
      versions = [],
      mode,
      config : { kubernetesVersion: initialVersion }
    } = this;

    // azure versions come in oldest to newest
    return this.versionChoiceService.parseCloudProviderVersionChoices(( versions || [] ).reverse(), initialVersion, mode, null, false, EXPERIMENTAL_RANGE, MINIMUM_VERSION);
  }),

  networkChoice: computed({
    set( _key, value = '' ) {
      const [subnet, virtualNetwork, virtualNetworkResourceGroup] = value.split(':');
      const config = get(this, 'config');

      if (subnet && virtualNetwork && virtualNetworkResourceGroup) {
        setProperties(config, {
          subnet,
          virtualNetwork,
          virtualNetworkResourceGroup
        });
      }

      return value;
    }
  }),

  filteredVirtualNetworks: computed('config.virtualNetwork', 'virtualNetworks', function() {
    const vnets = get(this, 'virtualNetworks') || [];
    const subNets = [];

    vnets.forEach( (vnet) => {
      (get(vnet, 'subnets') || []).forEach( (subnet) => {
        subNets.pushObject({
          name:  `${ get(subnet, 'name') } (${ get(subnet, 'addressRange') })`,
          group: get(vnet, 'name'),
          value: `${ get(subnet, 'name') }:${ get(vnet, 'name') }:${ get(vnet, 'resourceGroup') }`
        })
      });
    });

    return subNets;
  }),

  networkChoiceDisplay: computed('virtualNetworks', 'config.virtualNetwork', 'config.subnet', function() {
    const selected = (get(this, 'virtualNetworks') || []).findBy('name', get(this, 'config.virtualNetwork')) || {}
    const subnet = (get(selected, 'subnets') || []).findBy('name', get(this, 'config.subnet')) || {}

    return `${ get(subnet, 'name') } (${ get(subnet, 'addressRange') })`
  }),

  isChinaRegion: computed('config.resourceLocation', function() {
    return get(this, 'config.resourceLocation').startsWith('china');
  }),

  networkPolicyContent: computed('config.networkPlugin', function() {
    const netPolicies = [...NETWORK_POLICY];
    const azureNetPolicy = netPolicies.findBy('value', 'azure');

    if (this?.config?.networkPlugin === 'azure') {
      set(azureNetPolicy, 'disabled', false);
    } else {
      set(azureNetPolicy, 'disabled', true);
    }

    return netPolicies;
  }),

  validate() {
    const intl   = get(this, 'intl');
    let model = get(this, 'cluster');
    let clusterErrors = model.validationErrors() || [];
    const nodePoolErrors = this.validateNodePools();

    const vnetSet = !!get(this, 'config.virtualNetwork');

    if (vnetSet) {
      clusterErrors = clusterErrors.concat(this.validateVnetInputs());
    }

    if ( this.isNew && !get(this, 'config.resourceGroup') ) {
      clusterErrors.push(intl.t('validation.required', { key: intl.t('clusterNew.azureaks.resourceGroup.label') }));
    }

    if ( this.isNew && !get(this, 'config.dnsPrefix') ) {
      clusterErrors.push(intl.t('validation.required', { key: intl.t('clusterNew.azureaks.dns.label') }));
    }

    set(this, 'errors', [...(this.errors ?? []), ...clusterErrors, ...nodePoolErrors]);

    return this.errors.length === 0;
  },

  validateNodePools() {
    const nodePools = get(this, 'primaryResource.aksConfig.nodePools');
    const errors = [];

    if (!isEmpty(nodePools)) {
      const nodePoolErrors = [];

      nodePools.forEach((np) => {
        const npErr = np.validationErrors();
        const npOs = np?.osType;
        const npName = np?.name;

        // aka.ms/aks-naming-rules
        if (npOs === 'Linux') {
          if (npName.length > 11) {
            errors.push(this.intl.t('clusterNew.azureaks.nodePools.errors.linuxName'));
          }
        } else if (npOs === 'Windows') {
          if (npName.length > 6) {
            errors.push(this.intl.t('clusterNew.azureaks.nodePools.errors.windowsName'));
          }
        }

        if (!/^[a-z][a-z0-9]+$/.test(npName)) {
          errors.push(this.intl.t('clusterNew.azureaks.nodePools.errors.nameFormat'));
        }

        nodePoolErrors.push(npErr)
      });

      if (!isEmpty(nodePoolErrors)) {
        errors.pushObjects(nodePoolErrors.flat());
      }
    }

    return errors;
  },

  validateVnetInputs() {
    const intl   = get(this, 'intl');
    const errors = [];
    const config = get(this, 'config');
    const vnet   = get(this, 'virtualNetworks').findBy('name', get(config, 'virtualNetwork'));

    if (vnet) {
      let subnet = get(vnet, `subnets`).findBy('name', get(config, 'subnet'));
      let vnetRange  = ipaddr.parseCIDR(get(subnet, 'addressRange'));

      let {
        serviceCidr, dnsServiceIp, dockerBridgeCidr
      } = config;

      let parsedServiceCidr      = null;
      let parsedDnsServiceIp     = null;
      let parsedDockerBridgeCidr = null;

      if (!serviceCidr && !dnsServiceIp && !dockerBridgeCidr) {
        errors.pushObject('You must include all required fields when using a Virtual Network');
      }

      try {
        parsedServiceCidr = ipaddr.parseCIDR(serviceCidr);

        // check if serviceCidr falls within the VNet/Subnet range
        if (parsedServiceCidr && vnetRange[0].match(parsedServiceCidr)) {
          errors.pushObject(intl.t('clusterNew.azureaks.errors.included.parsedServiceCidr'));
        }
      } catch ( err ) {
        errors.pushObject(intl.t('clusterNew.azureaks.errors.included.serviceCidr'));
      }

      try {
        parsedDnsServiceIp = ipaddr.parse(dnsServiceIp);

        // check if dnsService exists in range
        if (parsedDnsServiceIp && vnetRange[0].match(parsedDnsServiceIp, vnetRange[1])) {
          errors.pushObject(intl.t('clusterNew.azureaks.errors.included.parsedDnsServiceIp'));
        }
      } catch ( err ) {
        errors.pushObject(intl.t('clusterNew.azureaks.errors.included.dnsServiceIp'));
      }

      try {
        parsedDockerBridgeCidr = ipaddr.parseCIDR(dockerBridgeCidr);

        // check that dockerBridge doesn't overlap
        if (parsedDockerBridgeCidr && ( vnetRange[0].match(parsedDockerBridgeCidr) || parsedServiceCidr[0].match(parsedDockerBridgeCidr) )) {
          errors.pushObject(intl.t('clusterNew.azureaks.errors.included.parsedDockerBridgeCidr'));
        }
      } catch ( err ) {
        errors.pushObject(intl.t('clusterNew.azureaks.errors.included.dockerBridgeCidr'));
      }
    }

    return errors;
  },

  willSave() {
    const enableMonitoring = get(this, 'config.monitoring')
    const config = get(this, 'config')

    if (!enableMonitoring) {
      setProperties(config, {
        logAnalyticsWorkspaceResourceGroup: null,
        logAnalyticsWorkspace:              null,
      })
    }

    set(config, 'clusterName', this.cluster.name);

    if ( get(this, 'isChinaRegion') ) {
      setProperties(config, {
        baseUrl:     CHINA_REGION_API_URL,
        authBaseUrl: CHINA_REGION_AUTH_URL
      })
    } else {
      delete config['baseUrl'];
      delete config['authBaseUrl'];
    }

    Object.keys(config).forEach((k) => {
      const val = get(config, k);

      if (isEmpty(val)) {
        delete config[k];
      }
    });

    return this._super(...arguments);
  },

  syncUpstreamConfig() {
    const originalCluster = get(this, 'model.originalCluster').clone();
    const ourClusterSpec = get(originalCluster, 'aksConfig');
    const upstreamSpec = get(originalCluster, 'aksStatus.upstreamSpec');

    if (!isEmpty(upstreamSpec)) {
      Object.keys(upstreamSpec).forEach((k) => {
        if (isEmpty(get(ourClusterSpec, k)) && !isEmpty(get(upstreamSpec, k))) {
          set(this, `config.${ k }`, get(upstreamSpec, k));
        }
      });
    }
  },
});


text:
package org.apache.activemq;

import java.util.List;
import java.util.Vector;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import javax.jms.TextMessage;

import org.apache.activemq.test.TestSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class JmsTopicRequestReplyTest extends TestSupport implements MessageListener {

   private static final Logger LOG = LoggerFactory.getLogger(JmsTopicRequestReplyTest.class);

   protected boolean useAsyncConsume;
   private Connection serverConnection;
   private Connection clientConnection;
   private MessageProducer replyProducer;
   private Session serverSession;
   private Destination requestDestination;
   private List<JMSException> failures = new Vector<>();
   private boolean dynamicallyCreateProducer;
   private String clientSideClientID;

   public void testSendAndReceive() throws Exception {
      clientConnection = createConnection();
      clientConnection.setClientID("ClientConnection:" + getSubject());

      Session session = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      clientConnection.start();

      Destination replyDestination = createTemporaryDestination(session);

      // lets test the destination
      clientSideClientID = clientConnection.getClientID();

      // TODO
      // String value = ActiveMQDestination.getClientId((ActiveMQDestination)
      // replyDestination);
      // assertEquals("clientID from the temporary destination must be the
      // same", clientSideClientID, value);
      LOG.info("Both the clientID and destination clientID match properly: " + clientSideClientID);

        /* build queues */
      MessageProducer requestProducer = session.createProducer(requestDestination);
      MessageConsumer replyConsumer = session.createConsumer(replyDestination);

        /* build requestmessage */
      TextMessage requestMessage = session.createTextMessage("Olivier");
      requestMessage.setJMSReplyTo(replyDestination);
      requestProducer.send(requestMessage);

      LOG.info("Sent request.");
      LOG.info(requestMessage.toString());

      Message msg = replyConsumer.receive(5000);

      if (msg instanceof TextMessage) {
         TextMessage replyMessage = (TextMessage) msg;
         LOG.info("Received reply.");
         LOG.info(replyMessage.toString());
         assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText());
      }
      else {
         fail("Should have received a reply by now");
      }
      replyConsumer.close();
      deleteTemporaryDestination(replyDestination);

      assertEquals("Should not have had any failures: " + failures, 0, failures.size());
   }

   public void testSendAndReceiveWithDynamicallyCreatedProducer() throws Exception {
      dynamicallyCreateProducer = true;
      testSendAndReceive();
   }

   /**
    * Use the asynchronous subscription mechanism
    */
   @Override
   public void onMessage(Message message) {
      try {
         TextMessage requestMessage = (TextMessage) message;

         LOG.info("Received request.");
         LOG.info(requestMessage.toString());

         Destination replyDestination = requestMessage.getJMSReplyTo();

         // TODO
         // String value =
         // ActiveMQDestination.getClientId((ActiveMQDestination)
         // replyDestination);
         // assertEquals("clientID from the temporary destination must be the
         // same", clientSideClientID, value);

         TextMessage replyMessage = serverSession.createTextMessage("Hello: " + requestMessage.getText());

         replyMessage.setJMSCorrelationID(requestMessage.getJMSMessageID());

         if (dynamicallyCreateProducer) {
            replyProducer = serverSession.createProducer(replyDestination);
            replyProducer.send(replyMessage);
         }
         else {
            replyProducer.send(replyDestination, replyMessage);
         }

         LOG.info("Sent reply.");
         LOG.info(replyMessage.toString());
      }
      catch (JMSException e) {
         onException(e);
      }
   }

   /**
    * Use the synchronous subscription mechanism
    */
   protected void syncConsumeLoop(MessageConsumer requestConsumer) {
      try {
         Message message = requestConsumer.receive(5000);
         if (message != null) {
            onMessage(message);
         }
         else {
            LOG.error("No message received");
         }
      }
      catch (JMSException e) {
         onException(e);
      }
   }

   @Override
   protected void setUp() throws Exception {
      super.setUp();

      serverConnection = createConnection();
      serverConnection.setClientID("serverConnection:" + getSubject());
      serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      replyProducer = serverSession.createProducer(null);

      requestDestination = createDestination(serverSession);

        /* build queues */
      final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination);
      if (useAsyncConsume) {
         requestConsumer.setMessageListener(this);
      }
      else {
         Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
               syncConsumeLoop(requestConsumer);
            }
         });
         thread.start();
      }
      serverConnection.start();
   }

   @Override
   protected void tearDown() throws Exception {
      super.tearDown();

      serverConnection.close();
      clientConnection.stop();
      clientConnection.close();
   }

   protected void onException(JMSException e) {
      LOG.info("Caught: " + e);
      e.printStackTrace();
      failures.add(e);
   }

   protected Destination createDestination(Session session) throws JMSException {
      if (topic) {
         return session.createTopic(getSubject());
      }
      return session.createQueue(getSubject());
   }

   protected Destination createTemporaryDestination(Session session) throws JMSException {
      if (topic) {
         return session.createTemporaryTopic();
      }
      return session.createTemporaryQueue();
   }

   protected void deleteTemporaryDestination(Destination dest) throws JMSException {
      if (topic) {
         ((TemporaryTopic) dest).delete();
      }
      else {
         ((TemporaryQueue) dest).delete();
      }
   }

}


text:
"""Generate tests"""
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from builtins import (  # pylint: disable=redefined-builtin, unused-import
    bytes, dict, int, list, object, range, str,
    ascii, chr, hex, input, next, oct, open,
    pow, round, super,
    filter, map, zip)
import skmsa
from utils import make_scenarios, tests_dir
from test_read import TEST, KVALS
import os

tdir = tests_dir()
for name, kw in make_scenarios(TEST, KVALS):
    source = os.path.join(tdir, kw['source'])
    name = os.path.join(tdir, name)
    kw['source'] = source
    sd = skmsa.read(**kw)
    sd.save(os.path.join(name))


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.program.model.address;

import java.util.Comparator;

/**
 * Compares an address against an AddressRange.
 *

 */
public class AddressRangeToAddressComparator implements Comparator<Object> {
	/**
	 * Compares an address against an AddressRange.
	 * @param obj1 the first object to compare. Must be an address or an address range.
	 * @param obj2 the second object to compare. Must be an address or an address range.
	 *

     * @return a negative integer, zero, or a positive integer
     *  if the first argument is less than, equal to, or greater than the second.
	 */
    public int compare(Object obj1, Object obj2) {
        if(obj1 instanceof AddressRange) {
            return ((AddressRange) obj1).compareTo((Address) obj2);
        }
        return -((AddressRange) obj2).compareTo((Address) obj1);
    }

}


text:
Initial thoughts on what admin should do after receiving a Pull Request for a developer's feature branch.  I have not checked these for accuracy (do the commands accomplish what I say?), and I'm in the dark on best practices.

## Notify other admins that you are handling the request? ##
Perhaps notify everyone (other admins, the developer, all subscribers) by commenting on the Pull Request

## Initial review in [GitHub][] ##
Using the links in the Pull-Request email:
- Is the change desirable?  If not, comment on the request.
- Eyeball the diffs to see if the code is reasonable: Does it look like it will work? Is the quality reasonable?

## Review the changes on your local machine ##
(Nathan floated the idea that each admin should have two local MO repos:  (1) one for your own development work (and where you act like any other developer), (2) one for admin work (like checking and merging other developer's work).)

### Get the changes ###
- If you haven't done it already, add the developer's personal [GitHub][] repo as a remote of your local repo and get the developer's repo.  Then create a local feature branch and switch to it. Use a [Git GUI][] or:
```
git remote add <your name for the remote> git@github.com:<DeveloperGitUserName>/mushroom-observer.git
git fetch <remote>
git checkout -b <branch> <remote>/<branch>
```
For instance, the following makes @JoeCohen's personal Github repository a remote (named "JoeCohen") of your local repo, and switches to its "myfix" branch:
```
git remote add git@github.com:JoeCohen/mushroom-observer.git
git fetch JoeCohen
git -b myfix JoeCohen/myfix
```
### Experiment with the changes ###

- run the MO test suite
- See if the change works as advertised
- Look for obvious bad side effects

## Add the changes to the [Official MO Repo][] ##
I'm again unsure of the best practice.  To be safe, it's probably best to  sync to the [Official MO Repo][] because if it changed, we need to make sure we're still compatible.  If everything's okay, merge the developer's work and push it to the [Official MO Repo][]. (If there are incompatibilties, either (a) the admin can fix them, complete the merge, and then push to the [Official MO Repo][], or (b) ask the developer to fix them.) Use a [Git GUI][] or
```
git checkout master
git fetch origin
git merge origin/master
git merge <developer's feature branch>
git push origin
```
Do we need to do anything in [Github][] or [Pivotal Tracker][]?

# References #
- [Git workflow][]
- [Integration-Manager Workflow][]
- [Maintaining a Project][]
- [Using pull requests][]

- - -
[comment]: # (The following are link reference definitions)
[Create a user in the new instance of MO]: /README.md#create-a-user-in-the-new-instance-of-mo)
[Forking Workflow]: https://www.atlassian.com/git/workflows#!workflow-forking
[Git fetch and merge]: http://longair.net/blog/2009/04/16/git-fetch-and-merge/
[Git GUI]: /DEVELOPER-WORKFLOW.md#git-guis/
[Git workflow]: https://sandofsky.com/blog/git-workflow.html
[Github]: https://github.com/
[GitHub GUI]: https://central.github.com/mac/latest
[Initial Database]: /DEVELOPER-WORKFLOW.md#intial-databse/
[Installing Ruby]: /DEVELOPER-WORKFLOW.md#installing-ruby/
[Integration-Manager Workflow]: http://git-scm.com/book/en/Distributed-Git-Distributed-Workflows#Integration-Manager-Workflow
[Official MO Repo]: https://github.com/MushroomObserver/mushroom-observer
[Maintaining a Project]: http://git-scm.com/book/en/Distributed-Git-Maintaining-a-Project
[Pivotal Tracker]: https://www.pivotaltracker.com/n/projects/224629
[PuTTY]: http://www.chiark.greenend.org.uk/~sgtatham/putty/
[README.md]: /README.md
[SourceTree]: http://www.sourcetreeapp.com
[Using pull requests]: https://help.github.com/articles/using-pull-requests
[What's the Workflow]: http://stackoverflow.com/questions/20956154/whats-the-workflow-to-contribute-to-an-open-source-project-using-git-pull-reque
[Workflow]: /DEVELOPER-WORKFLOW.md#workflow/


text:
Sometimes you don't want give your enduser ability to download all your Zabbix monitoring data but you want to inform them about downtime in friendly way.

## How?

Just run Dr. Z, preferably on zabbix host.

Then you can send generated result.json to some outside infra like cheap Digital Ocean VPS. You can get free $10 credit on DO by using [this link](https://www.digitalocean.com/?refcode=2cad4d210b4a).

By using javascript client for enduser status page you can even host it directly on AWS S3 only by syncing via cron result.json.

## TL;DR Quickstart on Ubuntu

```bash
sudo apt-get install php5-cli git
git clone https://github.com/lvlup-pro/dr-g.git lvlup-dr-g
cd lvlup-dr-g
curl -sS https://getcomposer.org/installer | php
php composer.phar install
php app.php
```


text:
package wire

import (
	"bytes"
	"errors"

	"github.com/lucas-clemente/quic-go/internal/protocol"
	"github.com/lucas-clemente/quic-go/internal/utils"
)

// A StopWaitingFrame in QUIC
type StopWaitingFrame struct {
	LeastUnacked    protocol.PacketNumber
	PacketNumberLen protocol.PacketNumberLen
	// PacketNumber is the packet number of the packet that this StopWaitingFrame will be sent with
	PacketNumber protocol.PacketNumber
}

var (
	errLeastUnackedHigherThanPacketNumber = errors.New("StopWaitingFrame: LeastUnacked can't be greater than the packet number")
	errPacketNumberNotSet                 = errors.New("StopWaitingFrame: PacketNumber not set")
	errPacketNumberLenNotSet              = errors.New("StopWaitingFrame: PacketNumberLen not set")
)

func (f *StopWaitingFrame) Write(b *bytes.Buffer, v protocol.VersionNumber) error {
	if v.UsesIETFFrameFormat() {
		return errors.New("STOP_WAITING not defined in IETF QUIC")
	}
	// make sure the PacketNumber was set
	if f.PacketNumber == protocol.PacketNumber(0) {
		return errPacketNumberNotSet
	}
	if f.LeastUnacked > f.PacketNumber {
		return errLeastUnackedHigherThanPacketNumber
	}

	b.WriteByte(0x06)
	leastUnackedDelta := uint64(f.PacketNumber - f.LeastUnacked)
	switch f.PacketNumberLen {
	case protocol.PacketNumberLen1:
		b.WriteByte(uint8(leastUnackedDelta))
	case protocol.PacketNumberLen2:
		utils.BigEndian.WriteUint16(b, uint16(leastUnackedDelta))
	case protocol.PacketNumberLen4:
		utils.BigEndian.WriteUint32(b, uint32(leastUnackedDelta))
	case protocol.PacketNumberLen6:
		utils.BigEndian.WriteUint48(b, leastUnackedDelta&(1<<48-1))
	default:
		return errPacketNumberLenNotSet
	}
	return nil
}

// Length of a written frame
func (f *StopWaitingFrame) Length(_ protocol.VersionNumber) protocol.ByteCount {
	return 1 + protocol.ByteCount(f.PacketNumberLen)
}

// parseStopWaitingFrame parses a StopWaiting frame
func parseStopWaitingFrame(r *bytes.Reader, packetNumber protocol.PacketNumber, packetNumberLen protocol.PacketNumberLen, _ protocol.VersionNumber) (*StopWaitingFrame, error) {
	frame := &StopWaitingFrame{}

	// read the TypeByte
	if _, err := r.ReadByte(); err != nil {
		return nil, err
	}

	leastUnackedDelta, err := utils.BigEndian.ReadUintN(r, uint8(packetNumberLen))
	if err != nil {
		return nil, err
	}
	if leastUnackedDelta > uint64(packetNumber) {
		return nil, errors.New("invalid LeastUnackedDelta")
	}
	frame.LeastUnacked = protocol.PacketNumber(uint64(packetNumber) - leastUnackedDelta)
	return frame, nil
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;

namespace DemoWebApi.DemoData
{
	public sealed class Constants
	{
		public const string DataNamespace = "http://fonlow.com/DemoData/2014/02";
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public enum AddressType
	{
		[EnumMember]
		Postal,
		[EnumMember]
		Residential,
	};

	[DataContract(Namespace = Constants.DataNamespace)]
	public enum MyEnumType
	{
		[EnumMember]
		First = 1,
		[EnumMember]
		Two = 2,
	};

	[DataContract(Namespace = Constants.DataNamespace)]
	public enum Days
	{
		[EnumMember]
		Sat = 1,
		[EnumMember]
		Sun,
		[EnumMember]
		Mon,
		[EnumMember]
		Tue,
		[EnumMember]
		Wed,
		/// <summary>
		/// Thursday
		/// </summary>
		[EnumMember]
		Thu,
		[EnumMember]
		Fri
	};

	[DataContract(Namespace = Constants.DataNamespace)]
	public class PhoneNumber
	{
		public PhoneNumber()
		{

		}

		public Guid Id { get; set; }

		[DataMember]
		public string FullNumber { get; set; }

		[DataMember]
		public PhoneType PhoneType { get; set; }

		public Guid EntityId { get; set; }
	}

	/// <summary>
	/// Phone type
	/// Tel, Mobile, Skyp and Fax
	///
	/// </summary>
	[DataContract(Namespace = Constants.DataNamespace)]
	public enum PhoneType
	{
		/// <summary>
		/// Land line
		/// </summary>
		[EnumMember]
		Tel = 0,

		/// <summary>
		/// Mobile phone
		/// </summary>
		[EnumMember]
		Mobile = 1,

		[EnumMember]
		Skype = 2,
		[EnumMember]
		Fax = 3,
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class Address
	{
		[DataMember]
		public Guid Id { get; set; }

		public Entity Entity { get; set; }

		/// <summary>
		/// Foreign key to Entity
		/// </summary>
		public Guid EntityId { get; set; }

		[DataMember]
		public string Street1 { get; set; }

		[DataMember]
		public string Street2 { get; set; }

		[DataMember]
		public string City { get; set; }

		[DataMember]
		public string State { get; set; }

		[DataMember]
		public string PostalCode { get; set; }

		[DataMember]
		[System.ComponentModel.DefaultValue("Australia")]
		public string Country { get; set; }

		[System.ComponentModel.DefaultValue(AddressType.Residential)]
		[DataMember]
		public AddressType Type { get; set; }

		/// <summary>
		/// It is a field
		/// </summary>
		[DataMember]
		public DemoWebApi.DemoData.Another.MyPoint Location;
	}

	/// <summary>
	/// Base class of company and person
	/// </summary>
	[DataContract(Namespace = Constants.DataNamespace)]
	public class Entity
	{
		public Entity()
		{
			Addresses = new List<Address>();
		}

		[DataMember]
		public Guid? Id { get; set; }

		/// <summary>
		/// Name of the entity.
		/// </summary>
		[DataMember(IsRequired =true)]//MVC and Web API does not care
		[System.ComponentModel.DataAnnotations.Required]//MVC and Web API care about only this
		public string Name { get; set; }

		/// <summary>
		/// Multiple addresses
		/// </summary>
		[DataMember]
		public IList<Address> Addresses { get; set; }

		[DataMember]
		public virtual ObservableCollection<PhoneNumber> PhoneNumbers { get; set; }

		public override string ToString()
		{
			return Name;
		}

		[DataMember]
		public Uri Web { get; set; }
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class Person : Entity
	{
		[DataMember]
		public string Surname { get; set; }
		[DataMember]
		public string GivenName { get; set; }

		/// <summary>
		/// Date of Birth.
		/// This is optional.
		/// </summary>
		[DataMember]
		public DateOnly? DOB { get; set; }

		[DataMember]
		[DataType(DataType.Date)]
		public DateTimeOffset? Baptised { get; set; }

		public override string ToString()
		{
			return Surname + ", " + GivenName;
		}

	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class Company : Entity
	{
		/// <summary>
		/// BusinessNumber to be serialized as BusinessNum
		/// </summary>
		[DataMember(Name ="BusinessNum")]
		public string BusinessNumber { get; set; }

		[DataMember]
		public string BusinessNumberType { get; set; }

		[DataMember]
		public string[][] TextMatrix
		{ get; set; }

		[DataMember]
		public int[][] Int2DJagged;

		[DataMember]
		public int[,] Int2D;

		[DataMember]
		public IEnumerable<string> Lines;

		[DataMember]
		public DateOnly RegisterDate { get; set; }

		[DataMember]
		[DataType(DataType.Date)]
		public DateTimeOffset FoundDate { get; set; }
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class MyPeopleDic
	{
		[DataMember]
		public IDictionary<string, Person> Dic { get; set; }

		[DataMember]
		public IDictionary<string, string> AnotherDic { get; set; }

		[DataMember]
		public IDictionary<int, string> IntDic { get; set; }

	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class MimsResult<T>
	{
		[DataMember]
		public T Result { get; set; }
		[DataMember]
		public DateTime GeneratedAt { get; set; }
		[DataMember]
		public bool Success { get; set; } = true;
		[DataMember]
		public string Message { get; set; }
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class MimsPackage
	{
		[DataMember]
		public MimsResult<decimal> Result { get; set; }

		[DataMember]
		public string Tag { get; set; }

		[DataMember]
		[Range(10, 100, ErrorMessage = "KK has to be between 10 and 100.")]
		[System.ComponentModel.DefaultValue(20)]
		public int KK { get; set; }

		/// <summary>
		/// Having an initialized value in the property is not like defining a DefaultValueAttribute. Such intialization happens at run time,
		/// and there's no reliable way for a codegen to know if the value is declared by the programmer, or is actually the natural default value like 0.
		/// </summary>
		[DataMember]
		public int KK2 { get; set; } = 2;

		[DataMember]
		public int? OptionalInt { get; set; }

		[DataMember]
		public MyEnumType? OptionalEnum { get; set; }
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	public class MyGeneric<T, K, U>
	{
		[DataMember]
		public T MyT { get; set; }

		[DataMember]
		public K MyK { get; set; }

		[DataMember]
		public U MyU { get; set; }

		[DataMember]
		public string Status { get; set; }
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
	public enum MedicalContraindiationResponseTypeReason
	{

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "Mm")]
		M = 0,

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "Ss")]
		S = 1,

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "Pp")]
		P = 2,

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "I")]
		I = 3,

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "A")]
		A = 4,
	}

	[DataContract(Namespace = Constants.DataNamespace)]
	//[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
	public enum MedicalContraindiationResponseTypeTypeCode
	{

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "P")]
		P = 0,

		[System.Runtime.Serialization.EnumMemberAttribute(Value = "Tt")]
		T = 1,
	}

	/// <summary>
	/// To test different serializations against Guid
	/// </summary>
	[DataContract(Namespace = Constants.DataNamespace)]
	public class IdMap
	{
		[DataMember]
		public Guid Id { get; set; }

		[DataMember]
		public Guid? NullableId { get; set; }

		[DataMember(EmitDefaultValue = false)]
		public Guid IdNotEmitDefaultValue { get; set; }

		[DataMember(IsRequired =true)]
		public string RequiredName { get; set; }

		[DataMember()]
		public string Text { get; set; }
	}

}

namespace DemoWebApi.DemoData.Another
{
	/// <summary>
	/// 2D position
	///         with X and Y
	/// for Demo
	/// </summary>
	[JsonObject]
	public struct MyPoint
	{
		/// <summary>
		/// X
		/// </summary>
		public double X;

		/// <summary>
		/// Y
		/// </summary>
		public double Y;
	}
}


text:
@implementation SlideRootLayer

+ (id) layer {
  SlideRootLayer *newLayer = [super layer];
  if (newLayer) {
    [newLayer setupConstraints];
  }
  return newLayer;
}

- (void) setupConstraints {
  self.layoutManager = [CAConstraintLayoutManager layoutManager];
}

@end


text:
<?php

namespace Renovate\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Renovate\MainBundle\Entity\Article;
use Renovate\MainBundle\Entity\Job;
use Renovate\MainBundle\Entity\News;
use Renovate\MainBundle\Entity\Result;
use Renovate\MainBundle\Entity\Share;
use Renovate\MainBundle\Entity\Vacancy;

class SearchController extends Controller
{
    public function indexAction(Request $request)
    {
    	$em = $this->getDoctrine()->getManager();
    	$parameters = array();

    	if ($request->isMethod('POST')){
    		if ($request->request->get('search'))
    		{
    			$articles = Article::searchArticles($em, $request->request->get('search'));
    			$parameters['articles'] = $articles;
    			$jobs = Job::searchJobs($em, $request->request->get('search'));
    			$parameters['jobs'] = $jobs;
    			$news = News::searchNews($em, $request->request->get('search'));
    			$parameters['news'] = $news;
    			$results = Result::searchResults($em, $request->request->get('search'));
    			$parameters['results'] = $results;
    			$shares = Share::searchShares($em, $request->request->get('search'));
    			$parameters['shares'] = $shares;
    			$vacancies = Vacancy::searchVacancies($em, $request->request->get('search'));
    			$parameters['vacancies'] = $vacancies;
    		}

    		$parameters['search'] = $request->request->get('search');
    	}

    	return $this->render('RenovateMainBundle:Search:index.html.twig', $parameters);
    }
}


text:
class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        # basically DFS with path recorder
        if not root:
            return []
        result = []
        cur = []

        self.helper(root, result, cur)
        return result

    def helper(self, node, result, cur):
        if not node.left and not node.right:
            cur += node,
            result.append('->'.join([str(i.val) for i in cur]))
            cur.pop(-1)
            return

        cur.append(node)
        if node.left:
            self.helper(node.left, result, cur)
        if node.right:
            self.helper(node.right, result,cur)
        cur.pop(-1)


text:
package source

import (
	"context"
	"errors"
	"io"
	"net"
	"testing"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"

	mcp "istio.io/api/mcp/v1alpha1"
	"istio.io/istio/pkg/mcp/internal/test"
	"istio.io/istio/pkg/mcp/status"
	"istio.io/istio/pkg/mcp/testing/monitoring"
)

type serverHarness struct {
	grpc.ServerStream
	*sourceTestHarness
}

func (h *serverHarness) EstablishResourceStream(ctx context.Context, opts ...grpc.CallOption) (mcp.ResourceSource_EstablishResourceStreamServer, error) { // nolint: lll
	return h, h.openError()
}

func (*serverHarness) SendHeader(metadata.MD) error {
	return nil
}

// avoid ambiguity between grpc.ServerStream and test.sourceTestHarness
func (h *serverHarness) Context() context.Context {
	return h.sourceTestHarness.Context()
}

func TestServerSinkRateLimitter(t *testing.T) {
	h := &serverHarness{
		sourceTestHarness: newSourceTestHarness(t),
	}

	fakeLimiter := test.NewFakeRateLimiter()
	authChecker := test.NewFakeAuthChecker()
	options := &Options{
		Watcher:            h,
		CollectionsOptions: CollectionOptionsFromSlice(test.SupportedCollections),
		Reporter:           monitoring.NewInMemoryStatsContext(),
		ConnRateLimiter:    test.NewFakePerConnLimiter(),
	}
	s := NewServer(options, &ServerOptions{AuthChecker: authChecker})
	s.rateLimiter = fakeLimiter

	// when rate limit returns an error
	errc := make(chan error)
	go func() {
		errc <- s.EstablishResourceStream(h)
	}()

	expectedErr := "something went wrong while waiting"

	fakeLimiter.WaitErr <- errors.New(expectedErr)

	err := <-errc
	if err == nil || err.Error() != expectedErr {
		t.Fatalf("Expected error from Wait: got %v want %v ", err, expectedErr)
	}
}

func TestServerSource(t *testing.T) {
	h := &serverHarness{
		sourceTestHarness: newSourceTestHarness(t),
	}

	authChecker := test.NewFakeAuthChecker()
	rateLimiter := test.NewFakePerConnLimiter()
	// force ratelimiter Wait to return nil by closing WaitErr
	close(rateLimiter.ErrCh)
	options := &Options{
		Watcher:            h,
		CollectionsOptions: CollectionOptionsFromSlice(test.SupportedCollections),
		Reporter:           monitoring.NewInMemoryStatsContext(),
		ConnRateLimiter:    rateLimiter,
	}

	fakeLimiter := test.NewFakeRateLimiter()
	// force ratelimiter Wait to return nil by closing WaitErr
	close(fakeLimiter.WaitErr)

	srvOptions := &ServerOptions{
		AuthChecker: authChecker,
		RateLimiter: fakeLimiter,
	}
	s := NewServer(options, srvOptions)

	errc := make(chan error)
	go func() {
		errc <- s.EstablishResourceStream(h)
	}()

	h.setRecvError(io.EOF)
	err := <-errc
	if err != nil {
		t.Fatalf("Stream exited with error: got %v", err)
	}

	// ProcessStream error
	wantError := errors.New("unknown")
	h.setRecvError(wantError)
	go func() {
		errc <- s.EstablishResourceStream(h)
	}()
	err = <-errc
	if err != wantError {
		t.Fatalf("Stream exited with error: got %v want %v", err, wantError)
	}

	h.setContext(peer.NewContext(context.Background(), &peer.Peer{
		Addr:     &net.IPAddr{IP: net.IPv4(192, 168, 1, 1)},
		AuthInfo: authChecker,
	}))
	authChecker.AllowError = errors.New("not allowed")
	err = s.EstablishResourceStream(h)
	if s, ok := status.FromError(err); !ok || s.Code() != codes.Unauthenticated {
		t.Fatalf("Connection should have failed: got %v want %v", err, nil)
	}

	authChecker.AllowError = nil

	h.resetStream()
	h.setRecvError(nil)

	go func() {
		errc <- s.EstablishResourceStream(h)
	}()

	h.injectWatchResponse(&WatchResponse{
		Collection: test.FakeType0Collection,
		Version:    "1",
		Resources:  []*mcp.Resource{test.Type0A[0].Resource},
	})
	h.injectWatchResponse(&WatchResponse{
		Collection: test.FakeType1Collection,
		Version:    "2",
		Resources:  []*mcp.Resource{test.Type1A[0].Resource},
	})
	h.injectWatchResponse(&WatchResponse{
		Collection: test.FakeType2Collection,
		Version:    "3",
		Resources:  []*mcp.Resource{test.Type2A[0].Resource},
	})

	h.requestsChan <- test.MakeRequest(false, test.FakeType0Collection, "", codes.OK)
	h.requestsChan <- test.MakeRequest(false, test.FakeType1Collection, "", codes.OK)
	h.requestsChan <- test.MakeRequest(false, test.FakeType2Collection, "", codes.OK)

	verifySentResourcesMultipleTypes(t, h.sourceTestHarness,
		map[string]*mcp.Resources{
			test.FakeType0Collection: test.MakeResources(false, test.FakeType0Collection, "1", "1", nil, test.Type0A[0]),
			test.FakeType1Collection: test.MakeResources(false, test.FakeType1Collection, "2", "2", nil, test.Type1A[0]),
			test.FakeType2Collection: test.MakeResources(false, test.FakeType2Collection, "3", "3", nil, test.Type2A[0]),
		},
	)

	want := 1
	for _, typeURL := range []string{test.FakeType0Collection, test.FakeType1Collection, test.FakeType2Collection} {
		if got := h.watchesCreated(typeURL); got != want {
			t.Fatalf("Wrong number of %v watches created: got %v want %v", typeURL, got, want)
		}
	}
}


text:
define(
	[
		'jsorrery/NameSpace',
		'jquery',
		'jsorrery/graphics3d/Dimensions',
		'jsorrery/graphics2d/Labels',
		'jsorrery/graphics3d/loaders/ResourceLoader',
		'three',
		'three/RingGeometry2',
		'vendor/greensock/TweenMax',
		'vendor/greensock/easing/EasePack'
	],
	function(ns, $, Dimensions, Labels, ResourceLoader) {
		'use strict';

		var Body3d = {

			init : function(celestialBody) {
				this.root = new THREE.Object3D();
				this.celestial = celestialBody;
				//max delta T to show rotation. If deltaT is larger than that, planet would spin too fast, so don't show sideral day
				this.maxDeltaForSideralDay = this.celestial.sideralDay && this.celestial.sideralDay / 20;

				this.setPlanet();

				//make this display object available from the celestial body
				this.celestial.getBody3D = function(){
					return this;
				}.bind(this);

				Labels.addPlanetLabel(this.celestial.title || this.celestial.name, this);

			},

			addEventLabel:function(){},

			getDisplayObject : function() {
				return this.root;
			},

			setParentDisplayObject : function(object3d) {
				this.parentContainer = object3d;
				this.parentContainer.add(this.root);
			},

			setPlanet : function(){
				var map = this.celestial.map;
				var matOptions = {};
				if(map){
					matOptions.map = ResourceLoader.loadTexture(map);
				} else {
					matOptions.color = this.celestial.color
				}

				var mat = new THREE.MeshPhongMaterial(matOptions);
				_.extend(mat, this.celestial.material || {});

				var radius = this.getPlanetSize();
				var segments = 50;
				var rings = 50;
				var sphere = new THREE.Mesh(
					new THREE.SphereGeometry(radius, segments, rings),
					mat
				);

				//console.log(this.celestial.name+' size ',radius, ' m');

				this.planet = new THREE.Object3D();
				this.planet.add(sphere);

				if(this.celestial.ring){
					var ringSize = [
						Dimensions.getScaled(this.celestial.ring.innerRadius * ns.KM),
						Dimensions.getScaled(this.celestial.ring.outerRadius * ns.KM)
					];

					var ringMap = ResourceLoader.loadTexture( this.celestial.ring.map );

					var ringMaterial = new THREE.MeshLambertMaterial({
						map: ringMap,
						transparent: true,
						side: THREE.DoubleSide
					});

					//var ringGeometry = new THREE.TorusGeometry(ringSize[1], ringSize[1] - ringSize[0], 2, 40);
					var ringGeometry = new THREE.RingGeometry2(ringSize[1], ringSize[0], 180, 1, 0, Math.PI * 2);
					ringGeometry.computeFaceNormals();

					var ring = new THREE.Mesh(ringGeometry, ringMaterial);
					ring.rotation.x = - Math.PI / 2;
					this.planet.add(ring);

				}

				var tilt = Math.PI / 2;
				if(this.celestial.tilt) tilt -= this.celestial.tilt * ns.DEG_TO_RAD;
				this.planet.rotation.x = tilt;

				this.root.add(this.planet);
				return this.planet;
			},

			setScale : function(scaleVal) {
				if(this.maxScale && this.maxScale < scaleVal) return;
				this.planet.scale.set(scaleVal, scaleVal, scaleVal);
			},

			getPlanetSize : function(){
				return Dimensions.getScaled(this.celestial.radius * ns.KM);
			},

			getPlanetStageSize : function(){
				return this.getPlanetSize() * this.planet.scale.x;
			},

			addCamera : function(name, camera){
				this.root.add(camera);
				this.cameras = this.cameras || {};
				this.cameras[name] = camera;
			},

			getCamera : function(name){
				return this.cameras && this.cameras[name];
			},

			drawMove : function(){
				var pos = this.getPosition();
				this.root.position.copy(pos);
				if(this.celestial.sideralDay && ns.U.deltaT <= this.maxDeltaForSideralDay){
					var curRotation = (ns.U.epochTime / this.celestial.sideralDay) * ns.CIRCLE;
					this.planet.rotation.y = (this.celestial.baseMapRotation || 0) + curRotation;
				}
				this.tracer && this.tracer.doTrace(pos);
				return pos;
			},

			getScreenSizeRatio : function(camPos, fov){
				var sz = this.getPlanetStageSize();
				//console.log(this.planet.scale.x);
				var dist = this.getPosition().sub(camPos).length();

				var height = 2 * Math.tan( (fov * ns.DEG_TO_RAD) / 2 ) * dist; // visible height, see http://stackoverflow.com/questions/13350875/three-js-width-of-view/13351534#13351534
				return sz/height;
			},

			getPosition : function(pos) {
				var curPosition = (pos && pos.clone()) || this.celestial.getPosition();
				return Dimensions.getScaled(curPosition);
			},

			getName : function(){
				return this.celestial.name;
			}
		};

		return Body3d;

	});


text:
package org.assertj.core.api.offsetdatetime;

import static org.junit.Assume.assumeTrue;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

import org.assertj.core.api.BaseTest;
import org.junit.experimental.theories.DataPoint;

/**
 * Base test class for {@link org.assertj.core.api.AbstractOffsetDateTimeAssert} tests.
 *
 * @author Joel Costigliola
 * @author Marcin Zajączkowski
 */
public class OffsetDateTimeAssertBaseTest extends BaseTest {

  @DataPoint
  public static OffsetDateTime offsetDateTime1 = OffsetDateTime.of(2000, 12, 14, 0, 0, 0, 0, ZoneOffset.UTC);
  @DataPoint
  public static OffsetDateTime offsetDateTime2 = OffsetDateTime.of(2000, 12, 13, 23, 59, 59, 999, ZoneOffset.UTC);
  @DataPoint
  public static OffsetDateTime offsetDateTime3 = OffsetDateTime.of(2000, 12, 14, 0, 0, 0, 1, ZoneOffset.UTC);
  @DataPoint
  public static OffsetDateTime offsetDateTime4 = OffsetDateTime.of(2000, 12, 14, 22, 15, 15, 875, ZoneOffset.UTC);
  @DataPoint
  public static OffsetDateTime offsetDateTime5 = OffsetDateTime.of(2000, 12, 14, 22, 15, 15, 874, ZoneOffset.UTC);
  @DataPoint
  public static OffsetDateTime offsetDateTime6 = OffsetDateTime.of(2000, 12, 14, 22, 15, 15, 876, ZoneOffset.UTC);

  protected static void testAssumptions(OffsetDateTime reference, OffsetDateTime before, OffsetDateTime equal,
                                        OffsetDateTime after) {
    assumeTrue(before.isBefore(reference));
    assumeTrue(equal.isEqual(reference));
    assumeTrue(after.isAfter(reference));
  }

}


text:
#include <pybind11/pybind11.h>

// convenience functions
#include <pybind11/operators.h>

#include "librealsense2-net/rs_net.hpp"

#define NAME pyrealsense2_net
#define SNAME "pyrealsense2_net"

namespace py = pybind11;
using namespace pybind11::literals;

auto device = (py::object) py::module::import("pyrealsense2").attr("device");

PYBIND11_MODULE(NAME, m) {
    m.doc() = "Wrapper for the librealsense ethernet device extension module";

    py::class_<rs2::net_device> net_device(m, "net_device", device);
    net_device.def(py::init<std::string>(), "address"_a)
        .def("add_to", &rs2::net_device::add_to, "Add net device to existing context.\n"
             "Any future queries on the context will return this device.\n"
             "This operation cannot be undone (except for destroying the context)", "ctx"_a);
}


text:
typedef struct GPBMessage_Storage {
  uint32_t _has_storage_[0];
} GPBMessage_Storage;

typedef struct GPBMessage_Storage *GPBMessage_StoragePtr;

@interface GPBMessage () {
 @package
  // NOTE: Because of the +allocWithZone code using NSAllocateObject(),
  // this structure should ideally always be kept pointer aligned where the
  // real storage starts is also pointer aligned. The compiler/runtime already
  // do this, but it may not be documented.

  // A pointer to the actual fields of the subclasses. The actual structure
  // pointed to by this pointer will depend on the subclass.
  // All of the actual structures will start the same as
  // GPBMessage_Storage with _has_storage__ as the first field.
  // Kept public because static functions need to access it.
  GPBMessage_StoragePtr messageStorage_;
}

// Gets an extension value without autocreating the result if not found. (i.e.
// returns nil if the extension is not set)
- (id)getExistingExtension:(GPBExtensionDescriptor *)extension;

// Parses a message of this type from the input and merges it with this
// message.
//
// Warning:  This does not verify that all required fields are present in
// the input message.
// Note:  The caller should call
// -[CodedInputStream checkLastTagWas:] after calling this to
// verify that the last tag seen was the appropriate end-group tag,
// or zero for EOF.
// NOTE: This will throw if there is an error while parsing.
- (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input
                extensionRegistry:(GPBExtensionRegistry *)extensionRegistry;

// Parses the next delimited message of this type from the input and merges it
// with this message.
- (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
                         extensionRegistry:
                             (GPBExtensionRegistry *)extensionRegistry;

- (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data;

@end

CF_EXTERN_C_BEGIN

// Call this before using the readOnlySemaphore_. This ensures it is created only once.
void GPBPrepareReadOnlySemaphore(GPBMessage *self);

// Returns a new instance that was automatically created by |autocreator| for
// its field |field|.
GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass,
                                            GPBMessage *autocreator,
                                            GPBFieldDescriptor *field)
    __attribute__((ns_returns_retained));

// Returns whether |message| autocreated this message. This is NO if the message
// was not autocreated by |message| or if it has been mutated since
// autocreation.
BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent);

// Call this when you mutate a message. It will cause the message to become
// visible to its autocreator.
void GPBBecomeVisibleToAutocreator(GPBMessage *self);

// Call this when an array/dictionary is mutated so the parent message that
// autocreated it can react.
void GPBAutocreatedArrayModified(GPBMessage *self, id array);
void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary);

// Clear the autocreator, if any. Asserts if the autocreator still has an
// autocreated reference to this message.
void GPBClearMessageAutocreator(GPBMessage *self);

CF_EXTERN_C_END


text:
layout: page
title: Willis Wind Networks Seminar
date: 2016-05-24
author: Matthew Jimenez
tags: weekly links, java
status: published
summary: Vestibulum pellentesque mi risus, vel tristique.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 11/09/2017
  endDate: 11/13/2017
  ctyhocn: ISPNYHX
  groupCode: WWNS
published: true
---
Morbi vitae est est. Ut vulputate tortor erat, vel venenatis magna fringilla et. Aenean pharetra lacus arcu, a sollicitudin lorem condimentum ut. In volutpat, neque at sollicitudin interdum, urna lorem mattis leo, non laoreet velit risus in mauris. Mauris pretium quis mi eu auctor. Integer sollicitudin luctus libero in hendrerit. Praesent fermentum tellus orci, id consectetur lectus efficitur tincidunt. Nulla in turpis nisl.

* Nulla laoreet felis id est faucibus, scelerisque dignissim sapien aliquam
* Nunc eu dui quis urna tincidunt accumsan
* Donec quis libero ac sem gravida dapibus ac at ex
* Sed eget nisi sed nulla bibendum accumsan.

Vestibulum id viverra arcu. Donec vitae blandit massa. Aenean at eros vitae risus fringilla ornare. Nam in purus eget sapien interdum rhoncus. In rhoncus lacus dolor, sed venenatis nulla tristique ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut commodo nibh ac enim scelerisque ullamcorper. Proin accumsan vitae sem vitae congue. Duis in lacus vel leo pharetra molestie nec et orci. Donec nec est nec turpis vulputate scelerisque.


text:
cave.analyzer.budgets package
=============================

.. automodule:: cave.analyzer.budgets
   :members:
   :undoc-members:
   :show-inheritance:
   :inherited-members:
   :private-members:

.. toctree::

   cave.analyzer.budgets.bohb_learning_curves
   cave.analyzer.budgets.budget_correlation
   cave.analyzer.budgets.incumbents_over_budgets


text:
import { ValidationContext } from "../ValidationContext";
import { ASTVisitor } from "../../language/visitor";

/**
 * Fields on correct type
 *
 * A GraphQL document is only valid if all fields selected are defined by the
 * parent type, or are an allowed meta field such as __typename.
 */
export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor;