text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PublishConfigData" serverName="SweetlakePHP - Jasper" />
</project>

redpajama_set_name: RedPajamaGithub


text:
package com.twu.biblioteca;

/**
 * Created by ileppa on 9/11/15.
 */
public class BibliotecaAppTest {

}


text:
package io.confluent.admin.utils;

import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.common.protocol.SecurityProtocol;
import org.apache.kafka.common.utils.SystemTime;
import org.apache.kafka.common.utils.Time;
import org.assertj.core.data.Offset;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;

public class ClusterStatusTest {

    private static EmbeddedKafkaCluster kafka;
    private static int numBrokers = 3;
    private static int numZookeeperPeers = 3;

    @BeforeClass
    public static void setup() throws IOException {

        kafka = new EmbeddedKafkaCluster(numBrokers, numZookeeperPeers);
        kafka.start();
    }

    @AfterClass
    public static void tearDown() {
        kafka.shutdown();
    }

    @Test(timeout = 120000)
    public void zookeeperReady() throws Exception {
        assertThat(
                ClusterStatus.isZookeeperReady(this.kafka.getZookeeperConnectString(), 10000))
                .isTrue();
    }

    @Test(timeout = 120000)
    public void zookeeperReadyWithBadConnectString() throws Exception {
        assertThat(
                ClusterStatus.isZookeeperReady("localhost:3245", 10000))
                .isFalse();
    }

    @Test(timeout = 120000)
    public void isKafkaReady() throws Exception {

        Map<String, String> config = new HashMap<>();
        config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapBroker
                (SecurityProtocol.PLAINTEXT));
        assertThat(ClusterStatus.isKafkaReady(config, 3, 10000))
                .isTrue();
    }

    @Test(timeout = 120000)
    public void isKafkaReadyFailWithLessBrokers() throws Exception {
        try {
            Map<String, String> config = new HashMap<>();
            config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapBroker
                    (SecurityProtocol.PLAINTEXT));
            assertThat(ClusterStatus.isKafkaReady(config, 5, 10000))
                    .isFalse();
        } catch (Exception e) {
            fail("Unexpected error. " + e.getMessage());
        }

    }

    @Test(timeout = 120000)
    public void isKafkaReadyWaitFailureWithNoBroker() throws Exception {
        try {
            Map<String, String> config = new HashMap<>();
            config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "localhost:6789");
            assertThat(ClusterStatus.isKafkaReady(config, 3, 10000)).isFalse();
        } catch (Exception e) {
            fail("Unexpected error." + e.getMessage());
        }
    }

}


text:
<?php

if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
	define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Core', array('Helper', 'AppHelper', 'Controller', 'View'));
App::import('Helper', array('Session'));

/**
 * SessionHelperTest class
 *
 * @package       cake
 * @subpackage    cake.tests.cases.libs.view.helpers
 */
class SessionHelperTest extends CakeTestCase {

/**
 * setUp method
 *
 * @access public
 * @return void
 */
	function startTest() {
		$this->Session = new SessionHelper();

		$_SESSION = array(
			'test' => 'info',
			'Message' => array(
				'flash' => array(
					'element' => 'default',
					'params' => array(),
					'message' => 'This is a calling'
				),
				'notification' => array(
					'element' => 'session_helper',
					'params' => array('title' => 'Notice!', 'name' => 'Alert!'),
					'message' => 'This is a test of the emergency broadcasting system',
				),
				'classy' => array(
					'element' => 'default',
					'params' => array('class' => 'positive'),
					'message' => 'Recorded'
				),
				'bare' => array(
					'element' => null,
					'message' => 'Bare message',
					'params' => array(),
				),
			),
			'Deeply' => array('nested' => array('key' => 'value')),
		);
	}

/**
 * tearDown method
 *
 * @access public
 * @return void
 */
	function tearDown() {
		$_SESSION = array();
		unset($this->Session);
	}

/**
 * endTest
 *
 * @access public
 * @return void
 */
	function endTest() {
		App::build();
	}

/**
 * test construction and initial property settings
 *
 * @return void
 */
	function testConstruct() {
		$this->assertFalse(empty($this->Session->sessionTime));
		$this->assertFalse(empty($this->Session->security));
	}
/**
 * testRead method
 *
 * @access public
 * @return void
 */
	function testRead() {
		$result = $this->Session->read('Deeply.nested.key');
		$this->assertEqual($result, 'value');

		$result = $this->Session->read('test');
		$this->assertEqual($result, 'info');
	}

/**
 * testCheck method
 *
 * @access public
 * @return void
 */
	function testCheck() {
		$this->assertTrue($this->Session->check('test'));

		$this->assertTrue($this->Session->check('Message.flash.element'));

		$this->assertFalse($this->Session->check('Does.not.exist'));

		$this->assertFalse($this->Session->check('Nope'));
	}

/**
 * testWrite method
 *
 * @access public
 * @return void
 */
	function testWrite() {
		$this->expectError();
		$this->Session->write('NoWay', 'AccessDenied');
	}

/**
 * testFlash method
 *
 * @access public
 * @return void
 */
	function testFlash() {
		$result = $this->Session->flash('flash', true);
		$expected = '
This is a calling
';
		$this->assertEqual($result, $expected);
		$this->assertFalse($this->Session->check('Message.flash'));

		$expected = '
Recorded
';
		$result = $this->Session->flash('classy', true);
		$this->assertEqual($result, $expected);

		App::build(array(
			'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
		));
		$controller = new Controller();
		$this->Session->view = new View($controller);

		$result = $this->Session->flash('notification', true);
		$result = str_replace("\r\n", "\n", $result);
		$expected = "
\n\t
Alert!
\n\t
Notice!
\n\t
This is a test of the emergency broadcasting system
\n
";
		$this->assertEqual($result, $expected);
		$this->assertFalse($this->Session->check('Message.notification'));

		$result = $this->Session->flash('bare');
		$expected = 'Bare message';
		$this->assertEqual($result, $expected);
		$this->assertFalse($this->Session->check('Message.bare'));
	}

/**
 * testID method
 *
 * @access public
 * @return void
 */
	function testID() {
		$id = session_id();
		$result = $this->Session->id();
		$this->assertEqual($id, $result);
	}

/**
 * testError method
 *
 * @access public
 * @return void
 */
	function testError() {
		$result = $this->Session->error();
		$this->assertFalse($result);

		$this->Session->read('CauseError');
		$result = $this->Session->error();
		$expected = "CauseError doesn't exist";
		$this->assertEqual($result, $expected);
	}

/**
 * testDisabling method
 *
 * @access public
 * @return void
 */
	function testDisabling() {
		Configure::write('Session.start', false);
		$this->Session = new SessionHelper();
		$this->assertFalse($this->Session->check('test'));
		$this->assertFalse($this->Session->read('test'));

		$this->Session->read('CauseError');
		$this->assertFalse($this->Session->error());

		ob_start();
		$this->assertFalse($this->Session->flash('bare'));
		$result = ob_get_contents();
		ob_clean();
		$this->assertFalse($result);
	}

/**
 * testValid method
 *
 * @access public
 * @return void
 */
	function testValid() {
		//wierd it always ends up false in the test suite
		//$this->assertFalse($this->Session->valid());
	}
}


text:
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

// guestbookEntry represents the message object returned in the API.
type guestbookEntry struct {
	Author  string    `json:"author" bson:"author"`
	Message string    `json:"message" bson:"message"`
	Date    time.Time `json:"date" bson:"date"`
}

type guestbookServer struct {
	db database
}

// main starts a server listening on $PORT responding to requests "GET
// /messages" and "POST /messages" with a JSON API.
func main() {
	ctx := context.Background()

	// PORT environment variable is set in guestbook-backend.deployment.yaml.
	port := os.Getenv("PORT")
	if port == "" {
		log.Fatal("PORT environment variable not specified")
	}
	// GUESTBOOK_DB_ADDR environment variable is set in guestbook-backend.deployment.yaml.
	dbAddr := os.Getenv("GUESTBOOK_DB_ADDR")
	if dbAddr == "" {
		log.Fatal("GUESTBOOK_DB_ADDR environment variable not specified")
	}

	mongoURI := "mongodb://" + dbAddr
	connCtx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()
	dbConn, err := mongo.Connect(connCtx, options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatalf("failed to initialize connection to mongodb: %+v", err)
	}
	if err := dbConn.Ping(connCtx, readpref.Primary()); err != nil {
		log.Fatalf("ping to mongodb failed: %+v", err)
	}

	gs := &guestbookServer{
		db: &mongodb{
			conn: dbConn,
		},
	}

	log.Printf("backend server listening on port %s", port)
	http.Handle("/messages", gs)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func (s *guestbookServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf("received request: method=%s path=%s", r.Method, r.URL.Path)
	if r.Method == http.MethodGet {
		s.getMessagesHandler(w, r)
	} else if r.Method == http.MethodPost {
		s.postMessageHandler(w, r)
	} else {
		http.Error(w, fmt.Sprintf("unsupported method %s", r.Method), http.StatusMethodNotAllowed)
	}
}

func (s *guestbookServer) getMessagesHandler(w http.ResponseWriter, r *http.Request) {
	entries, err := s.db.entries(r.Context())
	if err != nil {
		http.Error(w, fmt.Sprintf("failed to read entries: %+v", err), http.StatusInternalServerError)
		// TODO return JSON error
		return
	}
	if err := json.NewEncoder(w).Encode(entries); err != nil {
		log.Printf("WARNING: failed to encode json into response: %+v", err)
	} else {
		log.Printf("%d entries returned", len(entries))
	}
}

func (s *guestbookServer) postMessageHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	var v guestbookEntry
	if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
		http.Error(w, fmt.Sprintf("failed to decode request body into json: %+v", err), http.StatusBadRequest)
		return
	}
	if v.Author == "" {
		http.Error(w, "empty 'author' value", http.StatusBadRequest)
		return
	}
	if v.Message == "" {
		http.Error(w, "empty 'message' value", http.StatusBadRequest)
		return
	}

	v.Date = time.Now()

	if err := s.db.addEntry(r.Context(), v); err != nil {
		http.Error(w, fmt.Sprintf("failed to save entry: %+v", err), http.StatusInternalServerError)
		return
	}
	log.Printf("entry saved: author=%q message=%q", v.Author, v.Message)
}


text:
//
// Copyright 2020 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//

using Google.Solutions.Mvvm.Binding;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

#pragma warning disable CS1690 // Accessing a member on a field of a marshal-by-reference class may cause a runtime exception

namespace Google.Solutions.Mvvm.Controls
{
    public class BindableTreeView<TModelNode> : TreeView
        where TModelNode : class, INotifyPropertyChanged
    {
        private Expression<Func<TModelNode, bool>> isExpandedExpression = null;
        private Expression<Func<TModelNode, string>> textExpression = null;

        private Expression<Func<TModelNode, int>> imageIndexExpression = null;
        private Expression<Func<TModelNode, int>> selectedImageIndexExpression = null;

        private bool imageIndexExpressionReadonly = false;
        private bool selectedImageIndexExpressionReadonly = false;

        private Func<TModelNode, bool> isLeafFunc = _ => false;
        private Action<TModelNode, bool> setExpandedFunc = (n, state) => { };
        private Func<TModelNode, bool> isExpandedFunc = _ => false;
        private Func<TModelNode, Task<ICollection<TModelNode>>> getChildrenAsyncFunc
            = _ => Task.FromResult<ICollection<TModelNode>>(new ObservableCollection<TModelNode>());

        private readonly TaskScheduler taskScheduler;

        public event EventHandler SelectedModelNodeChanged;
        public event EventHandler<ExceptionEventArgs> LoadingChildrenFailed;

        public BindableTreeView()
        {
            this.taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            this.BeforeExpand += (sender, args) => ((Node)args.Node).OnExpand();
            this.BeforeCollapse += (sender, args) => ((Node)args.Node).OnCollapse();

            // Consider right-click as a selection.
            this.NodeMouseClick += (sender, args) =>
            {
                if (args.Button == MouseButtons.Right)
                {
                    this.SelectedNode = args.Node;
                }
            };
            this.AfterSelect += (sender, args) =>
            {
                this.SelectedModelNodeChanged?.Invoke(this, EventArgs.Empty);
            };
        }

        public TModelNode SelectedModelNode
        {
            get
            {
                if (this.SelectedNode is Node node)
                {
                    return node.Model;
                }
                else
                {
                    return null;
                }
            }
        }

        //---------------------------------------------------------------------
        // Data Binding.
        //---------------------------------------------------------------------

        private static void DisposeAndClear(TreeNodeCollection nodes)
        {
            var disposables = nodes.OfType<Node>().ToList();
            nodes.Clear();

            foreach (var node in disposables)
            {
                node.Dispose();
            }
        }

        public void Bind(TModelNode rootNode)
        {
            DisposeAndClear(this.Nodes);
            this.Nodes.Add(new Node(this, rootNode));
        }

        public void BindIsLeaf(Func<TModelNode, bool> isLeafFunc)
        {
            this.isLeafFunc = isLeafFunc;
        }

        public void BindImageIndex(
            Expression<Func<TModelNode, int>> imageIndexExpression,
            bool readOnly = false)
        {
            this.imageIndexExpression = imageIndexExpression;
            this.imageIndexExpressionReadonly = readOnly;
        }

        public void BindSelectedImageIndex(Expression<Func<TModelNode, int>>
            selectedImageIndexExpression,
            bool readOnly = false)
        {
            this.selectedImageIndexExpression = selectedImageIndexExpression;
            this.selectedImageIndexExpressionReadonly = readOnly;
        }

        public void BindText(Expression<Func<TModelNode, string>> nameExpression)
        {
            this.textExpression = nameExpression;
        }

        public void BindIsExpanded(Expression<Func<TModelNode, bool>> propertyExpression)
        {
            if (propertyExpression.Body is MemberExpression memberExpression &&
                memberExpression.Member is PropertyInfo propertyInfo)
            {
                this.isExpandedExpression = propertyExpression;
                this.isExpandedFunc = propertyExpression.Compile();
                this.setExpandedFunc = (node, value) => propertyInfo.SetValue(node, value);
            }
            else
            {
                throw new ArgumentException("Expression does not resolve to a property");
            }
        }

        public void BindChildren(
            Func<TModelNode, Task<ObservableCollection<TModelNode>>> getChildrenAsyncFunc)
        {
            this.getChildrenAsyncFunc = async n => await getChildrenAsyncFunc(n).ConfigureAwait(true);
        }

        public void BindChildren(
            Func<TModelNode, Task<ICollection<TModelNode>>> getChildrenAsyncFunc)
        {
            this.getChildrenAsyncFunc = getChildrenAsyncFunc;
        }

        //---------------------------------------------------------------------
        // BindableTreeNode
        //---------------------------------------------------------------------

        internal sealed class Node : TreeNode, IDisposable
        {
            private readonly BindableTreeView<TModelNode> treeView;
            public TModelNode Model { get; }

            //
            // Flag indicating whether a lazy load has been kicked off (it
            // might not be finished yet though).
            //
            private bool lazyLoadTriggered = false;

            private readonly TaskCompletionSource<ICollection<TModelNode>> lazyLoadResult
                = new TaskCompletionSource<ICollection<TModelNode>>();

            private readonly IContainer bindings = new Container();

            public Node(BindableTreeView<TModelNode> treeView, TModelNode modelNode)
            {
                this.treeView = treeView;
                this.Model = modelNode;

                // Bind properties to keep TreeNode in sync with view model.
                // Note that binding is one-way (view model -> view) as TreeNodes
                // are not proper controls and do not provide the necessary events.
                if (this.treeView.textExpression != null)
                {
                    this.Name = this.Text = this.treeView.textExpression.Compile()(this.Model);
                    this.bindings.Add(this.Model.OnPropertyChange(
                        this.treeView.textExpression,
                        text => this.Text = text));
                }

                if (this.treeView.imageIndexExpression != null)
                {
                    this.ImageIndex = this.treeView.imageIndexExpression.Compile()(this.Model);
                    if (!this.treeView.imageIndexExpressionReadonly)
                    {
                        this.bindings.Add(this.Model.OnPropertyChange(
                            this.treeView.imageIndexExpression,
                            iconIndex => this.ImageIndex = iconIndex));
                    }
                }

                if (this.treeView.selectedImageIndexExpression != null)
                {
                    this.SelectedImageIndex = this.treeView.selectedImageIndexExpression.Compile()(this.Model);
                    if (!this.treeView.selectedImageIndexExpressionReadonly)
                    {
                        this.bindings.Add(this.Model.OnPropertyChange(
                            this.treeView.selectedImageIndexExpression,
                            iconIndex => this.SelectedImageIndex = iconIndex));
                    }
                }

                if (this.treeView.isExpandedExpression != null)
                {
                    this.bindings.Add(this.Model.OnPropertyChange(
                        this.treeView.isExpandedExpression,
                        expanded =>
                        {
                            if (expanded)
                            {
                                this.Expand();
                            }
                            else
                            {
                                this.Collapse();
                            }
                        }));
                }

                if (this.treeView.isLeafFunc(this.Model))
                {
                    // This node does not have children.
                }
                else
                {
                    // This node might have children. Add a dummy node
                    // to ensure that the '+' control is being displayed.
                    this.Nodes.Add(new LoadingTreeNode());

                    if (this.treeView.isExpandedFunc(this.Model))
                    {
                        // Eagerly load children.
                        this.Expand();
                        LazyLoadChildren();
                    }
                    else
                    {
                        // Lazy load children. Nothing to do for now.
                    }
                }
            }

            internal void OnExpand()
            {
                if (!this.treeView.isExpandedFunc(this.Model))
                {
                    this.treeView.setExpandedFunc(this.Model, true);
                }

                LazyLoadChildren();
            }

            internal void OnCollapse()
            {
                if (this.treeView.isExpandedFunc(this.Model))
                {
                    this.treeView.setExpandedFunc(this.Model, false);
                }
            }

            private void LazyLoadChildren()
            {
                if (this.lazyLoadTriggered)
                {
                    return;
                }

                this.lazyLoadTriggered = true;
                this.treeView.getChildrenAsyncFunc(this.Model)
                    .ContinueWith(t =>
                    {
                        try
                        {
                            var children = t.Result;

                            try
                            {
                                //
                                // Suspend redrawing while updating nodes
                                // to reduce flicker and vertical scrolling.
                                //
                                this.treeView.BeginUpdate();

                                //
                                // Clear any dummy node if present.
                                //
                                Debug.Assert(!this.Nodes.OfType<Node>().Any());
                                DisposeAndClear(this.Nodes);

                                //
                                // Add nodes.
                                //
                                AddTreeNodesForModelNodes(children);
                            }
                            finally
                            {
                                this.treeView.EndUpdate();
                            }

                            //
                            // Observe for changes.
                            //
                            if (children is INotifyCollectionChanged observable)
                            {
                                observable.CollectionChanged += ModelChildrenChanged;
                            }

                            //
                            // Notify waiters (but only the first time, not on retry).
                            //
                            if (!this.lazyLoadResult.Task.IsCompleted)
                            {
                                this.lazyLoadResult.SetResult(children);
                            }
                        }
                        catch (Exception e)
                        {
                            //
                            // Reset state so that the action can be retried.
                            //
                            this.Collapse();
                            this.treeView.setExpandedFunc(this.Model, false);
                            this.lazyLoadTriggered = false;

                            //
                            // Report error.
                            //
                            this.treeView.LoadingChildrenFailed?.Invoke(
                                this.Model,
                                new ExceptionEventArgs(e));

                            //
                            // Notify waiters (but only the first time, not on retry).
                            //
                            if (!this.lazyLoadResult.Task.IsCompleted)
                            {
                                this.lazyLoadResult.SetException(e);
                            }
                        }
                    },
                    CancellationToken.None,
                    TaskContinuationOptions.None,

                    // Continue on UI thread.
                    // Note that there's a bug in the CLR that can cause
                    // TaskScheduler.FromCurrentSynchronizationContext() to become null.
                    // Therefore, use a task scheduler object captured previously.
                    // Cf. https://stackoverflow.com/questions/4659257/
                    this.treeView.taskScheduler);
            }

            public Task ExpandAsync()
            {
                Expand();

                //
                // Return task indicating the lazy load result. If the
                // node was expanded already/before, then this task might
                // have been completed for a while.
                //
                return this.lazyLoadResult.Task;
            }

            private void AddTreeNodesForModelNodes(IEnumerable<TModelNode> children)
            {
                foreach (var child in children)
                {
                    this.Nodes.Add(new Node(this.treeView, child));
                }
            }

            internal Node FindTreeNodeByModelNode(TModelNode modelNode)
            {
                return this.Nodes
                    .OfType<Node>()
                    .FirstOrDefault(n => n.Model.Equals(modelNode));
            }

            private void ModelChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        AddTreeNodesForModelNodes(e.NewItems.OfType<TModelNode>());
                        break;

                    case NotifyCollectionChangedAction.Remove:
                        foreach (var oldModelItem in e.OldItems.OfType<TModelNode>())
                        {
                            var oldTreeNode = FindTreeNodeByModelNode(oldModelItem);
                            if (oldTreeNode != null)
                            {
                                this.Nodes.Remove(oldTreeNode);
                                oldTreeNode.Dispose();
                            }
                        }

                        break;

                    case NotifyCollectionChangedAction.Replace:
                        if (e.OldItems.Count == e.NewItems.Count)
                        {
                            var count = e.OldItems.Count;
                            for (var i = 0; i < count; i++)
                            {
                                var oldModelItem = (TModelNode)e.OldItems[i];
                                var newModelItem = (TModelNode)e.NewItems[i];

                                var treeNode = FindTreeNodeByModelNode(oldModelItem);
                                if (treeNode != null)
                                {
                                    this.Nodes.Remove(treeNode);
                                    treeNode.Dispose();

                                    this.Nodes.Insert(
                                        e.NewStartingIndex,
                                        new Node(this.treeView, newModelItem));
                                }
                            }
                        }

                        break;

                    case NotifyCollectionChangedAction.Move:
                        // Not supported.
                        break;

                    case NotifyCollectionChangedAction.Reset:
                        // Reload everything.
                        DisposeAndClear(this.Nodes);

                        AddTreeNodesForModelNodes((ObservableCollection<TModelNode>)sender);
                        break;

                    default:
                        break;
                }
            }

            public void Dispose()
            {
                this.bindings.Dispose();
            }
        }

        private class LoadingTreeNode : TreeNode
        {
            public LoadingTreeNode()
                : base("Loading...")
            {
            }
        }
    }
}


text:
package org.apache.camel.component.grpc;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.googlecode.junittoolbox.MultithreadingTester;
import com.googlecode.junittoolbox.RunnableAssert;

import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GrpcConsumerConcurrentTest extends CamelTestSupport {
    private static final Logger LOG = LoggerFactory.getLogger(GrpcConsumerConcurrentTest.class);

    private static final int GRPC_ASYNC_REQUEST_TEST_PORT = AvailablePortFinder.getNextAvailable();
    private static final int GRPC_HEADERS_TEST_PORT = AvailablePortFinder.getNextAvailable();
    private static final int CONCURRENT_THREAD_COUNT = 30;
    private static final int ROUNDS_PER_THREAD_COUNT = 10;
    private static final String GRPC_TEST_PING_VALUE = "PING";
    private static final String GRPC_TEST_PONG_VALUE = "PONG";
    private static final String GRPC_USER_AGENT_PREFIX = "user-agent-";
    private static AtomicInteger idCounter = new AtomicInteger();

    public static Integer createId() {
        return idCounter.getAndIncrement();
    }

    public static Integer getId() {
        return idCounter.get();
    }

    @Test
    public void testAsyncWithConcurrentThreads() throws Exception {
        RunnableAssert ra = new RunnableAssert("foo") {

            @Override
            public void run() {
                final CountDownLatch latch = new CountDownLatch(1);
                ManagedChannel asyncRequestChannel = NettyChannelBuilder.forAddress("localhost", GRPC_ASYNC_REQUEST_TEST_PORT).usePlaintext(true).build();
                PingPongGrpc.PingPongStub asyncNonBlockingStub = PingPongGrpc.newStub(asyncRequestChannel);

                PongResponseStreamObserver responseObserver = new PongResponseStreamObserver(latch);
                int instanceId = createId();

                final PingRequest pingRequest = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(instanceId).build();
                StreamObserver<PingRequest> requestObserver = asyncNonBlockingStub.pingAsyncAsync(responseObserver);
                requestObserver.onNext(pingRequest);
                requestObserver.onNext(pingRequest);
                requestObserver.onCompleted();
                try {
                    latch.await(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                PongResponse pongResponse = responseObserver.getPongResponse();

                assertNotNull("instanceId = " + instanceId, pongResponse);
                assertEquals(instanceId, pongResponse.getPongId());
                assertEquals(GRPC_TEST_PING_VALUE + GRPC_TEST_PONG_VALUE, pongResponse.getPongName());

                asyncRequestChannel.shutdown().shutdownNow();
            }
        };

        new MultithreadingTester().add(ra).numThreads(CONCURRENT_THREAD_COUNT).numRoundsPerThread(ROUNDS_PER_THREAD_COUNT).run();
    }

    @Test
    public void testHeadersWithConcurrentThreads() throws Exception {
        RunnableAssert ra = new RunnableAssert("foo") {

            @Override
            public void run() {
                int instanceId = createId();
                final CountDownLatch latch = new CountDownLatch(1);
                ManagedChannel asyncRequestChannel = NettyChannelBuilder.forAddress("localhost", GRPC_HEADERS_TEST_PORT).userAgent(GRPC_USER_AGENT_PREFIX + instanceId)
                    .usePlaintext(true).build();
                PingPongGrpc.PingPongStub asyncNonBlockingStub = PingPongGrpc.newStub(asyncRequestChannel);

                PongResponseStreamObserver responseObserver = new PongResponseStreamObserver(latch);

                final PingRequest pingRequest = PingRequest.newBuilder().setPingName(GRPC_TEST_PING_VALUE).setPingId(instanceId).build();
                StreamObserver<PingRequest> requestObserver = asyncNonBlockingStub.pingAsyncAsync(responseObserver);
                requestObserver.onNext(pingRequest);
                requestObserver.onNext(pingRequest);
                requestObserver.onCompleted();
                try {
                    latch.await(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                PongResponse pongResponse = responseObserver.getPongResponse();

                assertNotNull("instanceId = " + instanceId, pongResponse);
                assertEquals(instanceId, pongResponse.getPongId());
                assertEquals(GRPC_USER_AGENT_PREFIX + instanceId, pongResponse.getPongName());

                asyncRequestChannel.shutdown().shutdownNow();
            }
        };

        new MultithreadingTester().add(ra).numThreads(CONCURRENT_THREAD_COUNT).numRoundsPerThread(ROUNDS_PER_THREAD_COUNT).run();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("grpc://org.apache.camel.component.grpc.PingPong?synchronous=true&consumerStrategy=AGGREGATION&host=localhost&port=" + GRPC_ASYNC_REQUEST_TEST_PORT)
                    .bean(new GrpcMessageBuilder(), "buildAsyncPongResponse");

                from("grpc://org.apache.camel.component.grpc.PingPong?synchronous=true&consumerStrategy=AGGREGATION&host=localhost&port=" + GRPC_HEADERS_TEST_PORT)
                    .process(new HeaderExchangeProcessor());
            }
        };
    }

    public class PongResponseStreamObserver implements StreamObserver<PongResponse> {
        private PongResponse pongResponse;
        private final CountDownLatch latch;

        public PongResponseStreamObserver(CountDownLatch latch) {
            this.latch = latch;
        }

        public PongResponse getPongResponse() {
            return pongResponse;
        }

        @Override
        public void onNext(PongResponse value) {
            pongResponse = value;
        }

        @Override
        public void onError(Throwable t) {
            LOG.info("Exception", t);
            latch.countDown();
        }

        @Override
        public void onCompleted() {
            latch.countDown();
        }
    }

    public class GrpcMessageBuilder {
        public PongResponse buildAsyncPongResponse(List<PingRequest> pingRequests) {
            return PongResponse.newBuilder().setPongName(pingRequests.get(0).getPingName() + GRPC_TEST_PONG_VALUE).setPongId(pingRequests.get(0).getPingId()).build();
        }
    }

    public class HeaderExchangeProcessor implements Processor {

        @SuppressWarnings("unchecked")
        public void process(Exchange exchange) throws Exception {
            List<PingRequest> pingRequests = (List<PingRequest>)exchange.getIn().getBody();
            String userAgentName = (String)exchange.getIn().getHeader(GrpcConstants.GRPC_USER_AGENT_HEADER);

            // As user agent name is prepended the library's user agent
            // information it's necessary to extract this value (before first
            // space)
            PongResponse pongResponse = PongResponse.newBuilder().setPongName(userAgentName.substring(0, userAgentName.indexOf(' '))).setPongId(pingRequests.get(0).getPingId())
                .build();
            exchange.getIn().setBody(pongResponse);
        }
    }
}


text:
import * as timus from './timus';
import * as acmp from './acmp';
import * as cf from './cf';
import * as ejudge from './ejudge';
import * as yandex from './yandex';
import * as yandexOfficial from './yandex.official';
import * as manager from './manager';
import * as worker from './worker';

export {
  timus,
  acmp,
  cf,
  ejudge,
  yandex,
  yandexOfficial,
  manager,
  worker
};


text:
'use strict';

var gulp = require('gulp'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    livereload = require('gulp-livereload');

var gulp = require('gulp');

var bowerPath = 'vendor/bower_components/';

gulp.task('copy', function() {

  gulp.src(bowerPath + 'bootstrap/less/**/*.less')
    .pipe(gulp.dest('assets/less/bootstrap'));

  gulp.src(bowerPath + 'bootstrap/js/*.js')
    .pipe(gulp.dest('assets/js/bootstrap'));

  gulp.src(bowerPath + 'jquery/dist/jquery.js')
    .pipe(gulp.dest('assets/js/jquery'));
});

gulp.task('less', function() {
  gulp.src('assets/less/app.less')
    .pipe(less())
    //.pipe(minifyCSS())
    .pipe(gulp.dest('web/css'))
    .pipe(livereload());
});

var jsFiles = [//'assets/js/jquery/jquery.js',
               'assets/js/bootstrap/transition.js',
               'assets/js/bootstrap/collapse.js',
               'assets/js/bootstrap/dropdown.js',
               'assets/js/main.js'];

gulp.task('js', function() {
  gulp.src(jsFiles)
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest('web/js'));
    //.pipe(livereload());
});

gulp.task('twig', function() {
  gulp.src('templates/**/*.html.twig')
    .pipe(livereload());
});

gulp.task('livereload', ['less'], function() {
  livereload.listen();
  gulp.watch('assets/less/**/*.less', ['less']);
  gulp.watch('templates/**/*.html.twig', ['twig']);
});


text:
# In previous versions, the S record included the number of scan points.
# If so, set this to true.
s_record_has_count = True

# Class holding log data of our Lego robot.
# The logfile understands the following records:
# P reference position (of the robot)
# S scan data
# I indices of poles in the scan data (determined by an external algorithm)
# M motor (ticks from the odometer) data
# F filtered data (robot position, or position and heading angle)
# L landmark (reference landmark, fixed)
# D detected landmark, in the scanner's coordinate system
#
class LegoLogfile(object):
    def __init__(self):
        self.reference_positions = []
        self.scan_data = []
        self.pole_indices = []
        self.motor_ticks = []
        self.filtered_positions = []
        self.landmarks = []
        self.detected_cylinders = []
        self.last_ticks = None

    def read(self, filename):
        """Reads log data from file. Calling this multiple times with different
           files will result in a merge of the data, i.e. if one file contains
           M and S data, and the other contains M and P data, then LegoLogfile
           will contain S from the first file and M and P from the second file."""
        # If information is read in repeatedly, replace the lists instead of appending,
        # but only replace those lists that are present in the data.
        first_reference_positions = True
        first_scan_data = True
        first_pole_indices = True
        first_motor_ticks = True
        first_filtered_positions = True
        first_landmarks = True
        first_detected_cylinders = True
        f = open(filename)
        for l in f:
            sp = l.split()
            # P is the reference position.
            # File format: P timestamp[in ms] x[in mm] y[in mm]
            # Stored: A list of tuples [(x, y), ...] in reference_positions.
            if sp[0] == 'P':
                if first_reference_positions:
                    self.reference_positions = []
                    first_reference_positions = False
                self.reference_positions.append( (int(sp[2]), int(sp[3])) )

            # S is the scan data.
            # File format:
            #  S timestamp[in ms] distances[in mm] ...
            # Or, in previous versions (set s_record_has_count to True):
            #  S timestamp[in ms] count distances[in mm] ...
            # Stored: A list of tuples [ [(scan1_distance,... ), (scan2_distance,...) ]
            #   containing all scans, in scan_data.
            elif sp[0] == 'S':
                if first_scan_data:
                    self.scan_data = []
                    first_scan_data = False
                if s_record_has_count:
                    self.scan_data.append(tuple(map(int, sp[3:])))
                else:
                    self.scan_data.append(tuple(map(int, sp[2:])))

            # I is indices of poles in the scan.
            # The indices are given in scan order (counterclockwise).
            # -1 means that the pole could not be clearly detected.
            # File format: I timestamp[in ms] index ...
            # Stored: A list of tuples of indices (including empty tuples):
            #  [(scan1_pole1, scan1_pole2,...), (scan2_pole1,...)...]
            elif sp[0] == 'I':
                if first_pole_indices:
                    self.pole_indices = []
                    first_pole_indices = False
                self.pole_indices.append(tuple(map(int, sp[2:])))

            # M is the motor data.
            # File format: M timestamp[in ms] pos[in ticks] tachoCount[in ticks] acceleration[deg/s^2] rotationSpeed[deg/s] ...
            #   (4 values each for: left motor, right motor, and third motor (not used)).
            # Stored: A list of tuples [ (inc-left, inc-right), ... ] with tick increments, in motor_ticks.
            # Note that the file contains absolute ticks, but motor_ticks contains the increments (differences).
            elif sp[0] == 'M':
                ticks = (int(sp[2]), int(sp[6]))
                if first_motor_ticks:
                    self.motor_ticks = []
                    first_motor_ticks = False
                    self.last_ticks = ticks
                self.motor_ticks.append(
                    tuple([ticks[i]-self.last_ticks[i] for i in range(2)]))
                self.last_ticks = ticks

            # F is filtered trajectory. No time stamp is used.
            # File format: F x[in mm] y[in mm]
            # OR:          F x[in mm] y[in mm] heading[in radians]
            # Stored: A list of tuples, each tuple is (x y) or (x y heading)
            elif sp[0] == 'F':
                if first_filtered_positions:
                    self.filtered_positions = []
                    first_filtered_positions = False
                self.filtered_positions.append( tuple( map(float, sp[1:])) )

            # L is landmark. This is actually background information, independent
            # of time.
            # File format: L <type> info...
            # Supported types:
            # Cylinder: L C x y diameter.
            # Stored: List of (<type> info) tuples.
            elif sp[0] == 'L':
                if first_landmarks:
                    self.landmarks = []
                    first_landmarks = False
                if sp[1] == 'C':
                    self.landmarks.append( tuple(['C'] + map(float, sp[2:])) )

            # D is detected landmarks (in each scan).
            # File format: D <type> info...
            # Supported types:
            # Cylinder: D C x y x y ...
            # Stored: List of lists of (x, y) tuples of the cylinder positions,
            #  one list per scan.
            elif sp[0] == 'D':
                if sp[1] == 'C':
                    if first_detected_cylinders:
                        self.detected_cylinders = []
                        first_detected_cylinders = False
                    cyl = map(float, sp[2:])
                    self.detected_cylinders.append([(cyl[2*i], cyl[2*i+1]) for i in range(len(cyl)/2)])

        f.close()

    def size(self):
        """Return the number of entries. Take the max, since some lists may be empty."""
        return max(len(self.reference_positions), len(self.scan_data),
                   len(self.pole_indices), len(self.motor_ticks),
                   len(self.filtered_positions), len(self.detected_cylinders))

    @staticmethod
    def beam_index_to_angle(i, mounting_angle = -0.06981317007977318):
        """Convert a beam index to an angle, in radians."""
        return (i - 330.0) * 0.006135923151543 + mounting_angle

    def info(self, i):
        """Prints reference pos, number of scan points, and motor ticks."""
        s = ""
        if i < len(self.reference_positions):
            s += " | ref-pos: %4d %4d" % self.reference_positions[i]

        if i < len(self.scan_data):
            s += " | scan-points: %d" % len(self.scan_data[i])

        if i < len(self.pole_indices):
            indices = self.pole_indices[i]
            if indices:
                s += " | pole-indices:"
                for idx in indices:
                    s += " %d" % idx
            else:
                s += " | (no pole indices)"

        if i < len(self.motor_ticks):
            s += " | motor: %d %d" % self.motor_ticks[i]

        if i < len(self.filtered_positions):
            f = self.filtered_positions[i]
            s += " | filtered-pos:"
            for j in range(len(f)):
                s += " %.1f" % f[j]

        return s


text:
import React from 'react'
import { ClockIn } from 'components/ClockIn'
import { Jobcode } from 'components/Jobcode'
import { OrderedMap } from 'immutable'

export class Timecard extends React.Component {
  static propTypes = {
    timesheet: React.PropTypes.object.isRequired,
    onClockIn: React.PropTypes.func.isRequired,
    onClockOut: React.PropTypes.func.isRequired,
    jobcodes: React.PropTypes.instanceOf(OrderedMap).isRequired,
    parentId: React.PropTypes.number.isRequired,
    onChangeJobcode: React.PropTypes.func.isRequired,
    onChangeJobcodeParent: React.PropTypes.func.isRequired
  }
  constructor (props) {
    super(props)
  }

  render () {
    const {
      timesheet,
      onClockIn,
      onClockOut,
      jobcodes,
      parentId,
      onChangeJobcode,
      onChangeJobcodeParent
    } = this.props

    return (

Notes: {timesheet.notes}

Start: {this._renderTime(timesheet.start)}

End: {this._renderTime(timesheet.end)}

        <Jobcode
          jobcodes={jobcodes}
          parentId={parentId}
          onChange={onChangeJobcode}
          onChangeParent={onChangeJobcodeParent}
          currentId={timesheet.jobcode_id}
        />
        <ClockIn
          onTheClock={timesheet.on_the_clock}
          onClockIn={onClockIn}
          onClockOut={onClockOut}
          />

    )
  }

  _renderTime (time) {
    if (time instanceof Date) {
      return time.getTime()
    } else {
      return undefined
    }
  }
}

export default Timecard


text:
There're two kinds of configuration files. The first one is paste configuration and the second one is the api/taskmanager/conductor/guestagent configurations.

## /etc/tests

There're two json configuration file for tests.

They're used by `/run_tests.py`.

## /etc/trove

### /etc/trove/api-paste.ini

The most important is `troveapp` which is defined in `app_factory`.

### /etc/trove/trove.conf.test

These configuration files looks like the same.


text:
import { NgModule, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, OnInit, OnDestroy, ElementRef, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { animate, state, style, transition, trigger, AnimationEvent } from '@angular/animations';
import { DomHandler } from 'primeng/dom';
import { ZIndexUtils } from 'primeng/utils';
import { PrimeNGConfig } from 'primeng/api';

@Component({
    selector: 'p-scrollTop',
    template: `
        <button
            *ngIf="visible"
            [@animation]="{ value: 'open', params: { showTransitionParams: showTransitionOptions, hideTransitionParams: hideTransitionOptions } }"
            (@animation.start)="onEnter($event)"
            (@animation.done)="onLeave($event)"
            [ngClass]="containerClass()"
            (click)="onClick()"
            [class]="styleClass"
            [ngStyle]="style"
            type="button"
        >
            <span [class]="icon" [ngClass]="'p-scrolltop-icon'"></span>
        </button>
    `,
    changeDetection: ChangeDetectionStrategy.OnPush,
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./scrolltop.css'],
    animations: [
        trigger('animation', [
            state(
                'void',
                style({
                    opacity: 0
                })
            ),
            state(
                'open',
                style({
                    opacity: 1
                })
            ),
            transition('void => open', animate('{{showTransitionParams}}')),
            transition('open => void', animate('{{hideTransitionParams}}'))
        ])
    ],
    host: {
        class: 'p-element'
    }
})
export class ScrollTop implements OnInit, OnDestroy {
    @Input() styleClass: string;

    @Input() style: any;

    @Input() target: string = 'window';

    @Input() threshold: number = 400;

    @Input() icon: string = 'pi pi-chevron-up';

    @Input() behavior: string = 'smooth';

    @Input() showTransitionOptions: string = '.15s';

    @Input() hideTransitionOptions: string = '.15s';

    scrollListener: any;

    visible: boolean = false;

    overlay: any;

    constructor(public el: ElementRef, private cd: ChangeDetectorRef, public config: PrimeNGConfig) {}

    ngOnInit() {
        if (this.target === 'window') this.bindDocumentScrollListener();
        else if (this.target === 'parent') this.bindParentScrollListener();
    }

    onClick() {
        let scrollElement = this.target === 'window' ? window : this.el.nativeElement.parentElement;
        scrollElement.scroll({
            top: 0,
            behavior: this.behavior
        });
    }

    onEnter(event: AnimationEvent) {
        switch (event.toState) {
            case 'open':
                this.overlay = event.element;
                ZIndexUtils.set('overlay', this.overlay, this.config.zIndex.overlay);
                break;
            case 'void':
                this.overlay = null;
                break;
        }
    }

    onLeave(event: AnimationEvent) {
        switch (event.toState) {
            case 'void':
                ZIndexUtils.clear(event.element);
                break;
        }
    }

    checkVisibility(scrollY) {
        if (scrollY > this.threshold) this.visible = true;
        else this.visible = false;

        this.cd.markForCheck();
    }

    bindParentScrollListener() {
        this.scrollListener = () => {
            this.checkVisibility(this.el.nativeElement.parentElement.scrollTop);
        };

        this.el.nativeElement.parentElement.addEventListener('scroll', this.scrollListener);
    }

    bindDocumentScrollListener() {
        this.scrollListener = () => {
            this.checkVisibility(DomHandler.getWindowScrollTop());
        };

        window.addEventListener('scroll', this.scrollListener);
    }

    unbindParentScrollListener() {
        if (this.scrollListener) {
            this.el.nativeElement.parentElement.removeEventListener('scroll', this.scrollListener);
            this.scrollListener = null;
        }
    }

    unbindDocumentScrollListener() {
        if (this.scrollListener) {
            window.removeEventListener('scroll', this.scrollListener);
            this.scrollListener = null;
        }
    }

    containerClass() {
        return {
            'p-scrolltop p-link p-component': true,
            'p-scrolltop-sticky': this.target !== 'window'
        };
    }

    ngOnDestroy() {
        if (this.target === 'window') this.unbindDocumentScrollListener();
        else if (this.target === 'parent') this.unbindParentScrollListener();

        if (this.overlay) {
            ZIndexUtils.clear(this.overlay);
            this.overlay = null;
        }
    }
}

@NgModule({
    imports: [CommonModule],
    exports: [ScrollTop],
    declarations: [ScrollTop]
})
export class ScrollTopModule {}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta itemprop="name" content="Polymer - API reference">
<meta itemprop="description" content="Polymer is a library that uses the latest web technologies to let you create custom HTML elements. Build anything from a button to a complete application as an encapsulated, reusable element that works across desktop and mobile.">

<meta itemprop="image" content="../../images/instacod.png">

<title>

    API reference -
   Polymer
</title>
<link rel="publisher" href="../../../plus.google.com/107187849809354688692.html">
<link rel="shortcut icon" href="../../images/logos/p-logo-16.png">
<link href="../../css/site2d228.css?20140220" rel="stylesheet">

  <link rel="import" href="../../components/polymer/polymer.html">
  <link rel="import" href="../../elements/common_elements.vulcanized.html">

    <polymer-flex-layout id="logo-container" isContainer align="center">

      <polymer-ui-icon id="dropdown-toggle" size="35" src="../../images/picons/ic_arrowDropDown_dark_.png">
      </polymer-ui-icon>
    </polymer-flex-layout>

    <dropdown-panel>
      <polymer-ui-menu-item
        src="../../images/picons/ic_guide_dark_.png"
        label="Start"
        href="../start/everything.html"
        >
      </polymer-ui-menu-item>

      <polymer-ui-menu-item
        src="../../images/picons/ic_book_dark_.png"
        label="Docs"
        href="polymer.html"
        active>
      </polymer-ui-menu-item>

      <polymer-ui-menu-item
        src="../../images/picons/ic_feedback_dark_.png"
        label="Resources"
        href="../../resources/faq.html"
        >
      </polymer-ui-menu-item>

      <polymer-ui-menu-item
        src="../../images/picons/ic_people_dark.png"
        label="Community"
        href="../../discuss.html"
        >
      </polymer-ui-menu-item>
    </dropdown-panel>

    <docs-menu menu="docs"></docs-menu>

  <scroll-area sidebar>
    <site-banner type="core" navgroup="docs" shortname="Docs">

<app-bar theme="light" class="bar">
  Start
  Docs
  Resources
  Community

</app-bar>

API reference

          Core

    </site-banner>

  Edit on Github

API reference

          Core

  Table of contents

Element declaration

Attributes

Alternate ways to register an element

Adding public properties and methods

Adding private or static variables

Element lifecycle methods

The polymer-ready event

Features

Published properties

Data binding and custom attributes

Declarative event mapping

Observing properties

Automatic node finding

Firing custom events

Extending other elements

Advanced topics

Dealing with asynchronous tasks

Life of an element's bindings

How data changes are propagated

How Polymer elements prepare themselves

The Polymer core provides a thin layer of API on top of web components.
It expresses Polymer's opinion, provides the extra sugaring that all Polymer elements use, and is meant to help make developing web components much easier.

Element declaration

At the heart of Polymer are Custom Elements. Thus, it should be no surprise that defining a Polymer element is similar to the way you define a standard Custom Element. The major difference is that Polymer elements are created declaratively using <polymer-element>.

<polymer-element name="tag-name" constructor="TagName">
  <template>
    <!-- shadow DOM here -->
  </template>
  <script>Polymer('tag-name');</script>
</polymer-element>

Attributes

Polymer reserves special attributes to be used on <polymer-element>:

    Attribute	Required?	Description

    name	required	Name for the custom element. Requires a "-".

    attributes	optional	Used to publish properties.

    extends	optional	Used to extend other elements.

    noscript	optional	For simple elements that don't need to call Polymer(). See Alternate ways to register an element.

    constructor	optional	The name of the constructor to put on the global object. Allows users to create instances of your element using the new operator (e.g. var tagName = new TagName()).

Default attributes

Other attributes you declare on <polymer-element> will automatically be included
on each instance of the element. For example:

<polymer-element name="tag-name" class="active" mycustomattr>
  <template>...</template>
  <script>Polymer('tag-name');</script>
</polymer-element>

When an instance of <tag-name> is created, it contains class="active" mycustomattr
as default attributes:

<tag-name class="active" mycustomattr></tag-name>

Alternate ways to register an element

For convenient decoupling of script and markup, you don't have to inline your script.
Polymer elements can be created by referencing an external script
which calls Polymer('tag-name'):

<!-- 2. Script refereced inside the element definition. -->
<polymer-element name="tag-name">
  <template>...</template>
  <script src="path/to/tagname.js"></script>
</polymer-element>

<!-- 3. Script comes before the element definition. -->
<script src="path/to/tagname.js"></script>
<polymer-element name="tag-name">
  <template>...</template>
</polymer-element>

<!-- 4. No script -->
<polymer-element name="tag-name" constructor="TagName" noscript>
  <template>
    <!-- shadow DOM here -->
  </template>
</polymer-element>

Imperative registration

Elements can be registered in pure JavaScript like so:

<script>
  Polymer('name-tag', {nameColor: 'red'});
  var el = document.createElement('div');
  el.innerHTML = '\
    <polymer-element name="name-tag" attributes="name">\
      <template>\
        Hello <span style="color:{{nameColor}}">{{name}}</span>\
      </template>\
    </polymer-element>';
  // The custom elements polyfill can't see the <polymer-element>
  // unless you put it in the DOM.
  document.body.appendChild(el);
</script>

<name-tag name="John"></name-tag>

Note that you need to add the <polymer-element> to the document so that the
Custom Elements polyfill picks it up.

Adding public properties and methods

If you wish to define methods/properties on your element (optional), pass an object
as the second argument to Polymer(). This object is used to define
the element's prototype.

The following example defines a property message, a computed property greeting
using an ES5 getter, and a method foo:

<polymer-element name="tag-name">
  <template>...</template>
  <script>
    Polymer('tag-name', {
      message: "Hello!",
      get greeting() {
        return this.message + ' there!';
      },
      foo: function() {...}
    });
  </script>
</polymer-element>

Note: this references the custom element itself inside a Polymer element. For example, this.localName == 'tag-name'.

Important: Be careful when initializing properties that are objects or arrays. Due to the nature of prototype, you may run into unexpected "shared state" across instances of the same element. If you're initializing an array or object, do it in created() rather than directly on the prototype.

Do this:

Polymer('x-foo', {
  created: function() {
    this.list = []; // Initialize and hint type to be array.
    this.person = {}; // Initialize and hint type to an object.
  }
});

instead of this:

Polymer('x-foo', {
  list: [],
  person: {}
});

Adding private or static variables

If you need private state within an element, wrap your script using standard
techniques like anonymous self-calling functions:

<polymer-element name="tag-name">
  <template>...</template>
  <script>
    (function() {
      // Ran once. Private and static to the element.
      var foo_ = new Foo();

      // Ran for every instance of the element that's created.
      Polymer('tag-name', {
        get foo() { return foo_; }
      });
    })();
  </script>
</polymer-element>

Element lifecycle methods

Polymer has first class support for the Custom Element lifecycle
callbacks, though for convenience, implements them with shorter names.

All of the lifecycle callbacks are optional:

Polymer('tag-name', {
  created: function() { ... },
  ready: function() { ... },
  attached: function () { ... },
  detached: function() { ... },
  attributeChanged: function(attrName, oldVal, newVal) {
    //var newVal = this.getAttribute(attrName);
    console.log(attrName, 'old: ' + oldVal, 'new:', newVal);
  },
});

Below is a table of the lifecycle methods according to the Custom Elements
specification vs. the names Polymer uses.

      Spec
      Polymer
      Called when

      createdCallback
      created
      an instance of the element is created

      -
      ready
      The <polymer-element> has been fully prepared (e.g. Shadow DOM created, property observers setup, event listeners attached, etc.)

      attachedCallback
      attached
      an instance was inserted into the document

      detachedCallback
      detached
      an instance was removed from the document

      attributeChangedCallback
      attributeChanged
      an attribute was added, removed, or updated

The polymer-ready event

Polymer parses element definitions and handles their upgrade asynchronously.
If you prematurely fetch the element from the DOM before it has a chance to upgrade,
you'll be working with an HTMLUnknownElement. Polymer elements also support inline resources, such as stylesheets, that need to be loaded. These can cause FOUC issues if they're not fully loaded prior to rendering an element. To avoid FOUC, Polymer delays registering elements until stylesheets are fully loaded.

To know when elements have been registered/upgraded, and thus ready to be interacted with, use the polymer-ready event.

<head>
  <link rel="import" href="path/to/x-foo.html">
</head>
<body>
  <x-foo></x-foo>
  <script>
    window.addEventListener('polymer-ready', function(e) {
      var xFoo = document.querySelector('x-foo');
      xFoo.barProperty = 'baz';
    });
  </script>
</body>

Features

Published properties

When you publish a property name, you're making that property two-way data-bound and part
of the element's "public API". Published properties can be initialized by an HTML attribute
of the same name.

There are two ways to publish properties:

Preferred - Include its name in the <polymer-element>'s attributes attribute.

Include the name in a publish object on your prototype.

As an example, here's an element that publishes three public properties, foo, bar, and baz, using the attributes attribute:

<polymer-element name="x-foo" attributes="foo bar baz">
  <script>
    Polymer('x-foo');
  </script>
</polymer-element>

And here's one using the publish object:

<polymer-element name="x-foo">
  <script>
    Polymer('x-foo', {
      publish: {
        foo: 'I am foo!',
        bar: 'Hello, from bar',
        baz: 'Baz up in here'
      }
    });
  </script>
</polymer-element>

Let's look at the difference between the two and when you might prefer one option over the other.

Default property values

By default, properties defined in attributes are null:

<polymer-element name="x-foo" attributes="foo">
  <script>
    Polymer('x-foo'); // x-foo has a foo property with null value.
  </script>
</polymer-element>

As such, you can provide default values using a combination of the attributes attribute and the prototype:

<polymer-element name="x-foo" attributes="bar">
  <script>
    Polymer('x-foo', { // x-foo has a bar property with default value false.
      bar: false
    });
  </script>
</polymer-element>

Or you can define the whole thing using the publish property:

<polymer-element name="x-foo">
  <script>
    Polymer('x-foo', {
      publish: {
        bar: false
      }
    });
  </script>
</polymer-element>

Generally it's preferable to use the attributes attribute because it's the declarative approach and you can easily see all of the exposed properties at the top of the element.

You should opt for the publish property when either of the following is true:

Your element has many properties and placing them all on one line feels unwieldy.

You want to define default values for properties and prefer the DRYness of doing it all in one place.

Configuring an element via attributes

Attributes are a great way for users of your element to configure it, declaratively.
They can customize a published property by passing an initial value on the attribute
with the same name:

<x-foo name="Bob"></x-foo>

Hinting an attribute's type

When attribute values are converted to property values, Polymer attempts to convert the value to the correct type, depending on the default value of the property.

<polymer-element name="x-foo" attributes="foo">
  <script>
    Polymer('x-foo', {
      foo: false // hint that foo is Boolean
    });
  </script>
</polymer-element>

Property reflection to attributes

Property values are reflected back into their attribute counterpart. For example, setting this.name = "Joe" or calling this.setAttribute('name', 'Joe') from within the element updates the markup accordingly:

<x-foo name="Joe"></x-foo>

Data binding and custom attributes

Published properties are data-bound inside of Polymer elements and accessible
via {{}}. These bindings are by reference and are two-way.

For example, we can define a name-tag element that publishes two properties,
name and nameColor.

<polymer-element name="name-tag" attributes="name nameColor">
  <template>
    Hello! My name is <span style="color:{{nameColor}}">{{name}}</span>
  </template>
  <script>
    Polymer('name-tag', {
      nameColor: "orange"
    });
  </script>
</polymer-element>

In this example, name has initial value of null and nameColor has a value of "orange".
Thus, the <span>'s color will be orange.

Binding objects and arrays to attribute values

Important: Be careful when your properties are objects or arrays. Element registration
is evaluated once. This means only one instance of an object used in property initialization is ever created. Because of the nature of prototype, you may run into unexpected "shared state" across different instances of the same element if you're setting an initial value for a property which is an object or array. Do this type of initialization in created() rather than directly on the prototype.

Generally, attributes are string values, but Polymer makes it possible to bind references between elements using attributes. The binding engine interprets reference bindings
by interrogating the attribute's type. This means you
can bind an an object to an HTML attribute!

Let's modify the name-tag example to take an object instead of individual properties.

<polymer-element name="name-tag" attributes="person">
  <template>
    Hello! My name is <span style="color:{{person.nameColor}}">{{person.name}}</span>
  </template>
  <script>
    Polymer('name-tag', {
      created: function() {
        this.person = {
          name: "Scott",
          nameColor: "orange"
        }
      }
    });
  </script>
</polymer-element>

Now, imagine we make a new component called <visitor-creds> that uses name-tag:

<polymer-element name="visitor-creds">
  <template>
    <name-tag person="{{person}}"></name-tag>
  </template>
  <script>
    Polymer('visitor-creds', {
      created: function() {
        this.person = {
          name: "Scott2",
          nameColor: "red"
        }
      }
    });
  </script>
</polymer-element>

When an instance of <visitor-creds> is created, its person property (an object)
is also bound to <name-tag>'s person property. Now both components are using
the same person object.

Declarative event mapping

Polymer supports declarative binding of events to methods in the component.
It uses special on-event syntax to trigger this binding behavior.

<polymer-element name="g-cool" on-keypress="{{keypressHandler}}">
  <template>
    <button on-click="{{buttonClick}}"></button>
  </template>
  <script>
    Polymer('g-cool', {
      keypressHandler: function(event, detail, sender) { ...},
      buttonClick: function(event, detail, sender) { ... }
    });
  </script>
</polymer-element>

In this example, the on-keypress declaration maps the standard DOM "keypress" event to the keypressHandler method defined on the element. Similarly, a button within the element
declares a on-click handler for click events that calls the buttonClick method.
All of this is achieved without the need for any glue code.

Some things to notice:

The value of an event handler attribute is the string name of a method on the component. Unlike traditional syntax, you cannot put executable code in the attribute.

The event handler is passed the following arguments:

inEvent is the standard event object.

inDetail: A convenience form of inEvent.detail.

inSender: A reference to the node that declared the handler. This is often different from inEvent.target (the lowest node that received the event) and inEvent.currentTarget (the component processing the event), so  Polymer provides it directly.

Observing properties

Changed watchers

The simplest way to observe property changes on your element is to use a changed watcher.
All properties on Polymer elements can be watched for changes by implementing a propertyNameChanged handler. When the value of a watched property changes, the appropriate change handler is automatically invoked.

<polymer-element name="g-cool" attributes="better best">
  <script>
    Polymer('g-cool', {
      plain: '',
      best: '',
      betterChanged: function(oldValue, newValue) {
        ...
      },
      bestChanged: function(oldValue, newValue) {
        ...
      }
    });
  </script>
</polymer-element>

In this example, there are two watched properties, better and best. The betterChanged and bestChanged function will be called whenever better or best are modified, respectively.

Custom property observers - observe blocks

Sometimes a changed watcher is not enough. For more control over
property observation, Polymer provides observe blocks.

An observe block defines a custom property/observer mapping for one or more properties.
It can be used to watch for changes to nested objects or share the same callback
for several properties.

Example: - share a single observer

Polymer('x-element', {
  foo: '',
  bar: '',
  observe: {
    foo: 'validate',
    bar: 'validate'
  },
  ready: function() {
    this.foo = 'bar';
    this.bar = 'foo';
  },
  validate: function(oldValue, newValue) {
    ...
  },
});

In the example, validate() is called whenever foo or bar changes.

Example: - watching for changes to a nested object path

Polymer('x-element', {
  observe: {
    'a.b.c': 'validateSubPath'
  },
  ready: function() {
    this.a = {
      b: {
        c: 'exists'
      }
    };
  },
  validateSubPath: function(oldValue, newValue) {
    var value = Path.get('a.b.c').getValueFrom(this);
    // oldValue == undefined
    // newValue == value == this.a.b.c === 'exists'
  }
});

It's important to note that Polymer does not call the propertyNameChanged callback for properties included in an observe block. Instead, the defined observer gets called.

Polymer('x-element', {
  bar: '',
  observe: {
    bar: 'validate'
  },
  barChanged: function(oldValue, newValue) {
    console.log("I'm not called");
  },
  validate: function(oldValue, newValue) {
    console.log("I'm called instead");
  }
});

Automatic node finding

Another useful feature of Polymer is node reference marshalling. Every node in a component's shadow DOM that is tagged with an id attribute is automatically referenced in the component's this.$ hash.

For example, the following defines a component whose template contains an <input> element whose id attribute is nameInput. The component can refer to that element with the expression this.$.nameInput.

<polymer-element name="x-form">
  <template>
    <input type="text" id="nameInput">
  </template>
  <script>
    Polymer('x-form', {
      logNameValue: function() {
        console.log(this.$.nameInput.value);
      }
    });
  </script>
</polymer-element>

Firing custom events

Polymer core provides a convenient fire() method for
sending custom events. Essentially, it's a wrapper around your standard node.dispatchEvent(new CustomEvent(...)). In cases where you need to fire an event after microtasks have completed,
use the asynchronous version: asyncFire().

Example:

<polymer-element name="ouch-button">
  <template>
    <button on-click="{{onClick}}">Send hurt</button>
  </template>
  <script>
    Polymer('ouch-button', {
      onClick: function() {
        this.fire('ouch', {msg: 'That hurt!'}); // fire(inType, inDetail, inToNode)
      }
    });
  </script>
</polymer-element>

<ouch-button></ouch-button>

<script>
  document.querySelector('ouch-button').addEventListener('ouch', function(e) {
    console.log(e.type, e.detail.msg); // "ouch" "That hurt!"
  });
</script>

Tip: If your element is within another Polymer element, you can
use the special on-* handlers to deal with the event: <ouch-button on-ouch="{{myMethod}}"></ouch-button>

Extending other elements

A Polymer element can extend another element by using the extends
attribute. The parent's properties and methods are inherited by the child element
and data-bound.

<polymer-element name="polymer-cool">
  <!-- UI-less element -->
  <script>
    Polymer('polymer-cool', {
      praise: 'cool'
    });
  </script>
</polymer-element>

<polymer-element name="polymer-cooler" extends="polymer-cool">
  <template>
    {{praise}} <!-- "cool" -->
  </template>
  <script>
    Polymer('polymer-cooler');
  </script>
</polymer-element>

Overriding a parent's methods

When you override an inherited method, you can call the parent's method with this.super(), and optionally pass it a list of arguments (e.g. this.super([arg1, arg2])). The reason the paramater is an array is so you can write this.super(arguments).

<polymer-element name="polymer-cool">
  <script>
    {{site.project_title}}('polymer-cool', {
      praise: 'cool',
      makeCoolest: function() {
        this.praise = 'coolest';
      }
    });
  </script>
</polymer-element>

<polymer-element name="polymer-cooler" extends="polymer-cool" on-click="{{makeCoolest}}">
  <template>polymer-cooler is {{praise}}</template>
  <script>
    {{site.project_title}}('polymer-cooler', {
      praise: 'cooler',
      makeCoolest: function() {
        this.super(); // calls polymer-cool's makeCoolest()
      }
    });
  </script>
</polymer-element>

<polymer-cooler></polymer-cooler>

In this example, when the user clicks on a <polymer-cooler> element, its
makeCoolest() method is called, which in turn calls the parent's version
using this.super(). The praise property (inherited from <polymer-cool>) is set
to "coolest".

Advanced topics

async()

unbindAll() / cancelUnbindAll() / asyncUnbindAll()

.preventDispose

Platform.flush()

Dealing with asynchronous tasks

Many things in Polymer happen asynchronously. Changes are gathered up
and executed all at once, instead of executing right away. Batching
changes creates an optimization that (a) prevents duplicated work and (b) reduces unwanted FOUC.

Change watchers and situations that rely on data-bindings
are examples that fit under this async behavior. For example, conditional templates may not immediately render after setting properties because changes to those renderings are saved up and performed all at once after you return from JavaScript.

To do work after changes have been processed, Polymer provides async().
It's similar to window.setTimeout(), but automatically binds this to the correct value:

// async(inMethod, inArgs, inTimeout)
this.async(function() {
  this.foo = 3;
}, null, 1000);

// Roughly equivalent to:
//setTimeout(function() {
//  this.foo = 3;
//}.bind(this), 1000);

The first argument is a function or string name for the method to call asynchronously.
The second argument, inArgs, is an optional object or array of arguments to
pass to the callback.

In the case of property changes that result in DOM modifications, follow this pattern:

Polymer('my-element', {
  propChanged: function() {
    // If "prop" changing results in our DOM changing, schedule an update after
    // the new microtask.
    this.async(this.updateValues);
  },
  updateValues: function() {...}
});

Life of an element's bindings

Note: The section only applies to elements that are instantiated in JavaScript, not to those
declared in markup.

If you instantiate an element (e.g. document.createElement('x-foo')) and do not add it to the DOM,
Polymer asynchronously removes its {{}} bindings and *Changed methods.
This helps prevent memory leaks, ensuring the element will be garbage collected.

If you want the element to "remain active" when it's not in the document,
call cancelUnbindAll() right after you create or remove it. The lifecycle methods
are a good place for this:

Polymer('my-element', {
  ready: function() {
    // Ensure bindings remain active, even if we're never added to the DOM.
    this.cancelUnbindAll();
  },
  detached: function() {
    // Also keep bindings active if we're added, but later removed.
    this.cancelUnbindAll();
  }
});

Polymer typically handles this management for you, but when you
explicitly call cancelUnbindAll() (and the element is never added to/put back in the DOM),
it becomes your responsibility to eventually unbind the element using unbindAll()/asyncUnbindAll(),
otherwise your application may leak memory.

var el = document.createElement('my-element');
// Need to unbind if el is:
//   1. never added to the DOM
//   2. put in the DOM, but later removed
el.unbindAll();

Using preventDispose

To force bindings from being removed in call cases, set .preventDispose:

Polymer('my-element', {
  preventDispose: true
});

How data changes are propagated

Data changes in Polymer happen almost immediately (at end of a microtask)
when Object.observe() is available. When it's not supported, Polymer uses a polyfill (observe-js) to poll and periodically propagate data-changes throughout the system. This is done through a method called Platform.flush().

What is Platform.flush()?

Platform.flush() is part of Polymer's data observation polyfill, observe-js. It dirty check's all objects that have been observed and ensures notification callbacks are dispatched. Polymer automatically calls Platform.flush() periodically, and this should be sufficient for most application workflows. However, there are times when you'll want to call Platform.flush() in application code.

Note: on platforms that support Object.observe() natively, Platform.flush() does nothing.

When should I call Platform.flush()?

Instead of waiting for the next poll interval, one can manually schedule an update by calling Platform.flush(). There are very few cases where you need to call Platform.flush() directly.

If it's important that a data change propagates before the next screen paint, you may
need to manually call Platform.flush(). Here are specific examples:

A property change results in a CSS class being added to a node. Often, this works out fine, but sometimes, it's important to make sure the node does not display without the styling from the added class applied to it. To ensure this, call Platform.flush() in the property change handler after adding the CSS class.

The author of a slider element wants to ensure that data can propagate from it as the user slides the slider. A user of the element, might, for example, bind the slider's value to an input and expect to see the input change while the slider is moving. To achieve this, the element author calls Platform.flush() after setting the element's value in the ontrack event handler.

Note: Polymer is designed such that change notifications are asynchronous. Both Platform.flush() and Object.observe() (after which it's modeled) are asynchronous. Therefore, Platform.flush() should not be used to try to enforce synchronous data notifications. Instead, always use change watchers to be informed about state.

How Polymer elements prepare themselves

For performance reasons, <polymer-element>s avoid the expense of preparing ShadowDOM, event listeners, and property observers if they're created outside the main document.
This behavior is similar to how native elements such as <img> and <video> behave.
They remain in a semi-inert state when created outside the main document (e.g. an <img> avoids the expense of loading its src).

Polymer elements prepare themselves automatically in the following cases:

when they're created in a document that has a defaultView (the main document)

when they receive the attached callback

when they're created in the shadowRoot of another element that is preparing itself

In addition, if the .alwaysPrepare property is set to true, Polymer elements
prepare themselves even when they do not satisfies the above rules.

Polymer('my-element', {
  alwaysPrepare: true
});

Note: an element's ready() lifecycle callback is called after an element has been prepared. Use ready() to know when an element is done initializing itself.

  </scroll-area>

    <polymer-ui-toolbar>
      <polymer-ui-icon src="../../images/picons/ic_archive_dark_.png"></polymer-ui-icon>Get Polymer
      <polymer-ui-icon src="../../images/picons/ic_social_google_plus.png"></polymer-ui-icon>+Polymer
      <polymer-ui-icon src="../../images/picons/ic_social_twitter_dark_.png"></polymer-ui-icon>@polymer
      <polymer-ui-icon src="../../images/picons/ic_social_github.png"></polymer-ui-icon>/Polymer
    </polymer-ui-toolbar>

© 2014 Polymer Authors. Code licensed under the BSD License. Documentation licensed under CC BY 3.0.

<page-scrim></page-scrim>


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use yii\jui\AutoComplete;
use kartik\money\MaskMoney;
use kartik\widgets\Select2;
use kartik\widgets\SwitchInput;
use kartik\datetime\DateTimePicker;

use iutbay\yii2kcfinder\KCFinderInputWidget;

$module = Yii::$app->getModule('blog');

if ($module->enableUpload)
{
	// kcfinder options
	// http://kcfinder.sunhater.com/install#dynamic
	$kcfOptions = array_merge([], [
		'uploadURL' => Yii::getAlias($module->uploadURL),
		'uploadDir' => Yii::getAlias($module->uploadDir),
		'access' => [
			'files' => [
				'upload' => true,
				'delete' => false,
				'copy' => false,
				'move' => false,
				'rename' => false,
			],
			'dirs' => [
				'create' => true,
				'delete' => false,
				'rename' => false,
			],
		],
		'types'=>[
			'files'    =>  "",
			'images'   =>  "*img",
		],
		'thumbWidth' => 260,
		'thumbHeight' => 260,
	]);

	// Set kcfinder session options
	Yii::$app->session->set('KCFINDER', $kcfOptions);

}

/* @var $this yii\web\View */
/* @var $model amilna\blog\models\Category */
/* @var $form yii\widgets\ActiveForm */

$listParent = []+ArrayHelper::map(($model->isNewRecord?$model->parents():$model->parents($model->id)), 'id', 'title');
?>

    <?php $form = ActiveForm::begin(); ?>

			<?= $form->field($model, 'title')->textInput(['maxlength' => 65,'placeholder'=>Yii::t('app','Title contain a seo keyword if possible')]) ?>

			<?= $form->field($model, 'status')->widget(SwitchInput::classname(), [
					'type' => SwitchInput::CHECKBOX,
				]);
			?>

			<?= $form->field($model, 'description')->textArea(['maxlength' => 155,'placeholder'=>Yii::t('app','This description also used as meta description')]) ?>

			<?= $form->field($model, 'parent_id')->widget(Select2::classname(), [
				'model'=>$model,
				'attribute'=>'parent_id',
				'data' => $listParent,
				'options' => ['placeholder' => Yii::t('app','Select a account parent...')],
				'pluginOptions' => [
					'allowClear' => true
				],
				'pluginEvents' => [
					"change" => 'function() {
								}',
				],
			]);?>

			<?php
				if ($module->enableUpload)
				{
					echo $form->field($model, 'image')->widget(KCFinderInputWidget::className(), [
						'multiple' => false,
						'kcfOptions'=>$kcfOptions,
						'kcfBrowseOptions'=>[
							'type'=>'images',
							'lng'=>substr(Yii::$app->language,0,2),
						]
					]);
				}
				else
				{
					echo $form->field($model, 'image')->textInput(['placeholder'=>Yii::t('app','Url of image')]);
				}
			?>

			<?php
				/*= $form->field($model, 'type')->textInput() */
			?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
/**
 * Created by Shawn Liu on 14-12-19.
 */

var express = require("express");
var router = express.Router();
var PM2 = require("../lib/PM2");
var logger = require("log4js").getLogger("routes/system");
var config = require("config");
var Promise = require("bluebird");
var systemOperate = require("../lib/systemOperate");
router.get("/process/:processId",function (req, res) {
    systemOperate.processUsage(req.params.processId)
        .then(function (usage) {
            return systemOperate.killProcess(req.params.processId)
                .then(function () {
                    res.json({
                        "pid": req.params.proceddId,
                        "usage": usage
                    });
                })
        })
        .catch(function (err) {
            logger.error(err);
            res.json({
                "status": false,
                "message": err.message || err
            })
        })

})

module.exports = router;


text:
<?php
/**
 * Handles redirecting the user to login or access forbidden pages when trying
 * to access resources restricted by the Acl
 *
 * @category    Xi
 * @package     Xi_User
 * @subpackage  Xi_User_Controller
 * @author      Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
 */
class Xi_User_Controller_Plugin_Auth extends Xi_User_Controller_Plugin_Abstract
{
    /**
     * The redirection to apply when trying to access a resource to which the
     * user does not have access
     *
     * @var Xi_Controller_Request_Redirection_Interface
     */
    protected $_accessForbiddenRedirection;

    /**
     * The redirection to apply when trying to access a resource that requires
     * authentication as an unauthenticated user
     *
     * @var Xi_Controller_Request_Redirection_Interface
     */
    protected $_notAuthenticatedRedirection;

    /**
     * Whether to check for access rights on dispatch loop startup only
     * ({@link dispatchLoopStartup()} or on each individual request passed
     * through the front controller ({@link preDispatch()}).
     *
     * @var boolean
     */
    protected $_onlyOnStartup = true;

    /**
     * Target module, controller and action for the default access forbidden
     * redirection
     *
     * @var array
     */
    protected $_defaultAccessForbiddenTarget = array(
        'module' => 'default',
        'controller' => 'error',
        'action' => 'forbidden'
    );

    /**
     * Target module, controller and action for the default not authenticated
     * redirection
     *
     * @var array
     */
    protected $_defaultNotAuthenticatedTarget = array(
        'module' => 'default',
        'controller' => 'user',
        'action' => 'login'
    );

    /**
     * Provide redirection objects or Xi_Controller_Request_Redirection
     * constructor argument arrays to set default redirections
     *
     * @see Xi_Controller_Request_Redirection
     * @param Xi_Controller_Request_Redirection_Interface|array $notAuthenticated
     * @param Xi_Controller_Request_Redirection_Interface|array $accessForbidden
     * @return void
     */
    public function __construct($notAuthenticated = null, $accessForbidden = null)
    {
        if (null !== $notAuthenticated) {
            if (is_array($notAuthenticated)) {
                $notAuthenticated = Xi_Class::create('Xi_Controller_Request_Redirection', $notAuthenticated);
            }
            $this->setNotAuthenticatedRedirection($notAuthenticated);
        }
        if (null !== $accessForbidden) {
            if (is_array($accessForbidden)) {
                $accessForbidden = Xi_Class::create('Xi_Controller_Request_Redirection', $accessForbidden);
            }
            $this->setAccessForbiddenRedirection($accessForbidden);
        }
    }

    /**
     * @return Xi_Controller_Request_Redirection_Interface
     */
    public function getAccessForbiddenRedirection()
    {
        if (null === $this->_accessForbiddenRedirection) {
            $this->_accessForbiddenRedirection = $this->getDefaultAccessForbiddenRedirection();
        }
        return $this->_accessForbiddenRedirection;
    }

    /**
     * @return Xi_Controller_Request_Redirection_Interface
     */
    public function getDefaultAccessForbiddenRedirection()
    {
        $module = $this->_defaultAccessForbiddenTarget['module'];
        $controller = $this->_defaultAccessForbiddenTarget['controller'];
        $action = $this->_defaultAccessForbiddenTarget['action'];

        return $this->_createRedirection($action, $controller, $module);
    }

    /**
     * @param string $action
     * @param string $controller
     * @param string $module
     * @return Xi_Controller_Request_Redirection_Interface
     */
    protected function _createRedirection($action, $controller, $module)
    {
        return new Xi_Controller_Request_Redirection($action, $controller, $module);
    }

    /**
     * @param Xi_Controller_Request_Redirection_Interface $redirection
     * @return Xi_User_Controller_Plugin
     */
    public function setAccessForbiddenRedirection(Xi_Controller_Request_Redirection_Interface $redirection)
    {
        $this->_accessForbiddenRedirection = $redirection;
        return $this;
    }

    /**
     * @return Xi_Controller_Request_Redirection_Interface
     */
    public function getNotAuthenticatedRedirection()
    {
        if (null === $this->_notAuthenticatedRedirection) {
            $this->_notAuthenticatedRedirection = $this->getDefaultNotAuthenticatedRedirection();
        }
        return $this->_notAuthenticatedRedirection;
    }

    /**
     * @return Xi_Controller_Request_Redirection_Interface
     */
    public function getDefaultNotAuthenticatedRedirection()
    {
        $module = $this->_defaultNotAuthenticatedTarget['module'];
        $controller = $this->_defaultNotAuthenticatedTarget['controller'];
        $action = $this->_defaultNotAuthenticatedTarget['action'];

        return $this->_createRedirection($action, $controller, $module);
    }

    /**
     * @param Xi_Controller_Request_Redirection_Interface $redirection
     * @return Xi_User_Controller_Plugin
     */
    public function setNotAuthenticatedRedirection(Xi_Controller_Request_Redirection_Interface $redirection)
    {
        $this->_notAuthenticatedRedirection = $redirection;
        return $this;
    }

    /**
     * @param boolean $flag
     * @return Xi_User_Controller_Plugin
     */
    public function setOnlyOnStartup($flag)
    {
        $this->_onlyOnStartup = (boolean) $flag;
        return $this;
    }

    /**
     * @return boolean
     */
    public function getOnlyOnStartup()
    {
        return $this->_onlyOnStartup;
    }

    /**
     * Trigger {@link check()} if {@link $_onlyOnStartup} is enabled.
     *
     * @param Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        if ($this->getOnlyOnStartup()) {
            $this->check($request);
        }
    }

    /**
     * Trigger {@link check()} if {@link $_onlyOnStartup} is disabled.
     *
     * @param Zend_Controller_Request_Abstract $request
     * @return void
     */
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
	    if (!$this->getOnlyOnStartup()) {
	        $this->check($request);
	    }
	}

	/**
	 * Apply relevant redirection in case access to current request target is
	 * forbidden for user
	 *
	 * @param Zend_Controller_Request_Abstract $request
	 * @return
	 */
	public function check(Zend_Controller_Request_Abstract $request)
	{
	    $user = $this->getUser();

    	if ($user->isAllowed($this->getAclAction($request))) {
    	    return;
    	}

    	if ($user->isAuthed()) {
    	    $this->getAccessForbiddenRedirection()->apply($request);
    	} else {
    	    $this->getNotAuthenticatedRedirection()->apply($request);
    	}
	}

	/**
	 * Retrieve Xi_Acl_Action_Interface object based on request parameters
	 *
	 * @param Zend_Controller_Request_Abstract $request
	 * @return Xi_Acl_Action_Interface
	 */
	public function getAclAction(Zend_Controller_Request_Abstract $request)
	{
	    return Xi_Acl_Action_Fallback::createFromRequest($request);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <gradient android:centerColor="@color/colorCarot"
        android:startColor="@color/colorCarot"
        android:endColor="@color/colorCarot">

    </gradient>
</shape>


text:
package Paws::CloudDirectory::CreateObjectResponse;
  use Moose;
  has ObjectIdentifier => (is => 'ro', isa => 'Str');

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::CloudDirectory::CreateObjectResponse

=head1 ATTRIBUTES

=head2 ObjectIdentifier => Str

The identifier that is associated with the object.

=head2 _request_id => Str

=cut


text:
QSIMLIB_BASIC = ../qsimcirq/qsim_basic`python3-config --extension-suffix`
QSIMLIB_SSE = ../qsimcirq/qsim_sse`python3-config --extension-suffix`
QSIMLIB_AVX2 = ../qsimcirq/qsim_avx2`python3-config --extension-suffix`
QSIMLIB_AVX512 = ../qsimcirq/qsim_avx512`python3-config --extension-suffix`
QSIMLIB_CUDA = ../qsimcirq/qsim_cuda`python3-config --extension-suffix`
QSIMLIB_CUSTATEVEC = ../qsimcirq/qsim_custatevec`python3-config --extension-suffix`
QSIMLIB_DECIDE = ../qsimcirq/qsim_decide`python3-config --extension-suffix`

# The flags for the compilation of the simd-specific Pybind11 interfaces
PYBINDFLAGS_BASIC = -Wall -shared -std=c++17 -fPIC `python3 -m pybind11 --includes`
PYBINDFLAGS_SSE = -msse4.1 -Wall -shared -std=c++17 -fPIC `python3 -m pybind11 --includes`
PYBINDFLAGS_AVX2 = -mavx2 -mfma -Wall -shared -std=c++17 -fPIC `python3 -m pybind11 --includes`
PYBINDFLAGS_AVX512 = -mavx512f -mbmi2 -Wall -shared -std=c++17 -fPIC `python3 -m pybind11 --includes`

# The flags for the compilation of GPU-specific Pybind11 interfaces
PYBINDFLAGS_CUDA = -std=c++14 -x cu -Xcompiler "-Wall -shared -fPIC `python3 -m pybind11 --includes`"

# The flags for the compilation of cuStateVec-specific Pybind11 interfaces
PYBINDFLAGS_CUSTATEVEC = $(CUSTATEVECFLAGS) $(PYBINDFLAGS_CUDA)

# Check for nvcc to decide compilation mode.
ifeq ($(shell which $(NVCC)),)
pybind: pybind-cpu decide-cpu
else
# Check for the cuStateVec library.
ifeq ($(CUQUANTUM_DIR),)
pybind: pybind-cpu pybind-gpu decide-gpu
else
pybind: pybind-cpu pybind-gpu pybind-custatevec decide-custatevec
endif
endif

.PHONY: pybind-cpu
pybind-cpu:
	$(CXX) basic/pybind_main_basic.cpp -o $(QSIMLIB_BASIC) $(CXXFLAGS) $(PYBINDFLAGS_BASIC)
	$(CXX) sse/pybind_main_sse.cpp -o $(QSIMLIB_SSE) $(CXXFLAGS) $(PYBINDFLAGS_SSE)
	$(CXX) avx2/pybind_main_avx2.cpp -o $(QSIMLIB_AVX2) $(CXXFLAGS) $(PYBINDFLAGS_AVX2)
	$(CXX) avx512/pybind_main_avx512.cpp -o $(QSIMLIB_AVX512) $(CXXFLAGS) $(PYBINDFLAGS_AVX512)

.PHONY: decide-cpu
decide-cpu:
	$(CXX) decide/decide.cpp -o $(QSIMLIB_DECIDE) $(CXXFLAGS) $(PYBINDFLAGS_BASIC)

.PHONY: pybind-gpu
pybind-gpu:
	$(NVCC) cuda/pybind_main_cuda.cpp -o $(QSIMLIB_CUDA) $(NVCCFLAGS) $(PYBINDFLAGS_CUDA)

.PHONY: decide-gpu
decide-gpu:
	$(NVCC) decide/decide.cpp -o $(QSIMLIB_DECIDE) $(NVCCFLAGS) $(PYBINDFLAGS_CUDA)

.PHONY: pybind-custatevec
pybind-custatevec:
	$(NVCC) custatevec/pybind_main_custatevec.cpp -o $(QSIMLIB_CUSTATEVEC) $(NVCCFLAGS) $(PYBINDFLAGS_CUSTATEVEC)

.PHONY: decide-custatevec
decide-custatevec:
	$(NVCC) decide/decide.cpp -D__CUSTATEVEC__ -o $(QSIMLIB_DECIDE) $(NVCCFLAGS) $(PYBINDFLAGS_CUDA)

.PHONY: clean
clean:
	-rm -f ./basic/*.x ./basic/*.a ./basic/*.so ./basic/*.mod $(QSIMLIB_BASIC)
	-rm -f ./sse/*.x ./sse/*.a ./sse/*.so ./sse/*.mod $(QSIMLIB_SSE)
	-rm -f ./avx2/*.x ./avx2/*.a ./avx2/*.so ./avx2/*.mod $(QSIMLIB_AVX2)
	-rm -f ./avx512/*.x ./avx512/*.a ./avx512/*.so ./avx512/*.mod $(QSIMLIB_AVX512)
	-rm -f ./cuda/*.x ./cuda/*.a ./cuda/*.so ./cuda/*.mod $(QSIMLIB_CUDA)
	-rm -f ./custatevec/*.x ./custatevec/*.a ./custatevec/*.so ./custatevec/*.mod $(QSIMLIB_CUSTATEVEC)
	-rm -f ./decide/*.x ./decide/*.a ./decide/*.so ./decide/*.mod $(QSIMLIB_DECIDE)


text:
package org.assertj.core.internal.failures;

import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.api.WritableAssertionInfo;
import org.assertj.core.description.Description;
import org.assertj.core.error.ErrorMessageFactory;
import org.assertj.core.internal.Failures;
import org.assertj.core.internal.TestDescription;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests for <code>{@link Failures#failure(AssertionInfo, ErrorMessageFactory)}</code>.
 *
 * @author Alex Ruiz
 */
public class Failures_failure_with_ErrorMessage_Test {

  private WritableAssertionInfo info;
  private ErrorMessageFactory errorMessage;
  private Failures failures;

  @Before
  public void setUp() {
    info = new WritableAssertionInfo();
    errorMessage = mock(ErrorMessageFactory.class);
    failures = Failures.instance();
  }

  @Test
  public void should_create_use_overriding_error_message_if_it_is_specified() {
    info.overridingErrorMessage("my message");
    AssertionError failure = failures.failure(info, errorMessage);
    assertEquals("my message", failure.getMessage());
  }

  @Test
  public void should_use_ErrorMessage_when_overriding_error_message_is_not_specified() {
    Description description = new TestDescription("description");
    info.description(description);
    when(errorMessage.create(description, info.representation())).thenReturn("[description] my message");
    AssertionError failure = failures.failure(info, errorMessage);
    assertEquals("[description] my message", failure.getMessage());
  }
}