text:
// +build integration,!no-etcd

package integration

// This file tests the scheduler.

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client/cache"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client/record"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/master"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/wait"
	"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/admission/admit"
	"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler"
	_ "github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/algorithmprovider"
	"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/factory"
	"github.com/GoogleCloudPlatform/kubernetes/test/integration/framework"
)

type nodeMutationFunc func(t *testing.T, n *api.Node, nodeStore cache.Store, c *client.Client)

type nodeStateManager struct {
	makeSchedulable   nodeMutationFunc
	makeUnSchedulable nodeMutationFunc
}

func TestUnschedulableNodes(t *testing.T) {
	etcdStorage, err := framework.NewEtcdStorage()
	if err != nil {
		t.Fatalf("Couldn't create etcd storage: %v", err)
	}
	framework.DeleteAllEtcdKeys()

	var m *master.Master
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		m.Handler.ServeHTTP(w, req)
	}))
	defer s.Close()

	m = master.New(&master.Config{
		DatabaseStorage:       etcdStorage,
		KubeletClient:         client.FakeKubeletClient{},
		EnableCoreControllers: true,
		EnableLogsSupport:     false,
		EnableUISupport:       false,
		EnableIndex:           true,
		APIPrefix:             "/api",
		Authorizer:            apiserver.NewAlwaysAllowAuthorizer(),
		AdmissionControl:      admit.NewAlwaysAdmit(),
	})

	restClient := client.NewOrDie(&client.Config{Host: s.URL, Version: testapi.Version()})

	schedulerConfigFactory := factory.NewConfigFactory(restClient)
	schedulerConfig, err := schedulerConfigFactory.Create()
	if err != nil {
		t.Fatalf("Couldn't create scheduler config: %v", err)
	}
	eventBroadcaster := record.NewBroadcaster()
	schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: "scheduler"})
	eventBroadcaster.StartRecordingToSink(restClient.Events(""))
	scheduler.New(schedulerConfig).Run()

	defer close(schedulerConfig.StopEverything)

	DoTestUnschedulableNodes(t, restClient, schedulerConfigFactory.NodeLister.Store)
}

func podScheduled(c *client.Client, podNamespace, podName string) wait.ConditionFunc {
	return func() (bool, error) {
		pod, err := c.Pods(podNamespace).Get(podName)
		if errors.IsNotFound(err) {
			return false, nil
		}
		if err != nil {
			// This could be a connection error so we want to retry.
			return false, nil
		}
		if pod.Spec.NodeName == "" {
			return false, nil
		}
		return true, nil
	}
}

// Wait till the passFunc confirms that the object it expects to see is in the store.
// Used to observe reflected events.
func waitForReflection(s cache.Store, key string, passFunc func(n interface{}) bool) error {
	return wait.Poll(time.Millisecond*10, time.Second*20, func() (bool, error) {
		if n, _, err := s.GetByKey(key); err == nil && passFunc(n) {
			return true, nil
		}
		return false, nil
	})
}

func DoTestUnschedulableNodes(t *testing.T, restClient *client.Client, nodeStore cache.Store) {
	goodCondition := api.NodeCondition{
		Type:              api.NodeReady,
		Status:            api.ConditionTrue,
		Reason:            fmt.Sprintf("schedulable condition"),
		LastHeartbeatTime: util.Time{time.Now()},
	}
	badCondition := api.NodeCondition{
		Type:              api.NodeReady,
		Status:            api.ConditionUnknown,
		Reason:            fmt.Sprintf("unschedulable condition"),
		LastHeartbeatTime: util.Time{time.Now()},
	}
	// Create a new schedulable node, since we're first going to apply
	// the unschedulable condition and verify that pods aren't scheduled.
	node := &api.Node{
		ObjectMeta: api.ObjectMeta{Name: "node-scheduling-test-node"},
		Spec:       api.NodeSpec{Unschedulable: false},
		Status: api.NodeStatus{
			Capacity: api.ResourceList{
				api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI),
			},
			Conditions: []api.NodeCondition{goodCondition},
		},
	}
	nodeKey, err := cache.MetaNamespaceKeyFunc(node)
	if err != nil {
		t.Fatalf("Couldn't retrieve key for node %v", node.Name)
	}

	// The test does the following for each nodeStateManager in this list:
	//	1. Create a new node
	//	2. Apply the makeUnSchedulable function
	//	3. Create a new pod
	//  4. Check that the pod doesn't get assigned to the node
	//  5. Apply the schedulable function
	//  6. Check that the pod *does* get assigned to the node
	//  7. Delete the pod and node.

	nodeModifications := []nodeStateManager{
		// Test node.Spec.Unschedulable=true/false
		{
			makeUnSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c *client.Client) {
				n.Spec.Unschedulable = true
				if _, err := c.Nodes().Update(n); err != nil {
					t.Fatalf("Failed to update node with unschedulable=true: %v", err)
				}
				err = waitForReflection(s, nodeKey, func(node interface{}) bool {
					// An unschedulable node should get deleted from the store
					return node == nil
				})
				if err != nil {
					t.Fatalf("Failed to observe reflected update for setting unschedulable=true: %v", err)
				}
			},
			makeSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c *client.Client) {
				n.Spec.Unschedulable = false
				if _, err := c.Nodes().Update(n); err != nil {
					t.Fatalf("Failed to update node with unschedulable=false: %v", err)
				}
				err = waitForReflection(s, nodeKey, func(node interface{}) bool {
					return node != nil && node.(*api.Node).Spec.Unschedulable == false
				})
				if err != nil {
					t.Fatalf("Failed to observe reflected update for setting unschedulable=false: %v", err)
				}
			},
		},
		// Test node.Status.Conditions=ConditionTrue/Unknown
		{
			makeUnSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c *client.Client) {
				n.Status = api.NodeStatus{
					Capacity: api.ResourceList{
						api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI),
					},
					Conditions: []api.NodeCondition{badCondition},
				}
				if _, err = c.Nodes().UpdateStatus(n); err != nil {
					t.Fatalf("Failed to update node with bad status condition: %v", err)
				}
				err = waitForReflection(s, nodeKey, func(node interface{}) bool {
					return node != nil && node.(*api.Node).Status.Conditions[0].Status == api.ConditionUnknown
				})
				if err != nil {
					t.Fatalf("Failed to observe reflected update for status condition update: %v", err)
				}
			},
			makeSchedulable: func(t *testing.T, n *api.Node, s cache.Store, c *client.Client) {
				n.Status = api.NodeStatus{
					Capacity: api.ResourceList{
						api.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI),
					},
					Conditions: []api.NodeCondition{goodCondition},
				}
				if _, err = c.Nodes().UpdateStatus(n); err != nil {
					t.Fatalf("Failed to update node with healthy status condition: %v", err)
				}
				waitForReflection(s, nodeKey, func(node interface{}) bool {
					return node != nil && node.(*api.Node).Status.Conditions[0].Status == api.ConditionTrue
				})
				if err != nil {
					t.Fatalf("Failed to observe reflected update for status condition update: %v", err)
				}
			},
		},
	}

	for i, mod := range nodeModifications {
		unSchedNode, err := restClient.Nodes().Create(node)
		if err != nil {
			t.Fatalf("Failed to create node: %v", err)
		}

		// Apply the unschedulable modification to the node, and wait for the reflection
		mod.makeUnSchedulable(t, unSchedNode, nodeStore, restClient)

		// Create the new pod, note that this needs to happen post unschedulable
		// modification or we have a race in the test.
		pod := &api.Pod{
			ObjectMeta: api.ObjectMeta{Name: "node-scheduling-test-pod"},
			Spec: api.PodSpec{
				Containers: []api.Container{{Name: "container", Image: "kubernetes/pause:go"}},
			},
		}
		myPod, err := restClient.Pods(api.NamespaceDefault).Create(pod)
		if err != nil {
			t.Fatalf("Failed to create pod: %v", err)
		}

		// There are no schedulable nodes - the pod shouldn't be scheduled.
		err = wait.Poll(time.Second, time.Second*10, podScheduled(restClient, myPod.Namespace, myPod.Name))
		if err == nil {
			t.Errorf("Pod scheduled successfully on unschedulable nodes")
		}
		if err != wait.ErrWaitTimeout {
			t.Errorf("Test %d: failed while trying to confirm the pod does not get scheduled on the node: %v", i, err)
		} else {
			t.Logf("Test %d: Pod did not get scheduled on an unschedulable node", i)
		}

		// Apply the schedulable modification to the node, and wait for the reflection
		schedNode, err := restClient.Nodes().Get(unSchedNode.Name)
		if err != nil {
			t.Fatalf("Failed to get node: %v", err)
		}
		mod.makeSchedulable(t, schedNode, nodeStore, restClient)

		// Wait until the pod is scheduled.
		err = wait.Poll(time.Second, time.Second*10, podScheduled(restClient, myPod.Namespace, myPod.Name))
		if err != nil {
			t.Errorf("Test %d: failed to schedule a pod: %v", i, err)
		} else {
			t.Logf("Test %d: Pod got scheduled on a schedulable node", i)
		}

		err = restClient.Pods(api.NamespaceDefault).Delete(myPod.Name, nil)
		if err != nil {
			t.Errorf("Failed to delete pod: %v", err)
		}
		err = restClient.Nodes().Delete(schedNode.Name)
		if err != nil {
			t.Errorf("Failed to delete node: %v", err)
		}
	}
}


text:
layout: article
title: "Масштабирование контента для области просмотра"
description: "Большинство интернет-ресурсов не оптимизировано для просмотра на разных типах устройств. Изучив основы, вы узнаете, как обеспечить одинаково хорошую работу сайта на телефонах, планшетах, домашних компьютерах... в общем, на любых устройствах, у которых есть экран."
introduction: "Для просмотра сайтов на обычных компьютерах и мобильных устройствах используется вертикальная прокрутка. Если пользователю приходится прокручивать сайт по горизонтали или уменьшать масштаб, чтобы увидеть страницу полностью, он испытывает большие неудобства."
article:
  written_on: 2014-04-30
  updated_on: 2014-04-30
  order: 2
authors:
  - petelepage
collection: rwd-fundamentals
key-takeaways:
  set-viewport:
    - Чтобы контролировать масштабирование окна просмотра в браузере, используйте метатег viewport.
     - Добавьте width=device-width, чтобы адаптировать ширину окна просмотра к экрану устройства.
    - Вставьте initial-scale=1, чтобы обеспечить соотношение 1:1 между пикселями CSS и независимыми пикселями устройства.
    - Чтобы страница была доступна, проверьте, не отключено ли пользовательское масштабирование.
  size-content-to-vp:
    - Не используйте крупные элементы  с фиксированной шириной.
    - Для корректного отображения контента не ограничивайте его определенной шириной области просмотра.
    - Используйте медиазапросы CSS, чтобы указать разные стили для больших и маленьких экранов.
  media-queries:
    - Медиазапросы также позволяют выбрать стиль на основе характеристик устройства.
    - Добавьте min-width вместо min-device-width для корректного отображения сайта на большинстве устройств.
    - Чтобы не нарушать структуру макета, используйте элементы относительных размеров.
  choose-breakpoints:
    - Создавайте контрольные точки на основе контента, а не для отдельных устройств, продуктов или брендов.
    - Сначала разработайте дизайн для самого маленького мобильного устройства, а затем переходите к версиям для больших экранов.
    - Ограничьте длину строк 70-80 символами.
remember:
  use-commas:
    - Разделяйте атрибуты запятыми, чтобы устаревшие версии браузеров могли их правильно интерпретировать.
shortlinks:
  # NOTE: If the section titles or URL changes the following shortlinks must be updated
  - g.co/mobilesiteprinciple20
---
{% wrap content %}

{% include modules/takeaway.liquid list=page.key-takeaways.size-content-to-vp %}

Используя метатег viewport при разработке сайта для мобильных устройств, можно по ошибке создать контент страницы, которые не полностью соответствует определенной области просмотра. Например, если ширина показываемого изображения больше области просмотра, придется использовать горизонтальную прокрутку. Чтобы избавить пользователей от этой необходимости, потребуется подогнать контент под шир ну области просмотра.

Диапазон размеров экрана и ширины в пикселях CSS очень велик (например, телефоны могут значительно отличаться от планшетов или даже от других телефонов), поэтому отображение контента не должно зависеть от конкретной ширины области просмотра.

Установка больших абсолютных значений ширины CSS для компонентов страницы сделает div слишком большим для более узкой области просмотра (например, на устройствах шириной 320 пикселей CSS, таких как iPhone). Вместо этого можно использовать значения в относительных единицах, например width: 100%.  Также старайтесь избегать больших абсолютных значений позиционирования. Из-за них на маленьком экране элемент может оказаться эа пределами области просмотра.

    {% link_sample _code/vp-fixed.html %}

      См. пример
    {% endlink_sample %}

    {% link_sample _code/vp-fixed.html %}

      См. пример
    {% endlink_sample %}

{% include modules/nextarticle.liquid %}

{% endwrap %}

redpajama_set_name: RedPajamaGithub


text:
package org.ambientdynamix.contextplugins.info.meta;

public interface IWebSource extends IContextSource
{
	public String websiteURL();
}


text:
package com.scorptech.turtleremote.carManagementScreen;

import android.os.AsyncTask;
import android.util.Log;

import com.github.niqdev.mjpeg.Mjpeg;
import com.github.niqdev.mjpeg.MjpegInputStream;
import com.scorptech.turtleremote.mvp.Presenter;
import com.scorptech.turtleremote.socket.Client;
import com.scorptech.turtleremote.socket.CommandBuilder;
import com.scorptech.turtleremote.socket.SocketListener;
import com.scorptech.turtleremote.socket.TCPClient;
import com.scorptech.turtleremote.socket.UDPClient;
import com.scorptech.turtleremote.views.MovementControlPanel;

import java.util.regex.Pattern;

import rx.functions.Action1;

/**
 * Created by talhahavadar on 13/01/2017.
 */

public class CarManagementPresenter extends Presenter<CarManagementView> implements ICarManagementPresenter {

    CarManagementView mView;
    UDPClient client;
    TCPClient tcpClient;

    public CarManagementPresenter(CarManagementView view) {
        mView = view;
        client= new UDPClient(7777);
        tcpClient = new TCPClient("192.168.1.2", 4444);
    }

    @Override
    public CarManagementView getView() {
        return mView;
    }

    @Override
    public void setupSocketConnection() {
        client.setSocketListener(new SocketListener() {
            @Override
            public void onData(Client client, final String data) {
                if (getView().getActivity() != null) {
                    getView().getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String[] splittedResponse = data.split(Pattern.quote("|"));
                            String command = splittedResponse[0];
                            if (command.equalsIgnoreCase("dist_front")) {
                                String val = splittedResponse[1];
                            }
                        }
                    });
                }
            }
        });
        //client.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        client.connect();
        tcpClient.connect();
    }

    @Override
    public void setupMjpegConnection() {
        Mjpeg.newInstance().open("http://192.168.1.1:8080/?action=stream", 5)
                .subscribe(new Action1<MjpegInputStream>() {
                    @Override
                    public void call(MjpegInputStream mjpegInputStream) {
                        getView().mjpegConnectionSuccess(mjpegInputStream);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(getClass().getSimpleName(), "mjpeg error", throwable);
                        getView().mjpegConnectionError(throwable);
                    }
                });
    }

    @Override
    public void evaluateJoystick(MovementControlPanel.Joystick joystick) {

        MovementControlPanel.JoystickPosition jPosition = joystick.getPositionPercentage();
        CommandBuilder.Command command = new CommandBuilder()
                .setType(CommandBuilder.CommandType.JOYSTICK)
                .addArgument("" + jPosition.x)
                .addArgument("" + jPosition.y)
                .build();
        if (tcpClient != null)
            tcpClient.send(command.getCommandString());
        else {
            Log.e("TCPClient", "null");
        }
        //client.send(joystick.getResetPosition(MovementControlPanel.JPosType.RELATIVE_PERCENTAGE).toString(), "192.168.1.3", 4444);
    }
}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class DentalStateConfig(AppConfig):
    name = 'dentalstate'


text:
using namespace ofp;

bool EchoReply::isKeepAlive() const {
  return header_.xid() == EchoRequest::kKeepAliveXID &&
         echoData() == EchoRequest::kKeepAliveData;
}

EchoReplyBuilder::EchoReplyBuilder(UInt32 xid) {
  msg_.header_.setXid(xid);
}

void EchoReplyBuilder::send(Writable *channel) {
  UInt8 version = channel->version();
  size_t msgLen = sizeof(msg_) + data_.size();

  msg_.header_.setVersion(version);
  msg_.header_.setLength(msgLen);

  channel->write(&msg_, sizeof(msg_));
  channel->write(data_.data(), data_.size());
  channel->flush();
}


text:
$(document).ready(function () {

    var $button = $('#load-more-button');

    var page_num = 1;
    var max_pages = 2;
    var next_link = $button.data('load-link');

    var containerID = $button.data('container');

    var $container = $('#' + containerID );
    var container_has_isotope = false;

    if (page_num > max_pages) {
        $button.addClass('hidden-xs-up');
    }

    $button.on('click', function () {

        if (page_num <= max_pages && !$(this).hasClass('loading') && !$(this).hasClass('last-page')) {

            $.ajax({
                type: 'GET',
                url: next_link,
                dataType: 'html',
                beforeSend: function () {
                            $button.addClass('loading');
                },
                complete: function (XMLHttpRequest) {
                   $button.removeClass('loading');
                    if (XMLHttpRequest.status == 200 && XMLHttpRequest.responseText != '') {

                        page_num++;

                        if (page_num > max_pages) {
                            $button.addClass('hidden-xs-up');
                        }

                        if ($(XMLHttpRequest.responseText).length > 0) {
                            container_has_isotope = (typeof($container.isotope) === 'function');
                            $(XMLHttpRequest.responseText).each(function () {
                                var elem = $(this);
                                if (!container_has_isotope) {
                                    $container.append(elem);
                                } else {
                                    $container.append( elem )
                                        .isotope( 'appended', elem )
                                        .isotope('layout');
                                    $container.imagesLoaded(function () {
                                        $container.isotope('layout');
                                    });
                                }

                            });
                        }
                    }
                }
            });
        }
        return false;
    });
});


text:
/**
 * Created by Zhangyx on 2015/10/15.
 */
;(function($){
    var Caroursel = function (caroursel){
        var self = this;
        this.caroursel = caroursel;
        this.posterList = caroursel.find(".poster-list");
        this.posterItems = caroursel.find(".poster-item");
        this.firstPosterItem = this.posterItems.first();
        this.lastPosterItem = this.posterItems.last();
        this.prevBtn = this.caroursel.find(".poster-prev-btn");
        this.nextBtn = this.caroursel.find(".poster-next-btn");
        //ĬÈϲÎÊý
        this.setting = {
            "width":"1000",
            "height":"270",
            "posterWidth":"640",
            "posterHeight":"270",
            "scale":"0.8",
            "speed":"1000",
            "isAutoplay":"true",
            "dealy":"1000"
        }
        //×Ô¶¨Òå²ÎÊýÓëĬÈϲÎÊýºÏ²¢
        $.extend(this.setting,this.getSetting())
        //ÉèÖõÚһ֡λÖÃ
        this.setFirstPosition();
        //ÉèÖÃÊ£ÓàÖ¡µÄλÖÃ
        this.setSlicePosition();
        //Ðýת
        this.rotateFlag = true;
        this.prevBtn.bind("click",function(){
            if(self.rotateFlag){
                self.rotateFlag = false;
                self.rotateAnimate("left")
            }
        });
        this.nextBtn.bind("click",function(){
            if(self.rotateFlag){
                self.rotateFlag = false;
                self.rotateAnimate("right")
            }
        });
        if(this.setting.isAutoplay){
            this.autoPlay();
            this.caroursel.hover(function(){clearInterval(self.timer)},function(){self.autoPlay()})
        }
    };
    Caroursel.prototype = {
        autoPlay:function(){
          var that = this;
          this.timer =  window.setInterval(function(){
              that.prevBtn.click();
          },that.setting.dealy)
        },
        rotateAnimate:function(type){
            var that = this;
            var zIndexArr = [];
            if(type == "left"){//Ïò×óÒƶ¯
                this.posterItems.each(function(){
                   var self = $(this),
                    prev = $(this).next().get(0)?$(this).next():that.firstPosterItem,
                    width = prev.css("width"),
                    height = prev.css("height"),
                    zIndex = prev.css("zIndex"),
                    opacity = prev.css("opacity"),
                    left = prev.css("left"),
                    top = prev.css("top");
                    zIndexArr.push(zIndex);
                    self.animate({
                        "width":width,
                        "height":height,
                        "left":left,
                        "opacity":opacity,
                        "top":top,
                    },that.setting.speed,function(){
                        that.rotateFlag = true;
                    });
                });
                this.posterItems.each(function(i){
                    $(this).css("zIndex",zIndexArr[i]);
                });
            }
            if(type == "right"){//ÏòÓÒÒƶ¯
                this.posterItems.each(function(){
                    var self = $(this),
                    next = $(this).prev().get(0)?$(this).prev():that.lastPosterItem,
                        width = next.css("width"),
                        height = next.css("height"),
                        zIndex = next.css("zIndex"),
                        opacity = next.css("opacity"),
                        left = next.css("left"),
                        top = next.css("top");
                        zIndexArr.push(zIndex);
                    self.animate({
                        "width":width,
                        "height":height,
                        "left":left,
                        "opacity":opacity,
                        "top":top,
                    },that.setting.speed,function(){
                        that.rotateFlag = true;
                    });
                });
                this.posterItems.each(function(i){
                    $(this).css("zIndex",zIndexArr[i]);
                });
            }
        },
        setFirstPosition:function(){
            this.caroursel.css({"width":this.setting.width,"height":this.setting.height});
            this.posterList.css({"width":this.setting.width,"height":this.setting.height});
            var width = (this.setting.width - this.setting.posterWidth) / 2;
            //ÉèÖÃÁ½¸ö°´Å¥µÄÑùʽ
            this.prevBtn.css({"width":width , "height":this.setting.height,"zIndex":Math.ceil(this.posterItems.size()/2)});
            this.nextBtn.css({"width":width , "height":this.setting.height,"zIndex":Math.ceil(this.posterItems.size()/2)});
            this.firstPosterItem.css({
                "width":this.setting.posterWidth,
                "height":this.setting.posterHeight,
                "left":width,
                "zIndex":Math.ceil(this.posterItems.size()/2),
                "top":this.setVertialType(this.setting.posterHeight)
            });
        },
        setSlicePosition:function(){
            var _self = this;
            var sliceItems = this.posterItems.slice(1),
                level = Math.floor(this.posterItems.length/2),
                leftItems = sliceItems.slice(0,level),
                rightItems = sliceItems.slice(level),
                posterWidth = this.setting.posterWidth,
                posterHeight = this.setting.posterHeight,
                Btnwidth = (this.setting.width - this.setting.posterWidth) / 2,
                gap = Btnwidth/level,
                containerWidth = this.setting.width;
            //ÉèÖÃ×ó±ßÖ¡µÄλÖÃ
            var i = 1;
            var leftWidth = posterWidth;
            var leftHeight = posterHeight;
            var zLoop1 = level;
            leftItems.each(function(index,item){
                leftWidth = posterWidth * _self.setting.scale;
                leftHeight = posterHeight*_self.setting.scale;
                $(this).css({
                    "width":leftWidth,
                    "height":leftHeight,
                    "left": Btnwidth - i*gap,
                    "zIndex":zLoop1--,
                    "opacity":1/(i+1),
                    "top":_self.setVertialType(leftHeight)
                });
                i++;
            });
            //ÉèÖÃÓÒÃæÖ¡µÄλÖÃ
            var j = level;
            var zLoop2 = 1;
            var rightWidth = posterWidth;
            var rightHeight = posterHeight;
            rightItems.each(function(index,item){
                var rightWidth = posterWidth * _self.setting.scale;
                var rightHeight = posterHeight*_self.setting.scale;
                $(this).css({
                    "width":rightWidth,
                    "height":rightHeight,
                    "left": containerWidth -( Btnwidth - j*gap + rightWidth),
                    "zIndex":zLoop2++,
                    "opacity":1/(j+1),
                    "top":_self.setVertialType(rightHeight)
                });
                j--;
            });
        },
        getSetting:function(){
            var settting = this.caroursel.attr("data-setting");
            if(settting.length > 0){
                return $.parseJSON(settting);
            }else{
                return {};
            }
        },
        setVertialType:function(height){
            var algin = this.setting.algin;
            if(algin == "top") {
                return 0
            }else if(algin == "middle"){
                return (this.setting.posterHeight - height) / 2
            }else if(algin == "bottom"){
                return this.setting.posterHeight - height
            }else {
                return (this.setting.posterHeight - height) / 2
            }
        }
    }
    Caroursel.init = function (caroursels){
        caroursels.each(function(index,item){
            new Caroursel($(this));
        })  ;
    };
    window["Caroursel"] = Caroursel;
})(jQuery)


text:
"""Filters for Zinnia admin"""
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ungettext_lazy
from django.utils.translation import ugettext_lazy as _

from zinnia.models import Author
from django.db.models import Count

class AuthorListFilter(SimpleListFilter):
    """List filter for EntryAdmin filtering
    possibilities to published authors only."""
    title = _('author')
    parameter_name = 'author'

    def lookups(self, request, model_admin):
        """Return published authors choices with their entries number"""
        active_authors = Author.published.all().annotate(
            number_of_entries=Count('entries'))
        for author in active_authors:
            yield (str(author.pk), ungettext_lazy(
                '%(author)s (%(count)i entry)',
                '%(author)s (%(count)i entries)',
                author.number_of_entries) % {
                       'author': author.__unicode__(),
                       'count': author.number_of_entries})

    def queryset(self, request, queryset):
        """Return the author's entries if a value is set"""
        if self.value():
            return queryset.filter(authors__id=self.value())


text:
module Joey
  class Status < Model
    define_properties :time, :status_id, :message

    def validate
      valid = true
    end

    def valid?
      self.validate
      puts self.errors.inspect unless self.errors.empty?
      self.errors.empty?
    end
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jabook.commute.controller;

import com.jabook.common.ControllerClassInfo;
import com.jabook.common.ControllerMethodInfo;
import com.jabook.common.DispatcherServlet;
import com.jabook.commute.dao.MemberDao;
import com.jabook.commute.dao.WorkerDao;
import com.jabook.dbdriver.ResultMap;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author sshtel
 */

@ControllerClassInfo(name = "CommuteController")
public class WorkerController {
    private String myDir = "/commute/worker";

    @ControllerMethodInfo(controllerPage = "signUpWorkerForm.do", template = "single")
    public String signUpWorkerForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return myDir + "/signUpWorkerForm.jsp";
    }

    @ControllerMethodInfo(controllerPage = "addWorker.do")
    public String addWorker(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int myMemberNo = Integer.parseInt( (String)request.getSession().getAttribute("currentMemberNo") );
        String name = (String) request.getParameter("name");
        String phoneNumber = (String) request.getParameter("phoneNumber");
        String address = (String) request.getParameter("address");
        int myPlaceNo = 1;
        String comment = (String)request.getParameter("comment");
        String workerId = phoneNumber;
        String myWorkingStatus = "";
        String result = "false";

        if( WorkerDao.signupNewWorker(workerId, "1234", name, phoneNumber, address, myMemberNo, myPlaceNo, myWorkingStatus, comment) ) {
            result = "true";
        }
        else result = "false";
        request.setAttribute("result", result);
        return DispatcherServlet.RESULT_PAGE;
    }

    @ControllerMethodInfo(controllerPage = "workerPageForm.do", template = "main")
    public String workerPageForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String memberNo = (String)request.getSession().getAttribute("currentMemberNo");

        List<ResultMap>  myWorkers = WorkerDao.getDataByMemberNo(memberNo);
//
//        for( ResultMap r : myWorkers){
//            r.remove("password");
//            r.replace("name", "'" + r.get("name") + "'");
//            r.replace("address", "'" + r.get("address") + "'");
//            r.replace("phoneNumber", "'" + r.get("phoneNumber") + "'");
//            r.replace("workingStatus", "'" + r.get("workingStatus") + "'");
//            r.replace("id", "'" + r.get("id") + "'");
//            r.replace("comment", "'" + r.get("comment") + "'");
//        }
//
        request.setAttribute("myWorkers", myWorkers);

        return myDir + "/workerPageForm.jsp";
    }

    @ControllerMethodInfo(controllerPage = "updateWorker.do", template = "main")
    public String updateWorker(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String workerNo = (String)request.getParameter("workerNo");
        String fieldName = (String)request.getParameter("fieldName");
        String value = (String)request.getParameter("value");

        String result = "false";
        if(WorkerDao.updateWorker(workerNo, fieldName, value)) {
            result = "true";
        }
        request.setAttribute("result", result);
        return DispatcherServlet.RESULT_PAGE;
    }

    @ControllerMethodInfo(controllerPage = "deleteWorker.do", template = "main")
    public String deleteWorker(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String result = "false";
        String workerNo = (String)request.getParameter("workerNo");
        if(WorkerDao.deleteWorker(Integer.parseInt(workerNo))){
            result = "true";
        }
        request.setAttribute("result", result);
        return DispatcherServlet.RESULT_PAGE;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Indian Phytopath. 41(4): 522 (1989)

#### Original name
Blastocladia arborata S.N. Dasgupta & R. John

### Remarks
null


text:
""" Class definitions for atomic and molecular orbitals.

Notes:
    In this documentation, we use the following conventions for labeling orbitals:
      - atomic orbitals using lower case greek labels and subscripts, e.g.,
          :math:`\left| \mu \right \rangle, F_{\nu \lambda}, etc.
      - molecular orbitals use lower case labels and subscripts, e.g.,
          :math:`\left| i \right \rangle, F_{kl}, etc.
      - adiabatic electronic states are indexed using capital letters, _N_, _L_, _M_, etc.

"""
import numpy as np

from moldesign import units as u
from moldesign.utils import Alias

SHELLS = {0: 's', 1: 'p', 2: 'd', 3: 'f', 4: 'g', 5: 'h'}
ANGMOM = {v: k for k, v in SHELLS.iteritems()}

# See https://en.wikipedia.org/wiki/Table_of_spherical_harmonics#Real_spherical_harmonics
SPHERICALNAMES = {(0, 0): 's', (1, -1): 'p(x)', (1, 0): 'p(z)', (1, 1): 'p(y)',
                  (2, 0): 'd(z^2)', (2, -2): 'd(xy)', (2, -1): 'd(yz)',
                  (2, 1): 'd(xz)', (2, 2): 'd(x^2-y^2)',
                  (3, -3): 'f(3yx^2-y^3)', (3, -2): 'f(xyz)', (3, -1): 'f(yz^2)',
                  (3, 0): 'f(z^3)', (3, 1): 'f(xz^2)', (3, 2): 'f(zx^2-zy^2)',
                  (3, 3): 'f(x^3-3xy^2)'}
ANGULAR_NAME_TO_COMPONENT = {'': (0, 0), 'x': (1, -1), 'y': (1, 1), 'z': (1, 0),
                             'z^2': (2, 0), 'xy': (2, -2), 'yz': (2, -1), 'xz': (2, 1),
                             'x^2-y^2': (2, 2),
                             'zx^2-zy^2': (3, 2), 'xyz': (3, -2), 'z^3': (3, 0),
                             '3yx^2-y^3': (3, -3), 'x^3 - 3xy^2': (3, 3), 'xz^2': (3, 1),
                             'yz^2': (3, -1)}

class Orbital(object):
    r"""
    Stores a single orbital and its meta-data
    Generally wants to be part of a set of MolecularOrbitals

    The orbital is defined as
    .. math::
        \left| i \right \rangle = \sum_\mu c_{i \mu} \left| \mu \right \rangle

    where the coefficients :math:`c_{i \mu}` are stored in ``self.coeffs`` and the basis orbitals
    :math:`\left| \mu \right \rangle` are stored at ``self.basis``
    """
    def __init__(self, coeffs, basis=None, wfn=None,
                 occupation=None, name='unnamed'):
        """ Initialization:

        Args:
            coeffs (numpy.array): orbital coefficients
            basis (moldesign.orbitals.basis.BasisSet): basis for this orbital
            wfn (moldesign.orbitals.wfn.ElectronicWfn): total electronic wavefunction that this orbital is a part of
            occupation (float): occupation of this orbital
            name (str): optional label for this orbital:
        """
        self.coeffs = np.array(coeffs)
        self.name = name
        self.molecule = None
        self.basis = basis
        self.occupation = occupation
        self.wfn = wfn
        self.index = None  # will be set by the containing MolecularOrbitals object

        # Assign the basis functions
        if wfn is not None and wfn.aobasis is not None:
            if self.basis is not None:
                assert wfn.aobasis is self.basis
            else:
                self.basis = wfn.aobasis
        if self.basis is not None:
            assert len(self.coeffs) == len(self.basis)

    def overlap(self, other):
        """ Calculate overlap with another orbital

        Args:
            other (Orbital): calculate the overlap with this orbital

        Returns:
            float: orbital overlap
        """
        return self.coeffs.dot(self.basis.overlaps.dot(other.coeffs))

    def fock_element(self, other):
        """ Calculate fock matrix element with another orbital

        Args:
            other (Orbital): calculate the fock element with this orbital

        Returns:
            u.Scalar[energy]: fock matrix element
        """
        return self.wfn.fock_ao.dot(other.coeffs).ldot(self.coeffs)  # uses ldot to preserve units

    @property
    def energy(self):
        """ u.Scalar[energy]: This orbital's energy

        Note:
            This is equivalent to self.fock(self)
        """
        return self.fock_element(self)

    def __call__(self, coords):
        """ Calculate the orbital's value at a position (or list of positions)

        Args:
            coords (u.Vector[length]): Coordinates (shape ``(len(coords), 3)``)

        Returns:
            u.Scalar[length**(-3/2)]: value of the orbital
        """
        return self.basis(coords, coeffs=self.coeffs)

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.name)

    __len__ = Alias('coeffs.__len__')

class MolecularOrbitals(object):
    """
    Stores a wfn of molecular orbitals in an AO wfn
    Orbitals are accessed as orbs[orbital index, ao index]
    """
    def __init__(self, orbitals, wfn=None, basis=None,
                 canonical=False,
                 orbtype=None):
        """ Initialization:

        Args:
            orbitals (List[Orbital] OR numpy.array): EITHER a list of orbitals OR an
               array of coefficients (indexed as coeffs[orbital_index, basis_index])
            basis (moldesign.orbitals.basis.BasisSet): orbital basis set
            wfn (moldesign.orbitals.wfn.ElectronicWfn): total electronic wavefunction that this orbital is a part of
            canonical (bool): designate these as the canonical orbitals
            orbtype (str): description of these orbitals
        """
        # Determine if these are the canonical orbitals
        if canonical:
            assert orbtype is None or orbtype == 'canonical'
            orbtype = 'canonical'
        if orbtype == 'canonical':
            canonical = True

        if not hasattr(orbitals[0], 'basis'):
            coeffs = orbitals
            orbitals = []
            for c in coeffs:
                orbitals.append(Orbital(c, basis=basis, wfn=wfn))

        self.orbitals = orbitals
        self.coeffs = np.array([orb.coeffs for orb in self.orbitals])
        self.wfn = wfn
        self.basis = basis
        self.orbtype = orbtype

        if self.wfn is None:
            self.wfn = self.orbitals[0].wfn
        if self.basis is None:
            self.basis = self.orbitals[0].basis

        for iorb, orbital in enumerate(self.orbitals):
            orbital.index = iorb
            assert orbital.basis == self.basis
            assert orbital.wfn == self.wfn
            orbital.coeffs = self.coeffs[iorb, :]

        if canonical:
            self._set_cmo_names()

    def align_phases(self, other, threshold=0.5, assert_same_type=True):
        """ Flip the signs of these orbitals to bring them into maximum coincidence
        with another set of orbitals

        Args:
            other (MolecularOrbitals): the "reference" set of orbitals to match phases with
            threshold (float): only flip orbital if the overlap is less than -1*threshold
            assert_same_type (bool): require that ``self.orbtype == other.orbtype``

        Note:
            This function assumes that the overlap matrix is the same for both sets of
            orbitals - this is a reasonable assumption if the two sets of orbitals were
            calculated at very similar molecular geometries.
        """
        if assert_same_type:
            assert self.orbtype == other.orbtype, "Orbital type mismatch: %s vs. %s" % (
                self.orbtype, other.orbtype)
        for thisorb, otherorb in zip(self, other):
            if thisorb.overlap(otherorb) < -1.0 * threshold:
                thisorb.coeffs *= -1.0
                # TODO: print a warning if overlap is small?

    def overlap(self, other):
        """ Calculate overlaps between this and another set of orbitals

        Args:
            other (MolecularOrbitals):

        Returns:
            numpy.ndarray: overlaps between the two sets of orbitals

        Example:
            >>> canonical = mol.wfn.canonical
            >>> atomic = mol.wfn.basis
            >>> overlaps = canonical.overlap(atomic)
            >>> overlaps[i, j] == canonical.orbitals[i].overlap(atomic.orbitals[j])
            True
        """
        return self.coeffs.dot(self.wfn.aobasis.overlaps.dot(other.coeffs.T))

    def __iter__(self):
        return iter(self.orbitals)

    def __len__(self):
        return len(self.orbitals)

    def __str__(self):
        return '%s orbitals' % self.orbtype

    def __repr__(self):
        return '<%d %s %s in %s>' % (len(self), self.orbtype,
                                     self.__class__.__name__, str(self.wfn))

    def __getitem__(self, item):
        return self.orbitals[item]

    def _to_ao_density_matrix(self):
        c = self.coeffs * self.occupations[:, None]/2.0
        return 2.0*c.T.dot(c)

    @property
    def energies(self):
        """u.Vector[energy]: energies of the molecular orbitals

        This is just the diagonal of the fock matrix"""
        return self.fock.diagonal()

    @property
    def occupations(self):
        """ np.ndarray: orbital occupation numbers
        """
        return np.array([orb.occupation for orb in self.orbitals])

    @property
    def fock(self):
        """u.Array[energy]: Fock matrix for these orbitals"""
        return self.from_ao(self.wfn.fock_ao)

    @property
    def overlaps(self):
        """np.array: overlap matrix for these orbitals"""
        return self.from_ao(self.wfn.aobasis.overlaps)

    @property
    def h1e(self):
        """u.Array[energy]: 1-electron matrix elements for these orbitals"""
        return self.from_ao(self.wfn.aobasis.h1e)

    @property
    def h2e(self):
        """u.Array[energy]: 2-electron matrix elements for these orbitals"""
        return self.fock - self.h1e

    def from_ao(self, ao_operator):
        """ Transform an operator into this orbital basis from the ao basis

        Given the matrix elements :math:`\hat O_{\mu \nu}` of an operator over AO basis indices
        :math:`\mu,\nu`, returns the operator's matrix elements :math:`\hat O_{ij}` over
        orbital indices :math:`i,j`:

        ..math::
            \hat O_{ij} =
             \left \langle i \right| \hat O \left| j \right \rangle =
              \sum_{\mu \nu}C_{i \mu} O_{\mu \nu} C_{j \nu}

        where :math:`C_{i \mu}` is the expansion coefficient for AO basis function :math:`\mu` in
        molecular orbital _i_.

        Args:
            ao_operator (u.Array): matrix elements of the operator in the ao basis

        Returns:
            u.Array: matrix elements of the operator in this orbital basis

        Note:
            Assumes that this set of orbitals is orthogonal
        """
        # Dot doesn't place nice with units, so we need to pass them explicitly
        ao_units = u.get_units(ao_operator)
        return self.coeffs.dot(ao_operator.dot(self.coeffs.T)) * ao_units

    def to_ao(self, mo_operator):
        """ Transform an operator from this orbital basis into the AO basis

        Given the matrix elements :math:`\hat O_{ij}` of an operator over orbital basis indices
        :math:`i,j`, returns the operator's matrix elements :math:`\hat O_{\mu \nu}` over
        orbital indices :math:`\mu, \nu`:

        ..math::
           \hat O_{\mu \nu} =
           \left \langle \mu \right| \hat O \left| \nu \right \rangle =
           \sum_{i,j,\lambda,\kappa}S_{\mu \lambda} C_{i \lambda} O_{ij} C_{j \kappa} S_{\kappa \nu}

        where :math:`S_{\mu \nu} = \left \langle \mu | \nu \right \rangle` is the AO overlap matrix
        and :math:`C_{i \mu}` is the expansion coefficient for AO basis function :math:`\mu` in
        molecular orbital _i_.

        Args:
            mo_operator (u.Array): matrix elements of the operator in this orbital basis

        Returns:
            u.Array: matrix elements of the operator in the AO basis
        """
        units = u.get_units(mo_operator)
        s = self.wfn.aobasis.overlaps
        o_ao = s.dot(self.coeffs.T).dot(mo_operator).dot(self.coeffs).dot(s)
        return o_ao * units

    def _set_cmo_names(self):
        for i, orb in enumerate(self.orbitals):
            if orb.name != 'unnamed' and orb.name is not None:
                continue
            if i <= self.wfn.homo:
                if i < self.wfn.homo - 2:
                    orb.name = 'cmo %d' % i
                elif i == self.wfn.homo:
                    orb.name = 'HOMO'
                else:
                    orb.name = 'HOMO-%d' % (self.wfn.homo - i)
            else:
                if i == self.wfn.lumo:
                    orb.name = 'LUMO'
                elif i <= self.wfn.lumo + 2:
                    orb.name = 'LUMO+%d' % (i - self.wfn.lumo)
                else:
                    orb.name = 'virt cmo %d' % i


text:
Watches the messages emitted in the execution and reacts when
a message matches certain criteria.

Once the trap is set (once the execution interprets its branch), it
will trigger for any matching message, unless the `count:` attribute
is set (it will trigger for the first {count} matching messages).

When the execution terminates, the trap is removed.

By default, the observation range is the execution, only messages
in the execution where the trap was set are considered.
The trap can be extended via the `range:` attribute.

"trap" triggers a function, while "on" triggers a block.

## the point: criterion

The simplest thing to trap is a 'point'. Here, the trap is set for
any message whose point is 'terminated':
```
sequence
  trap 'terminated'
    def msg \ trace "terminated(f:$(msg.from))"
  trace "here($(nid))"
    # OR
#sequence
#  trap 'terminated'
#    def msg \ trace "terminated(f:$(msg.from))"
#  trace "here($(nid))"
```

## the heap: criterion

Given a procedure like `sequence`, `concurrence` or `apply`, trigger
a piece of code each time the procedure receives the "execute" or the
"receive" message.

```
trap heap: 'sequence'
  def msg
    trace "$(msg.point)-$(msg.tree.0)-$(msg.nid)<-$(msg.from)"
sequence
  noret _
#
# will trace:
#  0:execute-sequence-0_1<-0
#  1:receive--0_1<-0_1_0
#  2:receive--0<-0_1
```

## the heat: criterion

While `heap:` filters on the actual flor procedure names, `heat:` is
looser, it catches whatever stands "at the beginning of the flor line".
It's useful to catch function calls.

```
trap heat: 'fun0'
  def msg
    trace "t-$(msg.tree.0)-$(msg.nid)"
define fun0
  trace "c-fun0-$(nid)"
sequence
  fun0 _
  fun0 # not a call

# will trace:
# 0:t-fun0-0_2_0
# 1:c-fun0-0_1_1_0_0-2
# 2:t--0_2_0
# 3:t--0_2_0
# 4:t-fun0-0_2_1
```

`heat:` accepts strings or regular expressions:

```
trap heat: [ /^fun\d+$/ 'funx' ]
  def msg \ trace "t-$(msg.tree.0)-$(msg.nid)"
```

## the tag: criterion

Traps one or multiple tags. Default to trapping on "entered". May trap
leaving tags with `point: 'left'` or any with
`point: [ 'entered', 'left' ]`.

```
trap tag: 'x'
  def msg
    trace "$(msg.tags.-1)-$(msg.point)"
# ...
sequence tag: 'x'
  trace 'c'

# will trace "x-entered" and "c"
```

## the signal: criterion

`signal:` traps signals directed at the execution. Signals are
directly
```
trap signal: 'S0'
  def msg
    trace "S0"
# ...
signal 'S0'
```

Note that it's OK to trap all signals, whatever their name, directed at
the execution by using `point: 'signal'`, as in:
```
trap point: 'signal'
  def msg
    trace "caught signal '$(sig)'"
```

[on](on.md) is a macro that turns
```
on 'rejected'
  trace "execution received signal $(sig)"
```
into
```
trap signal: 'rejected'
  def msg
    trace "execution received signal $(sig)"
```
Please note how "on" accepts a block while "trap" accepts a function.

## the range: limit

The range limit determines what is the range, or scope of the trap.
By default the trap only care about nodes below its parent. In other words,
the trap binds itself to its parent and observes the messages occuring
in the execution in the branch of nodes whose root is the parent.

The possible values for `range:` are:
* 'subnid' (default)
* 'execution'
* 'domain'
* 'subdomain'

With 'execution', the trap observes all the messages emitted within the
same execution.

With 'domain', all the messages in all the execution of the same domain are
observed. For example,
```
trap point: 'signal', domain: 'net.acme'
  def msg \ trace "signal '$(sig)' caught"
```
once set, will be triggered for each signal received by an execution in the
'net.acme' domain.

Likewise,
```
trap point: 'signal', subdomain: 'org.acme'
  def msg \ trace "signal '$(sig)' caught"
```
Will trap all signals in the domain "org.acme" and its subdomains,
(org.acme.accounting, org.acme.engineering, org.acme.whatever.x.y.z, ...)

## the bnid: directive

"bound nid" by default is the nid of the parent expression to the "trap".
With `bnid:`, one can bind a trap to another expression.

## the count: limit

```
trap tag: 'x' count: 2
  # ...
```
will trigger when the execution enters the tag 'x', but will trigger only
twice.

## the payload: directive

The `payload:` attribute tells the trap what payload to hand to the
trap handler.

When `payload: 'event'`, the handler is given a copy of the fields as
seen in the event that triggered the trap.

When `payload: 'trap'`, the handler is given a copy of the fields as
they were when and where the trap was set.

When `payload: { a: 'A' }`, the given payload is used (here
`{ 'a' => 'A' }`).

## blocking trap

One can use a trap without a function. It will block the execution branch
until the expect event, signal, etc occurs
```
sequence
  technical_writer 'prepare documentation'
  team_manager 'submit documentation to review team'
  trap signal: 'green' # go on after the 'green' signal...
  team_manager 'deploy documentation'
```
Here the execution will block after the team manager submits the doc
for review. When the 'green' signal comes, the flow resumes to 'deploy
documentation'.

## see also

[On](on.md) and [signal](signal.md).

* [source](https://github.com/floraison/flor/tree/master/lib/flor/punit/trap.rb)
* [trap spec](https://github.com/floraison/flor/tree/master/spec/punit/trap_spec.rb)


text:
FROM jruby:9.1

ADD ./ /sinatra-sequel
WORKDIR /sinatra-sequel

ENV THREAD_FACTOR=2

RUN bundle install --jobs=4 --gemfile=/sinatra-sequel/Gemfile --path=/sinatra-sequel/sinatra-sequel/bundle

ENV DBTYPE=postgresql

EXPOSE 8080

CMD export MAX_CONCURRENCY=$(( 2 * $(nproc) )) && bundle exec torquebox run --io-threads $(( MAX_CONCURRENCY / 2 )) --worker-threads $MAX_CONCURRENCY -b 0.0.0.0 -p 8080 -e production


text:
import logging
class NullHandler(logging.Handler):
    def emit(self, record):
        pass
log = logging.getLogger('coapResource')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())

from . import coapException        as e
from . import coapDefines          as d

class coapResource(object):

    def __init__(self,path):

        assert type(path)==str

        # store params
        self.path     = path

        self.securityBinding = None

    #======================== abstract methods ================================

    def GET(self,options=[]):
        raise e.coapRcMethodNotAllowed()

    def PUT(self,options=[],payload=None):
        raise e.coapRcMethodNotAllowed()

    def POST(self,options=[],payload=None):
        raise e.coapRcMethodNotAllowed()

    def DELETE(self,options=[]):
        raise e.coapRcMethodNotAllowed()

    #======================== public ==========================================

    def matchesPath(self,pathToMatch):
        log.debug('"{0}" matches "{1}"?'.format(pathToMatch,self.path))
        temp_path        = self.path.lstrip('/').rstrip('/')
        temp_pathToMatch = pathToMatch.lstrip('/').rstrip('/')
        if temp_path==temp_pathToMatch:
            return True
        else:
            return False

    def addSecurityBinding(self, binding):
        (ctx, authorizedMethods) = binding
        assert isinstance(authorizedMethods, list)
        for method in authorizedMethods:
            assert method in d.METHOD_ALL

        log.debug('adding security binding for resource={0}, context={1}, authorized methods={2}'.format(self.path,
                                                                                ctx,
                                                                                authorizedMethods))
        self.securityBinding = binding

    def getSecurityBinding(self):
        if self.securityBinding:
            return self.securityBinding
        else:
            # if no context is bound to the resource, all methods are authorized
            return (None, d.METHOD_ALL)


text:
package com.raulh82vlc.topratemovies.models;

/**
 * Created by Raul Hernandez Lopez on 22/02/2015.
 * General constants used when variables passed
 * into Intents flow or General constants in the program
 */
public final class Constants {
    // param keys of activities
    public static final String A_NAME_FILM = "com.raulh82vlc.topratemovies.nFilm";
    public static final String A_RANKING = "com.raulh82vlc.topratemovies.nRanking";
    public static final String A_NAME_IMG = "com.raulh82vlc.topratemovies.nImgPath";
    // params keys of fragment
    public static final String F_AUTHOR = "com.raulh82vlc.topratemovies.paramAuthor";
    public static final String F_EMAIL = "com.raulh82vlc.topratemovies.paramEmail";
    public static final String F_NMOVIES = "com.raulh82vlc.topratemovies.nMovies";

    public static final int MIN = 1;
    public static final int MAX = 20;

    public static enum TOWARDS {TOP,BOTTOM};
}


text:
import com.imadethatcow.hipchat.users.PrivateMessenger
import org.scalatest._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global

class PrivateMessengerSpec extends FlatSpec with Matchers with WithConfig {
  val apiToken = config("auth_token")
  val room = config("test_room")
  val email = config("test_email")

  val message = "This is an automated private message"
  val messenger = new PrivateMessenger(apiToken)

  "Private message" should "not fail" in {
    val fut = messenger.sendMessage(email, message)
    Await.result(fut, Duration.Inf) shouldEqual true
  }
}


text:
id: 5900f5411000cf542c510053
title: 'Problem 469: Empty chairs'
challengeType: 5
forumTopicId: 302144
dashedName: problem-469-empty-chairs
---

# --description--

In a room N chairs are placed around a round table.

Knights enter the room one by one and choose at random an available empty chair.

To have enough elbow room the knights always leave at least one empty chair between each other.

When there aren't any suitable chairs left, the fraction C of empty chairs is determined. We also define E(N) as the expected value of C. We can verify that E(4) = 1/2 and E(6) = 5/9.

Find E(1018). Give your answer rounded to fourteen decimal places in the form 0.abcdefghijklmn.

# --hints--

`euler469()` should return 0.56766764161831.

```js
assert.strictEqual(euler469(), 0.56766764161831);
```

# --seed--

## --seed-contents--

```js
function euler469() {

  return true;
}

euler469();
```

# --solutions--

```js
// solution required
```


text:
// Autogenerated by hob
window.cls || (window.cls = {});
cls.ResourceManager || (cls.ResourceManager = {});
cls.ResourceManager["1.0"] || (cls.ResourceManager["1.0"] = {});

cls.ResourceManager["1.0"].Response = function(arr, parent)
{
  this.parent = parent || null;
  this.requestID = arr[0];
  this.resourceID = arr[1];
  this.time = arr[2];
  /**
    * HTTP response code, such as 200, 404, etc.
    */
  this.responseCode = arr[3];
  this.toString = function() { return "[message Response]"; }
};


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('room_manage', '0007_auto_20160503_2328'),
    ]

    operations = [
        migrations.CreateModel(
            name='NickSummary',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('network', models.TextField(db_index=True)),
                ('nick', models.CharField(max_length=40, db_index=True)),
                ('host_mask', models.CharField(max_length=80)),
                ('last_seen', models.DateTimeField()),
            ],
        ),
    ]


text:
'use strict';

describe('Controller: BarangCtrl', function() {

  // load the controller's module
  beforeEach(module('belajarOauth2ImplicitClientApp'));

  var BarangCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function($controller, $rootScope) {
    scope = $rootScope.$new();
    BarangCtrl = $controller('BarangCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function() {});
});


text:
package net.ssehub.easy.producer.core.persistence.datatypes;

import java.io.File;

import net.ssehub.easy.producer.core.mgmt.PLPInfo;
import net.ssehub.easy.producer.core.persistence.PersistenceException;

/**
 * General interface for different Persistencer plug-ins.
 * @author El-Sharkawy
 *
 */
public interface IPersistencer {

    /**
     * Loads a PersistentProject, which is an EASy project representation, from a storage (file system).
     * @return The PersistentProject of the project which should be loaded.
     * @throws PersistenceException In case of an incorrect data format of the configuration file,
     * this exception will be thrown.
     */
    public PersistentProject load() throws PersistenceException;

    /**
     * Saves given PersistentProject to storage.
     * @param plp The project which should be saved
     * @throws PersistenceException If files cannot be written to the file system.
     */
    public void save(PLPInfo plp) throws PersistenceException;

    /**
     * Creates an empty EASy project without any eclipse specific stuff.
     * @param projectName The name of the project, which should be created.
     * @param parentFolder The parentFolder, where the project should be created.
     * @param projectID The unique ID of the project which should be created.
     * @param lazy if true, create only required parts, else assume that project does not exist before
     * @throws PersistenceException Will be thrown if the System cannot create folders and files in the parentFolder.
     * @return IProjectCreationResult Information of newly created items.
     */
    public IProjectCreationResult createProject(String projectName, File parentFolder, String projectID, boolean lazy)
        throws PersistenceException;

    /**
     * Returns the ID of a given EASy project.
     *
     * @return the ID or null if the specified project has no configuration file.
     */
    public String getProjectID();

    /**
     * Updates the models in the given project.
     *
     * @throws PersistenceException if errors during the update occur
     */
    public void update() throws PersistenceException;

    /**
     * Returns the path environment for making absolute paths relative and vice versa.
     *
     * @return the path environment
     */
    public PathEnvironment getPathEnvironment();
}


text:
/**
 * @fileoverview
 * Implementation of container that can hold a set of other widgets.
 * @author Partridge Jiang
 */

/*
 * requires /lan/classes.js
 * requires /utils/kekule.utils.js
 * requires /utils/kekule.domUtils.js
 * requires /xbrowsers/kekule.x.js
 * requires /widgets/kekule.widget.base.js
 */

(function(){

/** @ignore */
Kekule.Widget.HtmlClassNames = Object.extend(Kekule.Widget.HtmlClassNames, {
	CONTAINER: 'K-Container',
	PANEL: 'K-Panel',
	PANEL_CAPTION: 'K-Panel-Caption',
	TOOLBAR: 'K-Toolbar'
});

var DU = Kekule.DomUtils;
var EU = Kekule.HtmlElementUtils;
var CNS = Kekule.Widget.HtmlClassNames;
var SU = Kekule.StyleUtils;

/**
 * An abstract widget container.
 * @class
 * @augments Kekule.Widget.BaseWidget
 *
 * @property {String} childWidth CSS width of all children. If set to null, width will be determined by child it self.
 * @property {String} childHeight CSS height of all children. If set to null, height will be determined by child it self.
 * @property {String} childMargin CSS margin property of all children.
 * @property {Bool} allowChildWrap Whether child widget can wrap in lines inside parent. Only work in horizontal layout.
 */
Kekule.Widget.Container = Class.create(Kekule.Widget.BaseWidget,
/** @lends Kekule.Widget.Container# */
{
	/** @private */
	CLASS_NAME: 'Kekule.Widget.Container',
	/** @construct */
	initialize: function(/*$super, */parentOrElementOrDocument)
	{
		this._defContainerElem = null;
	  this.tryApplySuper('initialize', [parentOrElementOrDocument])  /* $super(parentOrElementOrDocument) */;
		this.reactShowStateChangeBind = this.reactShowStateChange.bind(this);
		this.addEventListener('showStateChange', this.reactShowStateChangeBind);
	},
	/** @private */
	finalize: function(/*$super*/)
	{
		this.removeEventListener('showStateChange', this.reactShowStateChangeBind);
		this.clearWidgets();
		this.tryApplySuper('finalize')  /* $super() */;
	},
	/** @private */
	initProperties: function()
	{
		this.defineChildDimensionRelatedProp('childWidth');
		this.defineChildDimensionRelatedProp('childHeight');
		this.defineChildDimensionRelatedProp('childMargin');

		this.defineProp('firstChild', {'dataType': 'Kekule.Widget.BaseWidget', 'serializable': false, 'setter': null, 'scope': Class.PropertyScope.PUBLIC});
		this.defineProp('lastChild', {'dataType': 'Kekule.Widget.BaseWidget', 'serializable': false, 'setter': null, 'scope': Class.PropertyScope.PUBLIC});
		this.defineProp('allowChildWrap', {'dataType': DataType.BOOL, 'serializable': false,
			'setter': function(value)
			{
				this.setPropStoreFieldValue('allowChildWrap', value);
				if (value)
					this.removeClassName(CNS.NOWRAP);
				else
				{
					this.addClassName(CNS.NOWRAP);
				}
			}
		});
	},
	/** @ignore */
	initPropValues: function(/*$super*/)
	{
		this.tryApplySuper('initPropValues')  /* $super() */;
		this.setAllowChildWrap(true);
	},

	/** @private */
	defineChildDimensionRelatedProp: function(propName, options)
	{
		var ops = Object.extend({
			'dataType': DataType.STRING,
			'setter': function(value)
			{
				this.setPropStoreFieldValue(propName, value);
				this.updateChildSizes();
			}
		}, options || {});
		return this.defineProp(propName, ops);
	},

	/** @ignore */
	doGetWidgetClassName: function()
	{
		return CNS.CONTAINER;
	},
	/** @ignore */
	doCreateRootElement: function(doc)
	{
		var result = doc.createElement('span');
		return result;
	},
	/* @ignore */
	/*
	doCreateSubElements: function($super, doc, docFragment)
	{
		var result = $super(doc, docFragment) || [];
		var containerElem = this.doCreateContainerElement(doc);
		this._defContainerElem = containerElem;
		result.push(containerElem);
		docFragment.appendChild(containerElem);
		return result;
	},
	*/
	/**
	 * Create a element to hold the child widgets.
	 * Note: Container itself does not use this method by default, the child elements are directly appended to the core element.
	 * Descendants may utilize it although.
	 * @param {HTMLDocument} doc
	 * @param {String} name Container name, used for <slot> if possible.
	 * @param {String} fallbackTagName If <slot> is not available in browser, this tag name will be used to create element.
	 * @returns {HTMLElement}
	 */
	doCreateContainerElement: function(doc, name, fallbackTagName)
	{
		var tagName = Kekule.BrowserFeature.htmlSlot? Kekule.Widget.HtmlTagNames.CHILD_HOLDER: (fallbackTagName || 'span');
		var result = doc.createElement(tagName);
		result.className = CNS.CHILD_HOLDER;
		//result.setAttribute('name', name || Kekule.Widget.HtmlNames.CHILD_HOLDER);
		return result;
	},
	/**
	 * Returns the parent HTML element to hold all child widgets.
	 * Descendants can override this method.
	 * @return {HTMLElement}
	 */
	getContainerElement: function()
	{
		return this.getElement();
		//return this._defContainerElem || this.getElement();
	},
	/** @ignore */
	getChildrenHolderElement: function()
	{
		return this.getContainerElement();
	},

	/**
	 * Append an widget to container/
	 * @param {Kekule.Widget.BaseWidget} widget
	 */
	appendWidget: function(widget)
	{
		/*
		this.getContainerElement().appendChild(widget.getElement());
		*/
		//this._insertChildWidget(widget, null);
		widget.setParent(this);
		return this;
	},
	/**
	 * Insert an widget before refWidget.
	 * @param {Kekule.Widget.BaseWidget} widget
	 * @param {Kekule.Widget.BaseWidget} refWidget
	 */
	insertWidgetBefore: function(widget, refWidget)
	{
		/*
	  var refElem = refWidget? refWidget.getElement(): null;
		if (refElem)
			this.getContainerElement().insertBefore(widget.getElement(), refElem);
		else
			this.getContainerElement().appendChild(widget.getElement());
		*/
		//this._insertChildWidget(widget, refWidget);
		/*
		widget.setParent(this);
		var refIndex = refWidget? this.getChildWidgets().indexOf(refWidget): -1;
		if (refIndex >= 0)
			this._moveChild(widget, refIndex);
		*/
		widget.insertToWidget(this, refWidget);
		return this;
	},

	/**
	 * Remove an widget from container and destroy it.
	 * @param {Kekule.Widget.BaseWidget} widget
	 * @param {Bool} doNotFinalize If set to true, the widget will not be finalized.
	 */
	removeWidget: function(widget, doNotFinalize)
	{
		widget.setParent(null);
		if (!doNotFinalize)
			widget.finalize();
	},

	/**
	 * Remove all children in container and destroy them.
	 * @param {Bool} doNotFinalize If set to true, the widget will not be finalized.
	 */
	clearWidgets: function(doNotFinalize)
	{
		var children = this.getChildWidgets();
		for (var i = children.length - 1; i >= 0; --i)
		{
			var child = children[i];
			this.removeWidget(child, doNotFinalize);
		}
	},

	/** @private */
	_insertChildWidget: function(widget, refWidget)
	{
		var refElem = refWidget? refWidget.getElement(): null;
		var containerElem = this.getChildrenHolderElement();
		if (containerElem)
		{
			if (refElem)
				containerElem.insertBefore(widget.getElement(), refElem);
			else
				containerElem.appendChild(widget.getElement());
		}
	},

	/** @private */
	reactShowStateChange: function(e)
	{
		//if (e.target !== this)  // invoked by child widget
		{
			this.childrenModified();
		}
	},

	/** @private */
	childrenModified: function(/*$super*/)
	{
		this.tryApplySuper('childrenModified')  /* $super() */;
		// change first / last child if essential
		var widgets = this.getChildWidgets();
		var length = widgets.length;

		var index = 0;
		var curr = widgets[index];
		while (curr && (!curr.isShown(true)) && (index < length)) // check show ignoring DOM status
		{
			++index;
			curr = widgets[index];
		}  // get first visible child
		var newFirst = (index < length)? curr: null;

		var index = length - 1;
		var curr = widgets[length - 1];
		while (curr && (!curr.isShown(true)) && (index >= 0)) // check show ignoring DOM status
		{
			--index;
			curr = widgets[index];
		}
		var newLast = (index >= 0)? curr: null;

		var oldFirst = this.getFirstChild();
		var oldLast = this.getLastChild();
		if (newFirst !== oldFirst)
		{
			if (oldFirst)
				oldFirst.removeClassName(CNS.FIRST_CHILD);
			if (newFirst)
				newFirst.addClassName(CNS.FIRST_CHILD);
			this.setPropStoreFieldValue('firstChild', newFirst);
		}
		if (newLast !== oldLast)
		{
			if (oldLast)
				oldLast.removeClassName(CNS.LAST_CHILD);
			if (newLast)
				newLast.addClassName(CNS.LAST_CHILD);
			this.setPropStoreFieldValue('lastChild', newLast);
		}
	},
	/** @private */
	childWidgetAdded: function(/*$super, */widget)
	{
		this.tryApplySuper('childWidgetAdded', [widget])  /* $super(widget) */;
		var w = this.getChildWidth();
		if (w)
			widget.setWidth(w);
		var h = this.getChildHeight();
		if (h)
			widget.setHeight(h);
		var margin = this.getChildMargin();
		if (margin)
			widget.getStyle().margin = margin;

		this._insertChildWidget(widget, null);
	},
	/** @private */
	childWidgetRemoved: function(/*$super, */widget)
	{
		this.tryApplySuper('childWidgetRemoved', [widget])  /* $super(widget) */;
		//this.getContainerElement().removeChild(widget.getElement());
		// do not need to remove here, this work has been done in _removeChild method of BaseWidget
	},
	/** @private */
	childWidgetMoved: function(/*$super, */widget, newIndex)
	{
		this.tryApplySuper('childWidgetMoved', [widget, newIndex])  /* $super(widget, newIndex) */;
		var elem = widget.getElement();
		var refWidget = this.getChildWidgets()[newIndex + 1];
		var refElem = refWidget? refWidget.getElement(): null;
		if (refElem)
			this.getContainerElement().insertBefore(elem, refElem);
		else
			this.getContainerElement().appendChild(elem);
	},

	/**
	 * Change child widgets size according to childWidth/childHeight settings.
	 * @private
	 */
	updateChildSizes: function()
	{
		var children = this.getChildWidgets();
		var w = this.getChildWidth() || '';
		var h = this.getChildHeight() || '';
		var margin = this.getChildMargin() || '';
		var layout = this.getLayout();
		//var marginValue = (layout === Kekule.Widget.Layout.VERTICAL)? margin + ' auto': 'auto ' + margin;
		{
			for (var i = 0, l = children.length; i < l; ++i)
			{
				var widget = children[i];
				widget.setWidth(w);
				widget.setHeight(h);
				widget.getStyle().margin = margin;
			}
		}
	}
});

/**
 * An plain panel to contain child widgets.
 * @class
 * @augments Kekule.Widget.Container
 *
 */
Kekule.Widget.Panel = Class.create(Kekule.Widget.Container,
/** @lends Kekule.Widget.Panel# */
{
	/** @private */
	CLASS_NAME: 'Kekule.Widget.Panel',
	/** @private */
	initProperties: function()
	{
		this.defineProp('caption', {'dataType': DataType.STRING,
			'getter': function() {
				var elem = this.getCaptionElem(false);
				return elem && DU.getElementText(this.getCaptionElem());
			},
			'setter': function(value)
			{
				DU.setElementText(this.getCaptionElem(true), value);
				SU.setDisplay(this.getCaptionElem(), !!value);
			}
		});
		this.defineProp('captionElem', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null,
			'getter': function(canCreate){
				var result = this.getPropStoreFieldValue('captionElem');
				if (!result && canCreate)
				{
					result = this.getDocument().createElement('div');
					result.className = CNS.PANEL_CAPTION;
					// insert at the head of root elem
					var rootElem = this.getElement();
					rootElem.insertBefore(result, DU.getFirstChildElem(rootElem));
					this.setPropStoreFieldValue('captionElem', result);
				}
				return result;
			}
		})
	},
	/** @private */
	initPropValues: function(/*$super*/)
	{
		this.tryApplySuper('initPropValues')  /* $super() */;
		this.setUseCornerDecoration(true);
	},
	/** @ignore */
	doGetWidgetClassName: function(/*$super*/)
	{
		return this.tryApplySuper('doGetWidgetClassName')  /* $super() */ + ' ' + CNS.PANEL;
	}
});

/**
 * An widget group, all child widgets inside it should be regarded as a whole.
 * e.g, button group, edit-button group and so on.
 * @class
 * @augments Kekule.Widget.Container
 *
 */
Kekule.Widget.WidgetGroup = Class.create(Kekule.Widget.Container,
/** @lends Kekule.Widget.WidgetGroup# */
{
	/** @private */
	CLASS_NAME: 'Kekule.Widget.WidgetGroup',
	/** @construct */
	initialize: function(/*$super, */parentOrElementOrDocument)
	{
		this.tryApplySuper('initialize', [parentOrElementOrDocument])  /* $super(parentOrElementOrDocument) */;
	},
	/** @private */
	initPropValues: function(/*$super*/)
	{
		this.tryApplySuper('initPropValues')  /* $super() */;
		this.setUseCornerDecoration(true);
	},

	/** @ignore */
	doObjectChange: function(/*$super, */modifiedPropNames)
	{
		this.tryApplySuper('doObjectChange', [modifiedPropNames])  /* $super(modifiedPropNames) */;
		if (modifiedPropNames.indexOf('useCornerDecoration') >= 0)
			this._updateChildStyles();
	},

	/** @ignore */
	childWidgetAdded: function(/*$super, */widget)
	{
		if (widget.setUseCornerDecoration)
		{
			widget.setUseCornerDecoration(false);
		}
		this.tryApplySuper('childWidgetAdded', [widget])  /* $super(widget) */;
	},
	/** @ignore */
	layoutChanged: function(/*$super*/)
	{
		this.tryApplySuper('layoutChanged')  /* $super() */;
		this._updateChildStyles();
	},
	/** @ignore */
	childrenModified: function(/*$super*/)
	{
		this.tryApplySuper('childrenModified')  /* $super() */;
		this._updateChildStyles();
	},

	/** @private */
	_updateChildStyles: function()
	{
		var WL = Kekule.Widget.Layout;
		var layout = this.getLayout();
		var first = this.getFirstChild();
		var last = this.getLastChild();
		var useCorner = /*true; //*/ this.getUseCornerDecoration();
		var children = this.getChildWidgets();
		/*
		 var allFirstRoundClasses = [CNS.CORNER_LEFT, CNS.CORNER_TOP];
		 var firstRoundClass = (layout === WL.VERTICAL)? CNS.CORNER_TOP: CNS.CORNER_LEFT;
		 var allLastRoundClasses = [CNS.CORNER_RIGHT, CNS.CORNER_BOTTOM];
		 var lastRoundClass = (layout === WL.VERTICAL)? CNS.CORNER_BOTTOM: CNS.CORNER_RIGHT;
		 */
		var allRoundClasses = [CNS.CORNER_LEADING, CNS.CORNER_TAILING];

		// TODO: Now has to iterate all children, too slow, need to change later.
		for (var i = 0, l = children.length; i < l; ++i)
		{
			var child = children[i];
			child.removeClassName(allRoundClasses);
			if (child === first)
			{
				if (useCorner)
					child.addClassName(CNS.CORNER_LEADING);
			}
			if (child === last)
			{
				if (useCorner)
					child.addClassName(CNS.CORNER_TAILING);
			}
		}
		//console.log('update child style', children.length, useCorner, first, last);
	}
});

/**
 * An general toolbar that can contain child widgets.
 * @class
 * @augments Kekule.Widget.WidgetGroup
 *
 * @property {Array} childDefs Array of hash definition of child widgets.
 *   In definition, a special field "internalName" can be set. After created, the
 *   child widget can be refered by {@link Kekule.Widget.Toolbar.getChildWidgetByInternalName} method.
 *   When this property is set, new child widgets will be created by it and all old child widgets will be destroyed.
 */
Kekule.Widget.Toolbar = Class.create(Kekule.Widget.WidgetGroup,
/** @lends Kekule.Widget.Toolbar# */
{
	/** @private */
	CLASS_NAME: 'Kekule.Widget.Toolbar',
	/** @ignore */
	finalize: function(/*$super*/)
	{
		var map = this.getChildWidgetInternalNameMap();
		if (map)
			map.finalize();
		this.tryApplySuper('finalize')  /* $super() */;
	},
	/** @private */
	initProperties: function()
	{
		this.defineProp('childDefs', {
			'dataType': DataType.ARRAY,
			'setter': function(value)
			{
				this.setPropStoreFieldValue('childDefs', value);
				this.recreateChildrenByDefs();
			}
		});
		// private
		this.defineProp('childWidgetInternalNameMap', {'dataType': DataType.OBJECT, 'serializable': false});
	},
	/** @ignore */
	doGetWidgetClassName: function(/*$super*/)
	{
		return this.tryApplySuper('doGetWidgetClassName')  /* $super() */ + ' ' + CNS.TOOLBAR;
	},
	/** @private */
	doSetShowText: function(/*$super, */value)
	{
		this.tryApplySuper('doSetShowText', [value])  /* $super(value) */;
		this._updateAllChildTextGlyphStyles();
	},
	doSetShowGlyph: function(/*$super, */value)
	{
		this.tryApplySuper('doSetShowGlyph', [value])  /* $super(value) */;
		this._updateAllChildTextGlyphStyles();
	},

	/** @private */
	childWidgetAdded: function(/*$super, */widget)
	{
		this.tryApplySuper('childWidgetAdded', [widget])  /* $super(widget) */;
		this._updateChildTextGlyphStyles(widget);
	},

	/** @private */
	_updateChildTextGlyphStyles: function(widget)
	{
		if (widget.setShowText)
			widget.setShowText(this.getShowText());
		if (widget.setShowGlyph)
			widget.setShowGlyph(this.getShowGlyph());
	},
	/** @private */
	_updateAllChildTextGlyphStyles: function()
	{
		var children = this.getChildWidgets();
		for (var i = children.length - 1; i >= 0; --i)
		{
			this._updateChildTextGlyphStyles(children[i]);
		}
	},

	/** @private */
	recreateChildrenByDefs: function()
	{
		var defs = this.getChildDefs() || [];
		// remove old children first
		this.clearWidgets();
		var internalNameMap = new Kekule.MapEx(true);
		this.setChildWidgetInternalNameMap(internalNameMap);
		// add new ones
		var defWidgetClassName = this.getDefaultChildWidgetClassName();
		for (var i = 0, l = defs.length; i < l; ++i)
		{
			var def = defs[i];
			if (!def.widget && !def.widgetClass && defWidgetClassName)  // class not set, try to use default one
			{
				def = Object.extend({'widget': defWidgetClassName}, def);
			}
			var w = Kekule.Widget.createFromHash(this, def);
			if (w)
			{
				w.appendToWidget(this);
				if (def.internalName)
				{
					internalNameMap.set(def.internalName, w);
				}
			}
		}
	},
	/**
	 * Returns default class name of child widget.
	 * This method is used in create child widgets by hash definition.
	 * Descendants may override this method.
	 * @returns {String}
	 */
	getDefaultChildWidgetClassName: function()
	{
		return null;
	},

	/**
	 * Returns child widget defined by internalName.
	 * @param {String} name
	 * @returns {Kekule.Widget.BaseWidget}
	 */
	getChildWidgetByInternalName: function(name)
	{
		var map = this.getChildWidgetInternalNameMap();
		return map? map.get(name): null;
	}
});

})();


text:
<!--

Thank you for contributing to the Firebase community!

Have a usage question?
=======================
We get lots of those and we love helping you, but GitHub is not the best place for them and they
will be closed. Here are some resources to get help:

- Start with the documentation: https://github.com/firebase/geofire-js/blob/master/README.md
- Read the full API reference: https://github.com/firebase/geofire-js/blob/master/docs/reference.md
- Try out some examples: https://github.com/firebase/geofire-js/blob/master/examples/README.md

If the official documentation doesn't help, try asking through our official support channels:

https://firebase.google.com/support/

*Please avoid double posting across multiple channels!*

Think you found a bug?
=======================
Yeah, we're definitely not perfect! Please use the bug report template below and include a minimal
repro when opening the issue.

Have a feature request?
========================
Great, we love hearing how we can improve our products! Just remove the template below and
provide an explanation of your feature request. Provide code samples if applicable. Try to
think about what it will allow you to do that you can't do today? How will it make current
workarounds straightforward? What potential bugs and edge cases does it help to avoid?

-->

### Version info

<!-- What versions of the following libraries are you using? Note that your issue may already
be fixed in the latest versions. -->

**Firebase:**

**GeoFire:**

**Other (e.g. Node, browser, operating system) (if applicable):**

### Test case

<!-- Provide a minimal, complete, and verifiable example (http://stackoverflow.com/help/mcve)
using either Plunker (http://plnkr.co/) or JSFiddle (https://jsfiddle.net/). -->

### Steps to reproduce

<!-- Provide the steps needed to reproduce the issue given the above test case. -->

### Expected behavior

<!-- What is the expected behavior? -->

### Actual behavior

<!-- What is the actual behavior? -->


text:
import * as fs from 'fs';
import * as glob from 'glob';
import * as i18n from 'i18n';
import { Container } from "inversify";
import * as osLocale from 'os-locale';
import * as path from 'path';
import 'reflect-metadata';
import { IMapperService, MapperService } from 'simple-mapper';
import { CommandFactory, ICommandValidator, INewCmdArgs, INewCmdOpts, InfoCommand, ListCommand, NewCommand, NewCommandValidator, SetDirCommand } from '../commands';
import { ICommand, ICommandFactory, IInfoCmdArgs, IInfoCmdOpts } from "../commands/i";
import { ITemplateInfo } from "../commands/info/i/i-template-info";
import { InfoCommandValidator } from "../commands/info/info-command-validator";
import { TemplateInfo } from "../commands/info/template-info";
import { ListCommandValidator } from "../commands/list/list-command-validator";
import { ErrorReporter } from '../error-reporter';
import { FilePatterns } from '../file-patterns';
import { HandlerService } from '../handler-service';
import * as i from '../i';
import { BrowserInputManager, ClientFactory, CustomInputManager, DefaultsInputManager, Duplexer, IClientFactory, IDuplexer, IServerFactory, IWebSocketFactory, InputManager, PromptInputManager, ServerFactory, WebSocketFactory } from '../input-managers';
import * as m from '../models';
import { ITemplateManager, TemplateManager, ITemplatePreprocessor } from "../template-management";
import { FSTreeProcessor, RealTreeDiscoveryHandler, SimulatedTreeDiscoveryHandler } from "../template-runner";
import { IFSTreeProcessor, ITreeDiscoveryEventHandler } from "../template-runner/i";
import { TemplateRunner } from '../template-runner/template-runner';
import { TemplateValidator } from '../template-validator';
import { PathTransformManager, ContentTransformManager } from '../transformers';
import * as it from '../transformers/i';
import { UserMessager } from '../user-messager';
import { GlobFactory } from "../util/glob-factory";
import { IGlobFactory } from "../util/i-glob-factory";
import { Kernel, SettingsProvider } from "./entities";
import TYPES from "./types";
import { IDefaultsAnswerer } from '../input-managers/defaults/i-defaults-answerer';
import { DefaultsAnswerer } from '../input-managers/defaults/defaults-answerer';
import { IPluginManager } from '../plugin-manager/i-plugin-manager';
import { PluginManager } from '../plugin-manager/plugin-manager';
import { TemplatePreprocessor } from '../template-management/template-preprocessor';
import { ISearchHandlerFactory } from '../template-management/i-search-handler-factory';
import { SearchHandlerFactory } from '../template-management/search-handler-factory';
import { ISimpleTransformer, ToLocaleLowerCaseTransform, ToLocaleUpperCaseTransform, ToUpperCaseTransform, ToLowerCaseTransform } from '../input-managers/transforms/lib';
import { IBuiltinTransforms } from '../input-managers/transforms/i-builtin-transforms';
import { BuiltinTransforms } from '../input-managers/transforms/buildin-transforms';
import { IRegexer } from '../util/i-regexer';
import { Regexer } from '../util/regexer';
import { ITemplatePathUtil } from '../template-management/i-template-path-util';
import { TemplatePathUtil } from '../template-management/template-path-util';

export const containerBuilder = (packageJson: any = null, localesPath?: string): Container => {
    let json = packageJson || require(path.join(path.dirname(__filename), "../../package.json"));

    var container = new Container();
    container.bind<i.IKernel>(TYPES.Kernel).to(Kernel);
    container.bind<i.ITemplateRunner>(TYPES.TemplateRunner).to(TemplateRunner);
    container.bind<NodeJS.Process>(TYPES.Process).toDynamicValue(() => process);
    container.bind<i.IPackage>(TYPES.PackageJson).toConstantValue(json);
    container.bind<i.ISettingsProvider>(TYPES.SettingsProvider).to(SettingsProvider);
    container.bind<i.IHandlerService>(TYPES.HandlerService).to(HandlerService);
    container.bind<i.IUserMessager>(TYPES.UserMessager).to(UserMessager);
    container.bind<ITemplateManager>(TYPES.TemplateManager).to(TemplateManager);
    container.bind<it.ITransformManager>(TYPES.TransformManager).to(ContentTransformManager);
    container.bind<it.IPathTransformManager>(TYPES.PathTransformManager).to(PathTransformManager);
    container.bind<i.ITemplateValidator>(TYPES.TemplateValidator).to(TemplateValidator);
    container.bind<i.IFilePatterns>(TYPES.FilePatterns).to(FilePatterns);
    container.bind<i.IInputManager>(TYPES.InputManager).to(InputManager);
    container.bind<i.IInputManager>(TYPES.BrowserInputManager).to(BrowserInputManager);
    container.bind<i.IInputManager>(TYPES.CustomInputManager).to(CustomInputManager);
    container.bind<i.IInputManager>(TYPES.PromptInputManager).to(PromptInputManager);
    container.bind<i.IInputManager>(TYPES.DefaultsInputManager).to(DefaultsInputManager);
    container.bind<IDefaultsAnswerer>(TYPES.DefaultsAnswerer).to(DefaultsAnswerer);
    container.bind<IMapperService>(TYPES.Mapper).toDynamicValue(() => new MapperService());
    container.bind<i.IErrorReporter>(TYPES.ErrorReporter).to(ErrorReporter);
    container.bind<ITemplateInfo>(TYPES.TemplateInfo).to(TemplateInfo);
    container.bind(TYPES.SettingsType).toDynamicValue(() => m.Settings);
    container.bind<IFSTreeProcessor>(TYPES.FSTreeProcessor).to(FSTreeProcessor);
    container.bind<ITreeDiscoveryEventHandler>(TYPES.RealTreeDiscoveryHandler).to(RealTreeDiscoveryHandler);
    container.bind<ITreeDiscoveryEventHandler>(TYPES.SimulatedTreeDiscoveryHandler).to(SimulatedTreeDiscoveryHandler);
    container.bind<IDuplexer>(TYPES.BrowserClientDuplexer).to(Duplexer);
    container.bind<IServerFactory>(TYPES.BIMServerFactory).to(ServerFactory);
    container.bind<IClientFactory>(TYPES.BIMClientFactory).to(ClientFactory);
    container.bind<IWebSocketFactory>(TYPES.BIMWebSocketFactory).to(WebSocketFactory);
    container.bind<IPluginManager>(TYPES.PluginManager).to(PluginManager);
    container.bind<ITemplatePreprocessor>(TYPES.TemplatePreprocessor).to(TemplatePreprocessor);
    container.bind<ISearchHandlerFactory>(TYPES.SearchHandlerFactory).to(SearchHandlerFactory);
    container.bind<ITemplatePathUtil>(TYPES.TemplatePathUtil).to(TemplatePathUtil);

    container.bind<ISimpleTransformer>(TYPES.SimpleTransformer).to(ToLocaleLowerCaseTransform);
    container.bind<ISimpleTransformer>(TYPES.SimpleTransformer).to(ToLocaleUpperCaseTransform);
    container.bind<ISimpleTransformer>(TYPES.SimpleTransformer).to(ToUpperCaseTransform);
    container.bind<ISimpleTransformer>(TYPES.SimpleTransformer).to(ToLowerCaseTransform);

    container.bind<IBuiltinTransforms>(TYPES.BuiltinTransforms).to(BuiltinTransforms);
    container.bind<IRegexer>(TYPES.Regexer).to(Regexer);

    let lobj = <typeof i18n>{};
    i18n.configure({
        defaultLocale: 'en_US',
        directory: localesPath || path.join(__dirname, '..', "/locales"),
        register: lobj
    });
    let lang = osLocale.sync();
    i18n.setLocale(lang);
    container.bind<i.Ii18nFunction>(TYPES.i18n).toConstantValue(lobj.__mf);

    container.bind<ICommand<any, any>>(TYPES.Commands).to(SetDirCommand);
    container.bind<ICommand<any, any>>(TYPES.Commands).to(NewCommand);
    container.bind<ICommand<any, any>>(TYPES.Commands).to(ListCommand);
    container.bind<ICommand<any, any>>(TYPES.Commands).to(InfoCommand);
    container.bind<ICommandFactory>(TYPES.CommandFactory).to(CommandFactory);

    container.bind<ICommandValidator<INewCmdOpts, INewCmdArgs>>(TYPES.NewCommandValidator).to(NewCommandValidator);
    container.bind<ICommandValidator<IInfoCmdOpts, IInfoCmdArgs>>(TYPES.InfoCommandValidator).to(InfoCommandValidator);
    container.bind<ICommandValidator<any, any>>(TYPES.ListCommandValidator).to(ListCommandValidator);

    container.bind<i.IPath>(TYPES.Path).toConstantValue(path);
    container.bind<i.IFileSystem>(TYPES.FS).toConstantValue(fs);
    container.bind<IGlobFactory>(TYPES.GlobFactory).to(GlobFactory);
    return container;
};


text:
@interface MOViewController () <MOSliderMenuDelegate>

@property (nonatomic,weak) IBOutlet UILabel *infoLabel;

@end

@implementation MOViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    [self setupMenu];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupMenu
{
    NSArray *items = @[[[MOSliderMenuItem alloc] initWithText:@"ONE"],
                       [[MOSliderMenuItem alloc] initWithText:@"TWO"],
                       [[MOSliderMenuItem alloc] initWithText:@"THREE"],
                       [[MOSliderMenuItem alloc] initWithText:@"FOUR"],
                       [[MOSliderMenuItem alloc] initWithText:@"FIVE"]];

    MOSliderMenu *menu = [[MOSliderMenu alloc] initWithFrame:self.view.frame
                                                   menuItems:items
                                                 andDelegate:self];
    menu.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    [self.view addSubview:menu];
}

- (void)sliderMenu:(MOSliderMenu *)menu didSelectItemIndex:(NSInteger)index
{
    self.infoLabel.text = [NSString stringWithFormat:@"%@ : %.f", menu.selectedItem.text,menu.selectedItem.currentValue];
}

- (void)sliderMenuChangingSelectedItemValue:(MOSliderMenu *)menu
{
    self.infoLabel.text = [NSString stringWithFormat:@"%@ : %.f", menu.selectedItem.text,menu.selectedItem.currentValue];
}

@end


text:
'use strict';

var gulp = require('gulp'),
    rimraf = require('rimraf'),
    runSequence = require('run-sequence'),
    rename = require('gulp-rename'),
    diff = require('gulp-diff'),
    injectSelf = require('./index.js');

var srcDir = 'tests/input',
    dstDir = 'tests/actual',
    expectedDir = 'tests/expected';

gulp.task('clean', function(cb){
    rimraf(dstDir, cb);
});

gulp.task('test-1', function(){
    return gulp.src(srcDir + '/simple-stream.txt')
        .pipe(injectSelf(srcDir + '/dest.txt', /insert here/))
        .pipe(rename('dest1.txt'))
        .pipe(gulp.dest(dstDir));
});

gulp.task('test-2', function(){
    return gulp.src(srcDir + '/simple-stream.txt')
        .pipe(injectSelf(srcDir + '/dest.txt', /insert here/, {
            replaceWith: function(fileContent){
                return '$&\n' + fileContent;
            }
        }))
        .pipe(rename('dest2.txt'))
        .pipe(gulp.dest(dstDir));
});

gulp.task('test-3', function(){
    return gulp.src(srcDir + '/three-line-stream.txt')
        .pipe(injectSelf(srcDir + '/dest.txt', /insert here/, {
            replaceWith: function(fileContent){
                return '\n\n' + fileContent + '\n\n';
            }
        }))
        .pipe(rename('dest3.txt'))
        .pipe(gulp.dest(dstDir));
});

gulp.task('check-results', function(){
    return gulp.src(dstDir + '/*.**')
        .pipe(diff(expectedDir))
        .pipe(diff.reporter({ fail: true }));
});

gulp.task('default', function(cb){
    runSequence('clean', 'test-1', 'test-2', 'test-3', 'check-results', cb);
});


text:
package de.fu_berlin.agdb.importer.dwd.core;

import org.apache.commons.net.ftp.FTPFile;

public interface IFTPFileWorkerProvider {
	public FTPFile getFTPFileToWorkWith();
}


text:
{-# language NamedFieldPuns #-}
{-# language DataKinds #-}
{-# language OverloadedStrings #-}
{-# language ViewPatterns #-}

module Gueb (
        noJobs
    ,   makeHandlers
    ) where

import Data.Text
import Data.Map as Map
import Data.Aeson
import Data.Functor
import Data.Bifunctor (first)
import Data.Time
import Control.Lens
import Control.Exception
import Control.Monad
import Control.Comonad
import Control.Comonad.Cofree (coiter,unwrap)
import Control.Concurrent.MVar
import Control.Concurrent.Async
import Control.Monad.Trans.Except
import Control.Monad.IO.Class

import Servant

import Gueb.Types
import Gueb.Types.API

import System.Process.Streaming

noJobs :: Jobs () ()
noJobs = Jobs mempty

makeHandlers :: Plan -> IO (Server JobsAPI)
makeHandlers plan = do
    let theJobs  = Jobs (fmap (Executions () mempty) plan)
        idstream = Data.Text.pack . show <$> coiter (Identity . succ) (0::Int)
    tvar <- newMVar (idstream,theJobs)
    pure (makeHandlersFromRef tvar)

-- http://haskell-servant.readthedocs.org/en/tutorial/tutorial/Server.html
makeHandlersFromRef :: MVar (Unending ExecutionId,Jobs () (Async ())) -> Server JobsAPI
makeHandlersFromRef ref =
         (query id)
    :<|> (\jobid        -> query (jobs . ix jobid))
    :<|> (\jobid        -> command (startExecution jobid))
    :<|> (\jobid execid -> query (jobs . ix jobid . executions . ix execid))
    :<|> (\jobid execid -> command (cancelExecution jobid execid))
    where
    query somelens = do root <- void . addUri . extract <$> liftIO (readMVar ref)
                        Page <$> noteT err404
                                       (preview somelens root)
    command handler = do oldState <- liftIO (takeMVar ref)
                         catchE (do (newState,result) <- handler oldState deferrer
                                    liftIO (do putMVar ref newState
                                               return (Page <$> result)))
                                (\e -> do liftIO (putMVar ref oldState)
                                          throwE e)
    deferrer action post =
        async (do (do _ <- action
                      change <- post
                      notify change)
                      `onException` (do change <- post
                                        notify change))
    notify change = modifyMVar_ ref (\s -> evaluate (change s))

noteT :: Monad m => e -> Maybe a -> ExceptT e m a
noteT e = maybe (throwE e) pure
reason :: ServantErr -> Text -> ServantErr
reason err msg = err { errBody = jsonError msg }
    where
        jsonError = encode . Map.singleton ("result"::Text)

startExecution :: JobId
               -> GlobalState
               -> (IO () -> IO (GlobalState -> GlobalState) -> IO (Async ()))
               -> ExceptT ServantErr IO (GlobalState, Headers '[Header "Location" String] Created)
startExecution jobId (advance -> (executionId,root)) deferrer = do
    let Traversal runningJobs = Traversal (_2 . jobs . traversed . executions . traversed . currentState . _Right)
        Traversal ixJob       = Traversal (_2 . jobs . ix jobId)
        Traversal atExecution = Traversal (ixJob . executions . at executionId)
    unless (not (has runningJobs root))
           (throwE (err409 `reason` "Job already running"))
    Job {scriptPath} <- noteT (err404 `reason` "Job not found")
                              (preview (ixJob . executable) root)
    launched <- liftIO (launch scriptPath atExecution)
    return (set atExecution (Just launched) root
           ,let linkUri = mkExecutionUri jobId executionId
            in  addHeader linkUri (Created linkUri))
    where
        launch scriptPath atExecution = do
            pid <- deferrer (execute (piped (proc scriptPath [])) (pure ()))
                            (do t <- getCurrentTime
                                pure (set (atExecution . _Just . currentState) (Left t)))
            t <- getCurrentTime
            pure (Execution {executionView = (), startTime=t, _currentState=Right pid})

cancelExecution :: JobId
                -> ExecutionId
                -> GlobalState
                -> (IO () -> IO (GlobalState -> GlobalState) -> IO (Async ()))
                -> ExceptT ServantErr IO (GlobalState, Headers '[] Deleted)
cancelExecution jobId executionId root _ = do
    let Traversal ixJob            = Traversal (_2 . jobs . ix jobId)
        Traversal atExecutionState = Traversal (ixJob . executions . ix executionId . currentState . _Right)
    liftIO (forMOf_ atExecutionState root (async . cancel))
    let root' = set (ixJob . executions . at executionId) Nothing root
    return (root', Headers Deleted HNil)

{-| World's most obscure i++

-}
advance :: GlobalState -> (ExecutionId,GlobalState)
advance = first extract . duplicate . first (runIdentity . unwrap)

addUri :: Jobs () a -> Jobs Links a
addUri (Jobs j) = Jobs (iover itraversed addUriExecutions j)
    where
    addUriExecutions i xs =
        let topURI = pack ('/' : show (safeLink jobsAPI (Proxy::Proxy JobsEndpoint)))
            jobURI = pack ('/' : show (safeLink jobsAPI (Proxy::Proxy JobEndpoint) i))
        in  xs { executionsView = Links topURI jobURI,
                 _executions = iover itraversed (addUriExecution jobURI i) (_executions xs)}
    addUriExecution upwards i i' x =
        x { executionView = Links upwards (pack (mkExecutionUri i i')) }

mkExecutionUri :: Text -> Text -> String
mkExecutionUri i i' = '/': show (safeLink jobsAPI (Proxy::Proxy ExecutionEndpoint) i i')