text:
require "chef/provisioning/aws_driver/aws_provider"
require "date"
require "ipaddr"
require "set"

class Chef::Provider::AwsSecurityGroup < Chef::Provisioning::AWSDriver::AWSProvider
  include Chef::Provisioning::AWSDriver::TaggingStrategy::EC2ConvergeTags

  provides :aws_security_group

  def action_create
    sg = super

    apply_rules(sg)
  end

  protected

  def create_aws_object
    converge_by "create security group #{new_resource.name} in #{region}" do
      options = { description: new_resource.description.to_s }
      options[:vpc_id] = new_resource.vpc if new_resource.vpc
      options[:group_name] = new_resource.name
      if options[:description].nil? || (options[:description] == "")
        options[:description] = new_resource.name.to_s
      end
      options = AWSResource.lookup_options(options, resource: new_resource)
      Chef::Log.debug("VPC: #{options[:vpc_id]}")

      sg = new_resource.driver.ec2_resource.create_security_group(options)
      retry_with_backoff(::Aws::EC2::Errors::InvalidSecurityGroupsIDNotFound, ::Aws::EC2::Errors::InvalidGroupNotFound) do
        new_resource.driver.ec2_resource.create_tags(resources: [sg.id], tags: [{ key: "Name", value: new_resource.name }])
      end
      sg
    end
  end

  def update_aws_object(sg)
    if !new_resource.description.nil? && new_resource.description != sg.description
      raise "Security group descriptions cannot be changed after being created!  Desired description for #{new_resource.name} (#{sg.id}) was \"#{new_resource.description}\" and actual description is \"#{sg.description}\""
    end
    unless new_resource.vpc.nil?
      desired_vpc = Chef::Resource::AwsVpc.get_aws_object_id(new_resource.vpc, resource: new_resource)
      if desired_vpc != sg.vpc_id
        raise "Security group VPC cannot be changed after being created!  Desired VPC for #{new_resource.name} (#{sg.id}) was #{new_resource.vpc} (#{desired_vpc}) and actual VPC is #{sg.vpc_id}"
      end
    end
    apply_rules(sg)
  end

  def destroy_aws_object(sg)
    converge_by "delete security group #{new_resource} in #{region}" do
      sg.delete(dry_run: false)
    end
  end

  private

  def apply_rules(sg)
    vpc = sg.vpc_id
    update_outbound_rules(sg, vpc) unless new_resource.outbound_rules.nil?

    update_inbound_rules(sg, vpc) unless new_resource.inbound_rules.nil?
  end

  def update_inbound_rules(sg, vpc)
    #
    # Get desired rules
    #
    desired_rules = {}

    case new_resource.inbound_rules
    when Hash
      new_resource.inbound_rules.each do |sources_spec, port_spec|
        add_rule(desired_rules, get_port_ranges(port_spec), get_actors(vpc, sources_spec))
      end

    when Array
      # [ { port: X, protocol: Y, sources: [ ... ]}]
      new_resource.inbound_rules.each do |rule|
        port_ranges = get_port_ranges(rule)
        add_rule(desired_rules, port_ranges, get_actors(vpc, rule[:sources]))
      end

    else
      raise ArgumentError, "inbound_rules must be a Hash or Array (was #{new_resource.inbound_rules.inspect})"
    end

    #
    # Actually update the rules (remove, add)
    #
    update_rules(desired_rules, sg.ip_permissions,
                 authorize: proc do |port_range, protocol, actors|
                   names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
                   converge_by "authorize #{names.join(', ')} to send traffic to group #{new_resource.name} (#{sg.id}) on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
                     names.each do |iprange|
                       begin
                         if iprange.include?("-")
                           # user_id_group_pairs allows to add inbound rules for source security group
                           sg.authorize_ingress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               user_id_group_pairs: actors
                             }]
                           )
                         #               sg.authorize_ingress({
                         #                 group
                         #                 ip_permissions: [{
                         #                   ip_protocol: protocol,
                         #                   from_port: port_range.first,
                         #                   to_port: port_range.last,
                         #                   prefix_list_ids: [{
                         #                     prefix_list_id: iprange
                         #                   }]
                         #                 }]
                         #               })
                         else
                           sg.authorize_ingress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               ip_ranges: [{
                                 cidr_ip: iprange
                               }]
                             }]
                           )
                         end
                       rescue ::Aws::EC2::Errors::InvalidPermissionDuplicate => e
                         Chef::Log.debug("Ignoring duplicate permission")
                       end
                     end
                   end
                 end,

                 revoke: proc do |port_range, protocol, actors|
                   names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
                   converge_by "revoke the ability of #{names.join(', ')} to send traffic to group #{new_resource.name} (#{sg.id}) on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
                     names.each do |iprange|
                       begin
                         if iprange.include?("-")
                           # user_id_group_pairs allows to revoke inbound rules for source security group
                           sg.revoke_ingress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               user_id_group_pairs: actors
                             }]
                           )
                         #               sg.revoke_ingress({
                         #                 group
                         #                 ip_permissions: [{
                         #                   ip_protocol: protocol,
                         #                   from_port: port_range.first,
                         #                   to_port: port_range.last,
                         #                   prefix_list_ids: [{
                         #                     prefix_list_id: iprange
                         #                   }]
                         #                 }]
                         #               })
                         else
                           sg.revoke_ingress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               ip_ranges: [{
                                 cidr_ip: iprange
                               }]
                             }]
                           )
                         end
                       rescue ::Aws::EC2::Errors::InvalidPermissionNotFound => e
                         Chef::Log.debug("Ignoring missing permission")
                       end
                     end
                   end
                 end)
  end

  def update_outbound_rules(sg, vpc)
    #
    # Get desired rules
    #
    desired_rules = {}

    case new_resource.outbound_rules
    when Hash
      new_resource.outbound_rules.each do |port_spec, sources_spec|
        add_rule(desired_rules, get_port_ranges(port_spec), get_actors(vpc, sources_spec))
      end

    when Array
      # [ { port: X, protocol: Y, sources: [ ... ]}]
      new_resource.outbound_rules.each do |rule|
        add_rule(desired_rules, get_port_ranges(rule), get_actors(vpc, rule[:destinations]))
      end

    else
      raise ArgumentError, "outbound_rules must be a Hash or Array (was #{new_resource.outbound_rules.inspect})"
    end

    #
    # Actually update the rules (remove, add)
    #
    Chef::Log.info("dr: #{desired_rules}")
    update_rules(desired_rules, sg.ip_permissions_egress,
                 authorize: proc do |port_range, protocol, actors|
                   Chef::Log.info("proto: #{protocol.inspect}")
                   Chef::Log.info("port_range: #{port_range.inspect}")
                   names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
                   converge_by "authorize group #{new_resource.name} (#{sg.id}) to send traffic to #{names.join(', ')} on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
                     names.each do |iprange|
                       begin
                         if iprange.include?("-")
                           sg.authorize_egress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               user_id_group_pairs: actors
                             }]
                           )
                         #               sg.authorize_egress({
                         #                 group
                         #                 ip_permissions: [{
                         #                   ip_protocol: protocol,
                         #                   from_port: port_range.first,
                         #                   to_port: port_range.last,
                         #                   prefix_list_ids: [{
                         #                     prefix_list_id: iprange
                         #                   }]
                         #                 }]
                         #               })
                         else
                           sg.authorize_egress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               ip_ranges: [{
                                 cidr_ip: iprange
                               }]
                             }]
                           )
                         end
                       rescue ::Aws::EC2::Errors::InvalidPermissionDuplicate => e
                         Chef::Log.debug("Ignoring duplicate permission")
                       end
                     end
                   end
                 end,

                 revoke: proc do |port_range, protocol, actors|
                   names = actors.map { |a| a.is_a?(Hash) ? a[:group_id] : a }
                   converge_by "revoke the ability of group #{new_resource.name} (#{sg.id}) to send traffic to #{names.join(', ')} on port_range #{port_range.inspect} with protocol #{protocol || 'nil'}" do
                     names.each do |iprange|
                       begin
                         if iprange.include?("-")
                           sg.revoke_egress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               user_id_group_pairs: actors
                             }]
                           )
                         #               sg.revoke_egress({
                         #                 group
                         #                 ip_permissions: [{
                         #                   ip_protocol: protocol,
                         #                   from_port: port_range.first,
                         #                   to_port: port_range.last,
                         #                   prefix_list_ids: [{
                         #                     prefix_list_id: iprange
                         #                   }]
                         #                 }]
                         #               })
                         else
                           sg.revoke_egress(
                             ip_permissions: [{
                               ip_protocol: protocol,
                               from_port: port_range.first,
                               to_port: port_range.last,
                               ip_ranges: [{
                                 cidr_ip: iprange
                               }]
                             }]
                           )
                         end
                       rescue ::Aws::EC2::Errors::InvalidPermissionNotFound => e
                         Chef::Log.debug("Ignoring missing permission")
                       end
                     end
                   end
                 end)
  end

  def update_rules(desired_rules, actual_rules_list, authorize: nil, revoke: nil)
    actual_rules = {}
    actual_rules_list.each do |rule|
      rule = rule.to_h
      port_range = {
        port_range: rule[:from_port] ? rule[:from_port]..rule[:to_port] : -1..-1,
        protocol: rule[:ip_protocol].to_s.to_sym
      }
      rule[:user_id_group_pairs].map! { |h| h.reject { |x| x == :group_name } }
      add_rule(actual_rules, [port_range], rule[:user_id_group_pairs]) if rule[:user_id_group_pairs]
      add_rule(actual_rules, [port_range], rule[:ip_ranges].map { |r| r[:cidr_ip] }) if rule[:ip_ranges]
    end

    #
    # Get the list of permissions to add and remove
    #
    actual_rules.each do |port_range, actors|
      next unless desired_rules[port_range]
      intersection = actors & desired_rules[port_range]
      # Anything unhandled in desired_rules will be added
      desired_rules[port_range] -= intersection
      # Anything unhandled in actual_rules will be removed
      actual_rules[port_range] -= intersection
    end

    #
    # Add any new rules
    #
    desired_rules.each do |port_range, actors|
      unless actors.empty?
        authorize.call(port_range[:port_range], port_range[:protocol], actors)
      end
    end

    #
    # Remove any rules no longer in effect
    #
    actual_rules.each do |port_range, actors|
      unless actors.empty?
        revoke.call(port_range[:port_range], port_range[:protocol], actors)
      end
    end
  end

  def add_rule(rules, port_ranges, actors)
    unless actors.empty?
      port_ranges.each do |port_range|
        rules[port_range] ||= Set.new
        rules[port_range] += actors
      end
    end
  end

  # When protocol is unspecified (anything besides tcp, udp or icmp) then
  # you cannot specify ports.  When specifying tcp, udp, or icmp AWS wants
  # port_range 0..0.  -1..-1 will cause error
  def get_port_ranges(port_spec)
    case port_spec
    when Integer
      port_spec = 0 if port_spec == -1
      [{ port_range: port_spec..port_spec, protocol: :tcp }]
    when Range
      port_spec = 0..0 if port_spec == (-1..-1)
      [{ port_range: port_spec, protocol: :tcp }]
    when Array
      port_spec.map { |p| get_port_ranges(p) }.flatten
    when String, Symbol
      protocol = port_spec.to_s.downcase.to_sym
      if protocol.to_s =~ /(any|all|-1)/i
        [{ port_range: -1..-1, protocol: :"-1" }]
      else
        [{ port_range: 0..0, protocol: protocol }]
      end
    when Hash
      port_range = port_spec[:port_range] || port_spec[:ports] || port_spec[:port] || 0
      port_range = port_range..port_range if port_range.is_a?(Integer)
      if port_spec[:protocol]
        protocol = port_spec[:protocol].to_s.downcase.to_sym
        if protocol.to_s =~ /(any|all|-1)/i
          [{ port_range: -1..-1, protocol: :"-1" }]
        else
          [{ port_range: port_range, protocol: protocol }]
        end
      else
        get_port_ranges(port_range)
      end
      # The to_s.to_sym dance is because if you specify a protocol number, AWS symbolifies it,
      # but 26.to_sym doesn't work (so we have to to_s it first).
    when nil
      [{ port_range: -1..-1, protocol: :"-1" }]
    end
  end

  #
  # Turns an actor_spec into a uniform array, containing CIDRs, ::Aws::EC2::LoadBalancers and ::Aws::EC2::SecurityGroups.
  #
  def get_actors(vpc, actor_spec)
    result = case actor_spec

             # An array is always considered a list of actors.  Each one may follow any supported format.
             when Array
               actor_spec.map { |a| get_actors(vpc, a) }

             # Hashes come in several forms:
             when Hash
               # The default AWS Ruby SDK form with :user_id, :group_id and :group_name forms
               if actor_spec.keys.all? { |key| %i{user_id group_id group_name}.include?(key) }
                 if actor_spec.key?(:group_name)
                   vpc_object = Chef::Resource::AwsVpc.get_aws_object(vpc, resource: new_resource)
                   actor_spec[:group_id] ||= vpc_object.security_groups(filters: [name: "group-name", values: [actor_spec[:group_name]]]).first.id
                 end
                 actor_spec[:user_id] ||= new_resource.driver.account_id

                 { user_id: actor_spec[:user_id], group_id: actor_spec[:group_id] }

               # load_balancer: <load balancer name>
               elsif actor_spec.keys == [:load_balancer]
                 lb = Chef::Resource::AwsLoadBalancer.get_aws_object(actor_spec[:load_balancer], resource: new_resource)
                 get_actors(vpc, lb)

               # security_group: <security group name>
               elsif actor_spec.keys == [:security_group]
                 Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec[:security_group], resource: new_resource)

               else
                 raise "Unable to reference security group with spec #{actor_spec}"
               end

             # If a load balancer is specified, grab it and then get its automatic security group
             when /^elb-[a-fA-F0-9]+$/, Aws::ElasticLoadBalancing::Types::LoadBalancerDescription, Chef::Resource::AwsLoadBalancer
               lb = actor_spec
               if lb.class != Aws::ElasticLoadBalancing::Types::LoadBalancerDescription
                 lb = Chef::Resource::AwsLoadBalancer.get_aws_object(actor_spec, resource: new_resource)
               end
               # get secgroup via vpc_id
               vpc_object = Chef::Resource::AwsVpc.get_aws_object(vpc, resource: new_resource)
               results = vpc_object.security_groups.to_a.select { |s| s.group_name == lb.source_security_group.group_name }
               if results.size == 1
                 get_actors(vpc, results.first.id)
               else
                 raise ::Chef::Provisioning::AWSDriver::Exceptions::MultipleSecurityGroupError.new(lb.source_security_group.group_name, results)
               end

             # If a security group is specified, grab it
             when /^sg-[a-fA-F0-9]+$/, ::Aws::EC2::SecurityGroup, Chef::Resource::AwsSecurityGroup
               Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec, resource: new_resource)

             # If an IP addresses / CIDR are passed, return it verbatim; otherwise, assume it's the
             # name of a security group.
             when String
               begin
                 IPAddr.new(actor_spec)
                 # Add /32 to the end of raw IP addresses
                 actor_spec =~ /\// ? actor_spec : "#{actor_spec}/32"
               rescue IPAddr::InvalidAddressError
                 Chef::Resource::AwsSecurityGroup.get_aws_object(actor_spec, resource: new_resource)
               end

             else
               raise "Unexpected actor #{actor_spec} / #{actor_spec.class} in rules list"
              end

    result = { user_id: result.owner_id, group_id: result.id } if result.is_a?(::Aws::EC2::SecurityGroup)

    [result].flatten
  end
end


text:
require 'test_helper'

describe 'DirectPay24Sale JSON Schema' do
  let(:schema_path){ schema_path_for('direct_pay24_sale') }
  subject{ fixture('direct_pay24_sale') }
  let(:root_key){ subject.keys.first }

  root_wont_allow_additional_properties
  spec_attribute 'transaction_type', value: 'direct_pay24_sale'
  spec_attribute 'transaction_id'
  spec_attribute 'usage'
  spec_attribute 'remote_ip', required: true
  spec_attribute 'amount'
  spec_attribute 'currency'

  spec_attribute 'wire_reference_id'
  spec_attribute 'bank_account_holder', required: true
  spec_attribute 'bank_account_number', required: true
  spec_attribute 'bank_number'        , required: true

  spec_attribute 'customer_email', required: true
  spec_attribute 'customer_phone'
  spec_attribute 'billing_address', required: true
  spec_attribute 'shipping_address', spec: 'billing_address'
  spec_attribute 'risk_params'
  spec_attribute 'meta'

  spec_attribute 'notification_url',   spec: 'url'
  spec_attribute 'return_success_url', spec: 'url'
  spec_attribute 'return_failure_url', spec: 'url'
end

redpajama_set_name: RedPajamaGithub


text:
    Url

    <input ref="input" name="data[url]" type="text" class="form-control" lang="en" spellcheck="true" value="" id="url-url" aria-labelledby="l-url-url " aria-required="true"></input>


text:
package com.github.wreulicke.simple.user;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Entity
@Data
@Table(name = "users")
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column
  Long id;

  @Column
  private String username;

  @Column
  private String password;

}


text:
claz
=======

### Another OOP implementation for javascript

#### claz.claz:

```javascript
var Person = claz.claz(
    function init(name, age){
        /** one would normally validate {@link name} and {@link age} here ... */
        this._name = name;
        this._age = age;
        this._summary = this._createSummary(name, age);
    },
    {
        _alias: 'that guy',
        _createSummary: function(name, age){
            /** one would normally validate {@link name} and {@link age} here ... */
            return name + ' ('+ age +')'
        },
        getSummary: function() {
            return this._summary
        },
        getName: function() {
            return this._name
        },
        getAge: function() {
            return this._age
        },
        getAlias: function() {
            return this._alias
        }
    }
);

var albert = Person("Albert", 30);

/** {@link albert} object gets all the public methods */
// typeof albert.getSummary === "function"
// typeof albert.getName === "function"
// typeof albert.getAge === "function"
// typeof albert.getAlias === "function"

/** all the private members are not visible */
// albert._summary == null
// albert._createSummary == null
// albert._alias == null

/** all the public methods are callable */
// albert.getName() === "Albert"
// albert.getAge() === 30
// albert.getSummary() === "Albert (30)"
// albert.getAlias() === "that guy"
```

#### claz.WizClazBuilder:

```javascript

var ValueGetter = claz.claz(
        function(v){
            this.v = v
        },
        {
            v: 0,
            getValue: function(){
                return this.v
            }
        }
    ),
    Incrementing = {
        getValue: function(){
            return this.super() + 1
        }
    },
    Doubling = claz.claz({
        getValue: function(){
            return this.super() * 2
        }
    }),
    Top = {
        init: function(v){
            switch (arguments.length) {
                case 0:
                    return;
                case 1:
                    this.v = v;
                    return;
            }
        },
    },
    IncrementingDoublingValueGetter = claz.WizClazBuilder(Top).wiz(ValueGetter).wiz(Incrementing).wiz(Doubling).build(),
    vGetter1 = IncrementingDoublingValueGetter();

vGetter1.getValue(); // 2 = (1) * 2 = ((0) + 1) * 2

var vGetter2 = IncrementingDoublingValueGetter(2);
vGetter2.getValue(); // 6 = (3) * 2 = ((2) + 1) * 2
```

#### claz.wiz:

```javascript

var ValueGetter = claz.claz(
        function(v){
            this.v = v
        },
        {
            v: 0,
            getValue: function(){
                return this.v
            }
        }
    ),
    Incrementing = {
        getValue: function(){
            return this.super() + 1
        }
    },
    Doubling = claz.claz({
        getValue: function(){
            return this.super() * 2
        }
    }),
    IncrementingDoublingValueGetter = claz.wiz(
        {
            init: function(v){
                switch (arguments.length) {
                    case 0:
                        return;
                    case 1:
                        this.v = v;
                        return;
                }
            },
        },
        ValueGetter, Incrementing, Doubling
    ),
    vGetter1 = IncrementingDoublingValueGetter();

vGetter1.getValue(); // 2 = (1) * 2 = ((0) + 1) * 2

var vGetter2 = IncrementingDoublingValueGetter(2);
vGetter2.getValue(); // 6 = (3) * 2 = ((2) + 1) * 2
```


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>goog.editor.plugins.LinkDialogPlugin Tests</title>

<link rel="stylesheet" href="../../css/dialog.css"/>
<link rel="stylesheet" href="../../css/editor/dialog.css"/>
<link rel="stylesheet" href="../../css/editor/linkdialog.css"/>


text:
package org.cerebryo.profile;

/**
 * Contains the client IDs and scopes for allowed clients consuming the helloworld API.
 */
public class Constants {
  public static final String WEB_CLIENT_ID = "262342788785-bieclaai8dq9jeehgcddjglq9dti9uvf.apps.googleusercontent.com";
  public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID";
  public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
  public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;

  public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";

  public static final String API_EXPLORER_CLIENT_ID = com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID;
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class Category</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

 Category

Description

					Description |
															Methods (details)

											Constants

Categor Object definition

author: Valentin Bora <contact@valentinbora.com>

version: 1.0

			Located in /Iterators/categoryObject.php (line 14)

ArrayObject
   |
   --Category

Method Summary

			Description |
															Constants

									Methods (details)

											void
										getChildren
										()

											void
										getProperty
											( $property)

											void
										__get
											( $name)

											void
										__set
											( $name,  $val)

Methods

			Description |
													Methods (details)

		getChildren (line 24)

access: public

		void

			getChildren

				()

		getProperty (line 32)

access: public

		void

			getProperty

					( $property)

				$property

		__get (line 20)

access: public

		void

			__get

					( $name)

				$name

		__set (line 16)

access: public

		void

			__set

					( $name,  $val)

				$name

				$val

Inherited Methods

Inherited From ArrayObject (Internal Class)

							constructor __construct ( $array )

							append ( $value )

							asort (  )

							count (  )

							exchangeArray ( $array )

							getArrayCopy (  )

							getFlags (  )

							getIterator (  )

							getIteratorClass (  )

							ksort (  )

							natcasesort (  )

							natsort (  )

							offsetExists ( $index )

							offsetGet ( $index )

							offsetSet ( $index, $newval )

							offsetUnset ( $index )

							setFlags ( $flags )

							setIteratorClass ( $iteratorClass )

							uasort ( $cmp_function )

							uksort ( $cmp_function )

Class Constants

			Description |
										Constants (details)

										|
									Methods (details)

Inherited Constants

Inherited from ArrayObject (Internal Class)

								ARRAY_AS_PROPS = 2

								STD_PROP_LIST = 1

		Documentation generated on Mon, 13 Apr 2009 19:03:30 +0300 by phpDocumentor 1.4.2


text:
import os
from bdbcontrib.verify_notebook import run_and_verify_notebook
from util import session
from bdbcontrib.population import OPTFILE

INDEX_DIR=os.path.join(os.path.dirname(os.path.dirname(__file__)))

# TODO: I want to check that all the links in markup cells are non-broken.
# The standard cell check only gets called on pyout cells. I should fix that.
# But that can wait for another commit.

def test_index():
  os.chdir(INDEX_DIR)
  with session(INDEX_DIR):
    run_and_verify_notebook(os.path.join(INDEX_DIR, "Index"))
    optfile = os.path.join(INDEX_DIR, OPTFILE)
    assert os.path.exists(optfile)
    if 'DEBUG_TESTS' not in os.environ:
      with open(optfile, 'r') as opt:
        assert " <>\n" == opt.read()


text:
/**
 * Extends interfaces in Vue.js
 */

import Vue, { ComponentOptions } from "vue";
import { Store } from "./index";

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {
    store?: Store<any>;
  }
}

declare module "vue/types/vue" {
  interface Vue {
    $store: Store<any>;
  }
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import './strings.m.js';
import '//resources/cr_elements/cr_button/cr_button.js';
import '//resources/cr_elements/cr_checkbox/cr_checkbox.js';
import '//resources/cr_elements/cr_dialog/cr_dialog.js';
import '//resources/cr_elements/cr_input/cr_input.js';
import '//resources/cr_elements/cr_radio_button/cr_radio_button.js';
import '//resources/cr_elements/cr_radio_group/cr_radio_group.js';
import '//resources/cr_elements/cr_shared_style.css.js';
import '//resources/cr_elements/cr_shared_vars.css.js';

import {CrDialogElement} from '//resources/cr_elements/cr_dialog/cr_dialog.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {getTemplate} from './cast_feedback_ui.html.js';

enum FeedbackType {
  BUG = 'Bug',
  FEATURE_REQUEST = 'FeatureRequest',
  MIRRORING_QUALITY = 'MirroringQuality',
  DISCOVERY = 'Discovery',
  OTHER = 'Other',
}

/**
 * Keep in sync with MediaRouterCastFeedbackEvent in enums.xml.
 */
export enum FeedbackEvent {
  OPENED = 0,
  SENDING = 1,
  RESENDING = 2,
  SUCCEEDED = 3,
  FAILED = 4,
  MAX_VALUE = 4,
}

/**
 * See
 * https://docs.google.com/document/d/1c20VYdwpUPyBRQeAS0CMr6ahwWnb0s26gByomOwqDjk
 */
export interface FeedbackUiBrowserProxy {
  /**
   * Records an event using Chrome Metrics.
   */
  recordEvent(event: FeedbackEvent): void;

  /**
   * Proxy for chrome.feedbackPrivate.sendFeedback().
   */
  sendFeedback(info: chrome.feedbackPrivate.FeedbackInfo):
      Promise<chrome.feedbackPrivate.Status>;
}

export class FeedbackUiBrowserProxyImpl implements FeedbackUiBrowserProxy {
  recordEvent(event: FeedbackEvent) {
    chrome.send(
        'metricsHandler:recordInHistogram',
        ['MediaRouter.Cast.Feedback.Event', event, FeedbackEvent.MAX_VALUE]);
  }

  sendFeedback(info: chrome.feedbackPrivate.FeedbackInfo) {
    return new Promise<chrome.feedbackPrivate.Status>(
        resolve => chrome.feedbackPrivate.sendFeedback(
            info, /*loadSystemInfo=*/ undefined, /*formOpenTime=*/ undefined,
            resolve));
  }

  static getInstance(): FeedbackUiBrowserProxy {
    return instance || (instance = new FeedbackUiBrowserProxyImpl());
  }

  static setInstance(obj: FeedbackUiBrowserProxy) {
    instance = obj;
  }
}

let instance: FeedbackUiBrowserProxy|null = null;

// Define static map of local DOM elements that have IDs.
// https://polymer-library.polymer-project.org/3.0/docs/devguide/dom-template#node-finding
export interface FeedbackUiElement {
  $: {
    logsDialog: CrDialogElement,
    sendDialog: CrDialogElement,
  };
}

export class FeedbackUiElement extends PolymerElement {
  static get is() {
    return 'feedback-ui';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      allowContactByEmail_: {
        type: Boolean,
        value: false,
      },

      attachLogs_: {
        type: Boolean,
        value: true,
      },

      audioQuality_: String,
      comments_: String,

      /**
       * Possible values of |FeedbackType| for use in HTML.
       */
      feedbackTypeEnum_: {
        type: Object,
        value: FeedbackType,
      },

      /**
       * Controls which set of UI elements is displayed to the user.
       */
      feedbackType_: {
        type: String,
        value: FeedbackType.BUG,
      },

      hasNetworkSoftware_: String,
      networkDescription_: String,

      logData_: {
        type: String,
        value() {
          return loadTimeData.getString('logData');
        },
      },

      categoryTag_: {
        type: String,
        value() {
          return loadTimeData.getString('categoryTag');
        },
      },

      projectedContentUrl_: String,
      sendDialogText_: String,
      sendDialogIsInteractive_: Boolean,

      /**
       * Set by onFeedbackChanged_() to control whether the "submit" button is
       * active.
       */
      sufficientFeedback_: {
        type: Boolean,
        computed:
            'computeSufficientFeedback_(feedbackType_, videoSmoothness_, ' +
            'videoQuality_, audioQuality_, comments_, visibleInSetup_)',
      },

      userEmail_: String,
      videoQuality_: String,
      videoSmoothness_: String,
      visibleInSetup_: String,
    };
  }

  private allowContactByEmail_: boolean;
  private attachLogs_: boolean;
  private audioQuality_: string;
  private comments_: string;
  private feedbackType_: FeedbackType;
  private hasNetworkSoftware_: string;
  private networkDescription_: string;
  private logData_: string;
  private categoryTag_: string;
  private projectedContentUrl_: string;
  private sendDialogText_: string;
  private sendDialogIsInteractive_: boolean;
  private sufficientFeedback_: boolean;
  private userEmail_: string;
  private videoQuality_: string;
  private videoSmoothness_: string;
  private visibleInSetup_: string;

  private browserProxy_: FeedbackUiBrowserProxy =
      FeedbackUiBrowserProxyImpl.getInstance();

  // Public/mutable for testing.
  resendDelayMs: number = 10000;
  maxResendAttempts: number = 4;
  feedbackSent: boolean = false;

  constructor() {
    super();

    chrome.feedbackPrivate.getUserEmail(email => {
      this.userEmail_ = email;
    });

    this.browserProxy_.recordEvent(FeedbackEvent.OPENED);
  }

  override ready() {
    super.ready();
    this.shadowRoot!.querySelector('#send-logs a')!.addEventListener(
        'click', event => {
          event.preventDefault();
          this.$.logsDialog.showModal();
        });
  }

  private computeSufficientFeedback_() {
    switch (this.feedbackType_) {
      case FeedbackType.MIRRORING_QUALITY:
        return Boolean(
            this.videoSmoothness_ || this.videoQuality_ || this.audioQuality_ ||
            this.comments_);
      case FeedbackType.DISCOVERY:
        return Boolean(this.visibleInSetup_ || this.comments_);
      default:
        return Boolean(this.comments_);
    }
  }

  private showDefaultSection_(): boolean {
    switch (this.feedbackType_) {
      case FeedbackType.MIRRORING_QUALITY:
      case FeedbackType.DISCOVERY:
        return false;
      default:
        return true;
    }
  }

  private showMirroringQualitySection_(): boolean {
    return this.feedbackType_ === FeedbackType.MIRRORING_QUALITY;
  }

  private showDiscoverySection_(): boolean {
    return this.feedbackType_ === FeedbackType.DISCOVERY;
  }

  private onSubmit_() {
    const parts = [`Type: ${this.feedbackType_}`, ''];

    function append(label: string, value: string) {
      if (value) {
        parts.push(`${label}: ${value}`);
      }
    }

    switch (this.feedbackType_) {
      case FeedbackType.MIRRORING_QUALITY:
        append('Video Smoothness', this.videoSmoothness_);
        append('Video Quality', this.videoQuality_);
        append('Audio', this.audioQuality_);
        append('Projected Content/URL', this.projectedContentUrl_);
        append('Comments', this.comments_);
        break;
      case FeedbackType.DISCOVERY:
        append('Chromecast Visible in Setup', this.visibleInSetup_);
        append(
            'Using VPN/proxy/firewall/NAS Software', this.hasNetworkSoftware_);
        append('Network Description', this.networkDescription_);
        append('Comments', this.comments_);
        break;
      default:
        parts.push(this.comments_);
        break;
    }

    const feedback: chrome.feedbackPrivate.FeedbackInfo = {
      productId: 85561,
      description: parts.join('\n'),
      email: this.allowContactByEmail_ ? this.userEmail_ : '',
      flow: chrome.feedbackPrivate.FeedbackFlow.REGULAR,
      categoryTag: this.categoryTag_,
      systemInformation: this.getProductSpecificData_(),
    };
    if (this.attachLogs_) {
      feedback.attachedFile = {
        name: 'log.json',
        data: new Blob([this.logData_]),
      };
    }

    this.updateSendDialog_(FeedbackEvent.SENDING, 'sending', false);
    this.$.sendDialog.showModal();
    this.trySendFeedback_(feedback, 0, 0);
  }

  /**
   * Schedules an attempt to send feedback after |delayMs| milliseconds.
   */
  private trySendFeedback_(
      feedback: chrome.feedbackPrivate.FeedbackInfo, failureCount: number,
      delayMs: number) {
    setTimeout(() => {
      const sendStartTime = Date.now();
      this.browserProxy_.sendFeedback(feedback).then(status => {
        if (status === chrome.feedbackPrivate.Status.SUCCESS) {
          this.feedbackSent = true;
          this.updateSendDialog_(FeedbackEvent.SUCCEEDED, 'sendSuccess', true);
        } else if (failureCount < this.maxResendAttempts) {
          this.updateSendDialog_(FeedbackEvent.RESENDING, 'resending', false);
          const sendDuration = Date.now() - sendStartTime;
          this.trySendFeedback_(
              feedback, failureCount + 1,
              Math.max(0, this.resendDelayMs - sendDuration));
        } else {
          this.updateSendDialog_(FeedbackEvent.FAILED, 'sendFail', true);
        }
      });
    }, delayMs);
  }

  /**
   * Updates the status of the "send" dialog and records the event.
   */
  private updateSendDialog_(
      event: FeedbackEvent, stringKey: string, isInteractive: boolean) {
    this.browserProxy_.recordEvent(event);
    this.sendDialogText_ = loadTimeData.getString(stringKey);
    this.sendDialogIsInteractive_ = isInteractive;
  }

  private onSendDialogOk_() {
    if (this.feedbackSent) {
      chrome.send('close');
    } else {
      this.$.sendDialog.close();
    }
  }

  private onCancel_() {
    if (!this.comments_ ||
        confirm(loadTimeData.getString('discardConfirmation'))) {
      chrome.send('close');
    }
  }

  private onLogsDialogOk_() {
    this.$.logsDialog.close();
  }

  private getProductSpecificData_(): Array<{key: string, value: string}> {
    const data = [
      {
        key: 'global_media_controls_cast_start_stop',
        value: String(
            !!loadTimeData.getBoolean('globalMediaControlsCastStartStop')),
      },
      {
        key: 'feedbackUserCtlConsent',
        value: String(!!this.allowContactByEmail_),
      },
    ];
    return data;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'feedback-ui': FeedbackUiElement;
  }
}

customElements.define(FeedbackUiElement.is, FeedbackUiElement);


text:
package uk.gov.hmrc.nisp.errorHandler

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.mockito.Mockito.when
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Application
import play.api.i18n.{Lang, MessagesApi, MessagesImpl}
import play.api.inject.bind
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.Request
import play.api.test.{FakeRequest, Injecting}
import play.twirl.api.Html
import uk.gov.hmrc.nisp.config.ApplicationConfig
import uk.gov.hmrc.nisp.utils.UnitSpec
import java.util.Locale

class ErrorHandlerSpec extends UnitSpec with GuiceOneAppPerSuite with Injecting with BeforeAndAfterEach {

  implicit val request: Request[_] = FakeRequest()

  val mockApplicationConfig = mock[ApplicationConfig]

  override def fakeApplication(): Application = GuiceApplicationBuilder()
    .overrides(
      bind[ApplicationConfig].toInstance(mockApplicationConfig)
    )
    .build()

  override def beforeEach(): Unit = {
    super.beforeEach()
    when(mockApplicationConfig.urBannerUrl).thenReturn("/urResearch")
    when(mockApplicationConfig.reportAProblemNonJSUrl).thenReturn("/reportAProblem")
    when(mockApplicationConfig.contactFormServiceIdentifier).thenReturn("/id")
  }

  val errorHandler                    = inject[ErrorHandler]
  implicit val messages: MessagesImpl = MessagesImpl(Lang(Locale.getDefault), inject[MessagesApi])

  "standardErrorTemplate" must {
    "return the global error view" in {
      val title   = "testTitle"
      val heading = "testHeading"
      val message = "testMessage"

      val standardErrorTemplate: Html = errorHandler.standardErrorTemplate(title, heading, message)
      val doc: Document               = Jsoup.parse(standardErrorTemplate.toString())

      val docTitle   = doc.select("title").text()
      val docHeading = doc.select("h1").text()
      val docMessage = doc.select("p").text()

      docTitle   shouldBe title
      docHeading shouldBe heading
      docMessage shouldBe message
    }
  }

  "internalServerErrorTemplate" must {
    "return the service error 500 view" in {
      val serverErrorTemplate: Html = errorHandler.internalServerErrorTemplate
      val doc: Document             = Jsoup.parse(serverErrorTemplate.toString())

      val docTitle = doc.select("title").text()
      docTitle should include(messages("global.error.InternalServerError500.title"))
    }
  }

  "notFoundTemplate" must {
    "return the page not found view" in {
      val notFoundTemplate: Html = errorHandler.notFoundTemplate
      val doc: Document          = Jsoup.parse(notFoundTemplate.toString())

      val docTitle = doc.select("title").text()
      docTitle should include(messages("global.page.not.found.error.title"))
    }
  }
}


text:
Change Password

		<form action="index.php?page=lChangePassword1" method="post" onsubmit="return check()" name="form">

					Old Password :

					<input type="password" name="old" class="form-control" required>

					New Password :

					<input type="password" name="new" class="form-control" required>

					Confirm New Password :

					<input type="password" name="confirm" class="form-control" required>

					Back
					<input type="submit" class="btn btn-success" value="Submit">
					<input type="reset" class="btn btn-danger" value="Reset">

		</form>


text:
module Locomotive
  module Extensions
    module Page
      module Templatized

        extend ActiveSupport::Concern

        included do

          ## fields ##
          field :templatized,             :type => Boolean, :default => false
          field :templatized_from_parent, :type => Boolean, :default => false
          field :target_klass_name

          ## validations ##
          validates_presence_of :target_klass_name, :if => :templatized?
          validate              :ensure_target_klass_name_security

          ## callbacks ##
          before_validation :get_templatized_from_parent
          before_validation :set_slug_if_templatized
          before_validation :ensure_target_klass_name_security
          after_save        :propagate_templatized

          ## scopes ##
          scope :templatized, :where => { :templatized => true }

          ## virtual attributes ##
          attr_accessor :content_entry
        end

        # Returns the class specified by the target_klass_name property
        #
        # @example
        #
        #   page.target_klass_name = 'Locomotive::Entry12345'
        #   page.target_klass = Locomotive::Entry12345
        #
        # @return [ Class ] The target class
        #
        def target_klass
          target_klass_name.constantize
        end

        # Returns the slug related to the target_klass.
        # In other words, it returns the slug of the target content type.
        #
        # @return [ String ] The slug of the target class / content type. Nil if no target klass.
        #
        def target_klass_slug
          if self.target_klass_name =~ /^Locomotive::Entry([a-z0-9]+)$/
            @content_type ||= self.site.content_types.find($1)
            @content_type.slug
          else
            nil
          end
        end

        # Gives the name which can be used in a liquid template in order
        # to reference an entry. It uses the slug property if the target klass
        # is a Locomotive content type or the class name itself for the other classes.
        #
        # @example
        #
        #   page.target_klass_name = 'Locomotive::Entry12345' # related to the content type Articles
        #   page.target_entry_name = 'article'
        #
        #   page.target_klass_name = 'OurProduct'
        #   page.target_entry_name = 'our_product'
        #
        # @return [ String ] The name in lowercase and underscored
        #
        def target_entry_name
          if self.target_klass_name =~ /^Locomotive::Entry([a-z0-9]+)$/
            @content_type ||= self.site.content_types.find($1)
            @content_type.slug.singularize
          else
            self.target_klass_name.underscore
          end
        end

        # Finds the entry both specified by the target klass and identified by the permalink
        #
        # @param [ String ] permalink The permalink of the entry
        #
        # @return [ Object ] The document
        #
        def fetch_target_entry(permalink)
          target_klass.find_by_permalink(permalink)
        end

        protected

        def get_templatized_from_parent
          return if self.parent.nil?

          if self.parent.templatized?
            self.templatized        = self.templatized_from_parent = true
            self.target_klass_name  = self.parent.target_klass_name
          elsif !self.templatized?
            self.templatized        = self.templatized_from_parent = false
            self.target_klass_name  = nil
          end
        end

        def set_slug_if_templatized
          self.slug = 'content_type_template' if self.templatized? && !self.templatized_from_parent?
        end

        # Makes sure the target_klass is owned by the site OR
        # if it belongs to the models allowed by the application
        # thanks to the models_for_templatization option.
        #
        def ensure_target_klass_name_security
          return if !self.templatized? || self.target_klass_name.blank?

          if self.target_klass_name =~ /^Locomotive::Entry([a-z0-9]+)$/
            content_type = Locomotive::ContentType.find($1)

            if content_type.site_id != self.site_id
              self.errors.add :target_klass_name, :security
            end
          elsif !Locomotive.config.models_for_templatization.include?(self.target_klass_name)
            self.errors.add :target_klass_name, :security
          end
        end

        # Sets the templatized, templatized_from_parent properties of
        # the children of the current page ONLY IF the templatized
        # attribute got changed.
        #
        def propagate_templatized
          return unless self.templatized_changed?

          selector = { 'parent_ids' => { '$in' => [self._id] } }
          operations  = {
            '$set' => {
              'templatized'             => self.templatized,
              'templatized_from_parent' => self.templatized,
              'target_klass_name'       => self.target_klass_name
            }
          }

          self.collection.update selector, operations, :multi => true
        end

      end
    end
  end
end


text:
package command

import (
	"fmt"
	"github.com/zupzup/calories/datasource"
	"github.com/zupzup/calories/renderer"
	"strconv"
)

// WeightCommand is the command to save and show the configuration
type WeightCommand struct {
	DataSource datasource.DataSource
	Renderer   renderer.Renderer
	Weight     string
	Mode       int
}

// Execute shows the weight timeline, if no parameters are given,
// otherwise it sets the given weight
func (c *WeightCommand) Execute() (string, error) {
	config, err := c.DataSource.FetchConfig()
	if err != nil {
		return "", err
	}
	if c.Mode > 0 {
		weight, parseErr := strconv.ParseFloat(c.Weight, 64)
		if parseErr != nil {
			return "", fmt.Errorf("wrong format for weight: %s must be a decimal number", c.Weight)
		}
		err = c.DataSource.AddWeight(weight)
		if err != nil {
			return "", fmt.Errorf("could not save weight: %.0f", weight)
		}
		return c.Renderer.AddWeight(weight, config)
	}

	weights, err := c.DataSource.FetchWeights()
	if err != nil {
		return "", err
	}
	return c.Renderer.WeightHistory(weights, config)
}


text:
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define([
			'jquery',
			'./ui-controlbar',
			'./ui-list',
			'./ui-stats'
		], factory);
    } else {
        factory(
			window.jQuery,
			window.RakkaUIControlBar,
			window.RakkaUIList,
			window.RakkaUIStats
		);
    }
}(function($, RakkaUIControlBar, RakkaUIList, RakkaUIStats) {

	function RakkaUI(options) {
		var subopts;
		var theme;

		// Setup events
		this.bus = options.bus;

		// Setup main options
		if( options && -1 !== ['none', 'light', 'dark'].indexOf(options.theme) ) {
			this.theme = options.theme;
		} else {
			this.theme = options.theme = 'none';
		}

		// Setup container
		this.$container = options.container;
		this.$container.addClass('rakka-container')
			.addClass('rakka-no-auto-hide');
		this.onThemeChange(this.theme);

		// Setup events
		this.bus.proxy(this);
		this.on('rakka.ui.theme.change', this.onThemeChange.bind(this));

		// Setup components
		function makeOpts(opts) {
			return $.extend({
				bus: options.bus,
				container: options.container,
				theme: options.theme
			}, typeof opts === 'object' ? opts : {});
		}

		if( options.controlBar ) {
			this.controlBar = new RakkaUIControlBar(makeOpts(options.controlBar));
		}

		if( options.list ) {
			this.list = new RakkaUIList(makeOpts(options.list));
		}

		if( options.stats ) {
			this.stats = new RakkaUIStats(makeOpts(options.stats));
		}

		this.listenForUserActivity();
	};

	RakkaUI.prototype.listenForUserActivity = function() {
		this._userActivity = true;
		var lastMoveX
		var lastMoveY;
		var mouseInProgress;
		var onActivity = function () {
			this._userActivity = true;
		}.bind(this);
		function onMouseMove(event) {
			var e = event.originalEvent;
			if( e.screenX != lastMoveX || e.screenY != lastMoveY ) {
				lastMoveX = e.screenX;
				lastMoveY = e.screenY;
				onActivity();
			}
		}
		function onMouseDown() {
			onActivity();
			clearInterval(mouseInProgress);
			mouseInProgress = setInterval(onActivity, 250);
		}
		function onMouseUp() {
			onActivity();
			clearInterval(mouseInProgress);
		}
		// @todo dispose?
		var w = $(window);
		w.on('mousedown', onMouseDown);
		w.on('mousemove', onMouseMove);
		w.on('mouseup', onMouseUp);
		w.on('keydown', onActivity);
		w.on('keyup', onActivity);
		this._activityInterval = setInterval(this.listenLoop.bind(this), 100);
	};

	RakkaUI.prototype.listenLoop = function() {
		if( !this._userActivity ) {
			return;
		}

		this._userActivity = false;
		this.userActive(true);

		clearTimeout(this._inactivityTimeout);
		this._inactivityTimeout = setTimeout(this.listenTimeout.bind(this), 5000);
	};

	RakkaUI.prototype.listenTimeout = function() {
		if( !this._userActivity ) {
			this.userActive(false);
		}
	};

	RakkaUI.prototype.onThemeChange = function(theme) {
		if( this.theme ) {
			this.$container.removeClass('rakka-theme-' + this.theme);
		}
		this.theme = theme;
		this.$container.addClass('rakka-theme-' + this.theme);
	};

	RakkaUI.prototype.userActive = function(state) {
		if( state ) {
			this.$container.addClass('rakka-user-active').removeClass('rakka-user-inactive');
		} else {
			this.$container.addClass('rakka-user-inactive').removeClass('rakka-user-active');
		}

		// Propogate
		this.bus.trigger('rakka.ui.userActive', state);
	};

	// Exports
	window.RakkaUI = RakkaUI;
	return RakkaUI;
}));


text:
'use strict'

const Element = require('./Element')

function Distribution (alpha, featureSet, sample) {
  this.alpha = alpha
  this.featureSet = featureSet
  this.sample = sample
}

// Returns the distribution as a string that can be stored for later usage
Distribution.prototype.toString = function () {

}

Distribution.prototype.weight = function (x) {
  let product = 1
  const that = this

  this.alpha.forEach(function (alphaj, j) {
    product *= Math.pow(alphaj, that.featureSet.getFeatures()[j].apply(x))
  })
  return product
}

Distribution.prototype.calculateAPriori = function (x) {
  if (!this.aPriorisBeforeNormalisation[x.toString()]) {
    this.aPriorisBeforeNormalisation[x.toString()] = this.weight(x)
  }
  return this.aPriorisBeforeNormalisation[x.toString()]// / this.aPrioriNormalisationConstant;
}

// Memoize a priori probabilities of sample elements
Distribution.prototype.prepareWeights = function () {
  this.aPriorisBeforeNormalisation = {}
  this.aPrioriNormalisationConstant = 0
  let sum = 0
  const that = this
  this.sample.elements.forEach(function (x) {
    that.aPriorisBeforeNormalisation[x.toString()] = that.weight(x)
    sum += that.aPriorisBeforeNormalisation[x.toString()]
  })
  this.aPrioriNormalisationConstant = sum
}

Distribution.prototype.calculateAPosteriori = function (x) {
  if (!this.aPriorisBeforeNormalisation[x.toString()]) {
    this.aPriorisBeforeNormalisation[x.toString()] = this.weight(x)
  }
  if (!this.aPosterioriNormalisationConstants[x.b.toString()]) {
    this.aPosterioriNormalisationConstants[x.b.toString()] = this.aPosterioriNormalisation(x.b)
  }
  return this.aPriorisBeforeNormalisation[x] / this.aPosterioriNormalisationConstants[x.b.toString()]
}

Distribution.prototype.aPosterioriNormalisation = function (b) {
  let sum = 0

  const that = this
  this.sample.getClasses().forEach(function (a) {
    sum += that.weight(new Element(a, b))
  })

  return (sum)
}

// Memoize a posteriori probabilities of sample elements
Distribution.prototype.prepareAPosterioris = function () {
  this.aPosterioriNormalisationConstants = {}

  const contextSeen = {}
  const that = this
  this.sample.elements.forEach(function (sampleElement) {
    const context = sampleElement.b
    if (!contextSeen[context]) {
      contextSeen[context] = true
      that.aPosterioriNormalisationConstants[context] =
        that.aPosterioriNormalisation(context)
    }
  })
}

// Memoize all probabilities of sample elements
Distribution.prototype.prepare = function () {
  this.prepareWeights()
  // console.log("Weights prepared");
  this.prepareAPosterioris()
}

// Relative entropy between observered distribution and derived distribution
Distribution.prototype.KullbackLieblerDistance = function () {
  let sum = 0
  const that = this
  this.sample.elements.forEach(function (x) {
    sum += that.sample.observedProbability(x) * Math.log(that.sample.observedProbability(x) / that.calculateAPriori(x))
  })
  return sum
}

Distribution.prototype.logLikelihood = function () {
  let sum = 0
  const that = this
  this.sample.elements.forEach(function (x) {
    sum += that.sample.observedProbability(x) * Math.log(that.calculateAPriori(x))
  })
  return sum
}

Distribution.prototype.entropy = function () {
  let sum = 0
  const that = this
  this.sample.elements.forEach(function (x) {
    const p = that.calculateAPriori(x)
    sum += p * Math.log(p)
  })
  return sum
}

Distribution.prototype.checkSum = function () {
  let sum = 0
  const that = this
  this.sample.elements.forEach(function (x) {
    sum += that.calculateAPriori(x)
  })
  // console.log("Distribution.checkSum is " + sum);
  return sum
}

module.exports = Distribution


text:
class LoginController < ApplicationController
  layout 'simple'
end


text:
require([
    'jquery', 'crimeprediction/js/overlay/overlay', 'hammerjs',
    'jquery-hammerjs', 'materialize',
], function($, overlay) {
    $('.modal-trigger').leanModal();
    $('select').material_select();

    $('#train').on('click', trainModel);
    $('#predict').on('click', predict);

    function trainModel(e){
        e.preventDefault();
        var modal = $('#model-popup');
        overlay.indeterminate('This may take some time... Please Wait.');
        var crimeType = modal.find('select#crime_type').val();
        var grid_size = modal.find('select#grid_size').val();
        var period = modal.find('select#period').val();
        var seasonality = modal.find('.switch#seasonality input').prop('checked')
        console.log(seasonality);
        $.ajax({
            url: '/train',
            type: 'get',
            data: {
                grid_size: grid_size,
                period: period,
                crime_type: crimeType,
                seasonality: seasonality
            },
            success: function() {
                overlay.remove();
            },
        });
    }

    function predict(e){
        e.preventDefault();
        overlay.indeterminate('This may take some time... Please Wait.');
        $.ajax({
            url: '/predict',
            type: 'get',
            data: {},
            success: function() {
                overlay.remove();
            },
        });
    }
});