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

package cmd

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"hash"
	"io"
	"path"
	"sort"
	"strings"

	"github.com/minio/minio/pkg/mimedb"
	"github.com/minio/sha256-simd"
)

// fsObjects - Implements fs object layer.
type fsObjects struct {
	storage StorageAPI

	// List pool management.
	listPool *treeWalkPool

	// To manage the appendRoutine go0routines
	bgAppend *backgroundAppend
}

// list of all errors that can be ignored in tree walk operation in FS
var fsTreeWalkIgnoredErrs = []error{
	errFileNotFound,
	errVolumeNotFound,
}

// newFSObjects - initialize new fs object layer.
func newFSObjects(storage StorageAPI) (ObjectLayer, error) {
	if storage == nil {
		return nil, errInvalidArgument
	}

	// Load format and validate.
	_, err := loadFormatFS(storage)
	if err != nil {
		return nil, fmt.Errorf("Unable to recognize backend format, %s", err)
	}

	// Initialize meta volume, if volume already exists ignores it.
	if err = initMetaVolume([]StorageAPI{storage}); err != nil {
		return nil, fmt.Errorf("Unable to initialize '.minio.sys' meta volume, %s", err)
	}

	// Initialize fs objects.
	fs := fsObjects{
		storage:  storage,
		listPool: newTreeWalkPool(globalLookupTimeout),
		bgAppend: &backgroundAppend{
			infoMap: make(map[string]bgAppendPartsInfo),
		},
	}

	// Return successfully initialized object layer.
	return fs, nil
}

// Should be called when process shuts down.
func (fs fsObjects) Shutdown() error {
	// List if there are any multipart entries.
	prefix := ""
	entries, err := fs.storage.ListDir(minioMetaMultipartBucket, prefix)
	if err != nil {
		// A non nil err means that an unexpected error occurred
		return toObjectErr(traceError(err))
	}
	if len(entries) > 0 {
		// Should not remove .minio.sys if there are any multipart
		// uploads were found.
		return nil
	}
	if err = fs.storage.DeleteVol(minioMetaMultipartBucket); err != nil {
		return toObjectErr(traceError(err))
	}
	// List if there are any bucket configuration entries.
	_, err = fs.storage.ListDir(minioMetaBucket, bucketConfigPrefix)
	if err != errFileNotFound {
		// A nil err means that bucket config directory is not empty hence do not remove '.minio.sys' volume.
		// A non nil err means that an unexpected error occurred
		return toObjectErr(traceError(err))
	}
	// Cleanup and delete tmp bucket.
	if err = cleanupDir(fs.storage, minioMetaTmpBucket, prefix); err != nil {
		return err
	}
	if err = fs.storage.DeleteVol(minioMetaTmpBucket); err != nil {
		return toObjectErr(traceError(err))
	}

	// Remove format.json and delete .minio.sys bucket
	if err = fs.storage.DeleteFile(minioMetaBucket, fsFormatJSONFile); err != nil {
		return toObjectErr(traceError(err))
	}
	if err = fs.storage.DeleteVol(minioMetaBucket); err != nil {
		if err != errVolumeNotEmpty {
			return toObjectErr(traceError(err))
		}
	}
	// Successful.
	return nil
}

// StorageInfo - returns underlying storage statistics.
func (fs fsObjects) StorageInfo() StorageInfo {
	info, err := fs.storage.DiskInfo()
	errorIf(err, "Unable to get disk info %#v", fs.storage)
	storageInfo := StorageInfo{
		Total: info.Total,
		Free:  info.Free,
	}
	storageInfo.Backend.Type = FS
	return storageInfo
}

/// Bucket operations

// MakeBucket - make a bucket.
func (fs fsObjects) MakeBucket(bucket string) error {
	// Verify if bucket is valid.
	if !IsValidBucketName(bucket) {
		return traceError(BucketNameInvalid{Bucket: bucket})
	}
	if err := fs.storage.MakeVol(bucket); err != nil {
		return toObjectErr(traceError(err), bucket)
	}
	return nil
}

// GetBucketInfo - get bucket info.
func (fs fsObjects) GetBucketInfo(bucket string) (BucketInfo, error) {
	// Verify if bucket is valid.
	if !IsValidBucketName(bucket) {
		return BucketInfo{}, traceError(BucketNameInvalid{Bucket: bucket})
	}
	vi, err := fs.storage.StatVol(bucket)
	if err != nil {
		return BucketInfo{}, toObjectErr(traceError(err), bucket)
	}
	return BucketInfo{
		Name:    bucket,
		Created: vi.Created,
	}, nil
}

// ListBuckets - list buckets.
func (fs fsObjects) ListBuckets() ([]BucketInfo, error) {
	var bucketInfos []BucketInfo
	vols, err := fs.storage.ListVols()
	if err != nil {
		return nil, toObjectErr(traceError(err))
	}
	var invalidBucketNames []string
	for _, vol := range vols {
		// StorageAPI can send volume names which are incompatible
		// with buckets, handle it and skip them.
		if !IsValidBucketName(vol.Name) {
			invalidBucketNames = append(invalidBucketNames, vol.Name)
			continue
		}
		// Ignore the volume special bucket.
		if vol.Name == minioMetaBucket {
			continue
		}
		bucketInfos = append(bucketInfos, BucketInfo{
			Name:    vol.Name,
			Created: vol.Created,
		})
	}
	// Print a user friendly message if we indeed skipped certain directories which are
	// incompatible with S3's bucket name restrictions.
	if len(invalidBucketNames) > 0 {
		errorIf(errors.New("One or more invalid bucket names found"), "Skipping %s", invalidBucketNames)
	}
	sort.Sort(byBucketName(bucketInfos))
	return bucketInfos, nil
}

// DeleteBucket - delete a bucket.
func (fs fsObjects) DeleteBucket(bucket string) error {
	// Verify if bucket is valid.
	if !IsValidBucketName(bucket) {
		return traceError(BucketNameInvalid{Bucket: bucket})
	}
	// Attempt to delete regular bucket.
	if err := fs.storage.DeleteVol(bucket); err != nil {
		return toObjectErr(traceError(err), bucket)
	}
	// Cleanup all the previously incomplete multiparts.
	if err := cleanupDir(fs.storage, minioMetaMultipartBucket, bucket); err != nil && errorCause(err) != errVolumeNotFound {
		return toObjectErr(err, bucket)
	}
	return nil
}

/// Object Operations

// CopyObject - copy object source object to destination object.
// if source object and destination object are same we only
// update metadata.
func (fs fsObjects) CopyObject(srcBucket, srcObject, dstBucket, dstObject string, metadata map[string]string) (ObjectInfo, error) {
	// Stat the file to get file size.
	fi, err := fs.storage.StatFile(srcBucket, srcObject)
	if err != nil {
		return ObjectInfo{}, toObjectErr(traceError(err), srcBucket, srcObject)
	}

	// Check if this request is only metadata update.
	cpMetadataOnly := strings.EqualFold(pathJoin(srcBucket, srcObject), pathJoin(dstBucket, dstObject))
	if cpMetadataOnly {
		// Save objects' metadata in `fs.json`.
		fsMeta := newFSMetaV1()
		fsMeta.Meta = metadata

		fsMetaPath := pathJoin(bucketMetaPrefix, dstBucket, dstObject, fsMetaJSONFile)
		if err = writeFSMetadata(fs.storage, minioMetaBucket, fsMetaPath, fsMeta); err != nil {
			return ObjectInfo{}, toObjectErr(err, dstBucket, dstObject)
		}

		// Get object info.
		return fs.getObjectInfo(dstBucket, dstObject)
	}

	// Length of the file to read.
	length := fi.Size

	// Initialize pipe.
	pipeReader, pipeWriter := io.Pipe()

	go func() {
		startOffset := int64(0) // Read the whole file.
		if gerr := fs.GetObject(srcBucket, srcObject, startOffset, length, pipeWriter); gerr != nil {
			errorIf(gerr, "Unable to read %s/%s.", srcBucket, srcObject)
			pipeWriter.CloseWithError(gerr)
			return
		}
		pipeWriter.Close() // Close writer explicitly signalling we wrote all data.
	}()

	objInfo, err := fs.PutObject(dstBucket, dstObject, length, pipeReader, metadata, "")
	if err != nil {
		return ObjectInfo{}, toObjectErr(err, dstBucket, dstObject)
	}

	// Explicitly close the reader.
	pipeReader.Close()

	return objInfo, nil
}

// GetObject - reads an object from the disk.
// Supports additional parameters like offset and length
// which are synonymous with HTTP Range requests.
//
// startOffset indicates the starting read location of the object.
// length indicates the total length of the object.
func (fs fsObjects) GetObject(bucket, object string, offset int64, length int64, writer io.Writer) (err error) {
	if err = checkGetObjArgs(bucket, object); err != nil {
		return err
	}
	// Offset cannot be negative.
	if offset < 0 {
		return toObjectErr(traceError(errUnexpected), bucket, object)
	}
	// Writer cannot be nil.
	if writer == nil {
		return toObjectErr(traceError(errUnexpected), bucket, object)
	}

	// Stat the file to get file size.
	fi, err := fs.storage.StatFile(bucket, object)
	if err != nil {
		return toObjectErr(traceError(err), bucket, object)
	}

	// For negative length we read everything.
	if length < 0 {
		length = fi.Size - offset
	}

	// Reply back invalid range if the input offset and length fall out of range.
	if offset > fi.Size || offset+length > fi.Size {
		return traceError(InvalidRange{offset, length, fi.Size})
	}

	var totalLeft = length
	bufSize := int64(readSizeV1)
	if length > 0 && bufSize > length {
		bufSize = length
	}
	// Allocate a staging buffer.
	buf := make([]byte, int(bufSize))
	if err = fsReadFile(fs.storage, bucket, object, writer, totalLeft, offset, buf); err != nil {
		// Returns any error.
		return toObjectErr(err, bucket, object)
	}
	return nil
}

// getObjectInfo - wrapper for reading object metadata and constructs ObjectInfo.
func (fs fsObjects) getObjectInfo(bucket, object string) (ObjectInfo, error) {
	fi, err := fs.storage.StatFile(bucket, object)
	if err != nil {
		return ObjectInfo{}, toObjectErr(traceError(err), bucket, object)
	}
	fsMeta, err := readFSMetadata(fs.storage, minioMetaBucket, path.Join(bucketMetaPrefix, bucket, object, fsMetaJSONFile))
	// Ignore error if the metadata file is not found, other errors must be returned.
	if err != nil && errorCause(err) != errFileNotFound {
		return ObjectInfo{}, toObjectErr(err, bucket, object)
	}

	if len(fsMeta.Meta) == 0 {
		fsMeta.Meta = make(map[string]string)
	}

	// Guess content-type from the extension if possible.
	if fsMeta.Meta["content-type"] == "" {
		if objectExt := path.Ext(object); objectExt != "" {
			if content, ok := mimedb.DB[strings.ToLower(strings.TrimPrefix(objectExt, "."))]; ok {
				fsMeta.Meta["content-type"] = content.ContentType
			}
		}
	}

	objInfo := ObjectInfo{
		Bucket:          bucket,
		Name:            object,
		ModTime:         fi.ModTime,
		Size:            fi.Size,
		IsDir:           fi.Mode.IsDir(),
		MD5Sum:          fsMeta.Meta["md5Sum"],
		ContentType:     fsMeta.Meta["content-type"],
		ContentEncoding: fsMeta.Meta["content-encoding"],
	}

	// md5Sum has already been extracted into objInfo.MD5Sum.  We
	// need to remove it from fsMeta.Meta to avoid it from appearing as
	// part of response headers. e.g, X-Minio-* or X-Amz-*.
	delete(fsMeta.Meta, "md5Sum")
	objInfo.UserDefined = fsMeta.Meta

	return objInfo, nil
}

// GetObjectInfo - reads object metadata and replies back ObjectInfo.
func (fs fsObjects) GetObjectInfo(bucket, object string) (ObjectInfo, error) {
	if err := checkGetObjArgs(bucket, object); err != nil {
		return ObjectInfo{}, err
	}
	return fs.getObjectInfo(bucket, object)
}

// PutObject - creates an object upon reading from the input stream
// until EOF, writes data directly to configured filesystem path.
// Additionally writes `fs.json` which carries the necessary metadata
// for future object operations.
func (fs fsObjects) PutObject(bucket string, object string, size int64, data io.Reader, metadata map[string]string, sha256sum string) (objInfo ObjectInfo, err error) {
	if err = checkPutObjectArgs(bucket, object, fs); err != nil {
		return ObjectInfo{}, err
	}
	// No metadata is set, allocate a new one.
	if metadata == nil {
		metadata = make(map[string]string)
	}

	uniqueID := mustGetUUID()

	// Uploaded object will first be written to the temporary location which will eventually
	// be renamed to the actual location. It is first written to the temporary location
	// so that cleaning it up will be easy if the server goes down.
	tempObj := uniqueID

	// Initialize md5 writer.
	md5Writer := md5.New()

	hashWriters := []io.Writer{md5Writer}

	var sha256Writer hash.Hash
	if sha256sum != "" {
		sha256Writer = sha256.New()
		hashWriters = append(hashWriters, sha256Writer)
	}
	multiWriter := io.MultiWriter(hashWriters...)

	// Limit the reader to its provided size if specified.
	var limitDataReader io.Reader
	if size > 0 {
		// This is done so that we can avoid erroneous clients sending more data than the set content size.
		limitDataReader = io.LimitReader(data, size)
	} else {
		// else we read till EOF.
		limitDataReader = data
	}

	// Prepare file to avoid disk fragmentation
	if size > 0 {
		err = fs.storage.PrepareFile(minioMetaTmpBucket, tempObj, size)
		if err != nil {
			return ObjectInfo{}, toObjectErr(err, bucket, object)
		}
	}

	// Allocate a buffer to Read() from request body
	bufSize := int64(readSizeV1)
	if size > 0 && bufSize > size {
		bufSize = size
	}

	buf := make([]byte, int(bufSize))
	teeReader := io.TeeReader(limitDataReader, multiWriter)
	var bytesWritten int64
	bytesWritten, err = fsCreateFile(fs.storage, teeReader, buf, minioMetaTmpBucket, tempObj)
	if err != nil {
		fs.storage.DeleteFile(minioMetaTmpBucket, tempObj)
		errorIf(err, "Failed to create object %s/%s", bucket, object)
		return ObjectInfo{}, toObjectErr(err, bucket, object)
	}

	// Should return IncompleteBody{} error when reader has fewer
	// bytes than specified in request header.
	if bytesWritten < size {
		fs.storage.DeleteFile(minioMetaTmpBucket, tempObj)
		return ObjectInfo{}, traceError(IncompleteBody{})
	}

	// Delete the temporary object in the case of a
	// failure. If PutObject succeeds, then there would be
	// nothing to delete.
	defer fs.storage.DeleteFile(minioMetaTmpBucket, tempObj)

	newMD5Hex := hex.EncodeToString(md5Writer.Sum(nil))
	// Update the md5sum if not set with the newly calculated one.
	if len(metadata["md5Sum"]) == 0 {
		metadata["md5Sum"] = newMD5Hex
	}

	// md5Hex representation.
	md5Hex := metadata["md5Sum"]
	if md5Hex != "" {
		if newMD5Hex != md5Hex {
			// Returns md5 mismatch.
			return ObjectInfo{}, traceError(BadDigest{md5Hex, newMD5Hex})
		}
	}

	if sha256sum != "" {
		newSHA256sum := hex.EncodeToString(sha256Writer.Sum(nil))
		if newSHA256sum != sha256sum {
			return ObjectInfo{}, traceError(SHA256Mismatch{})
		}
	}

	// Entire object was written to the temp location, now it's safe to rename it to the actual location.
	err = fs.storage.RenameFile(minioMetaTmpBucket, tempObj, bucket, object)
	if err != nil {
		return ObjectInfo{}, toObjectErr(traceError(err), bucket, object)
	}

	if bucket != minioMetaBucket {
		// Save objects' metadata in `fs.json`.
		// Skip creating fs.json if bucket is .minio.sys as the object would have been created
		// by minio's S3 layer (ex. policy.json)
		fsMeta := newFSMetaV1()
		fsMeta.Meta = metadata

		fsMetaPath := path.Join(bucketMetaPrefix, bucket, object, fsMetaJSONFile)
		if err = writeFSMetadata(fs.storage, minioMetaBucket, fsMetaPath, fsMeta); err != nil {
			return ObjectInfo{}, toObjectErr(traceError(err), bucket, object)
		}
	}

	return fs.getObjectInfo(bucket, object)
}

// DeleteObject - deletes an object from a bucket, this operation is destructive
// and there are no rollbacks supported.
func (fs fsObjects) DeleteObject(bucket, object string) error {
	if err := checkDelObjArgs(bucket, object); err != nil {
		return err
	}

	if bucket != minioMetaBucket {
		// We don't store fs.json for minio-S3-layer created files like policy.json,
		// hence we don't try to delete fs.json for such files.
		err := fs.storage.DeleteFile(minioMetaBucket, path.Join(bucketMetaPrefix, bucket, object, fsMetaJSONFile))
		if err != nil && err != errFileNotFound {
			return toObjectErr(traceError(err), bucket, object)
		}
	}
	if err := fs.storage.DeleteFile(bucket, object); err != nil {
		return toObjectErr(traceError(err), bucket, object)
	}
	return nil
}

// ListObjects - list all objects at prefix upto maxKeys., optionally delimited by '/'. Maintains the list pool
// state for future re-entrant list requests.
func (fs fsObjects) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsInfo, error) {
	// Convert entry to ObjectInfo
	entryToObjectInfo := func(entry string) (objInfo ObjectInfo, err error) {
		if strings.HasSuffix(entry, slashSeparator) {
			// Object name needs to be full path.
			objInfo.Name = entry
			objInfo.IsDir = true
			return
		}
		if objInfo, err = fs.getObjectInfo(bucket, entry); err != nil {
			return ObjectInfo{}, err
		}
		return
	}

	if err := checkListObjsArgs(bucket, prefix, marker, delimiter, fs); err != nil {
		return ListObjectsInfo{}, err
	}

	// With max keys of zero we have reached eof, return right here.
	if maxKeys == 0 {
		return ListObjectsInfo{}, nil
	}

	// For delimiter and prefix as '/' we do not list anything at all
	// since according to s3 spec we stop at the 'delimiter'
	// along // with the prefix. On a flat namespace with 'prefix'
	// as '/' we don't have any entries, since all the keys are
	// of form 'keyName/...'
	if delimiter == slashSeparator && prefix == slashSeparator {
		return ListObjectsInfo{}, nil
	}

	// Over flowing count - reset to maxObjectList.
	if maxKeys < 0 || maxKeys > maxObjectList {
		maxKeys = maxObjectList
	}

	// Default is recursive, if delimiter is set then list non recursive.
	recursive := true
	if delimiter == slashSeparator {
		recursive = false
	}

	heal := false // true only for xl.ListObjectsHeal()
	walkResultCh, endWalkCh := fs.listPool.Release(listParams{bucket, recursive, marker, prefix, heal})
	if walkResultCh == nil {
		endWalkCh = make(chan struct{})
		isLeaf := func(bucket, object string) bool {
			// bucket argument is unused as we don't need to StatFile
			// to figure if it's a file, just need to check that the
			// object string does not end with "/".
			return !strings.HasSuffix(object, slashSeparator)
		}
		listDir := listDirFactory(isLeaf, fsTreeWalkIgnoredErrs, fs.storage)
		walkResultCh = startTreeWalk(bucket, prefix, marker, recursive, listDir, isLeaf, endWalkCh)
	}
	var objInfos []ObjectInfo
	var eof bool
	var nextMarker string
	for i := 0; i < maxKeys; {
		walkResult, ok := <-walkResultCh
		if !ok {
			// Closed channel.
			eof = true
			break
		}
		// For any walk error return right away.
		if walkResult.err != nil {
			// File not found is a valid case.
			if errorCause(walkResult.err) == errFileNotFound {
				return ListObjectsInfo{}, nil
			}
			return ListObjectsInfo{}, toObjectErr(walkResult.err, bucket, prefix)
		}
		objInfo, err := entryToObjectInfo(walkResult.entry)
		if err != nil {
			return ListObjectsInfo{}, nil
		}
		nextMarker = objInfo.Name
		objInfos = append(objInfos, objInfo)
		if walkResult.end {
			eof = true
			break
		}
		i++
	}
	params := listParams{bucket, recursive, nextMarker, prefix, heal}
	if !eof {
		fs.listPool.Set(params, walkResultCh, endWalkCh)
	}

	result := ListObjectsInfo{IsTruncated: !eof}
	for _, objInfo := range objInfos {
		result.NextMarker = objInfo.Name
		if objInfo.IsDir {
			result.Prefixes = append(result.Prefixes, objInfo.Name)
			continue
		}
		result.Objects = append(result.Objects, objInfo)
	}
	return result, nil
}

// HealObject - no-op for fs. Valid only for XL.
func (fs fsObjects) HealObject(bucket, object string) error {
	return traceError(NotImplemented{})
}

// HealBucket - no-op for fs, Valid only for XL.
func (fs fsObjects) HealBucket(bucket string) error {
	return traceError(NotImplemented{})
}

// ListObjectsHeal - list all objects to be healed. Valid only for XL
func (fs fsObjects) ListObjectsHeal(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsInfo, error) {
	return ListObjectsInfo{}, traceError(NotImplemented{})
}


text:
python unittest_mumodoIO.py -v > /dev/null
python unittest_xio.py -v > /dev/null
python unittest_InstantIO.py -v > /dev/null
python unittest_analysis.py -v > /dev/null
python unittest_corpus.py -v > /dev/null
python unittest_increco.py -v > /dev/null

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.file;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Before;
import org.junit.Test;

/**
 * @version
 */
public class FileConsumerMoveFailureTest extends ContextTestSupport {

    @Override
    @Before
    public void setUp() throws Exception {
        deleteDirectory("target/failed");
        super.setUp();
    }

    @Test
    public void testMoveFailed() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedBodiesReceived("Hello World");

        mock.expectedFileExists("target/failed/.camel/hello.txt", "Hello World");
        mock.expectedFileExists("target/failed/error/bye-error.txt", "Kabom");

        template.sendBodyAndHeader("file://target/failed", "Hello World", Exchange.FILE_NAME, "hello.txt");
        template.sendBodyAndHeader("file://target/failed", "Kabom", Exchange.FILE_NAME, "bye.txt");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("file://target/failed?initialDelay=0&delay=10&moveFailed=error/${file:name.noext}-error.txt")
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            String body = exchange.getIn().getBody(String.class);
                            if ("Kabom".equals(body)) {
                                throw new IllegalArgumentException("Forced");
                            }
                        }
                    }).convertBodyTo(String.class).to("mock:result");
            }
        };
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.sogou.calf</groupId>
    <artifactId>calf-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <groupId>com.sogou.calf</groupId>
  <artifactId>calf-master</artifactId>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>com.sogou.calf</groupId>
      <artifactId>calf-common</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

</project>


text:
#include "tensorflow/core/profiler/utils/event_span.h"

#include <string>
#include <utility>
#include <vector>

#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/utils/timespan.h"

namespace tensorflow {
namespace profiler {

namespace {

// Representing a boundary of an event.
struct EventBoundary {
  // Time at this boundary.
  uint64 time_ps;
  // Type of the event.
  EventType type;
  // True if this is the start of the event; False if this is the end.
  bool is_start;
  EventBoundary(uint64 time_ps, EventType type, bool is_start)
      : time_ps(time_ps), type(type), is_start(is_start) {}
};

// Returns true if EventBoundary a should appear before EventBoundary b.
bool CmpEventBoundaries(const EventBoundary& a, const EventBoundary& b) {
  if (a.time_ps == b.time_ps) {
    if (a.is_start == b.is_start) {
      // Puts the higher-priority type before the lower-priority type if they
      // have the same time and same boundary type.
      return a.type > b.type;
    } else {
      // Puts the "end" bounary before the "start" boundary if they have the
      // same time.
      return !a.is_start;
    }
  }
  // In ascending order of time.
  return a.time_ps < b.time_ps;
}

// Generates vector of event boundaries from the given overlapped_events.
std::vector<EventBoundary> GenerateEventBoundaries(
    const std::vector<EventTypeSpan>& overlapped_events) {
  std::vector<EventBoundary> boundaries;
  boundaries.reserve(2 * overlapped_events.size());
  for (const auto& event : overlapped_events) {
    boundaries.push_back(
        {event.span.begin_ps(), event.type, /*is_start=*/true});
    boundaries.push_back({event.span.end_ps(), event.type, /*is_start=*/false});
  }
  absl::c_sort(boundaries, CmpEventBoundaries);
  return boundaries;
}

// A class to track the highest priority that an event should be assigned.
class PriorityTracker {
 private:
  // The current maximum priority.
  EventType current_max_priority_;
  // A count for each possible priority.
  std::vector<int64> priority_count_;

 public:
  PriorityTracker() {
    current_max_priority_ = UNKNOWN_TIME;
    priority_count_.resize(LAST_EVENT_TYPE + 1, 0);
  }
  // Updates current_max_priority_ and priority_count_[] given the boundary.
  // Returns the new current_max_priority_.
  EventType Update(const EventBoundary& boundary) {
    EventType event_type = boundary.type;
    bool is_start = boundary.is_start;
    if (is_start) {
      priority_count_[event_type]++;
      if (event_type > current_max_priority_) {
        current_max_priority_ = event_type;
      }
    } else {
      priority_count_[event_type]--;
      if (event_type == current_max_priority_ &&
          priority_count_[event_type] == 0) {
        // Reduces current_max_priority_ to the first event type (starting from
        // the highest priority) that has a non-zero count.
        bool found = false;
        for (int i = event_type - 1; i >= 0; i--) {
          if (priority_count_[i] > 0) {
            current_max_priority_ = static_cast<EventType>(i);
            found = true;
            break;
          }
        }
        if (!found) current_max_priority_ = UNKNOWN_TIME;
      }
    }
    return current_max_priority_;
  }
};

void CombineStepDetails(const StepDetails& src, StepDetails* dst) {
  dst->AppendMarkers(src.Markers());
  dst->AppendEvents(src.Events());
  dst->AppendCollectives(src.Collectives());
  dst->AggregateDeviceMemoryTransfers(src.DeviceMemoryTransfers());
  if (dst->StepName().empty()) dst->SetStepName(src.StepName());
}

EventType ClassifyDeviceCompute(absl::string_view event_name,
                                absl::string_view tensor_shapes) {
  if (tensor_shapes.empty()) {
    // Deduces the precision from the name.
    if (absl::StrContains(event_name, "half") ||
        absl::StrContains(event_name, "fp16"))
      return DEVICE_COMPUTE_16;
    else
      return DEVICE_COMPUTE_32;
  } else {
    // Deduces the precision from the shapes.
    if (absl::StrContains(tensor_shapes, "half"))
      return DEVICE_COMPUTE_16;
    else
      return DEVICE_COMPUTE_32;
  }
}

constexpr int kNumGenericEventTypes = GenericEventType::kLastGenericEventType -
                                      GenericEventType::kFirstGenericEventType +
                                      1;

using GenericEventTypeStrMap =
    absl::flat_hash_map<GenericEventType, absl::string_view>;

const GenericEventTypeStrMap& GetGenericEventTypeStrMap() {
  static const auto* generic_event_type_str_map = new GenericEventTypeStrMap({
      {kDeviceCompute, "Device compute"},
      {kDeviceToDevice, "Device to device"},
      {kDeviceCollectives, "Device collective communication"},
      {kHostCompute, "Host compute"},
      {kHostPrepare, "Kernel launch"},
      {kInput, "Input"},
      {kOutput, "Output"},
      {kCompile, "Compilation"},
      {kAllOthers, "All others"},
  });
  DCHECK_EQ(generic_event_type_str_map->size(), kNumGenericEventTypes);
  return *generic_event_type_str_map;
}

}  // namespace

absl::string_view GetGenericEventTypeStr(GenericEventType event_type) {
  return GetGenericEventTypeStrMap().at(event_type);
}

EventType ClassifyGpuEvent(absl::string_view event_name,
                           absl::string_view tensor_shapes) {
  if (absl::StartsWithIgnoreCase(event_name, "MEMCPYHtoD"))
    return HOST_TO_DEVICE;
  if (absl::StartsWithIgnoreCase(event_name, "MEMCPYDtoH"))
    return DEVICE_TO_HOST;
  if (absl::StartsWithIgnoreCase(event_name, "MEMCPYDtoD"))
    return DEVICE_TO_DEVICE;
  if (absl::StartsWithIgnoreCase(event_name, "nccl")) {
    return DEVICE_COLLECTIVES;
  }
  return ClassifyDeviceCompute(event_name, tensor_shapes);
}

EventType ClassifyCpuEvent(absl::string_view event_name, int64 correlation_id,
                           bool has_device) {
  if (absl::StartsWithIgnoreCase(event_name, "MEMCPYHtoD") ||
      absl::StrContains(event_name, "Infeed"))
    return HOST_TO_DEVICE;
  if (absl::StartsWithIgnoreCase(event_name, "MEMCPYHtoH")) return HOST_TO_HOST;
  // TODO(b/150420972): Separate runtime overhead from actual compute for
  // CPU-only.
  if (has_device &&
      (correlation_id >= 0 ||
       absl::StartsWithIgnoreCase(event_name, "ExecutorState::Process"))) {
    return HOST_PREPARE;
  }
  if (absl::StartsWithIgnoreCase(event_name, "IteratorGetNext"))
    return HOST_WAIT_INPUT;
  return HOST_COMPUTE;
}

std::string PrintEventType(EventType event_type) {
  switch (event_type) {
    case UNKNOWN_TIME:
      return "unknown_time";
    case HOST_COMPUTE:
      return "host_compute";
    case HOST_COMPILE:
      return "host_compile";
    case HOST_TO_HOST:
      return "host_to_host";
    case HOST_TO_DEVICE:
      return "host_to_device";
    case HOST_PREPARE:
      return "host_prepare";
    case DEVICE_COLLECTIVES:
      return "device_collectives";
    case HOST_WAIT_INPUT:
      return "host_wait_input";
    case DEVICE_TO_DEVICE:
      return "device_to_device";
    case DEVICE_TO_HOST:
      return "device_to_host";
    case DEVICE_COMPUTE_32:
      return "device_compute_32";
    case DEVICE_COMPUTE_16:
      return "device_compute_16";
    case DEVICE_WAIT_DEVICE:
      return "device_wait_device";
    case DEVICE_WAIT_HOST:
      return "device_wait_host";
    default:
      return "unexpected";
  }
}

std::string PrintEventTypeSpan(const EventTypeSpan& event_type_span) {
  return absl::StrCat("(", PrintEventType(event_type_span.type), ", ",
                      event_type_span.span.DebugString(), ")");
}

absl::string_view PrintStepMarkerType(StepMarkerType type) {
  switch (type) {
    case StepMarkerType::kExplicitHostStepMarker:
      return "ExplicitHostStepMarker";
    case StepMarkerType::kImplicitHostStepMarker:
      return "ImplicitHostStepMarker";
    case StepMarkerType::kDeviceStepMarker:
      return "DeviceStepMarker";
  }
}

std::string PrintStepMarker(const StepMarker& step_marker) {
  return absl::StrCat("(", PrintStepMarkerType(step_marker.type), ", ",
                      step_marker.event_name, ", ",
                      step_marker.span.DebugString(), ")");
}

std::string PrintStepEvents(const StepEvents& step_events) {
  std::vector<int64> step_ids;
  step_ids.reserve(step_events.size());
  for (const auto& id_details : step_events) {
    step_ids.push_back(id_details.first);
  }
  absl::c_sort(step_ids);
  std::string result = "{";
  for (auto id : step_ids) {
    absl::StrAppend(&result, "\n");
    auto* details = gtl::FindOrNull(step_events, id);
    std::string details_str = details ? details->DebugString() : "()";
    absl::StrAppend(&result, id, ":", details_str);
  }
  return absl::StrCat(result, "\n}");
}

void CombineStepEvents(const StepEvents& src, StepEvents* dst) {
  for (const auto& step_details : src) {
    int64 step_id = step_details.first;
    const StepDetails& src_details = step_details.second;
    StepDetails* dst_details = &(*dst)[step_id];
    CombineStepDetails(src_details, dst_details);
  }
}

std::vector<EventTypeSpan> ToNonOverlappedEvents(
    const std::vector<EventTypeSpan>& overlapped_events) {
  std::vector<EventBoundary> event_boundaries =
      GenerateEventBoundaries(overlapped_events);
  std::vector<EventTypeSpan> result;
  if (event_boundaries.empty()) return result;
  result.reserve(event_boundaries.size());
  PriorityTracker priority_tracker;
  for (int64 i = 0, end = (event_boundaries.size() - 1); i < end; i++) {
    EventType highest_priority = priority_tracker.Update(event_boundaries[i]);
    result.push_back({highest_priority, Timespan::FromEndPoints(
                                            event_boundaries[i].time_ps,
                                            event_boundaries[i + 1].time_ps)});
  }
  return result;
}

// Converts from overlapped step-events to non-overlapped step-events.
StepEvents ToNonOverlappedStepEvents(const StepEvents& overlapped_step_events) {
  StepEvents non_overlapped_step_events;
  for (const auto& step_events : overlapped_step_events) {
    const auto& step_id = step_events.first;
    const auto& step_details = step_events.second;
    *non_overlapped_step_events[step_id].MutableMarkers() =
        step_details.Markers();
    *non_overlapped_step_events[step_id].MutableEvents() =
        ToNonOverlappedEvents(step_details.Events());
    *non_overlapped_step_events[step_id].MutableCollectives() =
        step_details.Collectives();
    *non_overlapped_step_events[step_id].MutableDeviceMemoryTransfers() =
        step_details.DeviceMemoryTransfers();
    non_overlapped_step_events[step_id].SetStepName(step_details.StepName());
  }
  return non_overlapped_step_events;
}

void StepDetails::AddMarker(const StepMarker& m) { markers_.push_back(m); }

void StepDetails::AddEvent(const EventTypeSpan& e) { events_.push_back(e); }

void StepDetails::AppendMarkers(const std::vector<StepMarker>& other_markers) {
  markers_.insert(markers_.end(), other_markers.begin(), other_markers.end());
}

void StepDetails::AppendEvents(const std::vector<EventTypeSpan>& other_events) {
  events_.insert(events_.end(), other_events.begin(), other_events.end());
}

void StepDetails::AppendCollectives(
    const absl::flat_hash_map<uint32, AllReduceDbResult>& collectives) {
  for (const auto& it : collectives) {
    collectives_[it.first] = it.second;
  }
}

void StepDetails::AggregateDeviceMemoryTransfers(
    const std::vector<DeviceMemoryTransfer> device_memory_transfers) {
  if (device_memory_transfers.size() != device_memory_transfers_.size()) {
    return;  // Sanity check.
  }
  for (size_t i = 0; i < device_memory_transfers.size(); ++i) {
    device_memory_transfers_[i].set_occurrence(
        device_memory_transfers_[i].occurrence() +
        device_memory_transfers[i].occurrence());
    device_memory_transfers_[i].set_bytes_transferred(
        device_memory_transfers_[i].bytes_transferred() +
        device_memory_transfers[i].bytes_transferred());
    device_memory_transfers_[i].set_time_us(
        device_memory_transfers_[i].time_us() +
        device_memory_transfers[i].time_us());
  }
}

void StepDetails::AddCollectiveOpEvent(uint64 core_id, const AllReduceInfo& e) {
  *collectives_[core_id].add_all_reduce_info() = e;
}

void StepDetails::AddDeviceMemoryTransferEvent(EventType event_type,
                                               const Timespan& time_span,
                                               uint64 bytes) {
  int index = 0;
  switch (event_type) {
    case HOST_TO_DEVICE:
      index = 0;
      break;
    case DEVICE_TO_HOST:
      index = 1;
      break;
    case DEVICE_TO_DEVICE:
      index = 2;
      break;
    default:
      return;
  }
  device_memory_transfers_[index].set_occurrence(
      device_memory_transfers_[index].occurrence() + 1);
  device_memory_transfers_[index].set_time_us(
      device_memory_transfers_[index].time_us() +
      time_span.duration_ps() / 1000000.0);
  device_memory_transfers_[index].set_bytes_transferred(
      device_memory_transfers_[index].bytes_transferred() + bytes);
}

Timespan StepDetails::StepTime() const {
  Timespan max_host_step_time;
  Timespan max_device_step_time;
  for (const auto& marker : markers_) {
    Timespan& cur_max_step_time =
        marker.type == StepMarkerType::kDeviceStepMarker ? max_device_step_time
                                                         : max_host_step_time;
    const Timespan& new_step_time = marker.span;
    if (new_step_time.duration_ps() > cur_max_step_time.duration_ps())
      cur_max_step_time = new_step_time;
  }
  // CPU-only profile.
  if (max_device_step_time.Empty()) {
    return max_host_step_time;
  }

  // If the host step time includes the device step time, use the host step
  // time. This covers the case where the device is synchronized at the end of
  // each step.
  if (max_host_step_time.Includes(max_device_step_time)) {
    return max_host_step_time;
  }
  return max_device_step_time;
}

std::string StepDetails::DebugString() const {
  std::string result = "([";
  for (int i = 0, end = markers_.size(); i < end; i++) {
    if (i > 0) absl::StrAppend(&result, ", ");
    absl::StrAppend(&result, PrintStepMarker(markers_[i]));
  }
  absl::StrAppend(&result, "], [");
  for (int i = 0, end = events_.size(); i < end; i++) {
    if (i > 0) absl::StrAppend(&result, ", ");
    absl::StrAppend(&result, PrintEventTypeSpan(events_[i]));
  }
  return absl::StrCat(result, "])");
}

bool StepDetails::operator==(const StepDetails& other) const {
  const auto& other_markers = other.Markers();
  if (markers_.size() != other_markers.size()) return false;
  for (uint64 i = 0; i < markers_.size(); i++) {
    if (markers_[i] != other_markers[i]) return false;
  }
  const auto& other_events = other.Events();
  if (events_.size() != other_events.size()) return false;
  for (uint64 i = 0; i < events_.size(); i++) {
    if (events_[i] != other_events[i]) return false;
  }
  return true;
}

bool operator==(const StepEvents& a, const StepEvents& b) {
  if (a.size() != b.size()) return false;
  for (const auto& id_details : a) {
    const auto a_id = id_details.first;
    const auto& a_details = id_details.second;
    const auto* b_details = gtl::FindOrNull(b, a_id);
    if (b_details == nullptr) return false;
    if (a_details != *b_details) return false;
  }
  return true;
}

PrecisionStats ComputePrecisionStats(
    const StepEvents& nonoverlapped_step_events) {
  int64 compute_32bit_ps = 0;
  int64 compute_16bit_ps = 0;
  for (const auto& id_details : nonoverlapped_step_events) {
    for (const auto& event : id_details.second.Events()) {
      switch (event.type) {
        case DEVICE_COMPUTE_32:
          compute_32bit_ps += event.span.duration_ps();
          break;
        case DEVICE_COMPUTE_16:
          compute_16bit_ps += event.span.duration_ps();
          break;
        default:
          break;
      }
    }
  }
  PrecisionStats precision_stats;
  precision_stats.set_compute_32bit_ps(compute_32bit_ps);
  precision_stats.set_compute_16bit_ps(compute_16bit_ps);
  return precision_stats;
}

}  // namespace profiler
}  // namespace tensorflow


text:
#ifndef _LINUX_WAIT_H
#define _LINUX_WAIT_H
#define WNOHANG 0x00000001
#define WUNTRACED 0x00000002
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define WSTOPPED WUNTRACED
#define WEXITED 0x00000004
#define WCONTINUED 0x00000008
#define WNOWAIT 0x01000000
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define __WNOTHREAD 0x20000000
#define __WALL 0x40000000
#define __WCLONE 0x80000000
#define P_ALL 0
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define P_PID 1
#define P_PGID 2
#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;

public partial class search : System.Web.UI.Page
{
    string constr = @"provider = microsoft.ace.oledb.12.0; data source = |DataDirectory|\onlinephone.accdb";
    protected void Page_Load(object sender, EventArgs e)
    {
        Label6.Visible = false;
        Label5.Visible = false;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection(constr);
        con.Open();
        string cmdstr = "select number, name from phone where name = @a";
        OleDbCommand com = new OleDbCommand(cmdstr, con);
        com.Parameters.AddWithValue("@a", TextBox3.Text.Trim());
        OleDbDataReader r;
        r = com.ExecuteReader();
        if (r.Read())
        {
            Label6.Visible = true;
            Label5.Visible = true;
            Label5.Text = (string)r[1] + ":";
            Label6.Text = (string)r[0];
        }
        else
        {
            Label6.Visible = true;
            Label6.Text = "Contact Not Found...!";
        }
    }
}


text:
<?php

namespace Humweb\Features\Strategy;

/**
 * DateTimeRange strategy.
 */
class DateTimeRangeStrategy extends AbstractStrategy
{

    /**
     * {@inheritdoc}
     */
    public function handle($args = [])
    {

        $strict = $this->argGet($args, 'strict', true);

        $dateRange = [
            [
                'date'     => $this->argGet($args, 'start'),
                'operator' => '<'
            ],
            [
                'date'     => $this->argGet($args, 'end'),
                'operator' => '>'
            ]
        ];

        foreach ($dateRange as $range) {

            if ( ! $strict) {
                $range['operator'] .= '=';
            }

            if ($this->runDateTimeStrategy($range['date'], $range['operator']) === false) {
                return false;
            }
        }

        return true;
    }

    /**
     * Run datetime strategy
     *
     * @param string|\DateTime $datetime
     * @param string           $operator
     *
     * @return bool
     */
    public function runDateTimeStrategy($datetime, $operator = '>=')
    {
        $strategy = new DateTimeStrategy();

        $args = [
            'datetime' => $datetime,
            'operator' => $operator
        ];

        if ( ! call_user_func_array([$strategy, 'handle'], [$args])) {
            return false;
        }

        return true;
    }
}


text:
Documentation

Component Inputs

      Input
      Type
      Description

      [settings]
      Object
      Table component configuration object, properties described below

      [source]
      Array|DataSource
      Table data, either an array or DataSource object (LocalDataSource currently supported)

Table Configuration

      Property
      Type
      Default
      Description

      Required Table Settings

      columns
      Object
      n/a

        Table column settings, by default an empty object.

        Example format:

          columns: {{ '{' }}
            columnKey: {{ '{' }}
              title: 'Some Title'
            {{ '}' }}
          {{ '}' }}

        Please note, columnKey must be the same as a key in data array objects.

      Column Settings

        List of a column's settings

      title
      string
      ''

        Column title

      class
      string
      ''

        Column class

      width
      string
      ''

        Column width, example: '20px', '20%'

      hide
      boolean
      false

        Whether to hide this column or not

      editable
      boolean
      true

        Whether this column is editable or not

      type
      'text'|'html'|'custom'
      'text'

        If type is text then cell value will be inserted as text.

        If type is html then cell value will be inserted as html.

        If type is custom the renderComponent property must be defined.

      renderComponent
      any
      null

        Custom component that will be responsible for rendering the cell content while in view mode.

        Type must be custom in order for this to work.

        You can see an example here

      onComponentInitFunction
      Function
      null

        Function which will be invoked after renderComponent instantiated and before ngOnInit hook. This function gets renderComponent instance in first param.

      editor
      Object
      n/a

        Editor attributes settings

      editor.type
      'text' | 'textarea' | 'completer' | 'list' | 'checkbox'
      'text'

        Editor used when new row is added or edited

      editor.config
      Object
      n/a

        Editor configuration settings. Mandatory only for editor types completer, list

      editor.config.true
      string
      ''

        Only on checkbox type.

        Defines the value to assign when the checkbox is checked. This parameter is optional, if omitted, true will be used.

      editor.config.false
      string
      ''

        Only on checkbox type.

        Defines the value to assign when the checkbox is not checked. This parameter is optional, if omitted, false will be used.

      editor.config.list
      Array
      [ ]

        Only on list type. Example format:

        {{ '{' }} value: 'Element Value', title: 'Element Title' {{ '}' }}

        Html is supported if column type is 'html'

      editor.config.completer
      Object
      n/a

        Only on completer type. Example format:

        Completer configuration settings

      editor.config.completer.data
      Array
      [ ]

        Autocomplete list data source.

        Example format:

        {{ '{' }} id: 10, name: 'Nick', email: 'rey@karina.biz' {{ '}' }}

      editor.config.completer.searchFields
      string
      ''

        Comma separated list of fields to search on. Fields may contain dots for nested attributes; if empty or null all data will be returned

      editor.config.completer.titleField
      string
      ''

       Name of the field to use as title for the list item

      editor.config.completer.descriptionField
      string
      ''

        Name of the field to use as description for the list item

      filter
      Object
      n/a

        Column filter attributes settings. This object accepts the same properties as the editor object.

        The available types are: checkbox, select, completer.

        The checkbox type accepts one more optional property compared to the editor version: resetText: string.
        It defines the text of the button to reset the checkbox selection.

        Click here to see an example on how to configure it.

      valuePrepareFunction
      Function

        n/a

        Function run against a value before it gets inserted into a cell.
        You can use it to modify how a value is displayed in the cell.

        This function will be invoked with 2 parameters: cell, row

      sort
      boolean
      true

        Column sort settings, enable/disable.

      sortDirection
      'asc'|'desc'
      n/a

        Sort table by this column with this direction by default.

        Applied only when sort = true.
        Note: multiple sort option is not supported yet, so sortDirection can be applied to only one column per table.

      compareFunction
      Function

        n/a

        Function run against the values to sort the table

      filter
      boolean
      true

        Column filter settings, enable/disable

      filterFunction
      Function
      n/a

        Function run against the column value when filtering is happening

      Other Table Settings

      mode
      'external'|'inline'
      'inline'

        Determines how to react on action links (Add, Edit, Delete).

        'external' - just trigger the events (LINK HERE).

        'inline' - process internally, show forms/inputs/etc

      hideHeader
      'boolean'
      false

        Set to true to not display the table header (which includes table column titles)

      hideSubHeader
      'boolean'
      false

        Set to true to not display the table sub-header (which includes filters and global table actions (currently - Add action))

      noDataMessage
      string
      'No data found'

        Message shown when there is no data in the table

      attr
      Object
      n/a

        Table attributes settings

      attr.id
      string
      ''

        Table element id

      attr.class
      string
      ''

        Table element class

      actions
      Object
      n/a

        Settings for the table actions

      actions.columnTitle
      string
      'Actions'

        Actions column title

      actions.add
      boolean
      true

        Show/not show Add button

      actions.edit
      boolean
      true

        Show/not show Edit button

      actions.delete
      boolean
      true

        Show/not show Delete button

      actions.position
      'left'|'right'
      'left'

        Choose actions column position

      filter
      Object
      n/a

        Settings for the table filter

      filter.inputClass
      string
      ''

        Filter input class

      edit
      Object
      n/a

        Edit action settings

      edit.inputClass
      string
      ''

        Editing form input class

      edit.editButtonContent
      string
      'Edit'

        Edit row button content/title

      edit.saveButtonContent
      string
      'Update'

        Update button content/title

      edit.cancelButtonContent
      string
      'Cancel'

        Cancel button content/title

      edit.confirmSave
      boolean
      false

        Enable/disable (confirmEdit) event. If enabled data will be edited only if confirm.resolve() called.

      add
      Object
      n/a

        Add action settings

      add.inputClass
      string
      ''

        New row input class

      add.addButtonContent
      string
      'Add New'

        Add New button content/title

      add.createButtonContent
      string
      'Create'

        Create button content/title

      add.cancelButtonContent
      string
      'Cancel'

        Cancel button content/title

      add.confirmCreate
      boolean
      false

        Enable/disable (confirmCreate) event. If enabled data will be added only if confirm.resolve() called.

      delete
      Object
      n/a

        Delete action settings

      delete.deleteButtonContent
      string
      'Delete'

        Delete row input class

      delete.confirmDelete
      boolean
      false

        Enable/disable (confirmDelete) event. If enabled data will be deleted only if confirm.resolve() called.

      pager
      Object
      n/a

        Pager settings

      pager.display
      boolean
      true

        Whether to display the pager or not

      pager.perPage
      number
      10

        Rows per page

      rowClassFunction
      Function
      row

        Handle css class for each row in the table

Component Outputs/Events

      Event
      Arguments
      Description

      (rowSelect)

        event: Object, consist of:

data: Object - selected row data object

source: DataSource - table data source

        Triggered once a row is selected (either clicked or selected automatically (after page is changed, after some row is deleted, etc)).

      (userRowSelect)

        event: Object, consist of:

data: Object - selected row data object

source: DataSource - table data source

        Triggered only on a user click event.

      (mouseover)

        event: Object, consist of:

data: Object - highlighted row data object

source: DataSource - table data source

        Triggered only on a user mouseover event.

      (create)

        event: Object, consist of:

source: DataSource - table data source

        Triggered once a Create button clicked. Triggered only if table mode = external.

      (createConfirm)

        event: Object, consist of:

newData: Object - data entered in a new row

source: DataSource - table data source

confirm: Deferred - Deferred object with resolve(newData: Object) and reject() methods.

        Triggered once a Create button clicked. Triggered only if table confirmCreate = true and mode = inline.
        Allows you to confirm changes before they are applied to the table data source.

      (edit)

        event: Object, consist of:

data: Object - row data object

source: DataSource - table data source

        Triggered once an Edit button clicked on a row. Triggered only if table mode = external.

      (editConfirm)

        event: Object, consist of:

data: Object - original row data

newData: Object - edited data

source: DataSource - table data source

confirm: Deferred - Deferred object with resolve(newData: Object) and reject() methods.

        Triggered once a Save button clicked. Triggered only if table confirmSave = true and mode = inline.
        Allows you to confirm changes before they are applied to the table data source.

      (delete)

        event: Object, consist of:

data: Object - row data object

source: DataSource - table data source

        Triggered once a Delete button clicked on a row. Triggered only if table mode = external.

      (deleteConfirm)

        event: Object, consist of:

data: Object - data object to delete

source: DataSource - table data source

confirm: Deferred - Deferred object with resolve() and reject() methods.

        Triggered once a Delete button clicked. Triggered only if table confirmDelete = true and mode = inline.
        Allows you to confirm changes before they are applied to the table data source.

Data Source Methods

      Method
      Arguments
      Description

      load

data: Array - data to load into the table

        Reload table with new data. For example if some data has received from the server.

      prepend

element: Object - object to add

        Add a new element to the beginning of the table.

      append

element: Object - object to add

        Add a new element to the end of the table. This also will switch current page to the last one.

      add

element: Object - object to add

        Add a new element to the table.

      remove

element: Object - object to remove

        Remove the element from the table.

      update

element: Object - object to update

values: Object - object with new values

        Update the element in the table.

      find

element: Object - object to find

        Find the element in the table.

      getElements

        n/a

        Get elements for current sort, filter and page.

      getFilteredAndSorted

        n/a

          Get sorted, filtered and not paginated elements.

      getAll

        n/a

        Get all data source elements.

      setSort

            conf: Array - array of sort setting objects, object format is:

field - string - columnKey

direction - string|null - 'asc'|'desc'|null - sort direction

compare - Function|null - custom compare function

            doEmit: boolean - emit event (to refresh the table) or not, default = true

        Set table sorts, example:

        this.source.setSort([{{ '{' }} field: 'id', direction: 'asc' {{ '}' }}]);

      setFilter

            conf: Array - array of filter setting objects, object format is:

field - string - columnKey

search - string - search query

filter - Function|null - custom filter function

            andOperator: boolean - how to process multiple filters (as AND or as OR), default = true (AND)

            doEmit: boolean - emit event (to refresh the table) or not, default = true

        Set table filters, example:

        this.source.setFilter([{{ '{' }} field: 'id', search: 'foobar' {{ '}' }}, {{ '{' }} field: 'name', search: 'foobar' {{ '}' }}]);

      addFilter

            conf: Object - one filter object, format is:

field - string - columnKey

search - string - search query

filter - Function|null - custom filter function

            andOperator: boolean - how to process multiple filters (as AND or as OR), default = true (AND)

            doEmit: boolean - emit event (to refresh the table) or not, default = true

        Set table filter for one column, example:

        this.source.addFilter({{ '{' }} field: 'id', search: 'foobar' {{ '}' }});

      setPaging

            page: number - page number

            perPage: number - about per page

            doEmit: boolean - emit event (to refresh the table) or not, default = true

        Set table pagination settings

      setPage

            page: number - page number

            doEmit: boolean - emit event (to refresh the table) or not, default = true

        Set table page

      reset

silent: boolean - if true - you have to additionally call `refresh` to reflect the changes

        Set data source to first page with empty filter and empty sort.

      refresh

        n/a

        Refresh data in the data source. In most cases you won't need this method.

      count

        n/a

        Return count of element in the data source.

      empty

        n/a

        Empty the data source.


text:
using JuliaFEM, Test, Statistics

datadir = first(splitext(basename(@__FILE__)))

mesh = abaqus_read_mesh(joinpath(datadir, "tet4.inp"))

upper = Problem(Elasticity, "UPPER", 3)
upper_elements = create_elements(mesh, "UPPER")
update!(upper_elements, "youngs modulus", 3*288.0)
update!(upper_elements, "poissons ratio", 1/3)
add_elements!(upper, upper_elements)
push!(upper.postprocess_fields, "strain", "stress")
@info("upper postprocess: $(upper.postprocess_fields)")

lower = Problem(Elasticity, "LOWER", 3)
lower_elements = create_elements(mesh, "LOWER")
update!(lower_elements, "youngs modulus", 288.0)
update!(lower_elements, "poissons ratio", 1/3)
add_elements!(lower, lower_elements)
push!(lower.postprocess_fields, "strain", "stress")
@info("lower postprocess: $(lower.postprocess_fields)")

bc_upper = Problem(Dirichlet, "UPPER_TOP", 3, "displacement")
bc_upper_elements = create_surface_elements(mesh, "UPPER_TOP")
update!(bc_upper_elements, "displacement 3", -0.4)
add_elements!(bc_upper, bc_upper_elements)

bc_lower = Problem(Dirichlet, "LOWER_BOTTOM", 3, "displacement")
bc_lower_elements = create_surface_elements(mesh, "LOWER_BOTTOM")
update!(bc_lower_elements, "displacement 3", 0.0)
add_elements!(bc_lower, bc_lower_elements)

# point-wise boundary conditions to prevent free body move
nid1 = find_nearest_nodes(mesh, [0.0, 0.0, 0.0])[1]
nid2 = find_nearest_nodes(mesh, [1.0, 0.0, 0.0])[1]
nid3 = find_nearest_nodes(mesh, [0.0, 1.0, 0.0])[1]
nid4 = find_nearest_nodes(mesh, [0.0, 0.0, 1.0])[1]
nid5 = find_nearest_nodes(mesh, [1.0, 0.0, 1.0])[1]
nid6 = find_nearest_nodes(mesh, [0.0, 1.0, 1.0])[1]

bc_sym13 = Problem(Dirichlet, "SYM13", 3, "displacement")
# nodes in X2=0 plane
bc_sym13_elements = [Element(Poi1, [j]) for j in [nid1, nid2, nid4, nid5]]
update!(bc_sym13_elements, "geometry", mesh.nodes)
update!(bc_sym13_elements, "displacement 2", 0.0)
add_elements!(bc_sym13, bc_sym13_elements)

bc_sym23 = Problem(Dirichlet, "SYM23", 3, "displacement")
# nodes in X1=0 plane
bc_sym23_elements = [Element(Poi1, [j]) for j in [nid1, nid3, nid4, nid6]]
update!(bc_sym23_elements, "geometry", mesh.nodes)
update!(bc_sym23_elements, "displacement 1", 0.0)
add_elements!(bc_sym23, bc_sym23_elements)

push!(bc_upper.postprocess_fields, "reaction force")
push!(bc_lower.postprocess_fields, "reaction force")
push!(bc_sym13.postprocess_fields, "reaction force")
push!(bc_sym23.postprocess_fields, "reaction force")

interface = Problem(Contact, "LOWER_TO_UPPER", 3, "displacement")
interface_slave_elements = create_surface_elements(mesh, "LOWER_TO_UPPER")
interface_master_elements = create_surface_elements(mesh, "UPPER_TO_LOWER")
update!(interface_slave_elements, "master elements", interface_master_elements)
interface.elements = [interface_slave_elements; interface_master_elements]
interface.properties.dual_basis = true
interface.properties.contact_state_in_first_iteration = :AUTO
push!(interface.postprocess_fields, "contact pressure")

analysis = Analysis(Nonlinear)
add_problems!(analysis, upper, lower, bc_upper, bc_lower,
              bc_sym13, bc_sym23, interface)

xdmf = Xdmf("contact_two_blocks_postprocess"; overwrite=true)
add_results_writer!(analysis, xdmf)
run!(analysis)

node_ids, displacement = get_nodal_vector(interface.elements, "displacement", 0.0)
node_ids, geometry = get_nodal_vector(interface.elements, "geometry", 0.0)
# node_ids, pressure = get_nodal_vector(interface.elements, "contact pressure", 0.0)
u3 = [u[3] for u in displacement]
maxabsu3 = maximum(abs.(u3))
stdabsu3 = std(abs.(u3))
@debug("max(abs(u3)) = $maxabsu3, std(abs(u3)) = $stdabsu3")
@test isapprox(stdabsu3, 0.0; atol=1.0e-12)
upper_X = [0.5, 0.5, 0.75]
lower_X = [0.5, 0.5, 0.25]
strain_upper = upper("strain", upper_X, 0.0)
stress_upper = upper("stress", upper_X, 0.0)
strain_lower = lower("strain", lower_X, 0.0)
stress_lower = lower("stress", lower_X, 0.0)
@debug("strain at $upper_X = $strain_upper")
@debug("stress at $upper_X = $stress_upper")
@debug("strain at $lower_X = $strain_lower")
@debug("stress at $lower_X = $stress_lower")


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
              android:orientation = "vertical"
              android:layout_width = "match_parent"
              android:layout_height = "match_parent"
              android:background = "@color/app_bg">

    <include layout = "@layout/header_bar_general"/>

    <LinearLayout
            android:id = "@+id/scv_setting_cloud_login"
            android:visibility = "gone"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/i_cloud"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:gravity = "center_vertical"
                android:layout_marginLeft = "14dp"
                android:drawableLeft = "@drawable/cloud_icon"
                android:drawablePadding = "10dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

    <!--<LinearLayout-->
    <!--android:id="@+id/scv_setting_cloud_login"-->
    <!--android:layout_width="match_parent"-->
    <!--android:layout_height="46dp"-->
    <!--android:background="@color/white">-->

    <!--<ImageView-->
    <!--android:layout_width="wrap_content"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:background="@drawable/cloud_icon"-->
    <!--android:layout_gravity="center_vertical"-->
    <!--android:layout_marginLeft="14dp"/>-->

    <!--<TextView-->
    <!--android:layout_width="wrap_content"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:text="@string/i_cloud"-->
    <!--style="@style/default_text"-->
    <!--android:layout_gravity="center_vertical"-->
    <!--android:layout_marginLeft="10dp"/>-->

    <!--<ImageView-->
    <!--android:layout_weight="1"-->
    <!--android:layout_width="wrap_content"-->
    <!--android:layout_height="match_parent"-->
    <!--android:src="@drawable/arrow"-->
    <!--android:layout_gravity="center_vertical"-->
    <!---->
    <!--android:layout_marginRight="14dp"/>-->
    <!--</LinearLayout>-->

    <RelativeLayout
            android:id = "@+id/rl_setting_no_wifi"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:layout_centerVertical = "true"
                android:layout_marginLeft = "14dp"
                android:text = "@string/down_file_nowifi"
                style = "@style/default_text_size"/>

        <com.jinglingtec.ijiazu.ui.SwitchButton
                android:id = "@+id/sb_set_wifi"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:layout_centerVertical = "true"
                android:layout_alignParentRight = "true"
                android:layout_marginRight = "16dp"/>

    </RelativeLayout>

    <View
            android:layout_width = "fill_parent"
            android:layout_height = "1dip"
            android:background = "@color/app_bg"/>

    <RelativeLayout
            android:id = "@+id/rl_setting_blue_tooth"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:layout_centerVertical = "true"
                android:layout_marginLeft = "14dp"
                android:text = "@string/blue_tooth"
                style = "@style/default_text_size"/>

        <com.jinglingtec.ijiazu.ui.SwitchButton
                android:id = "@+id/sb_set_ble"
                android:clickable = "true"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:layout_centerVertical = "true"
                android:layout_alignParentRight = "true"
                android:layout_marginRight = "16dp"/>

    </RelativeLayout>

    <LinearLayout
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white"
            android:layout_marginTop = "18dp"
            android:divider = "?android:attr/dividerHorizontal">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/version"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <TextView
                android:id = "@+id/tv_setting_ijiazu_version"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "15dp"/>

    </LinearLayout>

    <View
            android:layout_width = "fill_parent"
            android:layout_height = "1dip"
            android:background = "@color/app_bg"/>

    <LinearLayout
            android:id = "@+id/ll_setting_feed_back"
            android:visibility = "visible"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/feed_back"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

    <View
            android:layout_width = "fill_parent"
            android:layout_height = "1dip"
            android:background = "@color/app_bg"/>

    <LinearLayout
            android:visibility = "gone"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/fodrive_help"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

    <View
            android:visibility = "gone"
            android:layout_width = "fill_parent"
            android:layout_height = "1dip"
            android:background = "@color/app_bg"/>

    <LinearLayout
            android:id = "@+id/ll_setting_fodrive_about"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/about"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

    <LinearLayout
            android:id = "@+id/ll_setting_quick_buy"
            android:visibility = "gone"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:background = "@color/white"
            android:layout_marginTop = "18dp"
            android:divider = "?android:attr/dividerHorizontal">

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/shop"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/quick_buy"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "10dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

    <View
            android:layout_width = "fill_parent"
            android:layout_height = "1dip"
            android:background = "@color/app_bg"/>

    <LinearLayout
            android:id = "@+id/ll_setting_ecar_register"
            android:layout_width = "match_parent"
            android:layout_height = "46dp"
            android:layout_marginTop = "18dp"
            android:background = "@color/white"
            android:divider = "?android:attr/dividerHorizontal">

        <TextView
                android:layout_weight = "1"
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:text = "@string/ecar_register"
                style = "@style/default_text_size"
                android:layout_gravity = "center_vertical"
                android:layout_marginLeft = "14dp"/>

        <ImageView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:background = "@drawable/right_arrow"
                android:layout_gravity = "center_vertical"
                android:layout_marginRight = "14dp"/>

    </LinearLayout>

</LinearLayout>


text:
package org.glyptodon.guacamole.form;

/**
 * Represents a basic text field. The field may generally contain any data, but
 * may not contain multiple lines.
 *
 * @author Michael Jumper
 */
public class TextField extends Field {

    /**
     * Creates a new TextField with the given name.
     *
     * @param name
     *     The unique name to associate with this field.
     */
    public TextField(String name) {
        super(name, Field.Type.TEXT);
    }

}


text:
package CrystallineMagic.Blocks;

import CrystallineMagic.Main.ModItems;
import MiscUtils.Block.ModBlock;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;

import java.util.Random;

public class ModBlockGreenCrystalOre extends ModBlock {

    public ModBlockGreenCrystalOre() {
        super(Material.rock);
        this.setHardness(8);
    }

    public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_)

    {

        return ModItems.GreenCrystal;
    }

    public int quantityDroppedWithBonus(int p_149679_1_, Random p_149679_2_)
    {

        return this.quantityDropped(p_149679_2_) + p_149679_2_.nextInt(p_149679_1_ + 1);
    }

    public int quantityDropped(Random p_149745_1_)
    {
        return 1 + p_149745_1_.nextInt(3);
    }

}


text:
import React, { Component } from 'react';
import 'cropperjs/dist/cropper.css';
import Cropper from '../../src/rc-cropper';

const src = 'http://fengyuanchen.github.io/cropper/images/picture.jpg';

// Inspired by [react-cropper](https://github.com/roadmanfong/react-cropper)

export default class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      src,
      cropResult: null,
    };
    this._cropImage = this._cropImage.bind(this);
    this._onChange = this._onChange.bind(this);
    this._useDefaultImage = this._useDefaultImage.bind(this);
  }

  _cropImage() {
    if (typeof this.refs.cropper.getCroppedCanvas() === 'undefined') {
      return;
    }
    this.setState({
      cropResult: this.refs.cropper.getCroppedCanvas().toDataURL(),
    });
  }

  _onChange(e) {
    e.preventDefault();
    let files;
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }
    const reader = new FileReader();
    reader.onload = () => {
      this.setState({ src: reader.result });
    };
    reader.readAsDataURL(files[0]);
  }

  _useDefaultImage() {
    this.setState({ src });
  }

  render() {
    return (

          <input type="file" onChange={this._onChange} />
          <button onClick={this._useDefaultImage}>Use default img</button>

          <Cropper ref="cropper" src={this.state.src} showActions />

          <button onClick={this._cropImage}>Crop</button>

            {
              this.state.cropResult
              ?
              : null
            }

    );
  }
}


text:
/**
 * Dom utility
 *
 * @see
 * @since: 2015.09.02
 * @author: hw.shim
 */

/* jshint unused:false */

// @formatter:off
define(function (module) {
    'use strict';
// @formatter:on

    return {

        byId: function (id) {
            return document.getElementById(id);
        },

        byTag: function (tagName) {
            return document.getElementsByTagName(tagName);
        },

        bySelector: function (selector, element) {
            element = element || document;
            return element.querySelectorAll(selector);
        },

        getAppliedStyleClone: function (element) {
            /*jshint -W010 */
            var prop, result = new Object();
            /*jshint +W010 */
            for (prop in element.style) {
                if (element.style.hasOwnProperty(prop)) {
                    result[prop] = element.style[prop];
                }
            }
            return result;
        },

        getComputedStyleClone: function (element) {
            var styles = window.getComputedStyle(element), len = styles.length, i, prop, result = {};
            for (i = 0; i < len; i++) {
                prop = styles[i];
                //result[prop] = styles[prop];
                result[prop] = styles.getPropertyValue(prop);
            }
            return result;
        },

        getComputedStyleDiff: function (styleOrg, styleVar) {
            var prop, result = {};
            for (prop in styleOrg) {
                if (styleOrg[prop] !== styleVar[prop]) {
                    result[prop] = styleVar[prop];
                }
            }
            return result;
        },

        checkComputedStyleDiff: function (styleOrg, styleVar) {
            var i, check = false, result = this.getComputedStyleDiff(styleOrg, styleVar);
            for (i in result) {
                if (result.hasOwnProperty(i)) {
                    //console.log(i+' = '+result[i]);
                    check = true;
                }
            }
            return check;
        },

        getStyle: function (element, prop) {
            var styles = window.getComputedStyle(element);
            //return styles[prop];
            return styles.getPropertyValue(prop);
        },

        setStyles: function (element, propSet) {
            //console.log('dom.setStyles('+element.id+', propSet)');
            var prop, style = element.style;
            for (prop in propSet) {
                if (propSet.hasOwnProperty(prop)) {
                    style.setProperty(prop, propSet[prop]);
                }
            }
        },

        setAttributes: function (element, propSet) {
            var prop;
            for (prop in propSet) {
                if (propSet.hasOwnProperty(prop)) {
                    element.setAttribute(prop, propSet[prop]);
                }
            }
        },

        makeElementNs: function (tag, namespace, properties) {
            var element = document.createElementNS(namespace, tag);
            if (properties) {
                for (var p in properties) {
                    if (properties.hasOwnProperty(p)) {
                        element.setAttribute(p, properties[p]);
                    }
                }
            }
            return element;
        },

        makeSvgElement: function (tag, properties) {
            return this.makeElementNs(tag, 'http://www.w3.org/2000/svg', properties);
        },

        makeElement: function (tag, properties, where, win) {
            if (typeof win === 'undefined') {
                win = window;
            }
            var element = win.document.createElement(tag);
            if (properties) {
                for (var p in properties) {
                    if (properties.hasOwnProperty(p)) {
                        element.setAttribute(p, properties[p]);
                    }
                }
            }
            if (where) {
                this.addElement(element, where.element, where.position);
            }
            return element;
        }
    };
});


text:
layout: post.html
date: 2015-09-25
title: Have I greeted the world?
tags: life, science
---

Have I greeted the world? Just to be sure:

```
Hello world!
```


text:
<?php

/**
 * sfGuardUser form.
 *
 * @package    form
 * @subpackage sf_guard_user
 * @version    SVN: $Id$
 */
class sfGuardUserForm extends sfGuardUserAdminForm
{
  public function configure()
  {
    parent::configure();

    unset(
      $this['last_login'],
      $this['created_at'],
      $this['salt'],
      $this['algorithm'],
      $this['is_active'],
      $this['is_super_admin'],
      $this['sf_guard_user_group_list'],
      $this['sf_guard_user_permission_list']
    );
  }
}