text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#80000000"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/visualLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="30dp"
        android:background="@drawable/easy_dialog_bg_drawable"
        android:elevation="16dp"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp">

        <LinearLayout
            android:id="@+id/titleLayout"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_marginTop="6dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iconIV"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_gravity="center_vertical"
                android:layout_marginRight="15dp"
                android:scaleType="fitXY"
                android:src="@drawable/upgrade_ic"
                android:visibility="gone"
                tools:visibility="visible" />

            <TextView
                android:id="@+id/titleTV"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:maxLines="1"
                android:text="@string/dialog_title_default"
                android:textColor="@color/colorPrimary"
                android:textSize="20sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/contentLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="60dp"
            android:orientation="vertical">

            <ScrollView
                android:id="@+id/scrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:overScrollMode="ifContentScrolls">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/messageTV"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="8dp"
                        android:textColor="#ff313131"
                        android:textSize="16sp"
                        android:visibility="visible"
                        tools:text="测试多行文本\n测试多行文本\n测试多行文本"
                        tools:visibility="gone" />

                    <LinearLayout
                        android:id="@+id/progressLayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:visibility="gone"
                        tools:visibility="visible">

                        <TextView
                            android:id="@+id/percentLabelTV"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginBottom="5dp"
                            android:gravity="right"
                            android:textColor="@color/textColorPrimary"
                            android:textSize="12sp"
                            tools:text="54%" />

                        <ProgressBar
                            android:id="@+id/progressBar"
                            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
                            android:layout_width="match_parent"
                            android:layout_height="3dp"
                            android:progressDrawable="@drawable/progress_drawable"
                            tools:max="100"
                            tools:progress="100"
                            tools:secondaryProgress="45"
                            tools:visibility="visible" />

                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <TextView
                                android:id="@+id/sizeLabelTV"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_marginTop="8dp"
                                android:textColor="@color/textColorPrimary"
                                android:textSize="12sp"
                                tools:text="10.21MB / 22.3MB " />

                            <TextView
                                android:id="@+id/speedLabelTV"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_alignParentRight="true"
                                android:layout_marginTop="8dp"
                                android:textColor="@color/textColorPrimary"
                                android:textSize="12sp"
                                tools:text="1.02 MB/s" />
                        </RelativeLayout>
                    </LinearLayout>
                </RelativeLayout>
            </ScrollView>
        </LinearLayout>

        <FrameLayout
            android:id="@+id/customPanel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:visibility="gone"
            tools:visibility="gone">

            <FrameLayout
                android:id="@+id/customLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="5dip"
                android:paddingTop="5dip" />
        </FrameLayout>

        <RelativeLayout
            android:id="@+id/buttonLayout"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            tools:visibility="visible">

            <TextView
                android:id="@+id/mButtonPositive"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:background="@drawable/easy_dialog_btn_drawable"
                android:gravity="center"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:singleLine="true"
                android:text="@string/dialog_btn_label_upgrade"
                android:textColor="@color/dialogBtnColor"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/mButtonNegative"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_centerVertical="true"
                android:layout_marginRight="6dp"
                android:layout_toLeftOf="@id/mButtonPositive"
                android:background="@drawable/easy_dialog_btn_drawable"
                android:gravity="center"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:singleLine="true"
                android:text="@string/dialog_btn_label_cancel"
                android:textColor="@color/dialogBtnColor"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/mButtonNeutral"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_centerVertical="true"
                android:background="@drawable/easy_dialog_btn_drawable"
                android:gravity="center"
                android:paddingLeft="8dp"
                android:paddingRight="8dp"
                android:singleLine="true"
                android:textColor="@color/dialogBtnColor"
                android:textSize="16sp"
                android:visibility="gone"
                tools:text="@string/dialog_btn_label_talk_later" />
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>


text:
#region Copyright
// Copyright 2017 Gigya Inc.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Gigya.Microdot.Configuration;
using Gigya.Microdot.Interfaces.Configuration;

namespace Gigya.Microdot.Fakes
{
   public class ManualConfigurationEvents : IConfigurationDataWatcher
    {
        private readonly IConfigEventFactory _eventFactory;
        private readonly BroadcastBlock<bool> block = new BroadcastBlock<bool>(null);

        public ManualConfigurationEvents(IConfigEventFactory eventFactory)
        {
            _eventFactory = eventFactory;
        }

        public void RaiseChangeEvent()
        {
            block.Post(true);
            // Task.Delay(100).Wait();
        }

        public Task<T> ApplyChanges<T>(TimeSpan? timeout=null) where T : IConfigObject
        {
            timeout = timeout ?? TimeSpan.FromSeconds(5);

            var cancel = new CancellationTokenSource(timeout.Value);

            TaskCompletionSource<T> waitForConfigChange = new TaskCompletionSource<T>();
            cancel.Token.Register(
                () => waitForConfigChange.TrySetException(
                    new Exception(
                        $"Expected config to change in time, Timeout after {timeout.Value.TotalMilliseconds} ms")));
            waitForConfigChange.Task.ContinueWith(x => cancel.Dispose(), TaskContinuationOptions.OnlyOnRanToCompletion);

            var configEvent = _eventFactory.GetChangeEvent<T>();
            configEvent.LinkTo(new ActionBlock<T>(x =>
            {

                waitForConfigChange.TrySetResult(x);
            }));
            RaiseChangeEvent();

            return waitForConfigChange.Task;
        }

        public ISourceBlock<bool> DataChanges => block;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from distutils.core import setup
setup(name='maestro',
    version='0.1',
    description='Orchestration tools for multi-container docker environments',
    author='Kimbro Staken',
    author_email='kstaken@kstaken.com',
    url='https://github.com/toscanini/maestro',
    packages=['maestro'],
    scripts=['bin/maestro']
)


text:
(function(ko) {

	// Check if an object is an observable array
	ko.utils.isObservableArray = function(obj) {
		return ko.isObservable(obj) && obj.destroyAll !== undefined;
	},

    ko.utils.dispose = function(obj) {
        if(obj != null) {
            if(ko.isObservable(obj)) {
                if(ko.isComputed(obj)) {
                    obj.dispose()
                }
                ko.utils.dispose(obj())
            } else if($.isArray(obj)) {
                for(var i = 0, length = obj.length; i < length; i++) {
                    ko.utils.dispose(obj[i])
                }
                obj.length = 0
            } else if(typeof(obj) == 'object') {
                if(typeof(obj.dispose) == 'function') {
                    obj.dispose()
                }
            }
        }
    },

	ko.observableArray.fn.filterByProperty = function(propName, matchValue) {
    	var allItems, matchingItems;
    	allItems = this();
    	matchingItems = ko.observableArray([]);
        for (var i = 0; i < allItems.length; i++) {
            var current = allItems[i];
            if (ko.utils.unwrapObservable(current[propName]) === matchValue)
                matchingItems.push(current);
        }
        return matchingItems;
	};

    var subscribeOnce = function(observable, callback, context, eventName?) {
        var subscription = observable.subscribe(function(v) {
            callback.call(context || this, v);
            subscription.dispose();
        }, observable, eventName);
        return subscription;
    };

    ko.observable.fn.subscribeOnce = function(callback, context) {
        return subscribeOnce(this, callback, context);
    };

    ko.observable.fn.immediateSubscribe = ko.computed.fn.immediateSubscribe = function(callback, context, eventName) {
        var subscription = this.subscribe(callback, context || this, eventName);
        callback.call(context || this, this());
        return subscription;
    };

    ko.observable.fn.makeTrueIfNot = function(observable, ope) {
    	this.dependsOn(observable, function(b) { return !b; }, ope);
    };

    ko.observable.fn.dependsOn = function(observable, fn, ope) {

    	if(!this.__dependencies) {
	    	this.__dependencies = {
	    		_computed: null,
	    		all: ko.observableArray([])
	    	};

	    	this.__dependencies._computed = ko.computed(function() {
	    		var dependenciesArray = this.__dependencies.all();
	    		var r = null;
	    		for(var i = 0, len = dependenciesArray.length; i < len; i++) {
	    			var dependencyObservable = dependenciesArray[i];
	    			var rt = dependencyObservable.fn(dependencyObservable.obs());
                    if(r == null) {
                        r = rt;
                    } else {
    	    			if(dependencyObservable.ope == 0) {
    	    				r = r || rt;
    	    			} else {
    	    				r = r && rt;
    	    			}
                    }
	    		}
	    		return r;
	    	}, this);

	    	this.__dependencies._computed.subscribe(function(b) {
	    		if(isset(b)) {
	    			this(b);
	    		}
	    	}, this);

    	}

    	if(typeof(fn) != 'function') {
    		fn = function(v) { return v; };
    	}

    	this.__dependencies.all.push({
    		obs: observable,
    		fn :fn,
    		ope: ope || 0
    	});

        return;
    };

})(ko);


text:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by maxmya on 10/10/16.
 */
public class Demo {
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;
    private JButton button6;
    private JButton button7;
    private JButton button8;
    private JButton button9;
    private JButton button10;
    private JPanel mainPanel;

    Demo() {

        button4.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hoa");
            }
        });
    }

    public static void main(String[] args) {

        JFrame myAppFrame = new JFrame("Myapp");
        myAppFrame.setContentPane(new Demo().mainPanel);
        myAppFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myAppFrame.setSize(600, 600);
        myAppFrame.setVisible(true);

    }

}


text:
layout: post
status: publish
published: true
categories: blog
share: true
date: 2016-01-05 14:23:34 +1100
modified: 2016-01-07 08:44:52 +1100
title:  "Serve Jekyll Websites with servr and knitr"
comments: true
tags: [test, code, Rstudio]
---
# Writing in Rstudio
This blog post has been written in Rstudio and using the `rmd2md` function. When this is run it will convert any file (with the `*.rmd` extention) that is found within the `_rmd` folder to markdown that can be parsed by Jekyll and served on github pages. This is then moved to the `_posts` folder

be sure to include the header between three dashes:

{% highlight r %}
#layout: post
#status: process
#published: false
#date: 2016-01-05 14:23:34 +1100
#title:  "The Post Title"
#categories: blogs
{% endhighlight %}

The workflow is as follows:

1. Write a post with the above header, and put it in the `_rmd` folder.
2. Run the [rmd2md()](https://github.com/AndySouth/andysouth.github.io/blob/master/rmd2md.r) command within *Rstudio* which converts and copies the post to the `_posts` folder.
3. Run `servr::jekyll(command="bundle exec jekyll build",serve=FALSE)` from the [servr](https://github.com/yihui/servr) package in *Rstudio* to check that the site builds `serve=TRUE` allows you to view it locally.
4. Use the `git` version control system within *Rstudio* to add staged files, commit changes and push to the repository on [github](http://www.github.com).
5. Wait a few minutes for the site to build remotely (time varies) and navigate to page to check post has rendered correctly.

# Testing code chunks take 2
Here I will test the code display and see if I can generate a figure and place it on the page---it is mainly for my own reference.

{% highlight r %}
require(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
                 y = rnorm(30))
# Compute sample mean and standard deviation in each group
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))

ggplot() +
  geom_point(data = df, aes(x = gp, y = y)) +
  geom_point(data = ds, aes(x = gp, y = mean),
             colour = 'red', size = 3) +
  geom_errorbar(data = ds, aes(x = gp, y = mean,
                               ymin = mean - sd, ymax = mean + sd),
                colour = 'red', width = 0.4)
{% endhighlight %}

![plot of chunk unnamed-chunk-2](/figures/unnamed-chunk-2-1.png)

{% highlight r %}
ggsave(filename = "figures/Rplot.png")
{% endhighlight %}
Lets see if this works?


text:
module ApiV3
  module Plugin
    class CapabilitiesRepresenter < BaseRepresenter
      alias_method :capabilities, :represented

      property :can_search
      property :supported_auth_type
      property :can_authorize

    end
  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model vendor\vova07\qrcode\models\QrcodeBatchSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'description') ?>

    <?= $form->field($model, 'formats_id') ?>

    <?= $form->field($model, 'base_url') ?>

    <?php // echo $form->field($model, 'redirect_url') ?>

    <?php // echo $form->field($model, 'start_time') ?>

    <?php // echo $form->field($model, 'end_time') ?>

    <?php // echo $form->field($model, 'status_id') ?>

    <?php // echo $form->field($model, 'deleted') ?>

    <?php // echo $form->field($model, 'memo') ?>

    <?php // echo $form->field($model, 'author_id') ?>

    <?php // echo $form->field($model, 'created_at') ?>

    <?php // echo $form->field($model, 'updated_at') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

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


text:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <list>
#include <vector>
#include <map>
#include <exception>
#include <stdexcept>

#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <pwd.h>
#include <pthread.h>

#include "shared.h"

#include "nprd_types.h"
#include "nprd_configuration.h"
#include "nprd_monitor.h"
#include "nprd_pluginmessage.h"
#include "nprd_pluginconn.h"
#include "nprd_datapathmessage.h"
#include "nprd_datapathconn.h"
#include "nprd_plugincontrol.h"
#include "nprd_ipv4.h"
#include "nprd_arp.h"
#include "nprd_globals.h"
#include "nprd_requests.h"

using namespace npr;

PluginControl::PluginControl() throw()
{
  pthread_mutex_init(&plugin0_control_lock, NULL);
  pthread_mutex_init(&plugin1_control_lock, NULL);
  pthread_mutex_init(&plugin2_control_lock, NULL);
  pthread_mutex_init(&plugin3_control_lock, NULL);
  pthread_mutex_init(&plugin4_control_lock, NULL);

  plugin0_msg = NULL;
  plugin1_msg = NULL;
  plugin2_msg = NULL;
  plugin3_msg = NULL;
  plugin4_msg = NULL;

  plugin_debug_log = NULL;
}

PluginControl::~PluginControl() throw()
{
  pthread_mutex_destroy(&plugin0_control_lock);
  pthread_mutex_destroy(&plugin1_control_lock);
  pthread_mutex_destroy(&plugin2_control_lock);
  pthread_mutex_destroy(&plugin3_control_lock);
  pthread_mutex_destroy(&plugin4_control_lock);
}

// take the message from the rli and give it to the plugin. store the rli message
// in the correct local msg (one per plugin) so that when the response comes back
// we can correctly get it back to the rli.  only one outstanding message to each
// plugin is allowed at any one time, so other threads calling this method will
// block until the current message is cleared
void PluginControl::send_msg_to_plugin(unsigned int plugin, std::string msg, plugin_control_msg_req* rlim) throw(plugincontrol_exception, pluginconn_exception, pluginmessage_exception)
{
  write_log("PluginControl::send_msg_to_plugin");

  write_log("PluginControl::send_msg_to_plugin: got ME " + int2str(plugin));
  write_log("PluginControl::send_msg_to_plugin: got msg " + msg);

  unsigned int numbytes = msg.length() + 1;
  unsigned int numwords;
  if(numbytes % 4 == 0)
  {
    numwords = numbytes / 4;
  }
  else
  {
    numwords = (numbytes / 4) + 1;
  }

  char *padded_msg = new char[numwords*4];
  strcpy(padded_msg, msg.c_str());

  write_log("PluginControl::send_msg_to_plugin: calculate numwords to be " + int2str(numwords));

  unsigned int *msgwords = new unsigned int[numwords+1];
  plugin_control_header *hdr = (plugin_control_header *)&msgwords[0];
  for(unsigned int i=1; i<=numwords; ++i)
  {
    unsigned int si = (i-1)*4;
    msgwords[i]  = (padded_msg[si]   & 0xff) << 24;
    msgwords[i] |= (padded_msg[si+1] & 0xff) << 16;
    msgwords[i] |= (padded_msg[si+2] & 0xff) << 8;
    msgwords[i] |= (padded_msg[si+3] & 0xff);
  }

  write_log("PluginControl::send_msg_to_plugin: about to grab the lock for ME " + int2str(plugin));

  pthread_mutex_t *lock;
  if(plugin == 0)
  {
    lock = &plugin0_control_lock;
  }
  else if(plugin == 1)
  {
    lock = &plugin1_control_lock;
  }
  else if(plugin == 2)
  {
    lock = &plugin2_control_lock;
  }
  else if(plugin == 3)
  {
    lock = &plugin3_control_lock;
  }
  else if(plugin == 4)
  {
    lock = &plugin4_control_lock;
  }
  else
  {
    throw plugincontrol_exception("invalid plugin");
  }

  if(pthread_mutex_lock(lock) != 0)
  {
    throw plugincontrol_exception("system error");
  }

  if(plugin == 0)
  {
    plugin0_msg = rlim;
  }
  else if(plugin == 1)
  {
    plugin1_msg = rlim;
  }
  else if(plugin == 2)
  {
    plugin2_msg = rlim;
  }
  else if(plugin == 3)
  {
    plugin3_msg = rlim;
  }
  else// if(plugin == 4)
  {
    plugin4_msg = rlim;
  }

  hdr->type = PCONTROLMSG;
  hdr->response_needed = 1;
  hdr->num_words = numwords;
  hdr->mid = 0;

  for(unsigned int i=0; i<=numwords; ++i)
  {
    char logstr[256];
    sprintf(logstr, "PluginControl::send_msg_to_plugin: msgwords[%u] = 0x%.8x",i,msgwords[i]);
    write_log(logstr);
  }

  write_log("PluginControl::send_msg_to_plugin: about to allocate PluginMessage");

  PluginMessage *pm = new PluginMessage(msgwords, plugin);
  delete[] msgwords;
  delete[] padded_msg;

  write_log("PluginControl::send_msg_to_plugin: about to send message to plugin");

  plugin_conn->writemsg(pm);

  write_log("PluginControl::send_msg_to_plugin: done sending message");

  delete pm;

  write_log("PluginControl::send_msg_to_plugin: done");

  return;
}

// take the response from the plugin and formulate the response to the RLI
void PluginControl::pass_result_to_rli(PluginMessage *pm) throw(plugincontrol_exception, pluginmessage_exception)
{
  write_log("in pass_result_to_rli");

  unsigned int plugin = pm->getplugin();
  unsigned int num_words = pm->getnumwords();

  write_log("PluginControl::pass_result_to_rli: got ME " + int2str(plugin));
  write_log("PluginControl::pass_result_to_rli: got num_words " + int2str(num_words));

  unsigned int hdrval = pm->getword(0);
  char logstr[256];
  sprintf(logstr, "PluginControl::pass_result_to_rli: word(0) = 0x%.8x", hdrval);
  write_log(logstr);

  char *msg = new char[num_words*4+1];
  for(unsigned int i=0; i<num_words; ++i)
  {
    unsigned int word = pm->getword(i+1);

    sprintf(logstr, "PluginControl::pass_result_to_rli: word(%u) = 0x%.8x", i+1, word);
    write_log(logstr);

    msg[i*4]   = (word >> 24) & 0xff;
    msg[i*4+1] = (word >> 16) & 0xff;
    msg[i*4+2] = (word >> 8) & 0xff;
    msg[i*4+3] = (word) & 0xff;
  }
  msg[num_words*4] = '\0';

  pthread_mutex_t *lock;
  plugin_control_msg_req* orig_msg;
  if(plugin == 0)
  {
    lock = &plugin0_control_lock;
    orig_msg = plugin0_msg;
  }
  else if(plugin == 1)
  {
    lock = &plugin1_control_lock;
    orig_msg = plugin1_msg;
  }
  else if(plugin == 2)
  {
    lock = &plugin2_control_lock;
    orig_msg = plugin2_msg;
  }
  else if(plugin == 3)
  {
    lock = &plugin3_control_lock;
    orig_msg = plugin3_msg;
  }
  else if(plugin == 4)
  {
    lock = &plugin4_control_lock;
    orig_msg = plugin4_msg;
  }
  else
  {
    throw plugincontrol_exception("invalid plugin");
  }

  if(pthread_mutex_unlock(lock) != 0)
  {
    throw plugincontrol_exception("system error");
  }

  std::string smsg = msg;
  write_log("PluginControl::pass_result_to_rli: msg is (" + smsg + ")");
  write_log("PluginControl::pass_result_to_rli: about to send response");

  if(orig_msg == NULL)
  {
    delete[] msg;
    throw plugincontrol_exception("system error");
  }

  orig_msg->send_plugin_response(smsg);

  write_log("PluginControl::pass_result_to_rli: about to delete msg");
  delete[] msg;
  delete orig_msg;

  write_log("PluginControl::pass_result_to_rli: done");

  if(plugin == 0)
  {
    plugin0_msg = NULL;
  }
  else if(plugin == 1)
  {
    plugin1_msg = NULL;
  }
  else if(plugin == 2)
  {
    plugin2_msg = NULL;
  }
  else if(plugin == 3)
  {
    plugin3_msg = NULL;
  }
  else //if(plugin == 4)
  {
    plugin4_msg = NULL;
  }

  return;
}

void PluginControl::start_plugin_debugging(std::string filename) throw(plugincontrol_exception)
{
  write_log("PluginControl::start_plugin_debugging: filename " + filename);

  if(plugin_debug_log != NULL)
  {
    delete plugin_debug_log;
    plugin_debug_log = NULL;
  }

  if(filename[0] == '.' || filename[0] == '/' || filename[0] == '\\')
  {
    throw plugincontrol_exception("invalid filename");
  }

  std::string user = configuration->get_username();

  /* would like to use getpwnam or something here, but I couldn't get that to use the NIS map
   * so instead you get this ugliness
  struct passwd *passwd_entry = getpwnam(user);
  if(passwd_entry == NULL)
  {
    throw plugincontrol_exception("invalid user!");
  }
  */
  char shcmd[256];
  sprintf(shcmd, "/usr/sbin/ypcat passwd | /bin/egrep '^%s:' | cut -d: -s -f3 > /tmp/uid", user.c_str());
  if(system(shcmd) < 0)
  {
    throw plugincontrol_exception("system error");
  }

  FILE *uid_file = fopen("/tmp/uid", "r");
  if(uid_file == NULL)
  {
    throw plugincontrol_exception("system error");
  }

  int uid;
  int rv = fscanf(uid_file, "%d", &uid);
  if(rv != 1)
  {
    throw plugincontrol_exception("system error");
  }

  if(fclose(uid_file) != 0)
  {
    throw plugincontrol_exception("system error");
  }

  if(seteuid(uid) != 0)
  {
    throw plugincontrol_exception("system error");
  }

  std::string fn = "/users/" + user + "/" + filename;

  write_log("PluginControl::start_plugin_debugging: full filename " + fn);

  try
  {
    plugin_debug_log = new log_file(fn);
  }
  catch(std::exception& e)
  {
    plugin_debug_log = NULL;
    throw plugincontrol_exception("couldn't open file " + fn);
  }

  write_log("PluginControl::start_plugin_debugging: filename " + fn + " ready");
}

void PluginControl::plugin_debug_msg(PluginMessage *pm) throw(pluginmessage_exception)
{
  write_log("in plugin_debug_msg");

  if(plugin_debug_log == NULL)
  {
    return;
  }

  unsigned int plugin = pm->getplugin();
  unsigned int num_words = pm->getnumwords();
  char *msg = new char[num_words*4+1];

  for(unsigned int i=0; i<num_words; ++i)
  {
    unsigned int word = pm->getword(i+1);
    msg[i*4]   = (word >> 24) & 0xff;
    msg[i*4+1] = (word >> 16) & 0xff;
    msg[i*4+2] = (word >> 8) & 0xff;
    msg[i*4+3] = (word) & 0xff;
  }
  msg[num_words*4] = '\0';

  std::string msgstr = "Plugin " + int2str(plugin) + ": " + std::string(msg);

  try
  {
    plugin_debug_log->write(msgstr);
  }
  catch(std::exception& e)
  {
    plugin_debug_log = NULL;
    write_log("plugin_debug_msg: error writing msg " + msgstr);
  }

  delete[] msg;

  return;
}


text:
namespace Discord.Rpc
{
    public interface IRpcPrivateChannel
    {
    }
}


text:
//var logger   = require("loggero").create("controllers/builder");
var helpers    = require("./helpers");
var inherit    = require("../inherit");
var Module     = require("../module");
var Controller = require("../controller");
var Pipeline   = require("then-pipeline");

function Builder(context) {
  Controller.call(this, context);

  this.pipeline = new Pipeline([
    compile(context),
    link(context)
  ]);
}

inherit.base(Builder).extends(Controller);

Builder.prototype.build = function(id) {
  if (this.context.controllers.registry.getModuleState(id) === Module.State.READY) {
    return this.context.controllers.registry.getModule(id);
  }

  return build(this, this.context.controllers.registry.getModule(id));
};

function build(builder, moduleMeta) {
  if (!moduleMeta.getDependencyExportsByName) {
    moduleMeta = moduleMeta.configure({
      getDependencyExportsByName: getDependencyExportsByName(builder, moduleMeta)
    });
  }

  moduleMeta = moduleMeta.configure({
    source: moduleMeta.source + getSourceUrl(moduleMeta)
  });

  return builder.pipeline.runSync(moduleMeta);
}

function getDependencyExportsByName(builder, moduleMeta) {
  return function getDependency(name) {
    var deps = moduleMeta.deps.filter(function(dep) {
      return dep.name === name;
    });

    if (!deps.length || !moduleMeta.deps.length) {
      throw new TypeError("Module '" + name + "' not found. Referrer: " + moduleMeta.path);
    }

    return builder.build(deps[0].id).exports;
  };
}

function compile(context) {
  return helpers.serviceRunnerSync(context, Module.State.LOADED, Module.State.COMPILE, context.services.compile);
}

function link(context) {
  return helpers.serviceRunnerSync(context, Module.State.COMPILE, Module.State.READY, context.services.link);
}

/**
 * Builds a `# sourceURL` string from the URL.
 *
 * @private
 *
 * @param { Module } moduleMeta - Module meta object this function is processing
 * @returns {string} The proper source url to be inserted in the module source
 */
function getSourceUrl(moduleMeta) {
  return !moduleMeta.path || hasSourceURL(moduleMeta) ?
    "" :
    "\n//# sourceURL=" + moduleMeta.path.replace(/^(https?):\/\/\/?[^\/]*/, "");
}

/**
 * Verifies if the module already has a `sourceURL` so that we don't override it.
 * @private
 *
 * @param { Module } moduleMeta - Module meta object this function is processing
 * @returns {boolean}
 */
function hasSourceURL(moduleMeta) {
  return moduleMeta.source && moduleMeta.source.indexOf("//# sourceURL=") !== -1;
}

module.exports = Builder;


text:
importClass(net.mindengine.galen.components.JsTestRegistry);
JsTestRegistry.get().registerEvent("included.js was loaded");

this.includedObject = {
    name: "Included object"
};


text:
define(['app',
        'components/login/login.controller'],

    function (app,LoginController) {

    ApplicationConfig.$inject = ["$stateProvider", "$urlRouterProvider"];

    function ApplicationConfig($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise("/home");

        $stateProvider
            .state("home", {
                url: "/home",
                templateUrl: 'components/layout/home.html'
            })
            .state("register", {
                url: "/register",
                templateUrl: "components/register/register.html"
                //controller: "RegisterController"
            })
            .state("about", {
                url: "/about",
                templateUrl: "components/about/about.html"
            })
            .state("login", {
                url: "/login",
                templateUrl: "components/login/login.html",
                controller: "LoginController",
                controllerAs: 'vm'
            })

        console.log("Config Block");
    }

    app.config(ApplicationConfig);
});


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="AnimationLibrary" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		Container for [Animation] resources.
	</brief_description>
	<description>
		An animation library stores a set of animations accessible through [StringName] keys, for use with [AnimationPlayer] nodes.
	</description>
	<tutorials>
		<link title="Animation tutorial index">$DOCS_URL/tutorials/animation/index.html</link>
	</tutorials>
	<methods>
		<method name="add_animation">
			<return type="int" enum="Error" />
			<param index="0" name="name" type="StringName" />
			<param index="1" name="animation" type="Animation" />
			<description>
				Adds the [param animation] to the library, accessible by the key [param name].
			</description>
		</method>
		<method name="get_animation" qualifiers="const">
			<return type="Animation" />
			<param index="0" name="name" type="StringName" />
			<description>
				Returns the [Animation] with the key [param name]. If the animation does not exist, [code]null[/code] is returned and an error is logged.
			</description>
		</method>
		<method name="get_animation_list" qualifiers="const">
			<return type="StringName[]" />
			<description>
				Returns the keys for the [Animation]s stored in the library.
			</description>
		</method>
		<method name="has_animation" qualifiers="const">
			<return type="bool" />
			<param index="0" name="name" type="StringName" />
			<description>
				Returns [code]true[/code] if the library stores an [Animation] with [param name] as the key.
			</description>
		</method>
		<method name="remove_animation">
			<return type="void" />
			<param index="0" name="name" type="StringName" />
			<description>
				Removes the [Animation] with the key [param name].
			</description>
		</method>
		<method name="rename_animation">
			<return type="void" />
			<param index="0" name="name" type="StringName" />
			<param index="1" name="newname" type="StringName" />
			<description>
				Changes the key of the [Animation] associated with the key [param name] to [param newname].
			</description>
		</method>
	</methods>
	<members>
		<member name="_data" type="Dictionary" setter="_set_data" getter="_get_data" default="{}">
		</member>
	</members>
	<signals>
		<signal name="animation_added">
			<param index="0" name="name" type="StringName" />
			<description>
				Emitted when an [Animation] is added, under the key [param name].
			</description>
		</signal>
		<signal name="animation_removed">
			<param index="0" name="name" type="StringName" />
			<description>
				Emitted when an [Animation] stored with the key [param name] is removed.
			</description>
		</signal>
		<signal name="animation_renamed">
			<param index="0" name="name" type="StringName" />
			<param index="1" name="to_name" type="StringName" />
			<description>
				Emitted when the key for an [Animation] is changed, from [param name] to [param to_name].
			</description>
		</signal>
	</signals>
</class>


text:
package com.kendelong.web.jmxconsole;

public class TypeConverter
{
	// Surely this can't be necessary...
	public static Object convertObjectValue(String type, String value)
	{
		if(type.equals("java.lang.String"))
		{
			return value;
		}
		else if(type.equals("int") || type.equals("java.lang.Integer"))
		{
			return Integer.valueOf(value);
		}
		else if(type.equals("boolean") || type.equals("java.lang.Boolean"))
		{
			return Boolean.valueOf(value);
		}
		else if(type.equals("long") || type.equals("java.lang.Long"))
		{
			return Long.valueOf(value);
		}
		else if(type.equals("float") || type.equals("java.lang.Float"))
		{
			return Float.valueOf(value);
		}
		else if(type.equals("double") || type.equals("java.lang.Double"))
		{
			return Double.valueOf(value);
		}
		else
		{
			System.out.println("Cannot convert " + type);
			return null;
		}
	}

}


text:
AWS::EC2::NetworkAcl
====================

Creates a new network ACL in a VPC.

Syntax
------

``` {.programlisting}

{
   "Type" : "AWS::EC2::NetworkAcl",
   "Properties" : {
      "Tags" : [ Resource Tag, ... ],
      "VpcId" : String
   }
}

```

Properties
----------

 `Tags`
An arbitrary set of tags (key–value pairs) for this ACL.

*Required*: No

*Type*: [AWS CloudFormation Resource Tags](aws-properties-resource-tags.html "AWS CloudFormation Resource Tags Type")

*Update requires*: [No interruption](using-cfn-updating-stacks-update-behaviors.html#update-no-interrupt).

 `VpcId`
The ID of the VPC where the network ACL will be created.

*Required*: Yes

*Type*: String

*Update requires*: [Replacement](using-cfn-updating-stacks-update-behaviors.html#update-replacement)

Return Values
-------------

### Ref

When the logical ID of this resource is provided to the `Ref` intrinsic function, `Ref` returns the resource name.

For more information about using the `Ref` function, see [Ref](intrinsic-function-reference-ref.html "Ref").

Example
-------

``` {.programlisting}

{
   "AWSTemplateFormatVersion" : "2010-09-09",
   "Resources" : {
      "myNetworkAcl" : {
         "Type" : "AWS::EC2::NetworkAcl",
         "Properties" : {
            "VpcId" : { "Ref" : "myVPC" },
            "Tags" : [ { "Key" : "foo", "Value" : "bar" } ]
         }
      }
   }
}

```

See Also
--------

-   [CreateNetworkAcl](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkAcl.html) in the *Amazon EC2 API Reference*

-   [Network ACLs](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html) in the *Amazon Virtual Private Cloud User Guide*.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

using DataFactory.Tests.Utils;
using Microsoft.Azure.Management.DataFactory;
using Microsoft.Azure.Management.DataFactory.Models;
using Microsoft.Rest.Azure;
using System;
using System.Net;
using System.Threading.Tasks;
using Xunit;

namespace DataFactory.Tests.ScenarioTests
{
    public class PipelineRunScenarioTests : ScenarioTestBase<PipelineRunScenarioTests>
    {
        [Fact]
        [Trait(TraitName.TestType, TestType.Scenario)]
        public async Task CancelPipelineRun()
        {
            Func<DataFactoryManagementClient, Task> action = async (client) =>
            {
                Factory createResponse = client.Factories.CreateOrUpdate(this.ResourceGroupName, this.DataFactoryName, new Factory(location: FactoryLocation));
                CloudException exception = await Assert.ThrowsAsync<CloudException>(async () =>
                {
                    await client.PipelineRuns.CancelWithHttpMessagesAsync(this.ResourceGroupName, this.DataFactoryName, "efbe5443-9879-4495-94a6-4d7c394133ad");
                });

                Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
            };

            Func<DataFactoryManagementClient, Task> finallyAction = async (client) =>
            {
                await client.Factories.DeleteAsync(this.ResourceGroupName, this.DataFactoryName);
            };
            await this.RunTest(action, finallyAction);
        }
    }
}


text:
angular
    .module("${moduleName}")
    .factory("${className}", ${className});

function ${className}(\$resource) {
    var ${className} = \$resource(
        "${propertyName}/:id",
        {"id": "@id"},
        {"update": {method: "PUT"}, "list": {method: "GET", isArray: true}}
    );
    return ${className};
}


text:
using System.Text.RegularExpressions;
using OpenParser.EventResults;
using OpenParser.Filters;
using OpenParser.SubscriberStrategies;

namespace OpenParser.Subscriptions
{
    public class ExperienceSubscription : Subscription<Experience>
    {
        public ExperienceSubscription(LogFile logFile) : base(logFile)
        {
            Subscriber = new Subscriber<Experience>(logFile,
                new RegexStrategy<Experience>(CompiledRegex.ExperienceRegex, HandleMatches));
            Subscribe();
        }

        private Experience HandleMatches(LogEntry entry, Match match)
        {
            var isParty = !string.IsNullOrEmpty(match.Groups[1].Value);

            return new Experience(entry, isParty);
        }
    }
}


text:
tion><userServiceAuthorization><serviceName>Voice Messaging
User</serviceName><unauthorized>true</unauthorized></userServiceAuthorization><userServiceAuthorization><serviceName>Call
Forwarding
Selective</serviceName><unauthorized>true</unauthorized></userServiceAuthorization></command></BroadsoftDocument>]]></request></command></BroadsoftOCIReportingDocument>
<?xml version="1.0" encoding="ISO-8859-1"?><BroadsoftOCIReportingDocument
protocol="OCIReporting"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><command
xsi:type="OCIReportingReportNotification"><id>write13234570</id><userId>*XS
localhost
Admin*</userId><loginType>System</loginType><request><![CDATA[<?xml
version="1.0" encoding="ISO-8859-1"?><BroadsoftDocument protocol="OCI"
xmlns="C"><sessionId
xmlns="">XS_10.81.253.80.1423594801654</sessionId><command echo="552342864"
xsi:type="UserCallCenterModifyRequest17sp4" xmlns="" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"><userId>
teleorder.13@bidvestlogistics.com
</userId><agentACDState>Available</agentACDState></command></BroadsoftDocument>]]></request></command></BroadsoftOCIReportingDocument>


text:
package kornell.gui.client.event;

import com.google.gwt.event.shared.GwtEvent;

public class ActomEnteredEvent extends GwtEvent<ActomEnteredEventHandler> {
    public static final Type<ActomEnteredEventHandler> TYPE = new Type<ActomEnteredEventHandler>();

    private String actomKey;
    private String enrollmentUUID;

    public ActomEnteredEvent(String enrollmentUUID, String actomKey) {
        this.enrollmentUUID = enrollmentUUID;
        this.actomKey = actomKey;
    }

    @Override
    protected void dispatch(ActomEnteredEventHandler handler) {
        handler.onActomEntered(this);
    }

    @Override
    public Type<ActomEnteredEventHandler> getAssociatedType() {
        return TYPE;
    }

    public String getActomKey() {
        return actomKey;
    }

    public String getEnrollmentUUID() {
        return enrollmentUUID;
    }

    public void setActomKey(String actomKey) {
        this.actomKey = actomKey;
    }

    public void setEnrollmentUUID(String enrollmentUUID) {
        this.enrollmentUUID = enrollmentUUID;
    }
}


text:
/*
 * File:   TemporalWindow.cpp
 * Author: bam4d
 *
 * Created on 19 February 2012, 18:06
 */

#include "CNNGlobals.h"

TemporalWindow::TemporalWindow(int maxPoints)
{
        Window = new TimePoint[maxPoints];
        CurrentPoint = 0;
        MaxPoints = maxPoints;
}

TimePoint* TemporalWindow::operator[](int position)
{
    return &Window[(CurrentPoint+position)%MaxPoints];
}

void TemporalWindow::Release()
{
    delete[] Window;
}

TemporalWindow::~TemporalWindow() {
}


text:
namespace google {
namespace protobuf {
namespace compiler {

CodeGenerator::~CodeGenerator() {}
GeneratorContext::~GeneratorContext() {}

io::ZeroCopyOutputStream*
GeneratorContext::OpenForAppend(const string& filename) {
  return NULL;
}

io::ZeroCopyOutputStream* GeneratorContext::OpenForInsert(
    const string& filename, const string& insertion_point) {
  GOOGLE_LOG(FATAL) << "This GeneratorContext does not support insertion.";
  return NULL;  // make compiler happy
}

void GeneratorContext::ListParsedFiles(
    vector<const FileDescriptor*>* output) {
  GOOGLE_LOG(FATAL) << "This GeneratorContext does not support ListParsedFiles";
}

// Parses a set of comma-delimited name/value pairs.
void ParseGeneratorParameter(const string& text,
                             vector<pair<string, string> >* output) {
  vector<string> parts = Split(text, ",", true);

  for (int i = 0; i < parts.size(); i++) {
    string::size_type equals_pos = parts[i].find_first_of('=');
    pair<string, string> value;
    if (equals_pos == string::npos) {
      value.first = parts[i];
      value.second = "";
    } else {
      value.first = parts[i].substr(0, equals_pos);
      value.second = parts[i].substr(equals_pos + 1);
    }
    output->push_back(value);
  }
}

}  // namespace compiler
}  // namespace protobuf
}  // namespace google


text:
{% if site.components.share.enabled %}

{% endif %}


text:
exports.number_format = function(hexo){return function(num, options){
  var hexoHelpers = hexo.extend.helper.list();
  var opts = options.hash || {};
  var self = arguments[arguments.length - 1].data.root;
  return hexoHelpers.number_format.call(self, num, opts);
}};


text:
package it.unibz.inf.ontop.model.impl;

import it.unibz.inf.ontop.model.Predicate.COL_TYPE;
import it.unibz.inf.ontop.model.URIConstant;

/**
 * Provides a storage to put the URI constant.
 */
public class URIConstantImpl implements URIConstant {

	private static final long serialVersionUID = -1263974895010238519L;

	private final int identifier;
	private final String iristr;

	protected URIConstantImpl(String iri) {
		this.iristr = iri;
		this.identifier = iri.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null || !(obj instanceof URIConstantImpl)) {
			return false;
		}
		URIConstantImpl uri2 = (URIConstantImpl) obj;
		return this.identifier == uri2.identifier;
	}

	@Override
	public int hashCode() {
		return identifier;
	}

	@Override
	public String getURI() {
		return iristr;
	}

	@Override
	public URIConstant clone() {
		return this;
	}

	@Override
	public String toString() {
		return "<" + iristr + ">";
	}

	@Override
	public COL_TYPE getType() {
		return COL_TYPE.OBJECT;
	}

	@Deprecated
	public String getValue() {
		return iristr;
	}
}


text:
/**
 * @author artfable
 * 31.10.15
 */
import menuItemCollection from './menuItemCollection.js'
import { appState } from '../app.js'

export default new (Backbone.View.extend({
    templateUrl: 'views/components/menu.html',

    afterInitialize: function() {},

    resolve: function() {
        if (this.loaded) {
            this.$el.html(this.template({menu: menuItemCollection.toJSON(), page: appState.get('page')}));
        } else {
            var that = this;
            menuItemCollection.fetch({
                success: function (collection) {
                    that.$el.html(that.template({menu: collection.toJSON(), page: appState.get('page')}));
                    that.loaded = true;
                }
            });
        }
    }
}))();


text:
import React, {useCallback, useContext, useMemo} from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import {FixedSizeList} from 'react-window';
import {ProfilerContext} from './ProfilerContext';
import NoCommitData from './NoCommitData';
import CommitRankedListItem from './CommitRankedListItem';
import {scale} from './utils';
import {StoreContext} from '../context';
import {SettingsContext} from '../Settings/SettingsContext';

import styles from './CommitRanked.css';

import type {ChartData} from './RankedChartBuilder';
import type {CommitTree} from './types';

export type ItemData = {|
  chartData: ChartData,
  scaleX: (value: number, fallbackValue: number) => number,
  selectedFiberID: number | null,
  selectedFiberIndex: number,
  selectFiber: (id: number | null, name: string | null) => void,
  width: number,
|};

export default function CommitRankedAutoSizer(_: {||}) {
  const {profilerStore} = useContext(StoreContext);
  const {rootID, selectedCommitIndex, selectFiber} = useContext(
    ProfilerContext,
  );
  const {profilingCache} = profilerStore;

  const deselectCurrentFiber = useCallback(
    event => {
      event.stopPropagation();
      selectFiber(null, null);
    },
    [selectFiber],
  );

  let commitTree: CommitTree | null = null;
  let chartData: ChartData | null = null;
  if (selectedCommitIndex !== null) {
    commitTree = profilingCache.getCommitTree({
      commitIndex: selectedCommitIndex,
      rootID: ((rootID: any): number),
    });

    chartData = profilingCache.getRankedChartData({
      commitIndex: selectedCommitIndex,
      commitTree,
      rootID: ((rootID: any): number),
    });
  }

  if (commitTree != null && chartData != null && chartData.nodes.length > 0) {
    return (
      <div className={styles.Container} onClick={deselectCurrentFiber}>
        <AutoSizer>
          {({height, width}) => (
            <CommitRanked
              chartData={((chartData: any): ChartData)}
              commitTree={((commitTree: any): CommitTree)}
              height={height}
              width={width}
            />
          )}
        </AutoSizer>
      </div>
    );
  } else {
    return <NoCommitData />;
  }
}

type Props = {|
  chartData: ChartData,
  commitTree: CommitTree,
  height: number,
  width: number,
|};

function CommitRanked({chartData, commitTree, height, width}: Props) {
  const {lineHeight} = useContext(SettingsContext);
  const {selectedFiberID, selectFiber} = useContext(ProfilerContext);

  const selectedFiberIndex = useMemo(
    () => getNodeIndex(chartData, selectedFiberID),
    [chartData, selectedFiberID],
  );

  const itemData = useMemo<ItemData>(
    () => ({
      chartData,
      scaleX: scale(0, chartData.nodes[selectedFiberIndex].value, 0, width),
      selectedFiberID,
      selectedFiberIndex,
      selectFiber,
      width,
    }),
    [chartData, selectedFiberID, selectedFiberIndex, selectFiber, width],
  );

  return (
    <FixedSizeList
      height={height}
      innerElementType="svg"
      itemCount={chartData.nodes.length}
      itemData={itemData}
      itemSize={lineHeight}
      width={width}>
      {CommitRankedListItem}
    </FixedSizeList>
  );
}

const getNodeIndex = (chartData: ChartData, id: number | null): number => {
  if (id === null) {
    return 0;
  }
  const {nodes} = chartData;
  for (let index = 0; index < nodes.length; index++) {
    if (nodes[index].id === id) {
      return index;
    }
  }
  return 0;
};


text:
package filters

import (
	"testing"

	"github.com/stretchr/testify/assert"

	flowpb "github.com/cilium/cilium/api/v1/flow"
	v1 "github.com/cilium/cilium/pkg/hubble/api/v1"
)

func TestVerdictFilter(t *testing.T) {
	ev := &v1.Event{
		Event: &flowpb.Flow{
			Verdict: flowpb.Verdict_FORWARDED,
		},
	}
	assert.True(t, filterByVerdicts([]flowpb.Verdict{flowpb.Verdict_FORWARDED})(ev))
	assert.False(t, filterByVerdicts([]flowpb.Verdict{flowpb.Verdict_DROPPED})(ev))
	assert.False(t, filterByVerdicts([]flowpb.Verdict{flowpb.Verdict_REDIRECTED})(ev))
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:focusable="true"
    android:orientation="horizontal"
    android:background="?android:attr/selectableItemBackground">

    <ImageView
        android:id="@+id/saklar_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:src="@drawable/ic_lightbulb_outline_grey"/>

    <TextView
        android:id="@+id/saklar_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:layout_marginLeft="16dp"
        android:layout_weight="1"
        android:text="Lampu XXX"
        android:layout_gravity="center"/>

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/saklar_switch"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Menu\BreadcrumbTest.
 */

namespace Drupal\system\Tests\Menu;

use Drupal\Core\Url;
use Drupal\node\Entity\NodeType;
use Drupal\user\RoleInterface;

/**
 * Tests breadcrumbs functionality.
 *
 * @group Menu
 */
class BreadcrumbTest extends MenuTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('menu_test', 'block');

  /**
   * An administrative user.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
   * A regular user.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $webUser;

  /**
   * Test paths in the Standard profile.
   */
  protected $profile = 'standard';

  protected function setUp() {
    parent::setUp();

    $perms = array_keys(\Drupal::service('user.permissions')->getPermissions());
    $this->adminUser = $this->drupalCreateUser($perms);
    $this->drupalLogin($this->adminUser);

    // This test puts menu links in the Tools menu and then tests for their
    // presence on the page, so we need to ensure that the Tools block will be
    // displayed in the admin theme.
    $this->drupalPlaceBlock('system_menu_block:tools', array(
      'region' => 'content',
      'theme' => $this->config('system.theme')->get('admin'),
    ));
  }

  /**
   * Tests breadcrumbs on node and administrative paths.
   */
  function testBreadCrumbs() {
    // Prepare common base breadcrumb elements.
    $home = array('' => 'Home');
    $admin = $home + array('admin' => t('Administration'));
    $config = $admin + array('admin/config' => t('Configuration'));
    $type = 'article';

    // Verify Taxonomy administration breadcrumbs.
    $trail = $admin + array(
      'admin/structure' => t('Structure'),
    );
    $this->assertBreadcrumb('admin/structure/taxonomy', $trail);

    $trail += array(
      'admin/structure/taxonomy' => t('Taxonomy'),
    );
    $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags', $trail);
    $trail += array(
      'admin/structure/taxonomy/manage/tags' => t('Tags'),
    );
    $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/overview', $trail);
    $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/add', $trail);

    // Verify Menu administration breadcrumbs.
    $trail = $admin + array(
      'admin/structure' => t('Structure'),
    );
    $this->assertBreadcrumb('admin/structure/menu', $trail);

    $trail += array(
      'admin/structure/menu' => t('Menus'),
    );
    $this->assertBreadcrumb('admin/structure/menu/manage/tools', $trail);

    $trail += array(
      'admin/structure/menu/manage/tools' => t('Tools'),
    );
    $this->assertBreadcrumb("admin/structure/menu/link/node.add_page/edit", $trail);
    $this->assertBreadcrumb('admin/structure/menu/manage/tools/add', $trail);

    // Verify Node administration breadcrumbs.
    $trail = $admin + array(
      'admin/structure' => t('Structure'),
      'admin/structure/types' => t('Content types'),
    );
    $this->assertBreadcrumb('admin/structure/types/add', $trail);
    $this->assertBreadcrumb("admin/structure/types/manage/$type", $trail);
    $trail += array(
      "admin/structure/types/manage/$type" => t('Article'),
    );
    $this->assertBreadcrumb("admin/structure/types/manage/$type/fields", $trail);
    $this->assertBreadcrumb("admin/structure/types/manage/$type/display", $trail);
    $trail_teaser = $trail + array(
      "admin/structure/types/manage/$type/display" => t('Manage display'),
    );
    $this->assertBreadcrumb("admin/structure/types/manage/$type/display/teaser", $trail_teaser);
    $this->assertBreadcrumb("admin/structure/types/manage/$type/delete", $trail);
    $trail += array(
      "admin/structure/types/manage/$type/fields" => t('Manage fields'),
    );
    $this->assertBreadcrumb("admin/structure/types/manage/$type/fields/node.$type.body", $trail);

    // Verify Filter text format administration breadcrumbs.
    $filter_formats = filter_formats();
    $format = reset($filter_formats);
    $format_id = $format->id();
    $trail = $config + array(
      'admin/config/content' => t('Content authoring'),
    );
    $this->assertBreadcrumb('admin/config/content/formats', $trail);

    $trail += array(
      'admin/config/content/formats' => t('Text formats and editors'),
    );
    $this->assertBreadcrumb('admin/config/content/formats/add', $trail);
    $this->assertBreadcrumb("admin/config/content/formats/manage/$format_id", $trail);
    // @todo Remove this part once we have a _title_callback, see
    //   https://www.drupal.org/node/2076085.
    $trail += array(
      "admin/config/content/formats/manage/$format_id" => $format->label(),
    );
    $this->assertBreadcrumb("admin/config/content/formats/manage/$format_id/disable", $trail);

    // Verify node breadcrumbs (without menu link).
    $node1 = $this->drupalCreateNode();
    $nid1 = $node1->id();
    $trail = $home;
    $this->assertBreadcrumb("node/$nid1", $trail);
    // Also verify that the node does not appear elsewhere (e.g., menu trees).
    $this->assertNoLink($node1->getTitle());
    // Also verify that the node does not appear elsewhere (e.g., menu trees).
    $this->assertNoLink($node1->getTitle());

    $trail += array(
      "node/$nid1" => $node1->getTitle(),
    );
    $this->assertBreadcrumb("node/$nid1/edit", $trail);

    // Verify that breadcrumb on node listing page contains "Home" only.
    $trail = array();
    $this->assertBreadcrumb('node', $trail);

    // Verify node breadcrumbs (in menu).
    // Do this separately for Main menu and Tools menu, since only the
    // latter is a preferred menu by default.
    // @todo Also test all themes? Manually testing led to the suspicion that
    //   breadcrumbs may differ, possibly due to theme overrides.
    $menus = array('main', 'tools');
    // Alter node type menu settings.
    $node_type = NodeType::load($type);
    $node_type->setThirdPartySetting('menu_ui', 'available_menus', $menus);
    $node_type->setThirdPartySetting('menu_ui', 'parent', 'tools:');
    $node_type->save();

    foreach ($menus as $menu) {
      // Create a parent node in the current menu.
      $title = $this->randomMachineName();
      $node2 = $this->drupalCreateNode(array(
        'type' => $type,
        'title' => $title,
        'menu' => array(
          'enabled' => 1,
          'title' => 'Parent ' . $title,
          'description' => '',
          'menu_name' => $menu,
          'parent' => '',
        ),
      ));

      if ($menu == 'tools') {
        $parent = $node2;
      }
    }

    // Create a Tools menu link for 'node', move the last parent node menu
    // link below it, and verify a full breadcrumb for the last child node.
    $menu = 'tools';
    $edit = array(
      'title[0][value]' => 'Root',
      'link[0][uri]' => '/node',
    );
    $this->drupalPostForm("admin/structure/menu/manage/$menu/add", $edit, t('Save'));
    $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => 'Root'));
    $link = reset($menu_links);

    $edit = array(
      'menu[menu_parent]' => $link->getMenuName() . ':' . $link->getPluginId(),
    );
    $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published'));
    $expected = array(
      "node" => $link->getTitle(),
    );
    $trail = $home + $expected;
    $tree = $expected + array(
      'node/' . $parent->id() => $parent->menu['title'],
    );
    $trail += array(
      'node/' . $parent->id() => $parent->menu['title'],
    );

    // Add a taxonomy term/tag to last node, and add a link for that term to the
    // Tools menu.
    $tags = array(
      'Drupal' => array(),
      'Breadcrumbs' => array(),
    );
    $edit = array(
      'field_tags[target_id]' => implode(',', array_keys($tags)),
    );
    $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published'));

    // Put both terms into a hierarchy Drupal » Breadcrumbs. Required for both
    // the menu links and the terms itself, since taxonomy_term_page() resets
    // the breadcrumb based on taxonomy term hierarchy.
    $parent_tid = 0;
    foreach ($tags as $name => $null) {
      $terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $name));
      $term = reset($terms);
      $tags[$name]['term'] = $term;
      if ($parent_tid) {
        $edit = array(
          'parent[]' => array($parent_tid),
        );
        $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save'));
      }
      $parent_tid = $term->id();
    }
    $parent_mlid = '';
    foreach ($tags as $name => $data) {
      $term = $data['term'];
      $edit = array(
        'title[0][value]' => "$name link",
        'link[0][uri]' => "/taxonomy/term/{$term->id()}",
        'menu_parent' => "$menu:{$parent_mlid}",
        'enabled[value]' => 1,
      );
      $this->drupalPostForm("admin/structure/menu/manage/$menu/add", $edit, t('Save'));
      $menu_links = entity_load_multiple_by_properties('menu_link_content', array(
        'title' => $edit['title[0][value]'],
        'link.uri' => 'internal:/taxonomy/term/' . $term->id(),
      ));
      $tags[$name]['link'] = reset($menu_links);
      $parent_mlid = $tags[$name]['link']->getPluginId();
    }

    // Verify expected breadcrumbs for menu links.
    $trail = $home;
    $tree = array();
    // Logout the user because we want to check the active class as well, which
    // is just rendered as anonymous user.
    $this->drupalLogout();
    foreach ($tags as $name => $data) {
      $term = $data['term'];
      /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */
      $link = $data['link'];

      $link_path = $link->getUrlObject()->getInternalPath();
      $tree += array(
        $link_path => $link->getTitle(),
      );
      $this->assertBreadcrumb($link_path, $trail, $term->getName(), $tree);
      $this->assertEscaped($parent->getTitle(), 'Tagged node found.');

      // Additionally make sure that this link appears only once; i.e., the
      // untranslated menu links automatically generated from menu router items
      // ('taxonomy/term/%') should never be translated and appear in any menu
      // other than the breadcrumb trail.
      $elements = $this->xpath('//nav[@id=:menu]/descendant::a[@href=:href]', array(
        ':menu' => 'block-bartik-tools',
        ':href' => Url::fromUri('base:' . $link_path)->toString(),
      ));
      $this->assertTrue(count($elements) == 1, "Link to {$link_path} appears only once.");

      // Next iteration should expect this tag as parent link.
      // Note: Term name, not link name, due to taxonomy_term_page().
      $trail += array(
        $link_path => $term->getName(),
      );
    }

    // Verify breadcrumbs on user and user/%.
    // We need to log back in and out below, and cannot simply grant the
    // 'administer users' permission, since user_page() makes your head explode.
    user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
      'access user profiles',
    ));

    // Verify breadcrumb on front page.
    $this->assertBreadcrumb('<front>', array());

    // Verify breadcrumb on user pages (without menu link) for anonymous user.
    $trail = $home;
    $this->assertBreadcrumb('user', $trail, t('Log in'));
    $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());

    // Verify breadcrumb on user pages (without menu link) for registered users.
    $this->drupalLogin($this->adminUser);
    $trail = $home;
    $this->assertBreadcrumb('user', $trail, $this->adminUser->getUsername());
    $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());
    $trail += array(
      'user/' . $this->adminUser->id() => $this->adminUser->getUsername(),
    );
    $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername());

    // Create a second user to verify breadcrumb on user pages again.
    $this->webUser = $this->drupalCreateUser(array(
      'administer users',
      'access user profiles',
    ));
    $this->drupalLogin($this->webUser);

    // Verify correct breadcrumb and page title on another user's account pages.
    $trail = $home;
    $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername());
    $trail += array(
      'user/' . $this->adminUser->id() => $this->adminUser->getUsername(),
    );
    $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername());

    // Verify correct breadcrumb and page title when viewing own user account.
    $trail = $home;
    $this->assertBreadcrumb('user/' . $this->webUser->id(), $trail, $this->webUser->getUsername());
    $trail += array(
      'user/' . $this->webUser->id() => $this->webUser->getUsername(),
    );
    $this->assertBreadcrumb('user/' . $this->webUser->id() . '/edit', $trail, $this->webUser->getUsername());

    // Create an only slightly privileged user being able to access site reports
    // but not administration pages.
    $this->webUser = $this->drupalCreateUser(array(
      'access site reports',
    ));
    $this->drupalLogin($this->webUser);

    // Verify that we can access recent log entries, there is a corresponding
    // page title, and that the breadcrumb is just the Home link (because the
    // user is not able to access "Administer".
    $trail = $home;
    $this->assertBreadcrumb('admin', $trail, t('Access denied'));
    $this->assertResponse(403);

    // Since the 'admin' path is not accessible, we still expect only the Home
    // link.
    $this->assertBreadcrumb('admin/reports', $trail, t('Reports'));
    $this->assertNoResponse(403);

    // Since the Reports page is accessible, that will show.
    $trail += array('admin/reports' => t('Reports'));
    $this->assertBreadcrumb('admin/reports/dblog', $trail, t('Recent log messages'));
    $this->assertNoResponse(403);

    // Ensure that the breadcrumb is safe against XSS.
    $this->drupalGet('menu-test/breadcrumb1/breadcrumb2/breadcrumb3');
    $this->assertRaw('<script>alert(12);</script>');
    $this->assertEscaped('<script>alert(123);</script>');
  }

}


text:
{-# LANGUAGE OverloadedStrings, LambdaCase, ScopedTypeVariables, TupleSections #-}
{- |
  Simple persistent cache. Cache file is deleted if the modification time
  of any of the dependencies has changed.
 -}

module Gen2.Cache (getCached, putCached) where

import qualified Control.Exception      as E

import qualified Crypto.Hash.SHA1       as SHA1

import qualified Data.Binary            as DB
import qualified Data.Binary.Get        as DB
import qualified Data.Binary.Put        as DB
import           Data.ByteString        (ByteString)
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Lazy   as BL
import           Data.Text              (Text)
import qualified Data.Text              as T
import qualified Data.Text.Encoding     as T
import           Data.Time.Clock.POSIX

import           System.Directory
import           System.FilePath
import           System.IO.Error

import           DynFlags
import Prelude

import qualified Compiler.Info          as Info

getCacheMeta :: [FilePath] -> IO (Maybe BL.ByteString)
getCacheMeta files = do
  m <- mapM (\file -> (file,) <$> getModified file) files
  return $ if any ((==0).snd) m then Nothing else Just (DB.runPut $ DB.put m)

checkCacheMeta :: BL.ByteString -> IO Bool
checkCacheMeta meta =
  (and :: [Bool] -> Bool) <$> mapM (\(file,mod) -> (\m -> m==mod && m/=0) <$>
    getModified file) (DB.runGet DB.get $ meta)

getModified :: FilePath -> IO Integer
getModified file =
  (round . (*1000) . utcTimeToPOSIXSeconds <$> getModificationTime file)
    `catchIOError` \_ -> return 0

cacheFileName :: DynFlags
              -> Text
              -> Text
              -> IO (Maybe FilePath)
cacheFileName _dflags prefix key = do
  let b = prefix <> "-" <> (T.decodeUtf8 . B16.encode . SHA1.hash . T.encodeUtf8 $ key)
  Info.getUserCacheDir >>= \case
    Nothing   -> return Nothing
    Just cdir -> (createDirectoryIfMissing True cdir >> return (Just $ cdir </> T.unpack b <.> "cache"))
                   `catchIOError` \_ -> return Nothing

removeCacheFile :: FilePath -> IO ()
removeCacheFile file = removeFile file `catchIOError` \_ -> return ()

getCached :: DynFlags
          -> Text
          -> Text
          -> IO (Maybe ByteString)
getCached dflags prefix name =
  let getCacheEntry =
       cacheFileName dflags prefix name >>= \case
          Nothing   -> return Nothing
          Just file -> getCacheFile file `E.onException` removeCacheFile file
      getCacheFile file = do
        dat <- BL.readFile file
        let (meta, content) = DB.runGet DB.get dat
        valid <- checkCacheMeta meta
        if valid then content `seq` return (Just content)
                 else removeCacheFile file >> return Nothing
  in  getCacheEntry `E.catch` \(_::E.SomeException) -> return Nothing

{-
  put a file in the cache, returns False if the cache file could not be created
-}
putCached :: DynFlags
          -> Text        -- prefix name, ends up in file name
          -> Text        -- unique name (may be long)
          -> [FilePath]  -- files, invalidate cache item if these are modified
          -> ByteString  -- contents
          -> IO Bool
putCached dflags prefix key deps content =
  cacheFileName dflags prefix key >>= \case
    Nothing   -> return False
    Just file ->
      getCacheMeta deps >>= \case
        Nothing -> return False
        Just meta ->
          (BL.writeFile file (DB.runPut $ DB.put (meta, content)) >> return True) `catchIOError`
            \_ -> return False


text:
'''
Created on May 12, 2011

@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from arelle import (ViewWinGrid, )
from arelle.UiUtil import (gridBorder, gridSpacer, gridHdr, gridCell,
                     label,
                     TOPBORDER, LEFTBORDER, RIGHTBORDER, BOTTOMBORDER, CENTERCELL)

def viewTuplesGrid(modelXbrl, tabWin, tupleObjectId, lang=None):
    modelTuple = modelXbrl.modelObject(tupleObjectId)
    if modelTuple is not None:
        modelXbrl.modelManager.showStatus(_("viewing tuples {0}").format(modelTuple.localName))
        parentFacts = modelXbrl.facts
        try: # check if possible to get parent tuple facts
            parentFacts = modelTuple.getparent().modelTupleFacts
        except:
            pass
        view = ViewTuplesGrid(modelXbrl, tabWin, modelTuple, parentFacts, lang)

        # context menu
        menu = view.contextMenu()
        menu.add_cascade(label=_("Close"), underline=0, command=view.close)
        view.menuAddLangs()
        view.view()
        view.blockSelectEvent = 1
        view.blockViewModelObject = 0
        view.viewFrame.bind("<Enter>", view.cellEnter, '+')
        view.viewFrame.bind("<Leave>", view.cellLeave, '+')
        return view
    else:
        modelXbrl.modelManager.showStatus(_("viewing tuples requires selecting the tuple to report"), clearAfter=2000)

class ViewTuplesGrid(ViewWinGrid.ViewGrid):
    def __init__(self, modelXbrl, tabWin, tupleFact, parentFacts, lang):
        super(ViewTuplesGrid, self).__init__(modelXbrl, tabWin, "Tuples", True, lang)
        self.tupleFact = tupleFact
        self.tupleConcept = tupleFact.concept
        self.parentFacts = parentFacts

    def view(self):
        # remove old widgets
        self.viewFrame.clearGrid()

        # table name
        self.zAxisRows = 0
        self.dataCols = 0
        self.colHdrRows = 0
        self.dataRows = 0
        xFilters = []

        self.analyzeColHdrs(self.parentFacts, 1)
        self.colHdrTopRow = self.zAxisRows + (2 if self.zAxisRows else 1)
        self.dataFirstRow = self.colHdrTopRow + self.colHdrRows
        self.dataFirstCol = 2

        gridHdr(self.gridTblHdr, 0, 0,
                self.tupleFact.concept.label(lang=self.lang),
                anchor="nw",
                #columnspan=(self.dataFirstCol - 1),
                rowspan=(self.dataFirstRow),
                wraplength=200)
        self.xAxis(self.dataFirstCol, self.colHdrTopRow, self.colHdrTopRow + self.colHdrRows - 1,
                   self.tupleFact.modelTupleFacts, xFilters, True, True, True)
        self.bodyCells(self.dataFirstRow, 0, self.parentFacts, xFilters, True)

        # data cells

        #self.gridView.config(scrollregion=self.gridView.bbox(constants.ALL))

    def analyzeColHdrs(self, tupleFacts, depth):
        for xAxisChildObj in tupleFacts:
            isItem = xAxisChildObj.isItem
            if isItem:
                self.dataCols += 1
            if depth > self.colHdrRows: self.colHdrRows = depth
            self.analyzeColHdrs(xAxisChildObj.modelTupleFacts, depth+1) #recurse

    def xAxis(self, leftCol, topRow, rowBelow, tupleFacts, xFilters, childrenFirst, renderNow, atTop):
        parentRow = rowBelow
        noDescendants = True
        rightCol = leftCol
        widthToSpanParent = 0
        sideBorder = not xFilters
        if atTop and sideBorder and childrenFirst:
            gridBorder(self.gridColHdr, self.dataFirstCol, 1, LEFTBORDER, rowspan=self.dataFirstRow)
        for xAxisChildObj in tupleFacts:
            isItem = xAxisChildObj.isItem
            noDescendants = False
            rightCol, row, width, leafNode = self.xAxis(leftCol, topRow + 1, rowBelow, xAxisChildObj.modelTupleFacts, xFilters, # nested items before totals
                                                        childrenFirst, childrenFirst, False)
            if row - 1 < parentRow:
                parentRow = row - 1
            #if not leafNode:
            #    rightCol -= 1
            widthToSpanParent += width
            label = xAxisChildObj.concept.label(lang=self.lang)
            if childrenFirst:
                thisCol = rightCol
                sideBorder = RIGHTBORDER
            else:
                thisCol = leftCol
                sideBorder = LEFTBORDER
            if renderNow:
                columnspan = (rightCol - leftCol + (1 if isItem else 0))
                gridBorder(self.gridColHdr, leftCol, topRow, TOPBORDER, columnspan=columnspan)
                gridBorder(self.gridColHdr, leftCol, topRow,
                           sideBorder, columnspan=columnspan,
                           rowspan=(rowBelow - topRow + 1) )
                gridHdr(self.gridColHdr, leftCol, topRow,
                        label if label else "         ",
                        anchor="center",
                        columnspan=(rightCol - leftCol + (1 if isItem else 0)),
                        rowspan=(row - topRow + 1) if leafNode else 1,
                        wraplength=width,
                        objectId=xAxisChildObj.objectId(),
                        onClick=self.onClick)
                if isItem:
                    gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, BOTTOMBORDER)
                    xFilters.append(xAxisChildObj.concept,
                                     )
            if isItem:
                rightCol += 1
            if renderNow and not childrenFirst:
                self.xAxis(leftCol + (1 if isItem else 0), topRow + 1, rowBelow, xAxisChildObj.modelTupleFacts, xFilters, childrenFirst, True, False) # render on this pass
            leftCol = rightCol
        if atTop and sideBorder and not childrenFirst:
            gridBorder(self.gridColHdr, rightCol - 1, 1, RIGHTBORDER, rowspan=self.dataFirstRow)
        return (rightCol, parentRow, widthToSpanParent, noDescendants)

    def tupleDescendant(self, tupleParent, descendantConcept):
        for tupleChild in tupleParent.modelTupleFacts:
            if tupleChild.concept == descendantConcept:
                return tupleChild
            tupleDescendant = self.tupleDescendant(tupleChild, descendantConcept)
            if tupleDescendant is not None:
                return tupleDescendant
        return None

    def bodyCells(self, row, indent, tupleFacts, xFilters, zFilters):
        for modelTupleFact in tupleFacts:
            if modelTupleFact.concept == self.tupleConcept:
                for i, xColConcept in enumerate(xFilters):
                    fact = self.tupleDescendant(modelTupleFact, xColConcept)
                    if fact is not None:
                        value = fact.effectiveValue
                        objectId = fact.objectId()
                        justify = "right" if fact.isNumeric else "left"
                    else:
                        value = None
                        objectId = None
                    if value is not None:
                        gridCell(self.gridBody, self.dataFirstCol + i, row, value, justify=justify, width=12,
                                 objectId=objectId, onClick=self.onClick)
                    else:
                        gridSpacer(self.gridBody, self.dataFirstCol + i, row, CENTERCELL)
                    gridSpacer(self.gridBody, self.dataFirstCol + i, row, RIGHTBORDER)
                    gridSpacer(self.gridBody, self.dataFirstCol + i, row, BOTTOMBORDER)
                row += 1
        return row

    def onClick(self, event):
        self.modelXbrl.viewModelObject(event.widget.objectId)

    def cellEnter(self, *args):
        self.blockSelectEvent = 0

    def cellLeave(self, *args):
        self.blockSelectEvent = 1

    def cellSelect(self, *args):
        if self.blockSelectEvent == 0 and self.blockViewModelObject == 0:
            self.blockViewModelObject += 1
            #self.modelXbrl.viewModelObject(self.nodeToObjectId[self.treeView.selection()[0]])
            #self.modelXbrl.viewModelObject(self.treeView.selection()[0])
            self.blockViewModelObject -= 1

    def viewModelObject(self, modelObject):
        if self.blockViewModelObject == 0:
            self.blockViewModelObject += 1
            '''
            try:
                if isinstance(modelObject, ModelObject.ModelRelationship):
                    conceptId = modelObject.toModelObject.objectId()
                elif isinstance(modelObject, ModelObject.ModelFact):
                    conceptId = self.modelXbrl.qnameConcepts[modelObject.qname].objectId()
                else:
                    conceptId = modelObject.objectId()
                #node = self.objectIdToNode[conceptId]
                node = conceptId
                if self.treeView.exists(node):
                    self.treeView.see(node)
                    self.treeView.selection_set(node)
            except KeyError:
                    self.treeView.selection_set(())
            '''
            self.blockViewModelObject -= 1


text:
package org.apache.kafka.streams.state.internals;

import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.state.internals.SegmentedBytesStore.KeySchema;

import java.nio.ByteBuffer;

class SegmentedCacheFunction implements CacheFunction {

    private static final int SEGMENT_ID_BYTES = 8;

    private final KeySchema keySchema;
    private final long segmentInterval;

    SegmentedCacheFunction(final KeySchema keySchema, final long segmentInterval) {
        this.keySchema = keySchema;
        this.segmentInterval = segmentInterval;
    }

    @Override
    public Bytes key(final Bytes cacheKey) {
        return Bytes.wrap(bytesFromCacheKey(cacheKey));
    }

    @Override
    public Bytes cacheKey(final Bytes key) {
        return cacheKey(key, segmentId(key));
    }

    Bytes cacheKey(final Bytes key, final long segmentId) {
        final byte[] keyBytes = key.get();
        final ByteBuffer buf = ByteBuffer.allocate(SEGMENT_ID_BYTES + keyBytes.length);
        buf.putLong(segmentId).put(keyBytes);
        return Bytes.wrap(buf.array());
    }

    static byte[] bytesFromCacheKey(final Bytes cacheKey) {
        final byte[] binaryKey = new byte[cacheKey.get().length - SEGMENT_ID_BYTES];
        System.arraycopy(cacheKey.get(), SEGMENT_ID_BYTES, binaryKey, 0, binaryKey.length);
        return binaryKey;
    }

    public long segmentId(final Bytes key) {
        return segmentId(keySchema.segmentTimestamp(key));
    }

    long segmentId(final long timestamp) {
        return timestamp / segmentInterval;
    }

    long getSegmentInterval() {
        return segmentInterval;
    }

    int compareSegmentedKeys(final Bytes cacheKey, final Bytes storeKey) {
        final long storeSegmentId = segmentId(storeKey);
        final long cacheSegmentId = ByteBuffer.wrap(cacheKey.get()).getLong();

        final int segmentCompare = Long.compare(cacheSegmentId, storeSegmentId);
        if (segmentCompare == 0) {
            final byte[] cacheKeyBytes = cacheKey.get();
            final byte[] storeKeyBytes = storeKey.get();
            return Bytes.BYTES_LEXICO_COMPARATOR.compare(
                cacheKeyBytes, SEGMENT_ID_BYTES, cacheKeyBytes.length - SEGMENT_ID_BYTES,
                storeKeyBytes, 0, storeKeyBytes.length
            );
        } else {
            return segmentCompare;
        }
    }
}