text:
package server

import (
	"bytes"
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/gorilla/csrf"

	"github.com/gobuffalo/packr"
	"github.com/gorilla/handlers"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
	"github.com/pkg/errors"

	"go4.org/wkfs"
	"golang.org/x/crypto/acme/autocert"
	"golang.org/x/oauth2"

	wkfscache "github.com/nsheridan/autocert-wkfs-cache"
	"github.com/nsheridan/cashier/lib"
	"github.com/nsheridan/cashier/server/auth"
	"github.com/nsheridan/cashier/server/auth/github"
	"github.com/nsheridan/cashier/server/auth/gitlab"
	"github.com/nsheridan/cashier/server/auth/google"
	"github.com/nsheridan/cashier/server/auth/microsoft"
	"github.com/nsheridan/cashier/server/config"
	"github.com/nsheridan/cashier/server/metrics"
	"github.com/nsheridan/cashier/server/signer"
	"github.com/nsheridan/cashier/server/store"
	"github.com/sid77/drop"
)

func loadCerts(certFile, keyFile string) (tls.Certificate, error) {
	key, err := wkfs.ReadFile(keyFile)
	if err != nil {
		return tls.Certificate{}, errors.Wrap(err, "error reading TLS private key")
	}
	cert, err := wkfs.ReadFile(certFile)
	if err != nil {
		return tls.Certificate{}, errors.Wrap(err, "error reading TLS certificate")
	}
	return tls.X509KeyPair(cert, key)
}

// Run the server.
func Run(conf *config.Config) {
	var err error

	laddr := fmt.Sprintf("%s:%d", conf.Server.Addr, conf.Server.Port)
	l, err := net.Listen("tcp", laddr)
	if err != nil {
		log.Fatal(errors.Wrapf(err, "unable to listen on %s:%d", conf.Server.Addr, conf.Server.Port))
	}

	tlsConfig := &tls.Config{}
	if conf.Server.UseTLS {
		if conf.Server.LetsEncryptServername != "" {
			m := autocert.Manager{
				Prompt:     autocert.AcceptTOS,
				HostPolicy: autocert.HostWhitelist(conf.Server.LetsEncryptServername),
			}
			if conf.Server.LetsEncryptCache != "" {
				m.Cache = wkfscache.Cache(conf.Server.LetsEncryptCache)
			}
			tlsConfig = m.TLSConfig()
		} else {
			if conf.Server.TLSCert == "" || conf.Server.TLSKey == "" {
				log.Fatal("TLS cert or key not specified in config")
			}
			tlsConfig.Certificates = make([]tls.Certificate, 1)
			tlsConfig.Certificates[0], err = loadCerts(conf.Server.TLSCert, conf.Server.TLSKey)
			if err != nil {
				log.Fatal(errors.Wrap(err, "unable to create TLS listener"))
			}
		}
		l = tls.NewListener(l, tlsConfig)
	}

	if conf.Server.User != "" {
		log.Print("Dropping privileges...")
		if err := drop.DropPrivileges(conf.Server.User); err != nil {
			log.Fatal(errors.Wrap(err, "unable to drop privileges"))
		}
	}

	// Unprivileged section
	metrics.Register()

	var authprovider auth.Provider
	switch conf.Auth.Provider {
	case "github":
		authprovider, err = github.New(conf.Auth)
	case "gitlab":
		authprovider, err = gitlab.New(conf.Auth)
	case "google":
		authprovider, err = google.New(conf.Auth)
	case "microsoft":
		authprovider, err = microsoft.New(conf.Auth)
	default:
		log.Fatalf("Unknown provider %s\n", conf.Auth.Provider)
	}
	if err != nil {
		log.Fatal(errors.Wrapf(err, "unable to use provider '%s'", conf.Auth.Provider))
	}

	keysigner, err := signer.New(conf.SSH)
	if err != nil {
		log.Fatal(err)
	}

	certstore, err := store.New(conf.Server.Database)
	if err != nil {
		log.Fatal(err)
	}

	ctx := &app{
		cookiestore:   sessions.NewCookieStore([]byte(conf.Server.CookieSecret)),
		requireReason: conf.Server.RequireReason,
		keysigner:     keysigner,
		certstore:     certstore,
		authprovider:  authprovider,
		config:        conf.Server,
		router:        mux.NewRouter(),
	}
	ctx.cookiestore.Options = &sessions.Options{
		MaxAge:   900,
		Path:     "/",
		Secure:   conf.Server.UseTLS,
		HttpOnly: true,
	}

	logfile := os.Stderr
	if conf.Server.HTTPLogFile != "" {
		logfile, err = os.OpenFile(conf.Server.HTTPLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0640)
		if err != nil {
			log.Printf("error opening log: %v. logging to stdout", err)
		}
	}

	ctx.routes()
	ctx.router.Use(mwVersion)
	ctx.router.Use(handlers.CompressHandler)
	ctx.router.Use(handlers.RecoveryHandler())
	r := handlers.LoggingHandler(logfile, ctx.router)
	s := &http.Server{
		Handler:      r,
		ReadTimeout:  20 * time.Second,
		WriteTimeout: 20 * time.Second,
		IdleTimeout:  120 * time.Second,
	}

	log.Printf("Starting server on %s", laddr)
	s.Serve(l)
}

// mwVersion is middleware to add a X-Cashier-Version header to the response.
func mwVersion(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Cashier-Version", lib.Version)
		next.ServeHTTP(w, r)
	})
}

func encodeString(s string) string {
	var buffer bytes.Buffer
	chunkSize := 70
	runes := []rune(base64.StdEncoding.EncodeToString([]byte(s)))

	for i := 0; i < len(runes); i += chunkSize {
		end := i + chunkSize
		if end > len(runes) {
			end = len(runes)
		}
		buffer.WriteString(string(runes[i:end]))
		buffer.WriteString("\n")
	}
	buffer.WriteString(".\n")
	return buffer.String()
}

// app contains local context - cookiestore, authsession etc.
type app struct {
	cookiestore   *sessions.CookieStore
	authprovider  auth.Provider
	certstore     store.CertStorer
	keysigner     *signer.KeySigner
	router        *mux.Router
	config        *config.Server
	requireReason bool
}

func (a *app) routes() {
	// login required
	csrfHandler := csrf.Protect([]byte(a.config.CSRFSecret), csrf.Secure(a.config.UseTLS))
	a.router.Methods("GET").Path("/").Handler(a.authed(http.HandlerFunc(a.index)))
	a.router.Methods("POST").Path("/admin/revoke").Handler(a.authed(csrfHandler(http.HandlerFunc(a.revoke))))
	a.router.Methods("GET").Path("/admin/certs").Handler(a.authed(csrfHandler(http.HandlerFunc(a.getAllCerts))))
	a.router.Methods("GET").Path("/admin/certs.json").Handler(a.authed(http.HandlerFunc(a.getCertsJSON)))

	// no login required
	a.router.Methods("GET").Path("/auth/login").HandlerFunc(a.auth)
	a.router.Methods("GET").Path("/auth/callback").HandlerFunc(a.auth)
	a.router.Methods("GET").Path("/revoked").HandlerFunc(a.revoked)
	a.router.Methods("POST").Path("/sign").HandlerFunc(a.sign)

	a.router.Methods("GET").Path("/healthcheck").HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "ok")
	})
	a.router.Methods("GET").Path("/metrics").Handler(promhttp.Handler())
	box := packr.NewBox("static")
	a.router.PathPrefix("/static/").Handler(http.StripPrefix("/static", http.FileServer(box)))
}

func (a *app) getAuthToken(r *http.Request) *oauth2.Token {
	token := &oauth2.Token{}
	marshalled := a.getSessionVariable(r, "token")
	json.Unmarshal([]byte(marshalled), token)
	return token
}

func (a *app) setAuthToken(w http.ResponseWriter, r *http.Request, token *oauth2.Token) {
	v, _ := json.Marshal(token)
	a.setSessionVariable(w, r, "token", string(v))
}

func (a *app) getSessionVariable(r *http.Request, key string) string {
	session, _ := a.cookiestore.Get(r, "session")
	v, ok := session.Values[key].(string)
	if !ok {
		v = ""
	}
	return v
}

func (a *app) setSessionVariable(w http.ResponseWriter, r *http.Request, key, value string) {
	session, _ := a.cookiestore.Get(r, "session")
	session.Values[key] = value
	session.Save(r, w)
}

func (a *app) authed(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t := a.getAuthToken(r)
		if !t.Valid() || !a.authprovider.Valid(t) {
			a.setSessionVariable(w, r, "origin_url", r.URL.EscapedPath())
			http.Redirect(w, r, "/auth/login", http.StatusSeeOther)
			return
		}
		next.ServeHTTP(w, r)
	})
}


text:
'use strict';

angular
  .module('irma')
  .factory('Result', Result);

Result.$inject = ['$http'];

function Result($http) {
  function ResultModel(resultData) {
    if (resultData) {
      this.setData(resultData);
    }
  }

  ResultModel.prototype = {
    setData: setData
  };

  return ResultModel;

  function setData(resultData) {
    angular.extend(this, resultData);
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace WhiteTie.TestReference
{
  /// <summary>
  /// Dummy class for generating test XML documentation.
  /// </summary>
  public class Class1
  {
  }
}


text:
require 'rubygems'
require 'json'
require 'time'

# parse event
event = JSON.parse(STDIN.read, :symbolize_names => true)
t = Time.now

# Verify if we're opened for business
if t.wday.between?(1, 5)
  if t.between?(Time.parse('9:00'), Time.parse('17:00'))
    event.merge!(:mutated => true, :office_hours => true)
  end
end

# output modified event
puts event.to_json


text:
package migrate

import (
	"github.com/gophercloud/gophercloud"
)

func actionURL(client *gophercloud.ServiceClient, id string) string {
	return client.ServiceURL("servers", id, "action")
}


text:
var path = require('path');

module.exports = {
  entry: {
    "angularjs" : "./build/angularjs/module.js",
    "react" : "./build/react/LineChart.js"
  },
  output: {
    path: __dirname  + "/build/build",
    filename: "LineChart-[name].js",
    chunkFilename: "[name].js",
    library: 'n3',
    libraryTarget: "umd"
  },
  target: 'web',
  resolveLoader: {
    modules: [__dirname + "/node_modules"]
  },
  resolve: {
    extensions: ['.js'],
  },
}


text:
"""Small ResNet for CIFAR."""

from __future__ import absolute_import
from __future__ import division

import functools

from absl import flags
import tensorflow.compat.v1 as tf

from ieg.models.networks import StrategyNetBase

FLAGS = flags.FLAGS

L2 = 1e-4

def resnet_layer(inputs,
                 training,
                 num_filters=16,
                 kernel_size=3,
                 strides=1,
                 activation='relu',
                 batch_normalization=True,
                 conv_first=True):
  """2D Convolution-Batch Normalization-Activation stack builder.

  Args:
    inputs (tensor): input tensor from input image or previous layer
    training: if in traning stage
    num_filters (int): Conv2D number of filters
    kernel_size (int): Conv2D square kernel dimensions
    strides (int): Conv2D square stride dimensions
    activation (string): activation name
    batch_normalization (bool): whether to include batch normalization
    conv_first (bool): conv-bn-activation (True) or bn-activation-conv (False)

  Returns:
    x (tensor): tensor as input to the next layer
  """
  regularizer = tf.keras.regularizers.L2(L2)
  conv = functools.partial(
      tf.layers.conv2d,
      filters=num_filters,
      kernel_size=kernel_size,
      strides=strides,
      padding='same',
      use_bias=False,
      kernel_initializer=tf.initializers.glorot_normal(),
      kernel_regularizer=regularizer)

  batchnormalization_layer = functools.partial(
      tf.layers.batch_normalization,
      momentum=0.9,
      epsilon=1e-5,
      fused=True,
      training=training)

  x = inputs
  if conv_first:
    x = conv(inputs=x)
    if batch_normalization:
      x = batchnormalization_layer(inputs=x)
    if activation is not None:
      x = tf.nn.relu(x)
  else:
    if batch_normalization:
      x = batchnormalization_layer(inputs=x)
    if activation is not None:
      x = tf.nn.relu(x)
    x = conv(x)

  return x

def resnet_model_fn(inputs,
                    training,
                    num_classes,
                    num_res_blocks,
                    weight_decay=1e-4,
                    num_filters_in=16):
  """Create model for ResNet-v1.

  Args:
    inputs: input tensor.
    training: bool for training or evaluation mode.
    num_classes: number of classes.
    num_res_blocks: number of residual blocks depending on depth.
    weight_decay: weight decay.
    num_filters_in: initial filter size.

  Returns:
    logits tensor.
  """
  global L2
  L2 = weight_decay

  x = resnet_layer(
      inputs=inputs,
      num_filters=num_filters_in,
      conv_first=True,
      training=training)

  # Instantiate the stack of residual units
  for stage in range(3):
    for res_block in range(num_res_blocks):
      with tf.variable_scope('stage%d_block%d' % (stage, res_block)):
        batch_normalization = True
        strides = 1
        if stage == 0:
          num_filters_out = num_filters_in * 4
          if res_block == 0:  # first layer and first stage
            activation = None
            batch_normalization = False
        else:
          num_filters_out = num_filters_in * 2
          if res_block == 0:  # first layer but not first stage
            strides = 2  # downsample

        # bottleneck residual unit
        y = resnet_layer(
            inputs=x,
            num_filters=num_filters_in,
            kernel_size=1,
            strides=strides,
            activation=activation,
            batch_normalization=batch_normalization,
            conv_first=False,
            training=training)
        y = resnet_layer(
            inputs=y,
            num_filters=num_filters_in,
            conv_first=False,
            training=training)
        y = resnet_layer(
            inputs=y,
            num_filters=num_filters_out,
            kernel_size=1,
            conv_first=False,
            training=training)
        if res_block == 0:
          # linear projection residual shortcut connection to match
          # changed dimsresnet_v2
          x = resnet_layer(
              inputs=x,
              num_filters=num_filters_out,
              kernel_size=1,
              strides=strides,
              activation=None,
              batch_normalization=False,
              training=training)
        x = tf.math.add(x, y)

    num_filters_in = num_filters_out

  batchnormalization_layer = functools.partial(
      tf.layers.batch_normalization,
      momentum=0.9,
      epsilon=1e-5,
      fused=True,
      training=training)
  x = batchnormalization_layer(inputs=x)
  x = tf.nn.relu(x)
  x = tf.layers.average_pooling2d(x, (8, 8), (1, 1))
  y = tf.layers.flatten(x)

  regularizer = tf.keras.regularizers.L2(L2)
  outputs = tf.layers.dense(
      y, units=num_classes, kernel_regularizer=regularizer)

  return outputs

class ResNet(StrategyNetBase):
  """ResNet meta class for CIFAR."""

  def __init__(self, num_classes, depth):
    super(ResNet, self).__init__()

    if (depth - 2) % 9 != 0:
      raise ValueError('depth == 9n+2')

    self.depth = depth
    self.num_classes = num_classes
    self.regularization_loss = 0
    # Used by MetaImage to compute l2 regularizer
    self.wd = 1e-4

  def save(self, path):
    self.model.save(path)

  def load_weights(self, path):
    self.model.load_weights(path)

  def get_partial_variables(self, level=-1):
    vs = []
    if level == 0:
      # only get last fc layer
      for v in self.trainable_variables:
        if 'dense' in v.name:
          vs.append(v)
    elif level == 1:
      prefix = self.name + '/' + 'stage2'
      vs = self.get_vars_before(self.trainable_variables, prefix)
    elif level == 2:
      prefix = self.name + '/' + 'stage1'
      vs = self.get_vars_before(self.trainable_variables, prefix)
    elif level < 0 or level > 2:
      vs = self.trainable_variables
    else:
      raise ValueError
    assert vs, 'Length of obtained partial variable can`t be 0'
    return vs

  def __call__(self, inputs, name, training, reuse=True, custom_getter=None):

    num_res_blocks = int((self.depth - 2) / 9)
    if self.created and not reuse:
      tf.logging.error('Warning: are you parallel?')

    with tf.variable_scope(name, reuse=reuse, custom_getter=custom_getter):
      outputs = resnet_model_fn(
          inputs,
          training,
          self.num_classes,
          num_res_blocks,
          weight_decay=self.wd)

      if not isinstance(reuse, bool) or not reuse:
        # If it is tf.AUTO_REUSE or True to make sure regularization_loss is
        # added once.
        self.regularization_loss = self.get_regularization_loss(
            scope_name=name + '/')
        self.init(name, with_name='batch_normalization', outputs=outputs)
        self.count_parameters(name)

    return outputs


text:
package antares.zomblind.core.levels.conditions;

import android.content.Context;
import antares.zomblind.ZomblindActivity;

public class SinZombies implements _Condicion{
	ZomblindActivity _z;

	public SinZombies(Context ctx) {
		_z = (ZomblindActivity) ctx;
	}

	public boolean test(){
		return _z._entorno._npcs.noZombieInGame();
	}

}


text:
get "/login" do

erb :"users/login"

end

post "/login" do

	 if user = User.authenticate(params[:user][:email],params[:user][:password])
		session[:user_id] = user.id
		redirect to "/"
	else
		@login_error = "Invalid Login"
		erb :"users/login"
	end
end


text:
<?php

namespace Mbcraft\Laravel\Http\Middleware;

use Closure;
use Blade;

/**
 * This middleware adds blade support for :
 *
 * @can -> redefined to work with policy helper function
 *
 */
class BladePolicy2Syntax extends __AbstractBladeSyntax {

    /**
     * Contains the code for obtaining the currently auth user.
     *
     * @var string The code for getting the currently authorized user.
     */
    protected $GET_AUTH_USER = "Sentinel::getUser()";

    /**
     * Defines the @ican directive for Blade.
     */
    private function setupIcanBladeExtension() {

        \Log::debug("Setup @ican directive for blade ...");

        Blade::directive('ican', function($expression) {
            $params = $this->stringParamAsString($expression);
            $params = explode(',',$params);
            $method = $this->stringParamAsString($params[0]);
            if (count($params)>1) {
                array_shift($params);
                $policy_subject = $params[0];
                array_unshift($params,$this->GET_AUTH_USER);
                $method_params = join(",",$params);
            } else {
                $policy_subject = $this->GET_AUTH_USER;
                $method_params = $this->GET_AUTH_USER;
            }

            return "<?php if( policy($policy_subject)->$method($method_params) ): ?>";
        });
    }

    /**
     * Defines the @icannot directive for Blade.
     */
    private function setupIcannotBladeExtension() {

        \Log::debug("Setup @icannot directive for blade ...");

        Blade::directive('icannot', function($expression) {
            $params = $this->stringParamAsString($expression);
            $params = explode(',',$params);
            $method = $this->stringParamAsString($params[0]);
            if (count($params)>1) {
                array_shift($params);
                $policy_subject = $params[0];
                array_unshift($params,$this->GET_AUTH_USER);
                $method_params = join(",",$params);
            } else {
                $policy_subject = $this->GET_AUTH_USER;
                $method_params = $this->GET_AUTH_USER;
            }

            return "<?php if( !policy($policy_subject)->$method($method_params) ): ?>";
        });
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //overriding policy checking '@ican' and '@icannot' directives for blade
        $this->setupIcanBladeExtension();
        $this->setupIcannotBladeExtension();

        \Log::debug("Blade directives '@ican' and '@icannot' setup Completed!");
        //next middleware
        return $next($request);
    }
}


text:
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Klocman.Forms;
using Klocman.Tools;
using UniversalUninstaller.Properties;

namespace UniversalUninstaller
{
    public sealed partial class UninstallSelection : Form
    {
        public UninstallSelection(DirectoryInfo target)
        {
            InitializeComponent();
            targetList1.Populate(target);

            try
            {
                Icon = ProcessTools.GetIconFromEntryExe();
            }
            catch (Exception ex)
            {
                /* Fall back to a low quality icon */
                var handle = Resources.icon.GetHicon();
                Icon = Icon.FromHandle(handle);

                Console.WriteLine(ex);
                LogWriter.WriteMessageToLog(ex.ToString());
            }

            Text = string.Format(Localisation.UninstallSelection_Title, target.Name);
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var ex = LoadingDialog.ShowDialog(this, Localisation.UninstallSelection_DeleteProgress_Title,
                _ => Program.DeleteItems(targetList1.GetItemsToDelete().ToList()));

            if (ex != null)
            {
                Console.WriteLine(ex);
                MessageBox.Show(ex.ToString(), Localisation.UninstallSelection_DeleteProgress_FailedTitle,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                DeleteFailed = true;
            }

            Close();
        }

        public bool WasCancelled { get; private set; }
        public bool DeleteFailed { get; private set; }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            WasCancelled = true;
            Close();
        }
    }
}


text:
import { forwardRef, EventEmitter, Input, Output, Component, ElementRef, Renderer2, ChangeDetectorRef, ViewChild, ContentChild, ContentChildren, NgModule } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
import { CommonModule } from '@angular/common';
import { DomHandler } from 'primeng/dom';
import { ObjectUtils, FilterUtils } from 'primeng/utils';
import { Footer, Header, PrimeTemplate, SharedModule } from 'primeng/api';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { TooltipModule } from 'primeng/tooltip';

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const MULTISELECT_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => MultiSelect),
    multi: true
};
let MultiSelectItem = class MultiSelectItem {
    constructor() {
        this.onClick = new EventEmitter();
        this.onKeydown = new EventEmitter();
    }
    onOptionClick(event) {
        this.onClick.emit({
            originalEvent: event,
            option: this.option
        });
    }
    onOptionKeydown(event) {
        this.onKeydown.emit({
            originalEvent: event,
            option: this.option
        });
    }
};
__decorate([
    Input()
], MultiSelectItem.prototype, "option", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "selected", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "disabled", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "visible", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "itemSize", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "template", void 0);
__decorate([
    Input()
], MultiSelectItem.prototype, "maxSelectionLimitReached", void 0);
__decorate([
    Output()
], MultiSelectItem.prototype, "onClick", void 0);
__decorate([
    Output()
], MultiSelectItem.prototype, "onKeydown", void 0);
MultiSelectItem = __decorate([
    Component({
        selector: 'p-multiSelectItem',
        template: `

            {{option.label}}
            <ng-container *ngTemplateOutlet="template; context: {$implicit: option}"></ng-container>

    `
    })
], MultiSelectItem);
let MultiSelect = class MultiSelect {
    constructor(el, renderer, cd) {
        this.el = el;
        this.renderer = renderer;
        this.cd = cd;
        this.scrollHeight = '200px';
        this._defaultLabel = 'Choose';
        this.filter = true;
        this.displaySelectedLabel = true;
        this.maxSelectedLabels = 3;
        this.selectedItemsLabel = '{0} items selected';
        this.showToggleAll = true;
        this.emptyFilterMessage = 'No results found';
        this.resetFilterOnHide = false;
        this.dropdownIcon = 'pi pi-chevron-down';
        this.showHeader = true;
        this.autoZIndex = true;
        this.baseZIndex = 0;
        this.filterBy = 'label';
        this.showTransitionOptions = '225ms ease-out';
        this.hideTransitionOptions = '195ms ease-in';
        this.filterMatchMode = "contains";
        this.tooltip = '';
        this.tooltipPosition = 'right';
        this.tooltipPositionStyle = 'absolute';
        this.onChange = new EventEmitter();
        this.onFocus = new EventEmitter();
        this.onBlur = new EventEmitter();
        this.onClick = new EventEmitter();
        this.onPanelShow = new EventEmitter();
        this.onPanelHide = new EventEmitter();
        this.onModelChange = () => { };
        this.onModelTouched = () => { };
        this.disabledSelectedOptions = [];
    }
    set defaultLabel(val) {
        this._defaultLabel = val;
        this.updateLabel();
    }
    get defaultLabel() {
        return this._defaultLabel;
    }
    get options() {
        return this._options;
    }
    set options(val) {
        let opts = this.optionLabel ? ObjectUtils.generateSelectItems(val, this.optionLabel) : val;
        this.visibleOptions = opts;
        this._options = opts;
        this.updateLabel();
        if (this.filterValue && this.filterValue.length) {
            this.activateFilter();
        }
    }
    ngOnInit() {
        this.updateLabel();
    }
    ngAfterContentInit() {
        this.templates.forEach((item) => {
            switch (item.getType()) {
                case 'item':
                    this.itemTemplate = item.template;
                    break;
                case 'selectedItems':
                    this.selectedItemsTemplate = item.template;
                    break;
                default:
                    this.itemTemplate = item.template;
                    break;
            }
        });
    }
    ngAfterViewInit() {
        if (this.overlayVisible) {
            this.show();
        }
    }
    ngAfterViewChecked() {
        if (this.filtered) {
            this.alignOverlay();
            this.filtered = false;
        }
    }
    writeValue(value) {
        this.value = value;
        this.updateLabel();
        this.updateFilledState();
        this.setDisabledSelectedOptions();
        this.checkSelectionLimit();
        this.cd.markForCheck();
    }
    checkSelectionLimit() {
        if (this.selectionLimit && (this.value && this.value.length === this.selectionLimit)) {
            this.maxSelectionLimitReached = true;
        }
    }
    updateFilledState() {
        this.filled = (this.valuesAsString != null && this.valuesAsString.length > 0);
    }
    registerOnChange(fn) {
        this.onModelChange = fn;
    }
    registerOnTouched(fn) {
        this.onModelTouched = fn;
    }
    setDisabledState(val) {
        this.disabled = val;
    }
    onOptionClick(event) {
        let option = event.option;
        if (option.disabled) {
            return;
        }
        const optionValue = option.value;
        let selectionIndex = this.findSelectionIndex(optionValue);
        if (selectionIndex != -1) {
            this.value = this.value.filter((val, i) => i != selectionIndex);
            if (this.selectionLimit) {
                this.maxSelectionLimitReached = false;
            }
        }
        else {
            if (!this.selectionLimit || (!this.value || this.value.length < this.selectionLimit)) {
                this.value = [...this.value || [], optionValue];
            }
            this.checkSelectionLimit();
        }
        this.onModelChange(this.value);
        this.onChange.emit({ originalEvent: event.originalEvent, value: this.value, itemValue: optionValue });
        this.updateLabel();
        this.updateFilledState();
    }
    isSelected(value) {
        return this.findSelectionIndex(value) != -1;
    }
    findSelectionIndex(val) {
        let index = -1;
        if (this.value) {
            for (let i = 0; i < this.value.length; i++) {
                if (ObjectUtils.equals(this.value[i], val, this.dataKey)) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }
    toggleAll(event) {
        if (this.isAllChecked()) {
            if (this.disabledSelectedOptions && this.disabledSelectedOptions.length > 0) {
                let value = [];
                value = [...this.disabledSelectedOptions];
                this.value = value;
            }
            else {
                this.value = [];
            }
        }
        else {
            let opts = this.getVisibleOptions();
            if (opts) {
                let value = [];
                if (this.disabledSelectedOptions && this.disabledSelectedOptions.length > 0) {
                    value = [...this.disabledSelectedOptions];
                }
                for (let i = 0; i < opts.length; i++) {
                    let option = opts[i];
                    if (!option.disabled) {
                        value.push(opts[i].value);
                    }
                }
                this.value = value;
            }
        }
        this.onModelChange(this.value);
        this.onChange.emit({ originalEvent: event, value: this.value });
        this.updateLabel();
    }
    isAllChecked() {
        if (this.filterValue && this.filterValue.trim().length) {
            return this.value && this.visibleOptions && this.visibleOptions.length && this.isAllVisibleOptionsChecked();
        }
        else {
            let optionCount = this.getEnabledOptionCount();
            let disabledSelectedOptionCount = this.disabledSelectedOptions.length;
            return this.value && this.options && (this.value.length > 0 && this.value.length == optionCount + disabledSelectedOptionCount);
        }
    }
    isAllVisibleOptionsChecked() {
        if (!this.visibleOptions || this.visibleOptions.length === 0) {
            return false;
        }
        else {
            for (let option of this.visibleOptions) {
                if (!this.isSelected(option.value)) {
                    return false;
                }
            }
            return true;
        }
    }
    getEnabledOptionCount() {
        if (this.options) {
            let count = 0;
            for (let opt of this.options) {
                if (!opt.disabled) {
                    count++;
                }
            }
            return count;
        }
        else {
            return 0;
        }
    }
    setDisabledSelectedOptions() {
        if (this.options) {
            this.disabledSelectedOptions = [];
            if (this.value) {
                for (let opt of this.options) {
                    if (opt.disabled && this.isSelected(opt.value)) {
                        this.disabledSelectedOptions.push(opt.value);
                    }
                }
            }
        }
    }
    show() {
        if (!this.overlayVisible) {
            this.overlayVisible = true;
        }
        if (this.filter) {
            setTimeout(() => {
                if (this.filterInputChild != undefined) {
                    this.filterInputChild.nativeElement.focus();
                }
            }, 200);
        }
        this.bindDocumentClickListener();
    }
    onOverlayAnimationStart(event) {
        switch (event.toState) {
            case 'visible':
                this.overlay = event.element;
                this.appendOverlay();
                if (this.autoZIndex) {
                    this.overlay.style.zIndex = String(this.baseZIndex + (++DomHandler.zindex));
                }
                this.alignOverlay();
                this.bindDocumentClickListener();
                this.bindDocumentResizeListener();
                this.onPanelShow.emit();
                break;
            case 'void':
                this.onOverlayHide();
                break;
        }
    }
    appendOverlay() {
        if (this.appendTo) {
            if (this.appendTo === 'body')
                document.body.appendChild(this.overlay);
            else
                DomHandler.appendChild(this.overlay, this.appendTo);
            this.overlay.style.minWidth = DomHandler.getWidth(this.containerViewChild.nativeElement) + 'px';
        }
    }
    restoreOverlayAppend() {
        if (this.overlay && this.appendTo) {
            this.el.nativeElement.appendChild(this.overlay);
        }
    }
    alignOverlay() {
        if (this.overlay) {
            if (this.appendTo)
                DomHandler.absolutePosition(this.overlay, this.containerViewChild.nativeElement);
            else
                DomHandler.relativePosition(this.overlay, this.containerViewChild.nativeElement);
        }
    }
    hide() {
        this.overlayVisible = false;
        this.unbindDocumentClickListener();
        if (this.resetFilterOnHide) {
            this.filterInputChild.nativeElement.value = '';
            this.onFilter();
        }
        this.onPanelHide.emit();
    }
    close(event) {
        this.hide();
        event.preventDefault();
        event.stopPropagation();
    }
    onMouseclick(event, input) {
        if (this.disabled || this.readonly) {
            return;
        }
        this.onClick.emit(event);
        if (!this.panelClick) {
            if (this.overlayVisible) {
                this.hide();
            }
            else {
                input.focus();
                this.show();
            }
        }
        this.selfClick = true;
    }
    onInputFocus(event) {
        this.focus = true;
        this.onFocus.emit({ originalEvent: event });
    }
    onInputBlur(event) {
        this.focus = false;
        this.onBlur.emit({ originalEvent: event });
        this.onModelTouched();
    }
    onOptionKeydown(event) {
        if (this.readonly) {
            return;
        }
        switch (event.originalEvent.which) {
            //down
            case 40:
                var nextItem = this.findNextItem(event.originalEvent.target.parentElement);
                if (nextItem) {
                    nextItem.focus();
                }
                event.originalEvent.preventDefault();
                break;
            //up
            case 38:
                var prevItem = this.findPrevItem(event.originalEvent.target.parentElement);
                if (prevItem) {
                    prevItem.focus();
                }
                event.originalEvent.preventDefault();
                break;
            //enter
            case 13:
                this.onOptionClick(event);
                event.originalEvent.preventDefault();
                break;
        }
    }
    findNextItem(item) {
        let nextItem = item.nextElementSibling;
        if (nextItem)
            return DomHandler.hasClass(nextItem.children[0], 'ui-state-disabled') || DomHandler.isHidden(nextItem.children[0]) ? this.findNextItem(nextItem) : nextItem.children[0];
        else
            return null;
    }
    findPrevItem(item) {
        let prevItem = item.previousElementSibling;
        if (prevItem)
            return DomHandler.hasClass(prevItem.children[0], 'ui-state-disabled') || DomHandler.isHidden(prevItem.children[0]) ? this.findPrevItem(prevItem) : prevItem.children[0];
        else
            return null;
    }
    onKeydown(event) {
        switch (event.which) {
            //down
            case 40:
                if (!this.overlayVisible && event.altKey) {
                    this.show();
                }
                break;
            //space
            case 32:
                if (!this.overlayVisible) {
                    this.show();
                    event.preventDefault();
                }
                break;
            //escape
            case 27:
                this.hide();
                break;
        }
    }
    updateLabel() {
        if (this.value && this.options && this.value.length && this.displaySelectedLabel) {
            let label = '';
            for (let i = 0; i < this.value.length; i++) {
                let itemLabel = this.findLabelByValue(this.value[i]);
                if (itemLabel) {
                    if (label.length > 0) {
                        label = label + ', ';
                    }
                    label = label + itemLabel;
                }
            }
            if (this.value.length <= this.maxSelectedLabels) {
                this.valuesAsString = label;
            }
            else {
                let pattern = /{(.*?)}/;
                if (pattern.test(this.selectedItemsLabel)) {
                    this.valuesAsString = this.selectedItemsLabel.replace(this.selectedItemsLabel.match(pattern)[0], this.value.length + '');
                }
                else {
                    this.valuesAsString = this.selectedItemsLabel;
                }
            }
        }
        else {
            this.valuesAsString = this.defaultLabel;
        }
    }
    findLabelByValue(val) {
        let label = null;
        for (let i = 0; i < this.options.length; i++) {
            let option = this.options[i];
            if (val == null && option.value == null || ObjectUtils.equals(val, option.value, this.dataKey)) {
                label = option.label;
                break;
            }
        }
        return label;
    }
    onFilter() {
        let inputValue = this.filterInputChild.nativeElement.value;
        if (inputValue && inputValue.length) {
            this.filterValue = inputValue;
            this.activateFilter();
        }
        else {
            this.filterValue = null;
            this.visibleOptions = this.options;
            this.filtered = false;
        }
    }
    activateFilter() {
        if (this.options && this.options.length) {
            let searchFields = this.filterBy.split(',');
            this.visibleOptions = FilterUtils.filter(this.options, searchFields, this.filterValue, this.filterMatchMode);
            this.filtered = true;
        }
    }
    isItemVisible(option) {
        if (this.filterValue && this.filterValue.trim().length) {
            for (let i = 0; i < this.visibleOptions.length; i++) {
                if (this.visibleOptions[i].value == option.value) {
                    return true;
                }
            }
        }
        else {
            return true;
        }
    }
    getVisibleOptions() {
        return this.visibleOptions || this.options;
    }
    onHeaderCheckboxFocus() {
        this.headerCheckboxFocus = true;
    }
    onHeaderCheckboxBlur() {
        this.headerCheckboxFocus = false;
    }
    bindDocumentClickListener() {
        if (!this.documentClickListener) {
            this.documentClickListener = this.renderer.listen('document', 'click', () => {
                if (!this.selfClick && !this.panelClick && this.overlayVisible) {
                    this.hide();
                }
                this.selfClick = false;
                this.panelClick = false;
                this.cd.markForCheck();
            });
        }
    }
    unbindDocumentClickListener() {
        if (this.documentClickListener) {
            this.documentClickListener();
            this.documentClickListener = null;
        }
    }
    bindDocumentResizeListener() {
        this.documentResizeListener = this.onWindowResize.bind(this);
        window.addEventListener('resize', this.documentResizeListener);
    }
    unbindDocumentResizeListener() {
        if (this.documentResizeListener) {
            window.removeEventListener('resize', this.documentResizeListener);
            this.documentResizeListener = null;
        }
    }
    onWindowResize() {
        if (!DomHandler.isAndroid()) {
            this.hide();
        }
    }
    onOverlayHide() {
        this.unbindDocumentClickListener();
        this.unbindDocumentResizeListener();
        this.overlay = null;
    }
    ngOnDestroy() {
        this.restoreOverlayAppend();
        this.onOverlayHide();
    }
};
MultiSelect.ctorParameters = () => [
    { type: ElementRef },
    { type: Renderer2 },
    { type: ChangeDetectorRef }
];
__decorate([
    Input()
], MultiSelect.prototype, "scrollHeight", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "defaultLabel", null);
__decorate([
    Input()
], MultiSelect.prototype, "style", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "styleClass", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "panelStyle", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "panelStyleClass", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "inputId", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "disabled", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "readonly", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "filter", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "filterPlaceHolder", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "overlayVisible", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "tabindex", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "appendTo", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "dataKey", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "name", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "ariaLabelledBy", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "displaySelectedLabel", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "maxSelectedLabels", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "selectionLimit", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "selectedItemsLabel", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "showToggleAll", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "emptyFilterMessage", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "resetFilterOnHide", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "dropdownIcon", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "optionLabel", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "showHeader", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "autoZIndex", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "baseZIndex", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "filterBy", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "virtualScroll", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "itemSize", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "showTransitionOptions", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "hideTransitionOptions", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "ariaFilterLabel", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "filterMatchMode", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "tooltip", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "tooltipPosition", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "tooltipPositionStyle", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "tooltipStyleClass", void 0);
__decorate([
    ViewChild('container', { static: true })
], MultiSelect.prototype, "containerViewChild", void 0);
__decorate([
    ViewChild('filterInput', { static: false })
], MultiSelect.prototype, "filterInputChild", void 0);
__decorate([
    ContentChild(Footer, { static: true })
], MultiSelect.prototype, "footerFacet", void 0);
__decorate([
    ContentChild(Header, { static: true })
], MultiSelect.prototype, "headerFacet", void 0);
__decorate([
    ContentChildren(PrimeTemplate)
], MultiSelect.prototype, "templates", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onChange", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onFocus", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onBlur", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onClick", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onPanelShow", void 0);
__decorate([
    Output()
], MultiSelect.prototype, "onPanelHide", void 0);
__decorate([
    Input()
], MultiSelect.prototype, "options", null);
MultiSelect = __decorate([
    Component({
        selector: 'p-multiSelect',
        template: `

                <input #in type="text" readonly="readonly" [attr.id]="inputId" [attr.name]="name" (focus)="onInputFocus($event)" (blur)="onInputBlur($event)"
                       [disabled]="disabled" [attr.tabindex]="tabindex" (keydown)="onKeydown($event)" aria-haspopup="listbox" [attr.aria-expanded]="overlayVisible"
                       [attr.aria-labelledby]="ariaLabelledBy">

                    <ng-container *ngIf="!selectedItemsTemplate">{{valuesAsString}}</ng-container>
                    <ng-container *ngTemplateOutlet="selectedItemsTemplate; context: {$implicit: value}"></ng-container>

                <ng-content select="p-header"></ng-content>

                            <input type="checkbox" readonly="readonly" [checked]="isAllChecked()" (focus)="onHeaderCheckboxFocus()" (blur)="onHeaderCheckboxBlur()" (keydown.space)="toggleAll($event)">

                        <input #filterInput type="text" role="textbox" [value]="filterValue||''" (input)="onFilter()" class="ui-inputtext ui-widget ui-state-default ui-corner-all" [attr.placeholder]="filterPlaceHolder" [attr.aria-label]="ariaFilterLabel">

                        <ng-container *ngIf="!virtualScroll; else virtualScrollList">
                            <ng-template ngFor let-option let-i="index" [ngForOf]="options">

                            </ng-template>
                        </ng-container>
                        <ng-template #virtualScrollList>
                            <cdk-virtual-scroll-viewport #viewport [ngStyle]="{'height': scrollHeight}" [itemSize]="itemSize" *ngIf="virtualScroll && visibleOptions && visibleOptions.length">
                                <ng-container *cdkVirtualFor="let option of visibleOptions; let i = index; let c = count; let f = first; let l = last; let e = even; let o = odd">

                                </ng-container>
                            </cdk-virtual-scroll-viewport>
                        </ng-template>

{{emptyFilterMessage}}

                    <ng-content select="p-footer"></ng-content>

    `,
        animations: [
            trigger('overlayAnimation', [
                state('void', style({
                    transform: 'translateY(5%)',
                    opacity: 0
                })),
                state('visible', style({
                    transform: 'translateY(0)',
                    opacity: 1
                })),
                transition('void => visible', animate('{{showTransitionParams}}')),
                transition('visible => void', animate('{{hideTransitionParams}}'))
            ])
        ],
        host: {
            '[class.ui-inputwrapper-filled]': 'filled',
            '[class.ui-inputwrapper-focus]': 'focus'
        },
        providers: [MULTISELECT_VALUE_ACCESSOR]
    })
], MultiSelect);
let MultiSelectModule = class MultiSelectModule {
};
MultiSelectModule = __decorate([
    NgModule({
        imports: [CommonModule, SharedModule, ScrollingModule, TooltipModule],
        exports: [MultiSelect, SharedModule, ScrollingModule],
        declarations: [MultiSelect, MultiSelectItem]
    })
], MultiSelectModule);

/**
 * Generated bundle index. Do not edit.
 */

export { MULTISELECT_VALUE_ACCESSOR, MultiSelect, MultiSelectItem, MultiSelectModule };
//# sourceMappingURL=primeng-multiselect.js.map


text:
title: spring中BeanDefinition对象的理解
tags: [spring]
---

参考:https://www.cnblogs.com/davidwang456/p/4192318.html

BeanDefinition相当于一个数据结构,这个数据结构的生成过程是根据解析的resource资源对象中的bean定义而来的,这些bean在Spirng IoC容器内部表示成了的BeanDefintion这样的数据结构,IoC容器对bean的管理和依赖注入的实现都是通过操作BeanDefinition来进行的。

一般情况下,BeanDefinition只在容器启动时加载并解析,除非容器刷新或重启,这些信息不会发生变化,当然如果用户有特殊的需求,也可以通过编程的方式在运行期调整BeanDefinition的定义。

1)查看BeanDefinition接口定义

一个BeanDefinition描述了一个bean的实例,包括属性值,构造方法参数值和继承自它的类的更多信息。BeanDefinition仅仅是一个最简单的接口,主要功能是允许BeanFactoryPostProcessor在构建对象时修改并配置相关属性值。例如PropertyPlaceHolderConfigure能够检索并修改属性值和别的bean的元数据。

```
//bean标签的parent属性信息
String getParentName();
//bean标签的class属性信息
String getBeanClassName();
//bean标签的factory-bean属性信息
String getFactoryBeanName();
//bean标签的factory-method属性信息
String getFactoryMethodName();
//bean标签的scope属性信息
String getScope();
//bean标签的lazy-init属性信息
boolean isLazyInit();
//bean标签的depends-on属性信息
String[] getDependsOn();
//bean标签的autowire-candidate属性信息
boolean isAutowireCandidate();
//bean标签的primary属性信息
boolean isPrimary();
//构造函数参数对象constructor-arg标签
ConstructorArgumentValues getConstructorArgumentValues();
//property标签
MutablePropertyValues getPropertyValues();
//是否是单例
boolean isSingleton();
//通过拷贝的方式实现BeanDefinition时,会保留被拷贝对象的引用
BeanDefinition getOriginatingBeanDefinition();
...
```

ConstructorArgumentValues类构造参数,保存了构造方法所有的参数值,通常作为beanDefinition的一部分来使用。它不仅支持类型匹配的普通参数,也支持根据参数列表中的索引位置来提供参数。提供了两个变量来保存参数:带索引的和不带索引的

```
public class ConstructorArgumentValues {

    private final Map<Integer, ValueHolder> indexedArgumentValues = new LinkedHashMap<Integer, ValueHolder>(0);

    private final List<ValueHolder> genericArgumentValues = new LinkedList<ValueHolder>();
```

MutablePropertyValues类是PropertyValues接口的默认实现,支持对属性的简单操作,为构造方法提供深度复制和使用map获取构造的支持。

2)查看BeanDefinition实现接口

```
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement
```

AttributeAccessor接口定义

AttributeAccessor接口定义了最基本的对任意对象的元数据的修改或者获取,即设置的meta标签信息会封装到该接口定义的属性中。

```
String[] attributeNames()
Object getAttribute(String name)
boolean hasAttribute(String name)
Object removeAttribute(String name)
void setAttribute(String name, Object value)
```

BeanMetadataElement接口提供了一个getResource()方法,用来传输一个可配置的源对象。

3)常见的实现类

beanDefinition接口的直接实现类ChildBeanDefinition,GenericBeanDefinition,RootBeanDefinition。


text:
class CreatePermissions < ActiveRecord::Migration
  def change
    create_table :permissions do |t|
      t.references :user
      t.references :role

      t.timestamps
    end
    add_index :permissions, :user_id
    add_index :permissions, :role_id
  end
end


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("api", "0052_auto_20190104_1122")]

    operations = [
        migrations.AddField(
            model_name="check",
            name="subject",
            field=models.CharField(blank=True, max_length=100),
        )
    ]


text:
// Code generated by client-gen. DO NOT EDIT.

package v1

import (
	"context"
	"time"

	v1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
	scheme "kubevirt.io/client-go/generated/network-attachment-definition-client/clientset/versioned/scheme"
)

// NetworkAttachmentDefinitionsGetter has a method to return a NetworkAttachmentDefinitionInterface.
// A group's client should implement this interface.
type NetworkAttachmentDefinitionsGetter interface {
	NetworkAttachmentDefinitions(namespace string) NetworkAttachmentDefinitionInterface
}

// NetworkAttachmentDefinitionInterface has methods to work with NetworkAttachmentDefinition resources.
type NetworkAttachmentDefinitionInterface interface {
	Create(ctx context.Context, networkAttachmentDefinition *v1.NetworkAttachmentDefinition, opts metav1.CreateOptions) (*v1.NetworkAttachmentDefinition, error)
	Update(ctx context.Context, networkAttachmentDefinition *v1.NetworkAttachmentDefinition, opts metav1.UpdateOptions) (*v1.NetworkAttachmentDefinition, error)
	Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
	DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error
	Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.NetworkAttachmentDefinition, error)
	List(ctx context.Context, opts metav1.ListOptions) (*v1.NetworkAttachmentDefinitionList, error)
	Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
	Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.NetworkAttachmentDefinition, err error)
	NetworkAttachmentDefinitionExpansion
}

// networkAttachmentDefinitions implements NetworkAttachmentDefinitionInterface
type networkAttachmentDefinitions struct {
	client rest.Interface
	ns     string
}

// newNetworkAttachmentDefinitions returns a NetworkAttachmentDefinitions
func newNetworkAttachmentDefinitions(c *K8sCniCncfIoV1Client, namespace string) *networkAttachmentDefinitions {
	return &networkAttachmentDefinitions{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the networkAttachmentDefinition, and returns the corresponding networkAttachmentDefinition object, and an error if there is any.
func (c *networkAttachmentDefinitions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.NetworkAttachmentDefinition, err error) {
	result = &v1.NetworkAttachmentDefinition{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do(ctx).
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of NetworkAttachmentDefinitions that match those selectors.
func (c *networkAttachmentDefinitions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NetworkAttachmentDefinitionList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1.NetworkAttachmentDefinitionList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do(ctx).
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested networkAttachmentDefinitions.
func (c *networkAttachmentDefinitions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch(ctx)
}

// Create takes the representation of a networkAttachmentDefinition and creates it.  Returns the server's representation of the networkAttachmentDefinition, and an error, if there is any.
func (c *networkAttachmentDefinitions) Create(ctx context.Context, networkAttachmentDefinition *v1.NetworkAttachmentDefinition, opts metav1.CreateOptions) (result *v1.NetworkAttachmentDefinition, err error) {
	result = &v1.NetworkAttachmentDefinition{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(networkAttachmentDefinition).
		Do(ctx).
		Into(result)
	return
}

// Update takes the representation of a networkAttachmentDefinition and updates it. Returns the server's representation of the networkAttachmentDefinition, and an error, if there is any.
func (c *networkAttachmentDefinitions) Update(ctx context.Context, networkAttachmentDefinition *v1.NetworkAttachmentDefinition, opts metav1.UpdateOptions) (result *v1.NetworkAttachmentDefinition, err error) {
	result = &v1.NetworkAttachmentDefinition{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		Name(networkAttachmentDefinition.Name).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(networkAttachmentDefinition).
		Do(ctx).
		Into(result)
	return
}

// Delete takes name of the networkAttachmentDefinition and deletes it. Returns an error if one occurs.
func (c *networkAttachmentDefinitions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		Name(name).
		Body(&opts).
		Do(ctx).
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *networkAttachmentDefinitions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
	var timeout time.Duration
	if listOpts.TimeoutSeconds != nil {
		timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		VersionedParams(&listOpts, scheme.ParameterCodec).
		Timeout(timeout).
		Body(&opts).
		Do(ctx).
		Error()
}

// Patch applies the patch and returns the patched networkAttachmentDefinition.
func (c *networkAttachmentDefinitions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.NetworkAttachmentDefinition, err error) {
	result = &v1.NetworkAttachmentDefinition{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("network-attachment-definitions").
		Name(name).
		SubResource(subresources...).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(data).
		Do(ctx).
		Into(result)
	return
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FlatRedBall.Glue.Plugins;

namespace FlatRedBall.Glue.Controls
{
    public class PluginTab : TabPage
    {
        public delegate void ClosedByUserDelegate(object sender);
        public event ClosedByUserDelegate ClosedByUser;

        bool mDrawX = true;

        MenuItem moveToMenuItem;

        public TabControl LastTabControl { get; set; }

        TabControl ParentTabControl
        {
            get
            {
                return Parent as TabControl;
            }
        }

        public DateTime LastTimeClicked
        {
            get;
            set;
        }

        public bool DrawX
        {
            get { return mDrawX; }
            set { mDrawX = value; }
        }

        public PluginTab() : base()
        {
            this.ContextMenu = new ContextMenu();

            moveToMenuItem = this.ContextMenu.MenuItems.Add("MoveTo");

        }

        public void RefreshMoveToCommands()
        {
            moveToMenuItem.MenuItems.Clear();
            if (ParentTabControl != PluginManager.LeftTab)
            {
                moveToMenuItem.MenuItems.Add("Left Tab", HandleMoveToLeftTab);
            }

            if (ParentTabControl != PluginManager.RightTab)
            {
                moveToMenuItem.MenuItems.Add("Right Tab", HandleMoveToRightTab);
            }

            if (ParentTabControl != PluginManager.TopTab)
            {
                moveToMenuItem.MenuItems.Add("Top Tab", HandleMoveToTopTab);
            }

            if (ParentTabControl != PluginManager.BottomTab)
            {
                moveToMenuItem.MenuItems.Add("Bottom Tab", HandleMoveToBottomTab);
            }

            if (ParentTabControl != PluginManager.CenterTab)
            {
                moveToMenuItem.MenuItems.Add("Center Tab", HandleMoveToCenterTab);
            }
        }

        private void HandleMoveToLeftTab(object sender, EventArgs e)
        {
            ParentTabControl.TabPages.Remove(this);
            FlatRedBall.Glue.Plugins.PluginManager.LeftTab.TabPages.Add(this);
        }

        private void HandleMoveToRightTab(object sender, EventArgs e)
        {
            ParentTabControl.TabPages.Remove(this);
            FlatRedBall.Glue.Plugins.PluginManager.RightTab.TabPages.Add(this);

        }

        private void HandleMoveToTopTab(object sender, EventArgs e)
        {
            ParentTabControl.TabPages.Remove(this);
            FlatRedBall.Glue.Plugins.PluginManager.TopTab.TabPages.Add(this);

        }

        private void HandleMoveToBottomTab(object sender, EventArgs e)
        {
            ParentTabControl.TabPages.Remove(this);
            FlatRedBall.Glue.Plugins.PluginManager.BottomTab.TabPages.Add(this);

        }

        private void HandleMoveToCenterTab(object sender, EventArgs e)
        {
            ParentTabControl.TabPages.Remove(this);
            FlatRedBall.Glue.Plugins.PluginManager.CenterTab.TabPages.Add(this);

        }

        public void CloseTabByUser()
        {
            if (ClosedByUser != null)
                ClosedByUser(this);
        }
    }
}


text:
body { padding-bottom: 20px; }

/* Set padding to keep content from hitting the edges */

.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Override the default bootstrap behavior where horizontal description lists
   will truncate terms that are too long to fit in the left column
*/

.dl-horizontal dt { white-space: normal; }

/* Set width on the form input elements since they're 100% wide by default */

input,
select,
textarea { max-width: 280px; }

.counters { margin-top: 65px; }

.thumbnail { margin-bottom: 20px; }

.centered-text { text-align: center; }

.incrementor { margin: 0; }

.buy-vount-multiplier { font-size: 18px; }

.fund-driver-block { height: 185px; }

@media screen and (min-width: 768px) {
    .jumbotron {
        padding-bottom: 20px;
        padding-top: 20px;
    }
}


text:
require 'spec_helper'

describe "tweets/show.html.erb" do
  before(:each) do
    @tweet = assign(:tweet, stub_model(Tweet,
      :content => "Content",
      :repeat => false
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat-matchers flag if you want to use webrat matchers
    rendered.should match(/Content/)
    # Run the generator again with the --webrat-matchers flag if you want to use webrat matchers
    rendered.should match(/false/)
  end
end


text:
<?php

/**
 * This file is part of the ValueObject package.
 *
 * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 */

namespace ValueObject\Money;

use ValueObject\Quantity\QuantityInterface;

/**
 * Interface MoneyInterface.
 *
 * @package ValueObject
 * @author  Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 * @link    http://github.com/lorenzomar/valueobjects
 */
interface MoneyInterface extends QuantityInterface
{
    /**
     * currency.
     *
     * @return mixed
     */
    public function currency();

    /**
     * sameCurrencyOf.
     *
     * @param MoneyInterface $money
     *
     * @return bool
     */
    public function sameCurrencyOf(MoneyInterface $money);
}


text:
import os
import subprocess
import platform

import six

from hwk import udev

_LINUX_SYS_CLASS_NET_DIR = '/sys/class/net'
_INFO_HELP = """Network subsystem
===============================================================================
`hwk.net.Info` attributes:

nics (list of `hwk.net.NIC` objects)

  A list of objects describing the network interface controllers on the system

  `hwk.net.NIC` attributes:

  name (string)

    Name of the network controller according to the system, e.g. 'wls1' or
    'enp0s25'

  bus_type (string):

    The bus type used by the NIC, if known, e.g. 'pci'

  driver (string)

    The kernel network driver, if known, e.g. 'e1000e' or 'ath9k'

  mac_address (string)

    The MAC address of the NIC, as reported by the system

  model (string)

    String describing the NIC model, if known

  vendor (string)

    The NIC vendor, if known

  vendor_id (string)

    The ID of the vendor in hexadecimal, if known, e.g. '0x8086' or '0x168c'

  enabled_features (set of string)

    The set of features the NIC supports and has enabled, e.g.
    'rx-vlan-offload', 'tx-gso-partial', etc
"""

class Info(object):
    """Object describing the network information about a system."""

    def __init__(self):
        self.nics = []

    def __repr__(self):
        return "net (%d NICs)" % (
            len(self.nics),
        )

    def describe(self):
        return _INFO_HELP

class NIC(object):

    def __init__(self, name):
        self.name = name
        self.bus_type = None
        self.driver = None
        self.mac = None
        self.model = None
        self.vendor = None
        self.vendor_id = None
        self.enabled_features = set()

    def __repr__(self):
        vendor_str = ''
        if self.vendor is not None:
            vendor_str = ' [' + self.vendor.strip().decode('utf8') + ']'
        model_str = ''
        if self.model is not None:
            model_str = ' - ' + self.model.strip().decode('utf8')
        return "NIC %s%s%s" % (
            self.name,
            vendor_str,
            model_str,
        )

def _linux_nic_features(nic_name):
    cmd = ['ethtool', '-k', nic_name]
    try:
        out = subprocess.check_output(cmd)
        # The output of `ethtool -k <nic>` looks like the following:
        # $ ethtool -k enp0s25
        # Features for enp0s25:
        # rx-checksumming: on
        # tx-checksumming: on
        #         tx-checksum-ipv4: off [fixed]
        #         tx-checksum-ip-generic: on
        #         tx-checksum-ipv6: off [fixed]
        #         tx-checksum-fcoe-crc: off [fixed]
        #         tx-checksum-sctp: off [fixed]
        # scatter-gather: on
        #         tx-scatter-gather: on
        #         tx-scatter-gather-fraglist: off [fixed]
        # tcp-segmentation-offload: on
        #         tx-tcp-segmentation: on
        #         tx-tcp-ecn-segmentation: off [fixed]
        #         tx-tcp-mangleid-segmentation: off
        #         tx-tcp6-segmentation: on
        # udp-fragmentation-offload: off [fixed]
        # generic-segmentation-offload: on
        # generic-receive-offload: on
        # large-receive-offload: off [fixed]
        # rx-vlan-offload: on
        # tx-vlan-offload: on
        # ntuple-filters: off [fixed]
        # receive-hashing: on
        # highdma: on [fixed]
        # rx-vlan-filter: off [fixed]
        # vlan-challenged: off [fixed]
        # tx-lockless: off [fixed]
        # netns-local: off [fixed]
        # tx-gso-robust: off [fixed]
        # tx-fcoe-segmentation: off [fixed]
        # tx-gre-segmentation: off [fixed]
        # tx-gre-csum-segmentation: off [fixed]
        # tx-ipxip4-segmentation: off [fixed]
        # tx-ipxip6-segmentation: off [fixed]
        # tx-udp_tnl-segmentation: off [fixed]
        # tx-udp_tnl-csum-segmentation: off [fixed]
        # tx-gso-partial: off [fixed]
        # tx-sctp-segmentation: off [fixed]
        # fcoe-mtu: off [fixed]
        # tx-nocache-copy: off
        # loopback: off [fixed]
        # rx-fcs: off
        # rx-all: off
        # tx-vlan-stag-hw-insert: off [fixed]
        # rx-vlan-stag-hw-parse: off [fixed]
        # rx-vlan-stag-filter: off [fixed]
        # l2-fwd-offload: off [fixed]
        # busy-poll: off [fixed]
        # hw-tc-offload: off [fixed]
        all_features = set()
        enabled = set()
        for line in out.split(six.b('\n'))[1:]:
            line = line.decode('utf8')
            parts = line.split(':')
            if len(parts) != 2:
                continue
            feature = parts[0].strip()
            on_str = parts[1].strip().split(' ')[0]
            on = on_str == 'on'
            all_features.add(feature)
            if on:
                enabled.add(feature)
        return all_features, enabled
    except subprocess.CalledProcessError:
        return None

def nic_features(nic_name):
    """Given a NIC name, returns two sets of strings.  None if not mounted. The
    first set are all the features, the second are all features that are
    enabled.
    """
    return {
        "Linux": _linux_nic_features,
    }[platform.system()](nic_name)

def _linux_net_device_mac_address(dev):
    # Instead of use udevadm, we can get the device's MAC address by examing
    # the /sys/class/net/$DEVICE/address file in sysfs. However, for devices
    # that have addr_assign_type != 0, return None since the MAC address is
    # random.
    try:
        aat_path = os.path.join(
            _LINUX_SYS_CLASS_NET_DIR,
            dev,
            'addr_assign_type',
        )
        aat = int(open(aat_path, 'r').read().strip())
        if aat != 0:
            return None
        addr_path = os.path.join(_LINUX_SYS_CLASS_NET_DIR, dev, 'address')
        return open(addr_path, 'r').read().strip()
    except IOError:
        return None

def info():
    """Returns a `hwk.net.Info` object containing information on the network
    subsystem, or None if the information could not be determined.
    """
    return {
        "Linux": _linux_info,
    }[platform.system()]()

def _linux_info():
    nics = []
    for filename in os.listdir(_LINUX_SYS_CLASS_NET_DIR):
        # Ignore loopback...
        if filename == 'lo':
            continue

        net_path = os.path.join(_LINUX_SYS_CLASS_NET_DIR, filename)
        dest = os.readlink(net_path)
        if 'virtio' in dest:
            # Don't bother using udevadm for virtual devices... we'll get an
            # error "query needs a valid device specified by --path= or
            # --name="
            d_info = {}
        else:
            udev_path = _LINUX_SYS_CLASS_NET_DIR + '/' + filename
            d_info = udev.device_properties(udev_path)

        nic = NIC(filename)

        nic.mac = _linux_net_device_mac_address(filename)
        nic.vendor = d_info.get('ID_VENDOR_FROM_DATABASE')
        nic.vendor_id = d_info.get('ID_VENDOR_ID')
        nic.model = d_info.get('ID_MODEL_FROM_DATABASE')
        nic.bus_type = d_info.get('ID_BUS')
        nic.driver = d_info.get('ID_NET_DRIVER')
        features = _linux_nic_features(filename)
        if features is not None:
            nic.enabled_features = features[1]
        nics.append(nic)

    res = Info()
    res.nics = nics
    return res


text:
package hr;

import org.junit.Assert;
import org.junit.Test;

public class BetweenTwoSetsTest {

	@Test
	public void testGetNumbersBetweenSets() {
		int[] a = new int[]{2,4};
		int[] b = new int[]{16,32,96};
//		Assert.assertEquals(3, BetweenTwoSets.getNumbersBetweenSets(a, b));

		 a = new int[]{2,3};
		 b = new int[]{24,48};
//		 Assert.assertEquals(3, BetweenTwoSets.getNumbersBetweenSets(a, b));

		 a = new int[]{2,3};
		 b = new int[]{32,48};
//		 Assert.assertEquals(3, BetweenTwoSets.getNumbersBetweenSets(a, b));

	}

}


text:
package Dribbble;

/**
 * The class of some images link.
 *
 * @see Dribbble API #shots
 * @see Dribbble API #shots/rebounds
 */
public class Images {
    public static final String HIDPI = "hidpi";

    public static final String NORMAL = "normal";

    public static final String TEASER = "teaser";

    private String hidpi;
    public String getHidpi() {
        return hidpi;
    }
    public void setHidpi(String hidpi) {
        this.hidpi = hidpi;
    }

    private String normal;
    public String getNormal() {
        return normal;
    }
    public void setNormal(String normal) {
        this.normal = normal;
    }

    private String teaser;
    public String getTeaser() {
        return teaser;
    }
    public void setTeaser(String teaser) {
        this.teaser = teaser;
    }

    public Images() {
        this.hidpi = null;
        this.normal = null;
        this.teaser = null;
    }
}


text:
#ifndef APE_BOXGEOMETRYJSBIND_H
#define APE_BOXGEOMETRYJSBIND_H

#include "nbind/nbind.h"
#include "nbind/api.h"
#include "ape.h"
#include "apeIBoxGeometry.h"
#include "apeJsBindNodeImpl.h"
#include "apeManualMaterialJsBind.h"

#ifdef NBIND_CLASS

class BoxJsPtr
{
private:
	ape::BoxGeometryWeakPtr mPtr;

public:
	BoxJsPtr(ape::BoxGeometryWeakPtr ptr)
	{
		mPtr = ptr;
	}

	BoxJsPtr(ape::EntityWeakPtr ptr)
	{
		mPtr = std::static_pointer_cast<ape::IBoxGeometry>(ptr.lock());
	}

	// Pointers

	const ape::EntityWeakPtr getEntityWeakPtr()
	{
		return std::static_pointer_cast<ape::Entity>(mPtr.lock());
	}

	const ape::EntitySharedPtr getEntitySharedPtr()
	{
		return this->getEntityWeakPtr().lock();
	}

	ape::GeometryWeakPtr getGeometryWeakPtr()
	{
		return std::static_pointer_cast<ape::Geometry>(mPtr.lock());
	}

	ape::GeometrySharedPtr getGeometrySharedPtr()
	{
		return this->getGeometryWeakPtr().lock();
	}

	ape::BoxGeometrySharedPtr getBoxGeometrySharedPtr()
	{
		return std::static_pointer_cast<ape::IBoxGeometry>(mPtr.lock());
	}

	ape::BoxGeometryWeakPtr getBoxGeometryWeakPtr()
	{
		return mPtr;
	}

	// ParentNode

	ape::NodeWeakPtr getParentNodeWeakPtr()
	{
		return mPtr.lock()->getParentNode();
	}

	void setParentNodeWeakPtr(ape::NodeWeakPtr parentNode)
	{
		mPtr.lock()->setParentNode(parentNode);
	}

	NodeJsPtr getParentNodeJsPtr()
	{
		return NodeJsPtr(getParentNodeWeakPtr());
	}

	void setParentNodeJsPtr(NodeJsPtr parentNode)
	{
		mPtr.lock()->setParentNode(parentNode.getNodeWeakPtr());
	}

	// Entity

	const std::string getName()
	{
		return mPtr.lock()->getName();
	}

	const ape::Entity::Type getType()
	{
		return mPtr.lock()->getType();
	}

	// IBoxGeometry

	ape::GeometryBoxParameters getParameters()
	{
		return mPtr.lock()->getParameters();
	}

	void setParameters(ape::Vector3 dimensions)
	{
		mPtr.lock()->setParameters(dimensions);
	}

	void setManualMaterial(ManualMaterialJsPtr manualMaterial)
	{
		mPtr.lock()->setMaterial(manualMaterial.getManualMaterialSharedPtr());
	}
};

using namespace ape;
NBIND_CLASS(GeometryBoxParameters)
{
	construct<>();
	construct<Vector3>();

	method(getDimensions);

	method(toString);
}

NBIND_CLASS(BoxJsPtr)
{
	construct<ape::BoxGeometryWeakPtr>();
	construct<ape::EntityWeakPtr>();

	// Pointers

	method(getEntityWeakPtr);
	method(getEntitySharedPtr);
	method(getGeometryWeakPtr);
	method(getGeometrySharedPtr);
	method(getBoxGeometryWeakPtr);
	method(getBoxGeometrySharedPtr);

	// ParentNode

	method(getParentNodeWeakPtr);
	method(setParentNodeWeakPtr);

	method(getParentNodeJsPtr);
	method(setParentNodeJsPtr);

	// Entity

	method(getName);
	method(getType);

	// IBoxGeometry

	method(getParameters);
	method(setParameters);
	method(setManualMaterial);
}

#endif

#endif


text:
set serveroutput on
set feedback off
set verify off

create or replace package body pa_orcas_checksum
is
  function get_total_checksum return varchar2
  is
  begin
    return '&1';
  end;

  function get_extension_checksum return varchar2
  is
  begin
    return '&2';
  end;
end;
/


text:
import { tryReadVersionFrom } from "./version-reading-shared";

(function() {
  const
    { ZarroError } = requireModule("zarro-error"),
    parseXml = requireModule<ParseXml>("parse-xml"),
    readTextFile = requireModule<ReadTextFile>("read-text-file");

  module.exports = async function readProjectVersion(pathToCsProj: string) {
    const
      contents = await readTextFile(pathToCsProj),
      doc = await parseXml(contents);

    try {
      const
        propertyGroups = doc.Project.PropertyGroup
      return tryReadVersionFrom(propertyGroups, "Version");
    } catch (e) {
      throw new ZarroError(
        `Unable to read any xml node Project/PropertyGroup/PackageVersion in file ${ pathToCsProj }`
      );
    }
  }
})();

export {};