text:
package beacon

import (
	"bufio"
	"encoding/json"
	"sync"
	"time"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	influx "github.com/influxdata/influxdb/client/v2"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/context"
)

type Stat struct {
	ID              string
	Name            string
	Image           string
	ContainerJSON   types.ContainerJSON
	NumContainers   int
	NumImages       int
	NumVolumes      int
	NumNetworks     int
	CPUTotalUsage   uint64
	MemUsagePercent float64
	Networks        map[string]types.NetworkStats
	Stats           *types.StatsJSON
}

func (b *Beacon) sendContainerStats(id string, stats *types.StatsJSON, ec chan error, args ...interface{}) {
	log().Debugf("updating container stats: id=%s", id)

	image := ""
	if len(id) >= 12 {
		id = id[:12]
	}

	opts := types.ContainerListOptions{
		All:  true,
		Size: false,
	}
	allContainers, err := b.client.ContainerList(context.Background(), opts)
	if err != nil {
		log().Errorf("unable to list containers: %s", err)
		return
	}

	cInfo, err := b.client.ContainerInspect(context.Background(), id)
	if err != nil {
		log().Errorf("unable to inspect container: %s", err)
		return
	}

	cName := cInfo.Name
	image = cInfo.Config.Image

	// strip /
	if cName[0] == '/' {
		cName = cName[1:]
	}

	imgOpts := types.ImageListOptions{
		All: true,
	}
	allImages, err := b.client.ImageList(context.Background(), imgOpts)
	if err != nil {
		log().Errorf("unable to list images: %s", err)
		return
	}

	allVolumes, err := b.client.VolumeList(context.Background(), filters.Args{})
	if err != nil {
		log().Errorf("unable to list volumes: %s", err)
		return
	}

	networks, err := b.client.NetworkList(context.Background(), types.NetworkListOptions{})
	if err != nil {
		log().Errorf("unable to list networks: %s", err)
		return
	}

	totalUsage := stats.CPUStats.CPUUsage.TotalUsage
	memPercent := float64(stats.MemoryStats.Usage) / float64(stats.MemoryStats.Limit) * 100.0
	numContainers := len(allContainers)
	numImages := len(allImages)
	numVolumes := len(allVolumes.Volumes)
	numNetworks := len(networks)

	s := Stat{
		ID:              id,
		Image:           image,
		Name:            cName,
		ContainerJSON:   cInfo,
		NumContainers:   numContainers,
		NumImages:       numImages,
		NumVolumes:      numVolumes,
		NumNetworks:     numNetworks,
		CPUTotalUsage:   totalUsage,
		MemUsagePercent: memPercent,
		Networks:        stats.Networks,
		Stats:           stats,
	}

	log().Debugf("stats backend: type=%s", b.cfg.StatsBackendType)

	switch b.cfg.StatsBackendType {
	case "prometheus":
		log().Debug("updating rometheus")
		b.sendPrometheus(s)
	case "influxdb":
		log().Debugf("sending stats to influxdb: url=%s", b.cfg.StatsInfluxDBAddress)
		// TODO
		if err := b.sendInfluxDB(s); err != nil {
			log().Errorf("error sending stats to influxdb: %s", err)
			return
		}
	default:
		log().Errorf("unsupported stat backend: %s", b.cfg.StatsBackendType)
		return
	}
}

func (b *Beacon) sendPrometheus(stat Stat) {
	counterTotalContainers.With(prometheus.Labels{
		"type": "totals",
	}).Set(float64(stat.NumContainers))

	counterTotalImages.With(prometheus.Labels{
		"type": "totals",
	}).Set(float64(stat.NumImages))

	counterTotalNetworks.With(prometheus.Labels{
		"type": "totals",
	}).Set(float64(stat.NumNetworks))

	counterTotalVolumes.With(prometheus.Labels{
		"type": "totals",
	}).Set(float64(stat.NumVolumes))

	counterCpuTotalUsage.With(prometheus.Labels{
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
		"type":      "cpu",
	}).Set(float64(stat.CPUTotalUsage))

	counterMemoryUsage.With(prometheus.Labels{
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
		"type":      "memory",
	}).Set(float64(stat.Stats.MemoryStats.Usage))

	counterMemoryMaxUsage.With(prometheus.Labels{
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
		"type":      "memory",
	}).Set(float64(stat.Stats.MemoryStats.MaxUsage))

	counterMemoryPercent.With(prometheus.Labels{
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
		"type":      "memory",
	}).Set(float64(stat.MemUsagePercent))

	for netName, net := range stat.Networks {
		counterNetworkRxBytes.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.RxBytes))

		counterNetworkRxPackets.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.RxPackets))

		counterNetworkRxErrors.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.RxErrors))

		counterNetworkRxDropped.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.RxDropped))

		counterNetworkTxBytes.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.TxBytes))

		counterNetworkTxPackets.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.TxPackets))

		counterNetworkTxErrors.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.TxErrors))

		counterNetworkTxDropped.With(prometheus.Labels{
			"container": stat.ID,
			"image":     stat.Image,
			"name":      stat.Name,
			"network":   netName,
			"type":      "network",
		}).Set(float64(net.TxDropped))
	}
}

func (b *Beacon) sendInfluxDB(stat Stat) error {
	c, err := NewInfluxDBClient(b.cfg)
	if err != nil {
		return err
	}

	bp, err := influx.NewBatchPoints(influx.BatchPointsConfig{
		Database:  b.cfg.StatsInfluxDBDatabase,
		Precision: b.cfg.StatsInfluxDBPrecision,
	})
	if err != nil {
		return err
	}

	timestamp := time.Now()

	// cpu total
	pt, err := influx.NewPoint("containers", map[string]string{
		"type": "totals",
	}, map[string]interface{}{
		"total_containers": stat.NumContainers,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	if err := c.Write(bp); err != nil {
		return err
	}

	// images total
	pt, err = influx.NewPoint("images", map[string]string{
		"type": "totals",
	}, map[string]interface{}{
		"total_images": stat.NumImages,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// networks total
	pt, err = influx.NewPoint("networks", map[string]string{
		"type": "totals",
	}, map[string]interface{}{
		"total_networks": stat.NumNetworks,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// volumes total
	pt, err = influx.NewPoint("volumes", map[string]string{
		"type": "totals",
	}, map[string]interface{}{
		"total_volumes": stat.NumVolumes,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// cpu total
	pt, err = influx.NewPoint("cpu_usage", map[string]string{
		"cpu":       "cpu-total",
		"resource":  "container",
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
	}, map[string]interface{}{
		"value": stat.CPUTotalUsage,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// mem usage
	pt, err = influx.NewPoint("mem_usage", map[string]string{
		"memory":    "memory-usage",
		"resource":  "container",
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
	}, map[string]interface{}{
		"value": stat.Stats.MemoryStats.Usage,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// mem max usage
	pt, err = influx.NewPoint("mem_max_usage", map[string]string{
		"memory":    "memory-max-usage",
		"resource":  "container",
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
	}, map[string]interface{}{
		"value": stat.Stats.MemoryStats.MaxUsage,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// mem usage percent
	pt, err = influx.NewPoint("mem_usage_percent", map[string]string{
		"memory":    "memory-usage-percent",
		"resource":  "container",
		"container": stat.ID,
		"image":     stat.Image,
		"name":      stat.Name,
	}, map[string]interface{}{
		"value": stat.MemUsagePercent,
	}, timestamp)
	if err != nil {
		return err
	}
	bp.AddPoint(pt)

	// networks
	for netName, net := range stat.Networks {
		pt, err = influx.NewPoint("net_rx_bytes", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.RxBytes,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_rx_packets", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.RxPackets,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_rx_errors", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.RxErrors,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_rx_dropped", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.RxDropped,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_tx_bytes", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.TxBytes,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_tx_packets", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.TxPackets,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_tx_errors", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.TxErrors,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)

		pt, err = influx.NewPoint("net_tx_dropped", map[string]string{
			"resource":  "network",
			"container": stat.ID,
			"network":   netName,
			"image":     stat.Image,
			"name":      stat.Name,
		}, map[string]interface{}{
			"value": net.TxDropped,
		}, timestamp)
		if err != nil {
			return err
		}
		bp.AddPoint(pt)
	}

	if err := c.Write(bp); err != nil {
		return err
	}

	return nil
}

func (b *Beacon) collectStats() {
	wg := &sync.WaitGroup{}
	for id, _ := range b.monitored {
		wg.Add(1)
		go func(cID string) {
			defer wg.Done()

			c, err := b.client.ContainerInspect(context.Background(), cID)
			if err != nil {
				errChan <- err
				return
			}

			image := c.Config.Image

			// match rules
			if !b.ruleMatch(c.Config) {
				log().Debugf("unable to find rule matching container %s (%s); not monitoring", c.ID, image)
				return
			}

			log().Debugf("checking container stats: id=%s", cID)
			r, err := b.client.ContainerStats(context.Background(), cID, false)
			if err != nil {
				log().Errorf("unable to get container stats: %s", err)
				return
			}

			var stats *types.StatsJSON
			s := bufio.NewScanner(r.Body)
			for s.Scan() {
				if err := json.Unmarshal([]byte(s.Text()), &stats); err != nil {
					log().Errorf("unable to unmarshal stats: %s", err)
					return
				}

				b.sendContainerStats(cID, stats, errChan)
			}

		}(id)
	}

	wg.Wait()
}

func (b *Beacon) resetStats(id string) error {
	for _, c := range allCounters {
		c.Reset()
	}

	return nil
}


text:
package com.joypupil.study.design_pattern._06proxy.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

    //被代理的对象
    private Object target = null;

    //通过构造函数传递一个对象
    public MyInvocationHandler(Object _obj) {
        this.target = _obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //执行被代理的方法
        return method.invoke(this.target, args);
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Caldasia 12(no. 60): 564 + pl. 3, fig. 9 (1979)

#### Original name
Spirotremesporites ecuatorialis Dueñas

### Remarks
null


text:
/**
 *
 */
package org.arachna.bower.registry;

/**
 * A bower package. Bower packages have
 *

 *
a package name

 *
and can be obtained from a (GitHub-) URL.

 *

 *
 * @author Dirk Weigenand
 */
public interface BowerPackage {
    /**
     * Return the name of the bower package.
     *
     * @return name of the bower package.
     */
    String getName();

    /**
     * The URL of repository as String.
     *
     * @return The URL of repository as String.
     */
    String getUrl();
}


text:
#ifndef CDBUS_PIPE_H_
#define CDBUS_PIPE_H_

#include "cdbus/macros.h"
#include "cdbus/types.h"

CDBUS_BEGIN_DECLS

typedef struct cdbus_Pipe cdbus_Pipe;

cdbus_Pipe* cdbus_pipeNew();
void cdbus_pipeDestroy(cdbus_Pipe* pipe);
void cdbus_pipeGetFds(cdbus_Pipe* pipe, cdbus_Descriptor* readFd,
                        cdbus_Descriptor* writeFd);
cdbus_Int32 cdbus_pipeRead(cdbus_Pipe* pipe, void* buf, cdbus_UInt32 count);
cdbus_Int32 cdbus_pipeWrite(cdbus_Pipe* pipe, const void* buf,
                            cdbus_UInt32 count);

CDBUS_END_DECLS

#endif /* Guard for CDBUS_PIPE_H_ */


text:
/**
 * Created by vijanny on 2016/8/11.
 */
var base = require('./Base');
var ObjectId = base.ObjectId;

var categoryScheme =new base.Schema({
    controlPage:String,//内嵌的设备控制页连接
    icon:String,//图标
    categoryName:String,//类型名
    ver:String,
    src:String,
    DeviceStream:[{
        stream_id:{type:String},
        stream_name:{type:String},
        stream_description:{type:String},
        short_name:{type:String},
        images:{type:String},
        type:{type:Number},
        data_type:{type:Number},
        max_value:{type:Number},
        min_value:{type:Number},
        increment:{type:Number},
        unit:{type:String},
        unit_symbol:{type:String},
        manu_set:[{
            id:{type:Number},
            key:{type:String},
            value:{type:Number},
            comparison_opt:{type:String}
        }]
    }]
});
categoryScheme.index({categoryName:1},{"background" : true});//设置索引
var categoryEntity = base.mongoose.model('categoryEntity',categoryScheme,'category');//指定在数据库中的collection名称为user
exports.categoryEntity  = categoryEntity;//导出UserEntity实体


text:
class Stats::AggActiveCallOrigGateway < Stats::Base
  self.table_name = "stats.active_call_orig_gateways_hourly"

  include ::AggChart
   self.chart_entity_column = :gateway_id
end


text:
import {Component} from '@angular/core';
@Component({
  selector: 'f-loader',
  template: `
    <div class="fill-space loading">
        <md-spinner></md-spinner>
    </div>
  `,
  styles: [`
    .loading {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
  `]
})
export class LoaderComponent {
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Graphical User Interface — waveserv v1.2 documentation</title>
    <link rel="stylesheet" href="_static/haiku.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/print.css" type="text/css" />

    <link rel="top" title="waveserv v1.2 documentation" href="index.html" />
    <link rel="next" title="Development" href="development.html" />
    <link rel="prev" title="Command Line Interface" href="cli.html" />

          waveserv v1.2 documentation

Graphical User Interface

        «  Command Line Interface
          ::
        Contents
          ::
        Development  »

Graphical User Interface¶

The waveserv program directly indexes and reads the (SEG-Y) files in the directory working directory on the server, handling endian and floating point conversion, and provides a directory listing through the web-browser interface.  The web-based GUI is rendered by the waveserv executable, which is started using a Command Line Interface.

With the waveserv server running, navigate to http://localhost:1503/index to show the directory listing:

Directory listing rendered by waveserv.

Each type of file is grouped under a descriptive heading, and the entries under each heading are sorted.  Several pieces of information are available for each entry, including the filename, size, and modification time.  Additionally, for files that correspond to a particular frequency or iteration, this information is extracted from the filename.  Each of these headings can be used as a sort key; simply click the corresponding check box (beside the column heading) to change the sort key.  The current sort key is indicated by a box that is coloured differently from the others.

New in version 1.1: An indicator shows the freshness of each file graphically.

Each entry has two buttons, labelled Show and Get.  Clicking the Get button simply downloads the original file.  The Show button beside an entry displays a graphical representation of the file.  This takes you to http://localhost:1503/show/filename for a file filename, which is a web address that calls a plotting method, which generates a PNG image.

Example plot for an attenuation (1/Q) model, for the project line05.

        «  Command Line Interface
          ::
        Contents
          ::
        Development  »

        © Copyright 2012, Brendan Smithyman.
      Created using Sphinx 1.0.7.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ForwardingFileObject (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.tools.ForwardingFileObject class">
<meta name="keywords" content="fileObject">
<meta name="keywords" content="toUri()">
<meta name="keywords" content="getName()">
<meta name="keywords" content="openInputStream()">
<meta name="keywords" content="openOutputStream()">
<meta name="keywords" content="openReader()">
<meta name="keywords" content="getCharContent()">
<meta name="keywords" content="openWriter()">
<meta name="keywords" content="getLastModified()">
<meta name="keywords" content="delete()">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact3

javax.tools

Class ForwardingFileObject<F extends FileObject>

java.lang.Object

javax.tools.ForwardingFileObject<F>

Type Parameters:

F - the kind of file object forwarded to by this object

All Implemented Interfaces:

FileObject

Direct Known Subclasses:

ForwardingJavaFileObject

public class ForwardingFileObject<F extends FileObject>
extends Object
implements FileObject

Forwards calls to a given file object.  Subclasses of this class
 might override some of these methods and might also provide
 additional fields and methods.

Since:

1.6

Field Summary

Fields

Modifier and Type
Field and Description

protected F
fileObject

The file object which all methods are delegated to.

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
ForwardingFileObject(F fileObject)

Creates a new instance of ForwardingFileObject.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
delete()

Deletes this file object.

CharSequence
getCharContent(boolean ignoreEncodingErrors)

Gets the character content of this file object, if available.

long
getLastModified()

Gets the time this file object was last modified.

String
getName()

Gets a user-friendly name for this file object.

InputStream
openInputStream()

Gets an InputStream for this file object.

OutputStream
openOutputStream()

Gets an OutputStream for this file object.

Reader
openReader(boolean ignoreEncodingErrors)

Gets a reader for this object.

Writer
openWriter()

Gets a Writer for this file object.

URI
toUri()

Returns a URI identifying this file object.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

fileObject

protected final F extends FileObject fileObject

The file object which all methods are delegated to.

Constructor Detail

ForwardingFileObject

protected ForwardingFileObject(F fileObject)

Creates a new instance of ForwardingFileObject.

Parameters:

fileObject - delegate to this file object

Method Detail

toUri

public URI toUri()

Description copied from interface: FileObject

Returns a URI identifying this file object.

Specified by:

toUri in interface FileObject

Returns:

a URI

getName

public String getName()

Description copied from interface: FileObject

Gets a user-friendly name for this file object.  The exact
 value returned is not specified but implementations should take
 care to preserve names as given by the user.  For example, if
 the user writes the filename "BobsApp\Test.java" on
 the command line, this method should return "BobsApp\Test.java" whereas the toUri
 method might return file:///C:/Documents%20and%20Settings/UncleBob/BobsApp/Test.java.

Specified by:

getName in interface FileObject

Returns:

a user-friendly name

openInputStream

public InputStream openInputStream()
                            throws IOException

Description copied from interface: FileObject

Gets an InputStream for this file object.

Specified by:

openInputStream in interface FileObject

Returns:

an InputStream

Throws:

IllegalStateException - if this file object was
 opened for writing and does not support reading

UnsupportedOperationException - if this kind of file
 object does not support byte access

IOException - if an I/O error occurred

openOutputStream

public OutputStream openOutputStream()
                              throws IOException

Description copied from interface: FileObject

Gets an OutputStream for this file object.

Specified by:

openOutputStream in interface FileObject

Returns:

an OutputStream

Throws:

IllegalStateException - if this file object was
 opened for reading and does not support writing

UnsupportedOperationException - if this kind of
 file object does not support byte access

IOException - if an I/O error occurred

openReader

public Reader openReader(boolean ignoreEncodingErrors)
                  throws IOException

Description copied from interface: FileObject

Gets a reader for this object.  The returned reader will
 replace bytes that cannot be decoded with the default
 translation character.  In addition, the reader may report a
 diagnostic unless ignoreEncodingErrors is true.

Specified by:

openReader in interface FileObject

Parameters:

ignoreEncodingErrors - ignore encoding errors if true

Returns:

a Reader

Throws:

IllegalStateException - if this file object was
 opened for writing and does not support reading

UnsupportedOperationException - if this kind of
 file object does not support character access

IOException - if an I/O error occurred

getCharContent

public CharSequence getCharContent(boolean ignoreEncodingErrors)
                            throws IOException

Description copied from interface: FileObject

Gets the character content of this file object, if available.
 Any byte that cannot be decoded will be replaced by the default
 translation character.  In addition, a diagnostic may be
 reported unless ignoreEncodingErrors is true.

Specified by:

getCharContent in interface FileObject

Parameters:

ignoreEncodingErrors - ignore encoding errors if true

Returns:

a CharSequence if available; null otherwise

Throws:

IllegalStateException - if this file object was
 opened for writing and does not support reading

UnsupportedOperationException - if this kind of
 file object does not support character access

IOException - if an I/O error occurred

openWriter

public Writer openWriter()
                  throws IOException

Description copied from interface: FileObject

Gets a Writer for this file object.

Specified by:

openWriter in interface FileObject

Returns:

a Writer

Throws:

IllegalStateException - if this file object was
 opened for reading and does not support writing

UnsupportedOperationException - if this kind of
 file object does not support character access

IOException - if an I/O error occurred

getLastModified

public long getLastModified()

Description copied from interface: FileObject

Gets the time this file object was last modified.  The time is
 measured in milliseconds since the epoch (00:00:00 GMT, January
 1, 1970).

Specified by:

getLastModified in interface FileObject

Returns:

the time this file object was last modified; or 0 if
 the file object does not exist, if an I/O error occurred, or if
 the operation is not supported

delete

public boolean delete()

Description copied from interface: FileObject

Deletes this file object.  In case of errors, returns false.

Specified by:

delete in interface FileObject

Returns:

true if and only if this file object is successfully
 deleted; false otherwise

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
<?php

namespace Devcamp\Bundle\SupporterBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SupporterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SupporterRepository extends EntityRepository
{
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Jb. nassau. Ver. Naturk. 23-24: (1870)

#### Original name
Puccinia rhododendri Fuckel

### Remarks
null


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Localization
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Web;

    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.ComponentModel;
    using DotNetNuke.Data;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Tabs;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Services.Installer.Packages;

    /// <summary>
    /// LocaleContrller provides method to manage all pages with localization content.
    /// </summary>
    /// <remarks>
    /// Content localization in DotNetNuke will allow you to easily manage your web pages in a primary language
    /// and then utilize translators to keep the content synchronized in multiple secondary languages.
    /// Whether you are maintaining your site in a single language or dozens of languages, the content localization system
    /// will help guide your content editors and translators through the process.  Although content localization required
    /// extensive changes to the core platform, we have been able to add this new feature while still improving overall system performance.
    /// </remarks>
    public class LocaleController : ComponentBase<ILocaleController, LocaleController>, ILocaleController
    {
        public static bool IsValidCultureName(string name)
        {
            return
                CultureInfo
                .GetCultures(CultureTypes.SpecificCultures)
                .Any(c => c.Name == name);
        }

        /// <summary>
        /// Determines whether the language can be delete.
        /// </summary>
        /// <param name="languageId">The language id.</param>
        /// <returns>
        ///   <c>true</c> if the language can be delete; otherwise, <c>false</c>.
        /// </returns>
        public bool CanDeleteLanguage(int languageId)
        {
            return PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType.Equals("CoreLanguagePack", StringComparison.OrdinalIgnoreCase))
                        .Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID))
                        .All(languagePack => languagePack.LanguageID != languageId);
        }

        /// <summary>
        /// Gets the cultures from local list.
        /// </summary>
        /// <param name="locales">The locales.</param>
        /// <returns>culture list.</returns>
        public List<CultureInfo> GetCultures(Dictionary<string, Locale> locales)
        {
            return locales.Values.Select(locale => new CultureInfo(locale.Code)).ToList();
        }

        /// <summary>
        /// Gets the current locale for current request to the portal.
        /// </summary>
        /// <param name="PortalId">The portal id.</param>
        /// <returns></returns>
        public Locale GetCurrentLocale(int PortalId)
        {
            Locale locale = null;

            if (HttpContext.Current != null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["language"]))
            {
                locale = this.GetLocale(HttpContext.Current.Request.QueryString["language"]);
            }

            return locale ?? ((PortalId == Null.NullInteger)
                                ? this.GetLocale(Localization.SystemLocale)
                                : this.GetDefaultLocale(PortalId));
        }

        /// <summary>
        /// Gets the default locale of the portal.
        /// </summary>
        /// <param name="portalId">The portal id.</param>
        /// <returns></returns>
        public Locale GetDefaultLocale(int portalId)
        {
            var portal = PortalController.Instance.GetPortal(portalId);
            Locale locale = null;
            if (portal != null)
            {
                Dictionary<string, Locale> locales = this.GetLocales(portal.PortalID);
                if (locales != null && locales.ContainsKey(portal.DefaultLanguage))
                {
                    locale = locales[portal.DefaultLanguage];
                }
            }

            return locale ?? this.GetLocale(Localization.SystemLocale);
        }

        /// <summary>
        /// Gets the locale by code.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <returns></returns>
        public Locale GetLocale(string code)
        {
            return this.GetLocale(Null.NullInteger, code);
        }

        /// <summary>
        /// Gets the locale included in the portal.
        /// </summary>
        /// <param name="portalID">The portal ID.</param>
        /// <param name="code">The code.</param>
        /// <returns></returns>
        public Locale GetLocale(int portalID, string code)
        {
            Dictionary<string, Locale> dicLocales = this.GetLocales(portalID);
            Locale locale = null;

            if (dicLocales != null)
            {
                dicLocales.TryGetValue(code, out locale);
            }

            return locale;
        }

        /// <summary>
        /// Gets the locale included in the portal if culture code is not null or empty
        /// or else gets the current locale for current request to the portal.
        /// </summary>
        /// <param name="portalID">The portal ID.</param>
        /// <param name="code">The code.</param>
        /// <returns></returns>
        public Locale GetLocaleOrCurrent(int portalID, string code)
        {
            return string.IsNullOrEmpty(code)
                       ? LocaleController.Instance.GetCurrentLocale(portalID) : LocaleController.Instance.GetLocale(portalID, code);
        }

        /// <summary>
        /// Gets the locale.
        /// </summary>
        /// <param name="languageID">The language ID.</param>
        /// <returns></returns>
        public Locale GetLocale(int languageID)
        {
            Dictionary<string, Locale> dicLocales = this.GetLocales(Null.NullInteger);

            return (from kvp in dicLocales where kvp.Value.LanguageId == languageID select kvp.Value).FirstOrDefault();
        }

        /// <summary>
        /// Gets the locales.
        /// </summary>
        /// <param name="portalID">The portal ID.</param>
        /// <returns></returns>
        public Dictionary<string, Locale> GetLocales(int portalID)
        {
            if (Globals.Status != Globals.UpgradeStatus.Error)
            {
                Dictionary<string, Locale> locales;
                if (Globals.Status != Globals.UpgradeStatus.Install)
                {
                    string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID);
                    locales = CBO.GetCachedObject<Dictionary<string, Locale>>(new CacheItemArgs(cacheKey, DataCache.LocalesCacheTimeOut, DataCache.LocalesCachePriority, portalID), GetLocalesCallBack, true);
                }
                else
                {
                    locales = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguages(), new Dictionary<string, Locale>(StringComparer.OrdinalIgnoreCase));
                }

                return locales;
            }

            return null;
        }

        /// <summary>
        /// Gets the published locales.
        /// </summary>
        /// <param name="portalID">The portal ID.</param>
        /// <returns></returns>
        public Dictionary<string, Locale> GetPublishedLocales(int portalID)
        {
            return this.GetLocales(portalID).Where(kvp => kvp.Value.IsPublished).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }

        /// <summary>
        /// Determines whether the specified locale code is enabled.
        /// </summary>
        /// <param name="localeCode">The locale code.</param>
        /// <param name="portalId">The portal id.</param>
        /// <returns>
        ///   <c>true</c> if the specified locale code is enabled; otherwise, <c>false</c>.
        /// </returns>
        public bool IsEnabled(ref string localeCode, int portalId)
        {
            try
            {
                bool enabled = false;
                Dictionary<string, Locale> dicLocales = this.GetLocales(portalId);

                // if ((!dicLocales.ContainsKey(localeCode)))
                string locale = localeCode;
                if (dicLocales.FirstOrDefault(x => x.Key.ToLower() == locale.ToLower()).Key == null)
                {
                    // if localecode is neutral (en, es,...) try to find a locale that has the same language
                    if (localeCode.IndexOf("-", StringComparison.Ordinal) == -1)
                    {
                        foreach (string strLocale in dicLocales.Keys)
                        {
                            if (strLocale.Split('-')[0].ToLower() == localeCode.ToLower())
                            {
                                // set the requested _localecode to the full locale
                                localeCode = strLocale;
                                enabled = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    enabled = true;
                }

                return enabled;
            }
            catch (Exception ex)
            {
                // item could not be retrieved  or error
                Exceptions.Exceptions.LogException(ex);
                return false;
            }
        }

        /// <summary>
        /// Updates the portal locale.
        /// </summary>
        /// <param name="locale">The locale.</param>
        public void UpdatePortalLocale(Locale locale)
        {
            DataProvider.Instance().UpdatePortalLanguage(locale.PortalId, locale.LanguageId, locale.IsPublished, UserController.Instance.GetCurrentUserInfo().UserID);
            DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, locale.PortalId));
        }

        /// <summary>
        /// Determines the language whether is default language.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <returns>
        ///   <c>true</c> if the language is default language; otherwise, <c>false</c>.
        /// </returns>
        public bool IsDefaultLanguage(string code)
        {
            bool returnValue = code == PortalController.Instance.GetCurrentPortalSettings().DefaultLanguage;
            return returnValue;
        }

        /// <summary>
        /// Activates the language without publishing it.
        /// </summary>
        /// <param name="portalid">The portalid.</param>
        /// <param name="cultureCode">The culture code.</param>
        /// <param name="publish">if set to <c>true</c> will publishthe language.</param>
        public void ActivateLanguage(int portalid, string cultureCode, bool publish)
        {
            Dictionary<string, Locale> enabledLanguages = Instance.GetLocales(portalid);
            Locale enabledlanguage;
            if (enabledLanguages.TryGetValue(cultureCode, out enabledlanguage))
            {
                enabledlanguage.IsPublished = publish;
                Instance.UpdatePortalLocale(enabledlanguage);
            }
        }

        /// <summary>
        /// Publishes the language.
        /// </summary>
        /// <param name="portalid">The portalid.</param>
        /// <param name="cultureCode">The culture code.</param>
        /// <param name="publish">if set to <c>true</c> will publishthe language.</param>
        public void PublishLanguage(int portalid, string cultureCode, bool publish)
        {
            Dictionary<string, Locale> enabledLanguages = Instance.GetLocales(portalid);
            Locale enabledlanguage;
            if (enabledLanguages.TryGetValue(cultureCode, out enabledlanguage))
            {
                enabledlanguage.IsPublished = publish;
                Instance.UpdatePortalLocale(enabledlanguage);
                if (publish)
                {
                    // only publish tabs if we actually need to do that
                    // we cannot "unpublish"
                    TabController.Instance.PublishTabs(TabController.GetTabsBySortOrder(portalid, cultureCode, false));
                }
            }
        }

        private static object GetLocalesCallBack(CacheItemArgs cacheItemArgs)
        {
            var portalID = (int)cacheItemArgs.ParamList[0];
            Dictionary<string, Locale> locales = CBO.FillDictionary("CultureCode", portalID > Null.NullInteger
                                                                       ? DataProvider.Instance().GetLanguagesByPortal(portalID)
                                                                       : DataProvider.Instance().GetLanguages(), new Dictionary<string, Locale>(StringComparer.OrdinalIgnoreCase));
            return locales;
        }
    }
}


text:
/* eslint-disable */

const _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol"
  ? (obj) => typeof obj
  : (obj) => obj && typeof Symbol === "function" && obj.constructor === Symbol
    ? "symbol"
    : typeof obj;

const hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * inlined Object.is polyfill to avoid requiring consumers ship their own
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
 */
function is(x, y) {
  // SameValue algorithm
  if (x === y) {
    // Steps 1-5, 7-10
    // Steps 6.b-6.e: +0 != -0
    return x !== 0 || 1 / x === 1 / y;
  } else {
    // Step 6.a: NaN == NaN
    return x !== x && y !== y;
  }
}

/**
 * Performs equality by iterating through keys on an object and returning false
 * when any key has values which are not strictly equal between the arguments.
 * Returns true when the values of all keys are strictly equal.
 */
function shallowEqual(objA, objB, options = {}) {
  if (is(objA, objB)) {
    return true;
  }

  if ((typeof objA === 'undefined' ? 'undefined' : _typeof(objA)) !== 'object' || objA === null || (typeof objB === 'undefined' ? 'undefined' : _typeof(objB)) !== 'object' || objB === null) {
    return false;
  }

  if(objA instanceof Date && objB instanceof Date) {
    return objA === objB;
  }

  const keysA = Object.keys(objA);
  const keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  }

  const {
    omitKeys,
    deepKeys,
  } = options;

  // Test for A's keys different from B.
  for (let i = 0; i < keysA.length; i++) {
    // if key is an omitted key, skip comparison
    if (omitKeys && omitKeys.length && ~omitKeys.indexOf(keysA[i])) continue;

    if (deepKeys && deepKeys.length && ~deepKeys.indexOf(keysA[i])) {
      const result = shallowEqual(objA[keysA[i]], objB[keysA[i]]);

      if (!result) return false;
    } else if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
      return false;
    }
  }

  return true;
}

export default shallowEqual;


text:
if __name__ == '__main__':
    n = int(input())
    integer_list = map(int, input().split())
    print(hash(tuple(integer_list)))


text:
* [Reflection](../classes/td.models.reflection.md)

### Implemented by
* [DeclarationReflection](../classes/td.models.declarationreflection.md)
* [ParameterReflection](../classes/td.models.parameterreflection.md)
* [SignatureReflection](../classes/td.models.signaturereflection.md)
* [TypeParameterReflection](../classes/td.models.typeparameterreflection.md)

## Index

### Constructors
* [constructor](td.models.itypecontainer.md#constructor)

### Properties
* [anchor](td.models.itypecontainer.md#anchor)
* [comment](td.models.itypecontainer.md#comment)
* [cssClasses](td.models.itypecontainer.md#cssclasses)
* [decorates](td.models.itypecontainer.md#decorates)
* [decorators](td.models.itypecontainer.md#decorators)
* [flags](td.models.itypecontainer.md#flags)
* [hasOwnDocument](td.models.itypecontainer.md#hasowndocument)
* [id](td.models.itypecontainer.md#id)
* [kind](td.models.itypecontainer.md#kind)
* [kindString](td.models.itypecontainer.md#kindstring)
* [name](td.models.itypecontainer.md#name)
* [originalName](td.models.itypecontainer.md#originalname)
* [parent](td.models.itypecontainer.md#parent)
* [sources](td.models.itypecontainer.md#sources)
* [type](td.models.itypecontainer.md#type)
* [url](td.models.itypecontainer.md#url)

### Methods
* [findReflectionByName](td.models.itypecontainer.md#findreflectionbyname)
* [getAlias](td.models.itypecontainer.md#getalias)
* [getChildByName](td.models.itypecontainer.md#getchildbyname)
* [getFullName](td.models.itypecontainer.md#getfullname)
* [hasComment](td.models.itypecontainer.md#hascomment)
* [hasGetterOrSetter](td.models.itypecontainer.md#hasgetterorsetter)
* [kindOf](td.models.itypecontainer.md#kindof)
* [setFlag](td.models.itypecontainer.md#setflag)
* [toObject](td.models.itypecontainer.md#toobject)
* [toString](td.models.itypecontainer.md#tostring)
* [toStringHierarchy](td.models.itypecontainer.md#tostringhierarchy)
* [traverse](td.models.itypecontainer.md#traverse)

## Constructors

### new ITypeContainer(parent?: [Reflection](../classes/td.models.reflection.md), name?: string, kind?: [ReflectionKind](../enums/td.models.reflectionkind.md)): [ITypeContainer](td.models.itypecontainer.md)
Create a new BaseReflection instance.
* Inherited from [Reflection](../classes/td.models.reflection.md).[constructor](../classes/td.models.reflection.md#constructor)
* Defined in [td/models/Reflection.ts:303](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L303)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| parent? | [Reflection](../classes/td.models.reflection.md)|  |
| name? | string|  |
| kind? | [ReflectionKind](../enums/td.models.reflectionkind.md)|  |

#### Returns: [ITypeContainer](td.models.itypecontainer.md)

## Properties

### anchor: string
The name of the anchor of this child.
* Inherited from [Reflection](../classes/td.models.reflection.md).[anchor](../classes/td.models.reflection.md#anchor)
* Defined in [td/models/Reflection.ts:281](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L281)

### comment: [Comment](../classes/td.models.comment.md)
The parsed documentation comment attached to this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[comment](../classes/td.models.reflection.md#comment)
* Defined in [td/models/Reflection.ts:256](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L256)

### cssClasses: string
A list of generated css classes that should be applied to representations of thisreflection in the generated markup.
* Inherited from [Reflection](../classes/td.models.reflection.md).[cssClasses](../classes/td.models.reflection.md#cssclasses)
* Defined in [td/models/Reflection.ts:294](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L294)

### decorates: [Type](../classes/td.models.type.md)[]
A list of all types that are decorated by this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[decorates](../classes/td.models.reflection.md#decorates)
* Defined in [td/models/Reflection.ts:271](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L271)

### decorators: [IDecorator](td.models.idecorator.md)[]
A list of all decorators attached to this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[decorators](../classes/td.models.reflection.md#decorators)
* Defined in [td/models/Reflection.ts:266](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L266)

### flags: [IReflectionFlags](td.models.ireflectionflags.md)

* Inherited from [Reflection](../classes/td.models.reflection.md).[flags](../classes/td.models.reflection.md#flags)
* Defined in [td/models/Reflection.ts:246](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L246)

### hasOwnDocument: boolean
Is the url pointing to an individual document?When FALSE, the url points to an anchor tag on a page of a different reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[hasOwnDocument](../classes/td.models.reflection.md#hasowndocument)
* Defined in [td/models/Reflection.ts:288](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L288)

### id: number
Unique id of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[id](../classes/td.models.reflection.md#id)
* Defined in [td/models/Reflection.ts:224](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L224)

### kind: [ReflectionKind](../enums/td.models.reflectionkind.md)
The kind of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[kind](../classes/td.models.reflection.md#kind)
* Defined in [td/models/Reflection.ts:239](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L239)

### kindString: string
The human readable string representation of the kind of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[kindString](../classes/td.models.reflection.md#kindstring)
* Defined in [td/models/Reflection.ts:244](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L244)

### name: string
The symbol name of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[name](../classes/td.models.reflection.md#name)
* Defined in [td/models/Reflection.ts:229](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L229)

### originalName: string
The original name of the TypeScript declaration.
* Inherited from [Reflection](../classes/td.models.reflection.md).[originalName](../classes/td.models.reflection.md#originalname)
* Defined in [td/models/Reflection.ts:234](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L234)

### parent: [Reflection](../classes/td.models.reflection.md)
The reflection this reflection is a child of.
* Inherited from [Reflection](../classes/td.models.reflection.md).[parent](../classes/td.models.reflection.md#parent)
* Defined in [td/models/Reflection.ts:251](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L251)

### sources: [ISourceReference](td.models.isourcereference.md)[]
A list of all source files that contributed to this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[sources](../classes/td.models.reflection.md#sources)
* Defined in [td/models/Reflection.ts:261](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L261)

### type: [Type](../classes/td.models.type.md)

* Defined in [td/models/Reflection.ts:157](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L157)

### url: string
The url of this reflection in the generated documentation.
* Inherited from [Reflection](../classes/td.models.reflection.md).[url](../classes/td.models.reflection.md#url)
* Defined in [td/models/Reflection.ts:276](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L276)

## Methods

### findReflectionByName(name: string): [Reflection](../classes/td.models.reflection.md)findReflectionByName(names: string[]): [Reflection](../classes/td.models.reflection.md)
Try to find a reflection by its name.
* Inherited from [Reflection](../classes/td.models.reflection.md).[findReflectionByName](../classes/td.models.reflection.md#findreflectionbyname)
* Defined in [td/models/Reflection.ts:515](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L515)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| name | string| The name to look for. Might contain a hierarchy. |

#### Returns: [Reflection](../classes/td.models.reflection.md)
The found reflection or null.

Try to find a reflection by its name.
* Inherited from [Reflection](../classes/td.models.reflection.md).[findReflectionByName](../classes/td.models.reflection.md#findreflectionbyname)
* Defined in [td/models/Reflection.ts:520](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L520)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| names | string[]| The name hierarchy to look for. |

#### Returns: [Reflection](../classes/td.models.reflection.md)
The found reflection or null.

### getAlias(): string
Return an url safe alias for this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[getAlias](../classes/td.models.reflection.md#getalias)
* Defined in [td/models/Reflection.ts:436](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L436)

#### Returns: string

### getChildByName(name: string): [Reflection](../classes/td.models.reflection.md)getChildByName(names: string[]): [Reflection](../classes/td.models.reflection.md)
Return a child by its name.
* Inherited from [Reflection](../classes/td.models.reflection.md).[getChildByName](../classes/td.models.reflection.md#getchildbyname)
* Defined in [td/models/Reflection.ts:481](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L481)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| name | string| The name of the child to look for. Might contain a hierarchy. |

#### Returns: [Reflection](../classes/td.models.reflection.md)
The found child or NULL.

Return a child by its name.
* Inherited from [Reflection](../classes/td.models.reflection.md).[getChildByName](../classes/td.models.reflection.md#getchildbyname)
* Defined in [td/models/Reflection.ts:486](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L486)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| names | string[]| The name hierarchy of the child to look for. |

#### Returns: [Reflection](../classes/td.models.reflection.md)
The found child or NULL.

### getFullName(separator = ".": string): string
Return the full name of this reflection.The full name contains the name of this reflection and the names of all parent reflections.
* Inherited from [Reflection](../classes/td.models.reflection.md).[getFullName](../classes/td.models.reflection.md#getfullname)
* Defined in [td/models/Reflection.ts:354](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L354)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| separator = "." | string| Separator used to join the names of the reflections. |

#### Returns: string
The full name of this reflection.

### hasComment(): boolean
Has this reflection a visible comment?
* Inherited from [Reflection](../classes/td.models.reflection.md).[hasComment](../classes/td.models.reflection.md#hascomment)
* Defined in [td/models/Reflection.ts:468](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L468)

#### Returns: boolean
TRUE when this reflection has a visible comment.

### hasGetterOrSetter(): boolean

* Inherited from [Reflection](../classes/td.models.reflection.md).[hasGetterOrSetter](../classes/td.models.reflection.md#hasgetterorsetter)
* Defined in [td/models/Reflection.ts:473](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L473)

#### Returns: boolean

### kindOf(kind: [ReflectionKind](../enums/td.models.reflectionkind.md)): booleankindOf(kind: [ReflectionKind](../enums/td.models.reflectionkind.md)[]): boolean
Test whether this reflection is of the given kind.
* Inherited from [Reflection](../classes/td.models.reflection.md).[kindOf](../classes/td.models.reflection.md#kindof)
* Defined in [td/models/Reflection.ts:322](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L322)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| kind | [ReflectionKind](../enums/td.models.reflectionkind.md)| The kind to test for. |

#### Returns: boolean
Test whether this reflection is of the given kind.
* Inherited from [Reflection](../classes/td.models.reflection.md).[kindOf](../classes/td.models.reflection.md#kindof)
* Defined in [td/models/Reflection.ts:327](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L327)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| kind | [ReflectionKind](../enums/td.models.reflectionkind.md)[]| An array of kinds to test for. |

#### Returns: boolean

### setFlag(flag: [ReflectionFlag](../enums/td.models.reflectionflag.md), value = true: boolean): void
Set a flag on this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[setFlag](../classes/td.models.reflection.md#setflag)
* Defined in [td/models/Reflection.ts:366](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L366)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| flag | [ReflectionFlag](../enums/td.models.reflectionflag.md)|  |
| value = true | boolean|  |

#### Returns: void

### toObject(): any
Return a raw object representation of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[toObject](../classes/td.models.reflection.md#toobject)
* Defined in [td/models/Reflection.ts:553](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L553)

#### Returns: any

### toString(): string
Return a string representation of this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[toString](../classes/td.models.reflection.md#tostring)
* Defined in [td/models/Reflection.ts:603](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L603)

#### Returns: string

### toStringHierarchy(indent = "": string): string
Return a string representation of this reflection and all of its children.
* Inherited from [Reflection](../classes/td.models.reflection.md).[toStringHierarchy](../classes/td.models.reflection.md#tostringhierarchy)
* Defined in [td/models/Reflection.ts:613](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L613)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| indent = "" | string| Used internally to indent child reflections. |

#### Returns: string

### traverse(callback: [ITraverseCallback](td.models.itraversecallback.md)): void
Traverse all potential child reflections of this reflection.The given callback will be invoked for all children, signatures and type parametersattached to this reflection.
* Inherited from [Reflection](../classes/td.models.reflection.md).[traverse](../classes/td.models.reflection.md#traverse)
* Defined in [td/models/Reflection.ts:547](https://github.com/kimamula/typedoc/blob/HEAD/src/td/models/Reflection.ts#L547)

#### Parameters

| Name | Type | Description |
| ---- | ---- | ---- |
| callback | [ITraverseCallback](td.models.itraversecallback.md)| The callback function that should be applied for each child reflection. |

#### Returns: void

Generated using [TypeDoc](http://typedoc.io)


text:
<?php

namespace League\Csv\Exception;

use InvalidArgumentException;

/**
 *  Thrown when a data is not validated prior to insertion
 *
 * @package League.csv
 * @since  7.0.0
 *
 */
class InvalidRowException extends \InvalidArgumentException
{
    /**
     * Validator which did not validated the data
     * @var string
     */
    private $name;

    /**
     * Validator Data which caused the error
     * @var array
     */
    private $data;

    /**
     * New Instance
     *
     * @param string $name    validator name
     * @param array  $data    invalid  data
     * @param string $message exception message
     */
    public function __construct($name, array $data = [], $message = "")
    {
        parent::__construct($message);
        $this->name = $name;
        $this->data = $data;
    }

    /**
     * return the validator name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * return the invalid data submitted
     *
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }
}


text:
"use strict";

var demo4 = require("@training4developers/demo4");

demo4("test!");


text:
<?php
namespace Soluble\Db\Compat\Exception;

class UnsupportedDriverException extends \ErrorException
{
}


text:
/**
 * @ngdoc directive
 * @name ionView
 * @module ionic
 * @restrict E
 * @parent ionNavView
 *
 * @description
 * A container for view content and any navigational and header bar information. When a view
 * enters and exists its parent {@link ionic.directive:ionNavView}, the view also emits view
 * information, such as its title, whether the back button should show or not, whether the
 * corresponding {@link ionic.directive:ionNavBar} should show or not, which transition the view
 * should use to animate, and which direction to animate.
 *
 * *Views are cached to improve performance.* When a view is navigated away from, its element is
 * left in the DOM, and its scope is disconnected from the `$watch` cycle. When navigating to a
 * view that is already cached, its scope is reconnected, and the existing element, which was
 * left in the DOM, becomes active again. This can be disabled, or the maximum number of cached
 * views changed in {@link ionic.directive:ionicConfig}, in the view's `$state` configuration, or
 * as an attribute on the view itself (see below).
 *
 * @usage
 * Below is an example where our page will load with a {@link ionic.directive:ionNavBar} containing
 * "My Page" as the title.
 *
 * ```html
 * <ion-nav-bar></ion-nav-bar>
 * <ion-nav-view>
 *   <ion-view view-title="My Page">
 *     <ion-content>
 *       Hello!
 *     </ion-content>
 *   </ion-view>
 * </ion-nav-view>
 * ```
 *
 * ## View LifeCycle and Events
 *
 * Views can be cached, which means ***controllers normally only load once***, which may
 * affect your controller logic. To know when a view has entered or left, events
 * have been added that are emitted from the view's scope. These events also
 * contain data about the view, such as the title and whether the back button should
 * show. Also contained is transition data, such as the transition type and
 * direction that will be or was used.
 *
 *

 *

 *   $ionicView.loaded
 *   The view has loaded. This event only happens once per
 * view being created and added to the DOM. If a view leaves but is cached,
 * then this event will not fire again on a subsequent viewing. The loaded event
 * is good place to put your setup code for the view; however, it is not the
 * recommended event to listen to when a view becomes active.
 *

 *

 *   $ionicView.enter
 *   The view has fully entered and is now the active view.
 * This event will fire, whether it was the first load or a cached view.
 *

 *

 *   $ionicView.leave
 *   The view has finished leaving and is no longer the
 * active view. This event will fire, whether it is cached or destroyed.
 *

 *

 *   $ionicView.beforeEnter
 *   The view is about to enter and become the active view.
 *

 *

 *   $ionicView.beforeLeave
 *   The view is about to leave and no longer be the active view.
 *

 *

 *   $ionicView.afterEnter
 *   The view has fully entered and is now the active view.
 *

 *

 *   $ionicView.afterLeave
 *   The view has finished leaving and is no longer the active view.
 *

 *

 *   $ionicView.unloaded
 *   The view's controller has been destroyed and its element has been
 * removed from the DOM.
 *

 *

 *
 * ## Caching
 *
 * Caching can be disabled and enabled in multiple ways. By default, Ionic will
 * cache a maximum of 10 views. You can optionally choose to disable caching at
 * either an individual view basis, or by global configuration. Please see the
 * _Caching_ section in {@link ionic.directive:ionNavView} for more info.
 *
 * @param {string=} view-title A text-only title to display on the parent {@link ionic.directive:ionNavBar}.
 * For an HTML title, such as an image, see {@link ionic.directive:ionNavTitle} instead.
 * @param {boolean=} cache-view If this view should be allowed to be cached or not.
 * Please see the _Caching_ section in {@link ionic.directive:ionNavView} for
 * more info. Default `true`
 * @param {boolean=} hide-back-button Whether to hide the back button on the parent
 * {@link ionic.directive:ionNavBar} by default.
 * @param {boolean=} hide-nav-bar Whether to hide the parent
 * {@link ionic.directive:ionNavBar} by default.
 */
IonicModule
.directive('ionView', function() {
  return {
    restrict: 'EA',
    priority: 1000,
    controller: '$ionicView',
    compile: function(tElement) {
      tElement.addClass('pane');
      tElement[0].removeAttribute('title');
      return function link($scope, $element, $attrs, viewCtrl) {
        viewCtrl.init();
      };
    }
  };
});


text:
package com.glub.secureftp.wrapper.config;

import com.glub.secureftp.wrapper.*;
import com.glub.secureftp.common.*;

import java.io.*;
import java.util.*;

public class CertificateDataEntry {
  private PrintStream out = System.out;
  private BufferedReader stdin =
                           new BufferedReader(new InputStreamReader(System.in));
  private ServerInfo info = null;

  private String commonName = "";
  private String organization = "";
  private String unit = "";
  private String city = "";
  private String state = "";
  private String country = "";
  private int    days = 1025;

  private String caCertPath = "";
  private String privateKeyPath = "";
  private String publicCertPath = "";

  public CertificateDataEntry( ServerInfo info ) {
    this.info = info;
  }

  public void getData() throws CommandException {
    boolean boolResult = false;

    ArrayList response = new ArrayList(1);

    try {
      if ( getBoolean("Do you want to generate a certificate?",
                      getYN(true), response) ) {
        boolResult = ((Boolean)response.get(0)).booleanValue();

      }

      if ( boolResult ) {
        getCN();
        getO();
        getOU();
        getCity();
        getState();
        getCountry();
        getDays();
        generateCert();
     }
     else {
       getPrivateKey();
       getPublicCert();
       getCACerts();

       File privFile = new File( privateKeyPath );
       File pubFile = new File( publicCertPath );

       if ( privFile.exists() && pubFile.exists() ) {
         info.setPublicCert( pubFile );
         info.setPrivateKey( privFile );

         if ( caCertPath != null ) {
           info.setCACertsFromString( caCertPath );
         }

         try {
           ConfigurationManager.getInstance().writeConfiguration();
         }
         catch ( IOException ioe ) {
           System.out.println("Problem writing configuration: " +
                              ioe.getMessage());
         }
       }
       else {
           System.out.println("At least one of the files cannot be found.");
       }
     }
    }
    catch ( IOException ioe ) {
    }
  }

  protected void generateCert() {
    String certPrefix = info.getServerID();

    if ( info.getExplicitEnabled() ) {
      certPrefix += "_" + info.getExplicitPort();
    }

    if ( info.getImplicitEnabled() ) {
      certPrefix += "_" + info.getImplicitPort();
    }

    File configDir = new File( System.getProperty("user.dir") );
    File publicCertFile = new File( configDir, certPrefix + "_certificate.der" );
    File privateKeyFile = new File( configDir, certPrefix + "_private.pk8" );

    CertInfo certInfo =
      new CertInfo( commonName, organization, unit, city, state, country );

    boolean certGenerated =
      KeyUtil.writeCertAndKey( certInfo, days, publicCertFile, privateKeyFile );

    if ( certGenerated ) {
      info.setPublicCert( publicCertFile );
      info.setPrivateKey( privateKeyFile );

      try {
        ConfigurationManager.getInstance().writeConfiguration();
      }
      catch ( IOException ioe ) {
        System.out.println("Problem writing configuration: " +
                           ioe.getMessage());
      }
    }
  }

  protected void getCACerts() throws IOException {
    ArrayList response = new ArrayList(1);

    String def = "";
    if ( info.getCACertsAsString() != null) {
      def = info.getCACertsAsString();
    }

    getResponse("Absolute path to the CA cert", def, response);

    caCertPath = ((String)response.get(0)).toString();
  }

  protected void getPrivateKey() throws IOException {
    ArrayList response = new ArrayList(1);

    String def = "";
    if ( info.getPrivateKey() != null) {
      def = info.getPrivateKey().getAbsolutePath();
    }

    getResponse("Absolute path to Private key", def, response);
    String fileStr = ((String)response.get(0)).toString();
    File file = new File( fileStr );
    if ( !file.exists() ) {
      System.out.println( "WARNING: File not found." );
    }
    privateKeyPath = fileStr;
  }

  protected void getPublicCert() throws IOException {
    ArrayList response = new ArrayList(1);

    String def = "";
    if ( info.getPublicCert() != null) {
      def = info.getPublicCert().getAbsolutePath();
    }

    getResponse("Absolute path to Public cert", def, response);

    String fileStr = ((String)response.get(0)).toString();
    File file = new File( fileStr );
    if ( !file.exists() ) {
      System.out.println( "WARNING: File not found." );
    }
    publicCertPath = fileStr;
  }

  protected void getCN() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter the hostname", info.getServerID(), response);
    commonName = ((String)response.get(0)).toString();
  }

  protected void getO() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter your company's name", response);
    organization = ((String)response.get(0)).toString();
  }

  protected void getOU() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter your department", response);
    unit = ((String)response.get(0)).toString();
  }

  protected void getCity() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter your city", response);
    city = ((String)response.get(0)).toString();
  }

  protected void getState() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter your state", response);
    state = ((String)response.get(0)).toString();
  }

  protected void getCountry() throws IOException {
    ArrayList response = new ArrayList(1);

    getResponse("Enter your country", response);
    country = ((String)response.get(0)).toString();
  }

  protected void getDays() throws IOException {
    ArrayList response = new ArrayList(1);

    getInteger("Enter number of days cert is valid", "1025", response);
    days = ((Integer)response.get(0)).intValue();
  }

  protected boolean getResponse( String question,
                                 ArrayList response ) throws IOException {
    return getResponse( question, "", response );
  }

  protected boolean getResponse( String question, String def,
                                 ArrayList response ) throws IOException {
    boolean result = false;

    response.clear();

    if ( null != def )
      out.print(question + " [" + def + "]: ");
    else
      out.print(question + ": ");

    String in = stdin.readLine().trim();

    if ( in.length() > 0 )
      result = true;

    if ( in.length() == 0 ) {
      in = def;
    }

    response.add( in );

    return result;
  }

  protected boolean getInteger( String question, String def,
                                ArrayList response ) throws IOException {
    boolean result = getResponse( question, def, response );

    String responseStr = (String)response.get(0);

    Integer intResult = new Integer(def);
    try {
      intResult = new Integer(responseStr);
    }
    catch ( Exception e ) {}

    response.clear();
    response.add( intResult );

    return result;
  }

  protected boolean getBoolean( String question, String def,
                                ArrayList response ) throws IOException {
    boolean result = getResponse( question, def, response );

    String responseStr = (String)response.get(0);

    boolean boolResult = responseStr.equalsIgnoreCase(def);

    if ( responseStr.equalsIgnoreCase("y") ) {
      boolResult = true;
    }
    else {
      boolResult = false;
    }

    response.clear();
    response.add( new Boolean(boolResult) );

    if ( !result && boolResult ) {
      result = boolResult;
    }

    return result;
  }

  private String getYN( boolean doIt ) {
    if ( doIt )
      return "y";
    else
      return "n";
  }
}


text:
using System.Collections.Generic;
using System.Linq;

namespace GameEngine.Data.Tiles.Behaviors {
	public class TileBehaviorCollection : List<TileBehavior> {
		public static TileBehaviorCollection FromList(List<TileBehavior> l) {
			TileBehaviorCollection c = new TileBehaviorCollection();
			c.AddRange(l);
			return c;
		}

		public TileBehavior Get(byte id) {
			return this.FirstOrDefault(t => t.Id == id);
		}

		/// <summary>
		/// Returns a collection of behaviors container the tag.
		/// </summary>
		public TileBehaviorCollection Select(string tag) {
			return GetBehaviors(tag);
		}

		/// <summary>
		/// Returns a collection of behaviors containing the identifier and tag data.
		/// </summary>
		public TileBehaviorCollection Select(string identifier, object value) {
			return GetBehaviors(identifier, value);
		}

		/// <summary>
		/// Returns a collection of behaviors container the tag.
		/// </summary>
		public TileBehaviorCollection GetBehaviors(string tag) {
			return TileBehaviorCollection.FromList(this.Where(u => u.Tags.Contains(tag)).ToList());
		}

		/// <summary>
		/// Returns a collection of behaviors containing the identifier and tag data.
		/// </summary>
		public TileBehaviorCollection GetBehaviors(string identifier, object value) {
			TileBehaviorCollection c = new TileBehaviorCollection();
			c.AddRange(this.Where(t => t.Datas.Any(tuple => tuple.Item1 == identifier && tuple.Item2 == value)));
			return c;
		}
	}
}


text:
require 'launchable_item'

class HoneyPot

  def self.cached_marketplace_by_item(params)
    marketplace_item = find_by(params)

    if marketplace_item
      return  LaunchableItem.new(params, marketplace_item)
    end
  end

  def self.cached_marketplace_groups(params)
    Rails.cache.fetch("honeypot", expires_in: 10.minutes) do
      Api::Marketplaces.instance.list(params).marketplace_groups
    end
  end

  private

  def self.find_by(params)
    Rails.cache.fetch("honeypot_#{params['id']}", expires_in: 10.minutes) do
      Api::Marketplaces.instance.show(params).item
    end
  end
end


text:
"""Decorators for assigning DoFn types to specific storage models."""

from __future__ import annotations

import collections
import inspect
import itertools
import re

from core.jobs import job_utils
from core.jobs.types import base_validation_errors
from core.jobs.types import model_property
from core.platform import models

import apache_beam as beam
from apache_beam import typehints

(base_models,) = models.Registry.import_models([models.NAMES.base_model])

datastore_services = models.Registry.import_datastore_services()

_ALL_MODEL_TYPES = frozenset(models.Registry.get_all_storage_model_classes())
_ALL_BASE_MODEL_TYPES = frozenset(
    models.Registry.get_storage_model_classes([models.NAMES.base_model]))

_MODEL_TYPES_BY_BASE_CLASS = {
    base_class: frozenset({base_class}).union(
        t for t in _ALL_MODEL_TYPES if issubclass(t, base_class))
    for base_class in _ALL_BASE_MODEL_TYPES
}

class AuditsExisting:
    """Decorator for registering DoFns that audit storage models.

    DoFns registered by this decorator should assume that the models they
    receive as input do not have `deleted=True`.

    When decorating a DoFn that inherits from another, it overwrites the base
    class. For example, ValidateExplorationModelId overwrites ValidateModelId if
    and only if ValidateExplorationModelId inherits from ValidateModelId.
    """

    _DO_FN_TYPES_BY_KIND = collections.defaultdict(set)

    def __init__(self, *model_types):
        """Initializes the decorator to target the given types of models.

        Args:
            *model_types: tuple(class). The models the decorator will target. If
                an argument is a base class, all of its subclasses will be
                targeted as well.

        Raises:
            ValueError. No model given.
            TypeError. When a non-model type is provided.
        """
        if not model_types:
            raise ValueError('Must target at least one model')
        self._targeted_model_types = set()
        for t in model_types:
            if t in _MODEL_TYPES_BY_BASE_CLASS:
                self._targeted_model_types.update(_MODEL_TYPES_BY_BASE_CLASS[t])
            elif t in _ALL_MODEL_TYPES:
                self._targeted_model_types.add(t)
            else:
                raise TypeError(
                    '%r is not a model registered in core.platform' % t)
        self._targeted_kinds = {
            job_utils.get_model_kind(t) for t in self._targeted_model_types
        }

    def __call__(self, do_fn_type):
        """Decorator which registers the given DoFn to the targeted models.

        This decorator also installs type constraints on the DoFn to guard it
        from invalid argument types.

        Args:
            do_fn_type: type(DoFn). The new audting DoFn class to decorate.

        Returns:
            type(DoFn). The decorated DoFn.

        Raises:
            TypeError. When the new type is not a DoFn.
        """
        if not issubclass(do_fn_type, beam.DoFn):
            raise TypeError('%r is not a subclass of DoFn' % do_fn_type)

        # The "mro" (method resolution order) of a class is the list of types
        # the class is derived from, including itself, in the order they are
        # searched for methods and attributes.
        # To learn more, see: https://stackoverflow.com/a/2010732/4859885.
        base_types_of_do_fn_type = set(inspect.getmro(do_fn_type))

        for kind in self._targeted_kinds:
            registered_do_fn_types = self._DO_FN_TYPES_BY_KIND[kind]
            if any(issubclass(r, do_fn_type) for r in registered_do_fn_types):
                # Always keep the most-derived DoFn type.
                continue
            registered_do_fn_types -= base_types_of_do_fn_type
            registered_do_fn_types.add(do_fn_type)

        # Decorate the DoFn with type constraints that raise an error when args
        # or return values have the wrong type.
        with_input_types, with_output_types = (
            typehints.with_input_types(
                typehints.Union[self._targeted_model_types]),
            typehints.with_output_types(base_validation_errors.BaseAuditError))
        return with_input_types(with_output_types(do_fn_type))

    @classmethod
    def get_audit_do_fn_types_by_kind(cls):
        """Returns the sets of audit DoFns targeting a kind of model.

        Returns:
            dict(str: frozenset(type(DoFn))). DoFn types, keyed by the kind of
            model they have targeted.
        """
        return {
            kind: frozenset(do_fn_types)
            for kind, do_fn_types in cls._DO_FN_TYPES_BY_KIND.items()
        }

class RelationshipsOf:
    """Decorator for describing {Model.property: Model.ID} relationships.

    This decorator adds a domain-specific language (DSL) for defining the
    relationship between model properties and the IDs of related models.

    The name of the function is enforced by the decorator so that code reads
    intuitively:
        "Relationships Of [MODEL_CLASS]
        "define model_relationships(model):
            yield model.property, [RELATED_MODELS...]

    Example:
        @RelationshipsOf(UserAuthDetailsModel)
        def user_auth_details_model_relationships(model):
            yield (model.id, [UserSettingsModel])
            yield (model.firebase_auth_id, [UserIdByFirebaseAuthId])
            yield (model.gae_id, [UserIdentifiersModel])
    """

    # A dict(ModelProperty: set(str)). The keys are properties of a model whose
    # values refer to the IDs of their corresponding set of model kinds.
    _ID_REFERENCING_PROPERTIES = collections.defaultdict(set)

    def __init__(self, model_class):
        """Initializes a new RelationshipsOf decorator.

        Args:
            model_class: class. A subclass of BaseModel.
        """
        self._model_kind = self._get_model_kind(model_class)
        self._model_class = model_class

    def __call__(self, model_relationships):
        """Registers the property relationships of self._model_kind yielded by
        the generator.

        See RelationshipsOf's docstring for a usage example.

        Args:
            model_relationships: callable. Expected to yield tuples of type
                (Property, list(class)), where the properties are from the
                argument provided to the function.

        Returns:
            generator. The same object.
        """
        self._validate_name_of_model_relationships(model_relationships)

        yielded_items = model_relationships(self._model_class)
        for property_instance, referenced_models in yielded_items:
            property_of_model = model_property.ModelProperty(
                self._model_class, property_instance)
            self._ID_REFERENCING_PROPERTIES[property_of_model].update(
                self._get_model_kind(m)
                for m in referenced_models if m is not self._model_class)

        return model_relationships

    @classmethod
    def get_id_referencing_properties_by_kind_of_possessor(cls):
        """Returns properties whose values refer to the IDs of the corresponding
        set of model kinds, grouped by the kind of model the properties belong
        to.

        Returns:
            dict(str, tuple(tuple(ModelProperty, tuple(str)))). Tuples of
            (ModelProperty, set(kind of models)), grouped by the kind of model
            the properties belong to.
        """
        by_kind = lambda model_property: model_property.model_kind
        id_referencing_properties_by_kind_of_possessor = itertools.groupby(
            sorted(cls._ID_REFERENCING_PROPERTIES.keys(), key=by_kind),
            key=by_kind)
        references_of = lambda p: cls._ID_REFERENCING_PROPERTIES[p]
        return {
            kind: tuple((p, tuple(references_of(p))) for p in properties)
            for kind, properties in (
                id_referencing_properties_by_kind_of_possessor)
        }

    @classmethod
    def get_all_model_kinds_referenced_by_properties(cls):
        """Returns all model kinds that are referenced by another's property.

        Returns:
            set(str). All model kinds referenced by one or more properties,
            excluding the models' own ID.
        """
        return set(itertools.chain.from_iterable(
            cls._ID_REFERENCING_PROPERTIES.values()))

    @classmethod
    def get_model_kind_references(cls, model_kind, property_name):
        """Returns the kinds of models referenced by the given property.

        Args:
            model_kind: str. The kind of model the property belongs to.
            property_name: str. The property's name.

        Returns:
            list(str). The kinds of models referenced by the given property.
        """
        model_cls = job_utils.get_model_class(model_kind)
        prop = model_property.ModelProperty(
            model_cls, getattr(model_cls, property_name))
        return cls._ID_REFERENCING_PROPERTIES.get(prop, set())

    def _get_model_kind(self, model_class):
        """Returns the kind of the model class.

        Args:
            model_class: BaseModel. A subclass of BaseModel.

        Returns:
            str. The model's kind.

        Raises:
            TypeError. The model class is not a subclass of BaseModel.
        """
        if not isinstance(model_class, type):
            raise TypeError('%r is an instance, not a type' % model_class)
        if not issubclass(model_class, base_models.BaseModel):
            raise TypeError(
                '%s is not a subclass of BaseModel' % model_class.__name__)
        return job_utils.get_model_kind(model_class)

    def _validate_name_of_model_relationships(self, model_relationships):
        """Checks that the model_relationships function has the expected name.

        Args:
            model_relationships: callable. The function to validate.

        Raises:
            ValueError. The function is named incorrectly.
        """
        lower_snake_case_model_kind = (
            # Source: https://stackoverflow.com/a/1176023/4859885.
            re.sub(r'(?<!^)(?=[A-Z])', '_', self._model_kind).lower())
        expected_name = '%s_relationships' % lower_snake_case_model_kind
        actual_name = model_relationships.__name__
        if actual_name != expected_name:
            raise ValueError('Please rename the function from "%s" to "%s"' % (
                actual_name, expected_name))


text:
title: Dockerfile best practices
date: "2022-11-15T20:00:00+01:00"
tags:
- docker
- dockerfile
---

![Docker](cover.webp)

In this blog post, I will list the best practices when creating Dockerfiles. By
following these points, you can gain more confidence that your docker images are
secure and reliable.

# Use non-root user
The first and most important point when it comes to creating Dockerfiles is the avoidance
of running images using the root user. This is a key point if you want your docker
image to be as secure as possible. By default, Docker is using root as an account
that is performing all build steps and then running the docker entry-point
executable. By leaving the root user as it is and allowing programs inside
containers to be run by root, you are exposing yourself to huge risks. There are
cases when properly prepared, the exploit can escape the docker container due to root
privileges. When you are using a limited privilege account, such incidents are
close to impossible. The next thing is the risk when mounting directories to the docker
container. This is especially dangerous when you don't have access to
the Dockerfile of the image that you are running, and you don't know what is going on
under the hood. This might cause problems with files on a docker host, for example
removing important system configurations. To avoid such problems, always define
your custom user in Dockerfile:

```dockerfile
FROM ubuntu
RUN useradd -ms /bin/bash myuser
USER myuser
```

As an alternative, you can use an already existing non-root user from `/etc/passwd` in
base image.

If you want to run a docker image and force a user, you can use `-u` parameter. It
takes on option in the form `UID:GID`. So if you want to run some command as user
which UID and GID is 100 then add `-u` parameter like that:

```bash
docker run -u 100:100 ...
```

# Labels, volume, and expose aka documentation
Try to always define all labels that will help users of your image gain
knowledge about it very quickly. For example, you can add an author label to
give the user a contact point in case of problems with the image:

```dockerfile
LABEL org.opencontainers.image.authors="user@example.com"
```
Labels are commonly used to store information about the application and
dependencies version, for example, the base image tag. Labels have a form of
key-value pairs, so you are not limited to any kind of constraints when defining
Then.

The next documentation part of the Dockerfile is the `VOLUME` command. It has two main
roles. Firstly, it creates an external volume that will persist after the docker
run and makes sure that data that was defined in Dockerfile in the volume path
is copied to a new persistent volume. The next thing is information for the user that
a given directory in the docker container can be mounted to a custom location and
the contents of this directory are persistent.

The last documentation beat is the `EXPOSE` statement. It has a form of port and optional
protocol for example:

```dockerfile
EXPOSE 8080/tcp
```

This statement will help users quickly learn what ports are used by default by
applications built using a given Dockerfile. Those ports will also be listed along
with docker containers when the user gets the list of them via the `docker ps` command.

# Order of operations and frequency of changes
If you want to build your image as fast as possible, you need to order operations
in Dockerfile in a proper way. If you do it like that, then it will be possible to
reuse as many docker image layers as possible and run actual building commands
only in a few of them. This will improve build speed significantly. A general rule
of order of operations is that you need to put layers that will change most
often as the last ones in Dockerfile. Let's see the example of creating a Python docker
image with some web application in it:

```dockerfile
FROM python:3

# This section will probably not change
RUN mkdir /app
WORKDIR /app

# Dependencies will not change too often
ADD requirements.txt /app
RUN pip install -r /app/requirements.txt

# source code will change very often
ADD server.py /app
CMD [ "python", "./server.py" ]
```

By writing our Dockerfile like that, we make sure that when the source code is
changed (server.py file in that case)
building this image will take a very short. This is because all layers
including one with the installation of dependencies are reused in that case.
This will also impact network transfer times when you will push or pull your
image. If only the last few layers are modified then the rest of them will be reused
and downloading and uploading the image will take less time.

# Don't use the latest tag
It might be tempting to always tag your images using `latest` tags, but you
should avoid it. This tag can be very dangerous. Especially when your
production build is designed to use it.

In that case, we can imagine a situation where we update our application and the latest
tag is pushed. Then we deploy this image in production and there is some kind of
bug. Rolling back for this situation is very hard if we had not noted the image
identifier of the previous working image. You can optionally use the latest tag as an alias
to the tag that is currently deployed to production, but this should be treated only
as part of documentation and, you should not use the latest tag in your deployment.

There might be one more dangerous situation associated with using the latest tag.
If your docker deploy scripts are configured to always pull images from a remote
repository, then this might lead to an accidental unintended update of the application.
For example, if you are changing the configuration and this operation is leading to
docker container recreation (for example when changing environment vars) then
during this recreation, docker will download the latest tag and also update your
application when you do now want to do that.

# Always cleanup RUN layers
If you want to keep your images as small as possible, you should always
clean up the package's cache after any kind of apt / yum installation operation.
This point is not only for the cache cleanup, and it is more general, but we will
discuss it, taking that as an example because this technique is most often used
if an apt installation scenario. Let's have a look at Dockerfile describing this
situation.

```dockerfile
FROM ubuntu

# update packages, install tar, and clean up
RUN apt-get update && apt-get install -y tar \
  && rm -rf /var/lib/apt/lists/*
```

If we don't clean up the files in `/var/lib/apt/lists/` then there will be no way to clean
them up effectively in the next command/layer. Those files will be saved in
the apt-get update layer and deleting them from the next layer will not shrink the image
size.

# Use build arguments if you want to customize your build later
If you want to create reusable Dockerfiles, you can use the `ARG` command to achieve
that. This statement allows us to pass custom variables to the Dockerfile build
process. They can be then referenced as any other environment variables to
customize the build. Let's have a look at the example:

```dockerfile
FROM busybox
ARG username
USER $username
CMD echo "$username"
```

Having this Dockerfile if you want to specify `username` ARG you need to pass
`--build-arg` parameter to docker build command:

```bash
docker build --build-arg username=nobody .
```

In this way, we created a reusable Dockerfile that can be built multiple times
producing different images only by changing `--build-arg` parameters.

# Use multi-stage build instead of many Dockerfiles
If you want to separate building your application using build dependencies and
running your application using runtime dependencies, then you can create two
separate Dockerfile and use than one after another. This approach is very messy
and error-prone because you need to make sure that all elements of the build are
perfectly suitable for each other. Luckily for us, docker comes with an easy solution
for this problem, a multi-stage build. The syntax of this feature is shown in
the fragment of an example Dockerfile.

```dockerfile
FROM ubuntu AS builder
RUN # build commands go here
# let's assume that the executable is created as /opt/bin/program file

# We are using a smaller runtime image here
FROM alpine:latest
# We are adding the `--from=build` parameter to copy the file from our builder image
COPY --from=builder /opt/bin/program ./
CMD ["./program"]
```

This Dockerfile will build the first image and expose the results of this image as
a reference `builder` that can be used in the `COPY` command. Be specifying `--from`
the parameter we tell this layer that files should be copied from the image that was
aliased as `build`

# References
- https://docs.docker.com/engine/reference/builder/


text:
		<form action="" method="POST">

Name:<input type="text" name="author" required value="<?php echo $author; ?>" />

Mail:<input type="email" name="mail" value="<?php echo $mail; ?>" />

Hompage:<input type="text" name="homepage" value="<?php echo $homepage; ?>" />

Title:<input type="text" name="title" value="<?php echo $title; ?>" />

				Text:<textarea name="content" placeholder="Text here…" required><?php echo $content; ?></textarea>

				<input type="hidden" name="id" value="<?php echo $id; ?>">
				<input type="hidden" name="action" value="edit">
				<input type="submit" value="EDIT" />

		</form>


text:
package ch.zhaw.iwi.cis.kelvin.framework;

import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;

import __java.io.__Writer;
import __java.net.__HttpURLConnection;
import __java.net.__URL;
import __java.net.__URLConnection;
import __javax.servlet.__ServletRequest;
import __org.apache.commons.io.__IOUtils;

public class JsonServiceRequest extends ServiceRequest
{
	private String serviceName;
	private String serviceMethod;
	private String serviceRequestPayload;

	private JsonServiceRequest( String serviceName, String serviceMethod, String serviceRequestPayload )
	{
		super();
		this.serviceName = serviceName;
		this.serviceMethod = serviceMethod;
		this.serviceRequestPayload = serviceRequestPayload;
	}

	public static JsonServiceRequest getJsonServiceRequest( JavaServiceRequest javaServiceRequest )
	{
		String serviceName = javaServiceRequest.getServiceInterface().getSimpleName();
		String serviceMethod = javaServiceRequest.getServiceMethod().getName();
		String serviceRequestPayload = writeValueAsString( new ServiceRequestPayload( javaServiceRequest.getServiceArgs() ) );

		return new JsonServiceRequest( serviceName, serviceMethod, serviceRequestPayload );
	}

	public static JsonServiceRequest getJsonServiceRequest( HttpServletRequest servletRequest )
	{
		List< String > pathElementsAsList = getServiceNameAndMethod( servletRequest );
		String serviceName = pathElementsAsList.get( 0 );
		String serviceMethod = pathElementsAsList.get( 1 );
		String serviceRequestPayload = getServiceRequestPayload( servletRequest );

		return new JsonServiceRequest( serviceName, serviceMethod, serviceRequestPayload );
	}

	private static List< String > getServiceNameAndMethod( HttpServletRequest servletRequest )
	{
		String pathInfo = servletRequest.getPathInfo();
		String[] pathElements = pathInfo.split( "/" );
		List< String > pathElementsAsList = new ArrayList< String >( Arrays.asList( pathElements ) );
		pathElementsAsList.removeAll( Collections.singleton( "" ) );

		if ( pathElementsAsList.size() != 2 )
			throw new RuntimeException( "Wrong number of elements for service name and method; relative path=" + pathInfo );

		return pathElementsAsList;
	}

	private static String getServiceRequestPayload( HttpServletRequest servletRequest )
	{
		Reader reader = __ServletRequest.getReader( servletRequest );
		Writer writer = new StringWriter();

		__IOUtils.copy( null, reader, writer );
		__Writer.close( writer );
		String serviceRequestPayload = writer.toString();

		return serviceRequestPayload;
	}

	public JsonServiceResponse invoke( InetSocketAddress serverAddress, BasicAuthPrincipal principal, BasicAuthCredential credential )
	{
		HttpURLConnection connection = setupConnection( serverAddress, principal, credential );
		sendRequest( connection );
		JsonServiceResponse jsonServiceResponse = new JsonServiceResponse( getResponse( connection ) );

		return jsonServiceResponse;
	}

	private HttpURLConnection setupConnection( InetSocketAddress serverAddress, BasicAuthPrincipal principal, BasicAuthCredential credential )
	{
		String credentials = principal.getName() + ":" + credential.getPassword();
		URL requestURL = __URL.__new( "http://" + serverAddress.getHostName() + ":" + serverAddress.getPort() + KelvinServlet.SERVICES_BASE + "/" + serviceName + "/" + serviceMethod );
		HttpURLConnection connection = (HttpURLConnection)__URL.openConnection( requestURL );
		__HttpURLConnection.setRequestMethod( connection, "POST" );
		connection.setDoOutput( true );
		connection.addRequestProperty( "Authorization", "Basic " + DatatypeConverter.printBase64Binary( credentials.getBytes() ) );
		connection.addRequestProperty( "Accept", "application/json" );
		connection.addRequestProperty( "Content-Type", "application/json" );
		connection.addRequestProperty( "User-Agent", "Kelvin" );
		__URLConnection.connect( connection );

		return connection;
	}

	private void sendRequest( HttpURLConnection connection )
	{
		PrintWriter printWriter = new PrintWriter( __URLConnection.getOutputStream( connection ) );
		printWriter.println( serviceRequestPayload );
		printWriter.flush();
	}

	private String getResponse( HttpURLConnection connection )
	{
		InputStream inputStream = __URLConnection.getInputStream( connection );
		StringWriter stringWriter = new StringWriter();
		__IOUtils.copy( null, inputStream, stringWriter );

		return stringWriter.toString();
	}

	public String getServiceName()
	{
		return serviceName;
	}

	public void setServiceName( String serviceName )
	{
		this.serviceName = serviceName;
	}

	public String getServiceMethod()
	{
		return serviceMethod;
	}

	public void setServiceMethod( String serviceMethod )
	{
		this.serviceMethod = serviceMethod;
	}

	public String getServiceRequestPayload()
	{
		return serviceRequestPayload;
	}

	public void setServiceRequestPayload( String serviceRequestPayload )
	{
		this.serviceRequestPayload = serviceRequestPayload;
	}
}