text:
package main

// All actions under command group

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/url"
	"os"
	"strconv"
)

type GroupList struct {
	client *Client
	format Formatter
}

func (g GroupList) Apply(args []string) {
	switch len(args) {
	case 0:
		g.listGroups("")
	case 1:
		g.listGroups(args[0])
	default:
		Check(false, "expected 0 or 1 argument")
	}
}

func (g GroupList) listGroups(groupid string) {
	path := "/v2/groups"
	if groupid != "" {
		path += "/" + url.QueryEscape(groupid)
	}
	request := g.client.GET(path)
	response, e := g.client.Do(request)
	Check(e == nil, "failed to get response", e)
	defer response.Body.Close()
	fmt.Println(g.format.Format(response.Body, g.Humanize))
}

func (g GroupList) Humanize(body io.Reader) string {
	dec := json.NewDecoder(body)
	var root Group
	e := dec.Decode(&root)
	Check(e == nil, "failed to unmarshal response", e)
	return columnizeGroup(&root)
}

func columnizeGroup(group *Group) string {
	title := "GROUPID VERSION GROUPS APPS\n"
	var b bytes.Buffer
	gatherGroup(group, &b)
	text := title + b.String()
	return Columnize(text)
}

func gatherGroup(g *Group, b *bytes.Buffer) {
	b.WriteString(g.GroupID)
	b.WriteString(" ")
	b.WriteString(g.Version)
	b.WriteString(" ")
	b.WriteString(strconv.Itoa(len(g.Groups)))
	b.WriteString(" ")
	b.WriteString(strconv.Itoa(len(g.Apps)))
	b.WriteString("\n")
	for _, group := range g.Groups {
		gatherGroup(group, b)
	}
}

type GroupCreate struct {
	client *Client
	format Formatter
}

func (g GroupCreate) Apply(args []string) {
	Check(len(args) == 1, "must supply 1 jsonfile")
	f, e := os.Open(args[0])
	Check(e == nil, "failed to open jsonfile", e)
	defer f.Close()
	request := g.client.POST("/v2/groups", f)
	response, e := g.client.Do(request)
	Check(e == nil, "failed to get response")
	defer response.Body.Close()
	Check(response.StatusCode != 409, "group already exists")
	fmt.Println(g.format.Format(response.Body, g.Humanize))
}

func (g GroupCreate) Humanize(body io.Reader) string {
	dec := json.NewDecoder(body)
	var update Update
	e := dec.Decode(&update)
	Check(e == nil, "failed to decode response", e)
	title := "DEPLOYID VERSION\n"
	text := title + update.DeploymentID + " " + update.Version
	return Columnize(text)
}

type GroupDestroy struct {
	client *Client
	format Formatter
}

func (g GroupDestroy) Apply(args []string) {
	Check(len(args) == 1, "must specify groupid")
	groupid := url.QueryEscape(args[0])
	path := "/v2/groups/" + groupid
	request := g.client.DELETE(path)
	response, e := g.client.Do(request)
	Check(e == nil, "destroy group failed", e)
	defer response.Body.Close()
	c := response.StatusCode
	Check(c != 404, "unknown group")
	Check(c == 200, "destroy group bad status", c)

	fmt.Println(g.format.Format(response.Body, g.Humanize))
}

func (g GroupDestroy) Humanize(body io.Reader) string {
	dec := json.NewDecoder(body)
	var versionmap map[string]string // ugh
	e := dec.Decode(&versionmap)
	Check(e == nil, "failed to decode response", e)
	v, ok := versionmap["version"]
	Check(ok, "version missing")
	return "VERSION\n" + v
}

type GroupUpdate struct {
	client *Client
	format Formatter
}

func (g GroupUpdate) Apply(args []string) {
	Check(len(args) == 2, "must specify groupid and jsonfile")
	groupid := url.QueryEscape(args[0])
	f, e := os.Open(args[1])
	Check(e == nil, "failed to open jsonfile", e)
	defer f.Close()
	request := g.client.PUT("/v2/groups/"+groupid, f)
	response, e := g.client.Do(request)
	Check(e == nil, "failed to get response", e)
	defer response.Body.Close()

	sc := response.StatusCode
	Check(sc == 200, "bad status code", sc)

	fmt.Println(g.format.Format(response.Body, g.Humanize))
}

func (g GroupUpdate) Humanize(body io.Reader) string {
	dec := json.NewDecoder(body)
	var update Update
	e := dec.Decode(&update)
	Check(e == nil, "failed to decode response", e)
	title := "DEPLOYID VERSION\n"
	text := title + update.DeploymentID + " " + update.Version
	return Columnize(text)
}


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

namespace AutoMapper.UnitTests.Bug
{
    namespace EnumConditionsBug
    {
        [Flags]
        public enum Enum1 { One, Two };
        [Flags]
        public enum Enum2 { Three, Four }

        public class EnumTestSource
        {
            public IEnumerable<Enum1> Prop1 { get; set; }
            public IEnumerable<Enum2> Prop2 { get; set; }
        }

        public class EnumTestDest
        {
            public Enum1 Prop1 { get; set; }
            public Enum2 Prop2 { get; set; }
        }
        public class EnumMapperTest
        {
            [Fact]
            public void Mapper_respects_condition()
            {
                var _c1Called = false;
                var _c2Called = false;
                var config = new MapperConfiguration(cfg => cfg.CreateMap<EnumTestSource, EnumTestDest>()
                    .ForMember(m => m.Prop1, o =>
                    {
                        o.Condition((_, srcProp, destProp) => { _c1Called = true; return srcProp != null; });
                        o.ResolveUsing(f => f.Prop1?.Aggregate((current, next) => current | next));
                    })
                    .ForMember(m => m.Prop2, o =>
                    {
                        o.Condition((_, srcProp, destProp) => { _c2Called = true; return srcProp != null; });
                        o.ResolveUsing(f => f.Prop2?.Aggregate((current, next) => current | next));
                    }));
                var src = new EnumTestSource { Prop1 = new[] { Enum1.One }, Prop2 = null };
                var dest = config.CreateMapper().Map<EnumTestDest>(src); // will throw
                _c1Called.ShouldBeTrue();
                _c2Called.ShouldBeTrue();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ir.asparsa.hobbytaste.server.exception;

import org.springframework.http.HttpStatus;

/**
 * @author hadi
 * @since 12/11/2016 AD
 */
public class StoreNotFoundException extends BaseRuntimeException {

    public StoreNotFoundException(
            String message,
            String localizedMessageKey,
            String local
    ) {
        super(message, localizedMessageKey, local);
    }

    public StoreNotFoundException(
            String message,
            Throwable cause,
            String localizedMessageKey,
            String local
    ) {
        super(message, cause, localizedMessageKey, local);
    }

    @Override public HttpStatus getHttpStatus() {
        return HttpStatus.NOT_FOUND;
    }
}


text:
#pragma once
#include <aws/codepipeline/CodePipeline_EXPORTS.h>
#include <aws/codepipeline/CodePipelineRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CodePipeline
{
namespace Model
{

  /**
   *
Represents the input of a get pipeline execution action.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_CODEPIPELINE_API GetPipelineExecutionRequest : public CodePipelineRequest
  {
  public:
    GetPipelineExecutionRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline const Aws::String& GetPipelineName() const{ return m_pipelineName; }

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline void SetPipelineName(const Aws::String& value) { m_pipelineNameHasBeenSet = true; m_pipelineName = value; }

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline void SetPipelineName(Aws::String&& value) { m_pipelineNameHasBeenSet = true; m_pipelineName = std::move(value); }

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline void SetPipelineName(const char* value) { m_pipelineNameHasBeenSet = true; m_pipelineName.assign(value); }

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline GetPipelineExecutionRequest& WithPipelineName(const Aws::String& value) { SetPipelineName(value); return *this;}

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline GetPipelineExecutionRequest& WithPipelineName(Aws::String&& value) { SetPipelineName(std::move(value)); return *this;}

    /**
     *
The name of the pipeline about which you want to get execution details.

     */
    inline GetPipelineExecutionRequest& WithPipelineName(const char* value) { SetPipelineName(value); return *this;}

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline const Aws::String& GetPipelineExecutionId() const{ return m_pipelineExecutionId; }

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline void SetPipelineExecutionId(const Aws::String& value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId = value; }

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline void SetPipelineExecutionId(Aws::String&& value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId = std::move(value); }

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline void SetPipelineExecutionId(const char* value) { m_pipelineExecutionIdHasBeenSet = true; m_pipelineExecutionId.assign(value); }

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline GetPipelineExecutionRequest& WithPipelineExecutionId(const Aws::String& value) { SetPipelineExecutionId(value); return *this;}

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline GetPipelineExecutionRequest& WithPipelineExecutionId(Aws::String&& value) { SetPipelineExecutionId(std::move(value)); return *this;}

    /**
     *
The ID of the pipeline execution about which you want to get execution
     * details.

     */
    inline GetPipelineExecutionRequest& WithPipelineExecutionId(const char* value) { SetPipelineExecutionId(value); return *this;}

  private:
    Aws::String m_pipelineName;
    bool m_pipelineNameHasBeenSet;
    Aws::String m_pipelineExecutionId;
    bool m_pipelineExecutionIdHasBeenSet;
  };

} // namespace Model
} // namespace CodePipeline
} // namespace Aws


text:
from . import xs
from .model import Namespace, get_root, etree

namespace = Namespace('http://schemas.xmlsoap.org/soap/envelope/', 'soap')

schema = xs.schema(namespace)(
    xs.element('Envelope', xs.cts(
        xs.element('Header', xs.optional(xs.cts(
            xs.any(minOccurs=0, maxOccurs=xs.unbounded)))),
        xs.element('Body', xs.optional(xs.cts(
            xs.any(minOccurs=0, maxOccurs=xs.unbounded)))),
    )),
    xs.element('Fault', xs.cts(
        xs.element('faultcode', xs.string),
        xs.element('faultstring', xs.string),
        xs.element('faultactor', xs.optional(xs.string)),
        xs.element('detail', xs.optional(xs.string)),
    )),
)

Envelope = schema['Envelope']
Fault = schema['Fault']

def make_envelope(response=None, header=None):
    envelope = {}
    if response:
        envelope['Body'] = {'_any': [response]}
    if header:
        envelope['Header'] = {'_any': [header]}

    return Envelope.normalize(envelope)

def response_tostring(response=None, header=None):
    renvelope = make_envelope(response, header)
    tree = get_root(renvelope)
    tree.attrib['soap:encodingStyle'] = 'http://www.w3.org/2001/12/soap-encoding'
    return etree.tostring(tree, encoding='utf-8')


text:
#ifndef rvpgplot_h
#define rvpgplot_h

#ifdef __cplusplus
extern "C" {
#endif

#define RIVETONLY
#include <rivet.h>

/* Rivet/Tk PGPLOT-widget package-initialization command */

int Rvpgplot_Init(Tcl_Interp *interp);

/*
 * Record the official PGPLOT device name of the widget driver.
 */
#define TK_PGPLOT_DEVICE "XRV"

/*
 * The following function returns an unambiguous PGPLOT device-specification
 * that can be used as the FILE argument of cpgbeg() to open a given PGPLOT
 * widget. It simply returns a string composed of the widget name, followed
 * by a "/" followed by TK_PGPLOT_DEVICE. Note that the returned string is
 * owned by the widget and must not be free()d or overwritten.
 */
char *rvp_device_name(Rivetobj);

/*
 * After a widget has been opened to PGPLOT (via pgopen or pgbeg), the
 * following function can be used to return the PGPLOT id of the device.
 * When multiple PGPLOT devices are open this id can then be used with
 * the PGPLOT cpgslct() function to select the widget as the currently
 * selected PGPLOT graphics device.
 *
 * If the specified widget has not been opened to pgplot, or has been
 * closed and not re-opened, then 0 will be returned.
 */
int rvp_device_id(Rivetobj);

/*
 * Convert from X window pixel coordinates (px,py) to PGPLOT
 * world coordinates (*wx,*wy).
 */
int rvp_xwin2world(Rivetobj widget, int px, int py, float *wx, float *wy);

/*
 * Convert from PGPLOT world coordinates (wx,wy) to X window
 * pixel coordinates (*px,*py).
 */
int rvp_world2xwin(Rivetobj widget, float wx, float wy, int *px, int *py);

#ifdef __cplusplus
}
#endif

#endif


text:
require 'active_model/serializer/adapter/json_api/fragment_cache'

module ActiveModel
  class Serializer
    class Adapter
      class JsonApi < Adapter
        def initialize(serializer, options = {})
          super
          serializer.root = true
          @hash = { data: [] }

          if fields = options.delete(:fields)
            @fieldset = ActiveModel::Serializer::Fieldset.new(fields, serializer.json_key)
          else
            @fieldset = options[:fieldset]
          end
        end

        def serializable_hash(options = {})
          if serializer.respond_to?(:each)
            serializer.each do |s|
              result = self.class.new(s, @options.merge(fieldset: @fieldset)).serializable_hash
              @hash[:data] << result[:data]

              if result[:included]
                @hash[:included] ||= []
                @hash[:included] |= result[:included]
              end
            end
          else
            @hash[:data] = attributes_for_serializer(serializer, @options)
            add_resource_relationships(@hash[:data], serializer)
          end
          @hash
        end

        def fragment_cache(cached_hash, non_cached_hash)
          root = false if @options.include?(:include)
          JsonApi::FragmentCache.new().fragment_cache(root, cached_hash, non_cached_hash)
        end

        private

        def add_relationships(resource, name, serializers)
          resource[:relationships] ||= {}
          resource[:relationships][name] ||= { data: [] }
          resource[:relationships][name][:data] += serializers.map { |serializer| { type: serializer.type, id: serializer.id.to_s } }
        end

        def add_relationship(resource, name, serializer, val=nil)
          resource[:relationships] ||= {}
          resource[:relationships][name] = { data: nil }

          if serializer && serializer.object
            resource[:relationships][name][:data] = { type: serializer.type, id: serializer.id.to_s }
          end
        end

        def add_included(resource_name, serializers, parent = nil)
          unless serializers.respond_to?(:each)
            return unless serializers.object
            serializers = Array(serializers)
          end
          resource_path = [parent, resource_name].compact.join('.')
          if include_assoc?(resource_path)
            @hash[:included] ||= []

            serializers.each do |serializer|
              attrs = attributes_for_serializer(serializer, @options)

              add_resource_relationships(attrs, serializer, add_included: false)

              @hash[:included].push(attrs) unless @hash[:included].include?(attrs)
            end
          end

          serializers.each do |serializer|
            serializer.each_association do |name, association, opts|
              add_included(name, association, resource_path) if association
            end if include_nested_assoc? resource_path
          end
        end

        def attributes_for_serializer(serializer, options)
          if serializer.respond_to?(:each)
            result = []
            serializer.each do |object|
              result << resource_object_for(object, options)
            end
          else
            result = resource_object_for(serializer, options)
          end
          result
        end

        def resource_object_for(serializer, options)
          options[:fields] = @fieldset && @fieldset.fields_for(serializer)
          options[:required_fields] = [:id, :type]

          cache_check(serializer) do
            attributes = serializer.attributes(options)

            result = {
              id: attributes.delete(:id).to_s,
              type: attributes.delete(:type)
            }

            result[:attributes] = attributes if attributes.any?
            result
          end
        end

        def include_assoc?(assoc)
          return false unless @options[:include]
          check_assoc("#{assoc}$")
        end

        def include_nested_assoc?(assoc)
          return false unless @options[:include]
          check_assoc("#{assoc}.")
        end

        def check_assoc(assoc)
          include_opt = @options[:include]
          include_opt = include_opt.split(',') if include_opt.is_a?(String)
          include_opt.any? do |s|
            s.match(/^#{assoc.gsub('.', '\.')}/)
          end
        end

        def add_resource_relationships(attrs, serializer, options = {})
          options[:add_included] = options.fetch(:add_included, true)

          serializer.each_association do |name, association, opts|
            attrs[:relationships] ||= {}

            if association.respond_to?(:each)
              add_relationships(attrs, name, association)
            else
              if opts[:virtual_value]
                add_relationship(attrs, name, nil, opts[:virtual_value])
              else
                add_relationship(attrs, name, association)
              end
            end

            if options[:add_included]
              Array(association).each do |association|
                add_included(name, association)
              end
            end
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<oauth2:authorization-server  client-details-service-ref="inmemoryClientDetails"  authorization-request-manager-ref="defaultOauth2RequestFactory"   token-services-ref="defaultTokenService"  user-approval-handler-ref="tokenStoreUserApproval"  check-token-enabled="true" >
 <oauth2:authorization-code disabled="false" />
 <oauth2:refresh-token disabled="false"/>
 <oauth2:password disabled="false" authentication-manager-ref="authenticationManager"/>
</oauth2:authorization-server>

<!-- oauth2 Request Factory -->
<bean id="defaultOauth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
<constructor-arg ref="inmemoryClientDetails"></constructor-arg>
<property name="checkUserScopes" value="false"></property>
</bean>

<!-- token store  12 hours-->
<bean id="defaultTokenService" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="jwtKeyStore"></property>
<property name="supportRefreshToken" value="true"></property>
<property name="tokenEnhancer" ref="tokenEnhancerChain"></property>
</bean>

<bean id="tokenEnhancerChain" class="org.springframework.security.oauth2.provider.token.TokenEnhancerChain">
<property name="tokenEnhancers">
 <list>
 <ref bean="jwtAccessTokenConverter"/>
 <bean class="com.github.sawied.microservice.authorization.token.AdditionInfoTokenEnhancer"></bean>
 </list>
</property>
</bean>

<bean id="jwtKeyStore" class="org.springframework.security.oauth2.provider.token.store.JwtTokenStore">
<constructor-arg ref="jwtAccessTokenConverter"></constructor-arg>
</bean>

 <bean id="jwtAccessTokenConverter" class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter">
 <property name="signingKey" value="secert"></property>
 </bean>

<!--
<bean id="inMemorytokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"></bean>
 -->

<bean id="tokenStoreUserApproval" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
<property name="tokenStore" ref="jwtKeyStore"></property>
<property name="clientDetailsService" ref="inmemoryClientDetails"></property>
<property name="requestFactory" ref="defaultOauth2RequestFactory"></property>
</bean>

<oauth2:client-details-service id="inmemoryClientDetails">
  <oauth2:client  client-id="api-gateway"  autoapprove="true" authorities="ROLE_CLIENT" authorized-grant-types="authorization_code,refresh_token,password"  resource-ids="sawied-resource-service" scope="read,write,user" secret="secret"/>
  <oauth2:client client-id="sawied-user-resource" secret="sawied-1990" authorities="ROLE_RESOURCE" />
</oauth2:client-details-service>

<oauth2:resource-server id="oAuth2AuthenticationProcessingFilter" resource-id="sawied-resource-service" token-services-ref="defaultTokenService" stateless="false"></oauth2:resource-server>

</beans>


text:
[![Build Status](https://travis-ci.org/lbausch/laravel-cornerstone.svg?branch=master)](https://travis-ci.org/lbausch/laravel-cornerstone)

Some helper functions for Laravel

## Documentation

### Helper functions

#### alert

Create a simple alert message.

`function alert($type, $message)`

`$type` can be one of `info`, `warning`, `error` or `success`. Requires Twitter Bootstrap to be displayed correctly.

Example usage: `alert('error', 'This didn\'t work');`

#### is_active

Checks if current request matches certain controllers and returns the string `active` if so. Useful for highlighting corresponding navigation items.

`function is_active($needles, $css_classes = ['active'])`

Example usage: `is_active('SomeController')` or `is_active(['SomeController', 'OtherController'])`. You may also specify the css classes to return with `$css_classes`.

#### link_back

Renders a back link. Takes an optional link or tries to use JavaScript.

`function link_back($target = null)`

Example usage: `link_back()` or `link_back(action('SomeController@someMethod'))`

#### redact

For use in controller methods. Replaces the `redirect(action('SomeController@someMethod'))` construct.

`function redact($name, $parameters = array(), $status = 302, $headers = array(), $secure = null)`

Added bonus: Use `_self` to refer to the Controller the function is called in. For example: `return redact('_self@index');`.

### Repositories

#### BaseRepositoryInterface

An interface for Repositories. See `src/Repositories/BaseRepositoryInterface.php` for methods you need to implement.

#### EloquentAbstractRepository

Abstract implementation for Eloquent of the above interface. Provides default implementation to extend on. See `src/Repositories/EloquentAbstractRepository.php` for actual implementation.

### Keep alive

Prevent the CSRF token from timing out. Simple send an AJAX GET request every 5 minutes to the route `lbausch/laravel-cornerstone/keepalive`. Of course this is only necessary on pages which contain a `_token` field. To achieve this with jQuery use the following snippet:

```js
if ($('input[name=_token]').length > 0) {
    setInterval(function () {
        $.get('lbausch/laravel-cornerstone/keepalive');
    }, 3e5);
}
```


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="match_parent"
              android:gravity="center"
              android:orientation="vertical"
              android:paddingLeft="@dimen/padding_container"
              android:paddingRight="@dimen/padding_container">

    <com.digits.sdk.android.DigitsAuthButton
        android:id="@+id/signup_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/verify_credentials_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/verify_credentials"/>

    <Button
        android:id="@+id/clear_session_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clear_session"/>

    <Button
        android:id="@+id/find_your_friends_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/find_your_friends"/>

    <TextView
        android:id="@+id/user_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>

    <TextView
        android:id="@+id/token"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>

    <TextView
        android:id="@+id/secret"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>
</LinearLayout>


text:
#include "splashscreen_impl.h"

#include "../libpng/png.h"

#include <setjmp.h>

#define SIG_BYTES 8

void PNGAPI
my_png_read_stream(png_structp png_ptr, png_bytep data, png_size_t length)
{
    png_uint_32 check;

    SplashStream * stream = (SplashStream*)png_ptr->io_ptr;
    check = stream->read(stream, data, length);
    if (check != length)
        png_error(png_ptr, "Read Error");
}

int
SplashDecodePng(Splash * splash, png_rw_ptr read_func, void *io_ptr)
{
    int stride;
    ImageFormat srcFormat;
    png_uint_32 i, rowbytes;
    png_bytepp row_pointers = NULL;
    png_bytep image_data = NULL;
    int success = 0;
    double gamma;

    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;

    png_uint_32 width, height;
    int bit_depth, color_type;

    ImageRect srcRect, dstRect;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png_ptr) {
        goto done;
    }

    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        goto done;
    }

    if (setjmp(png_ptr->jmpbuf)) {
        goto done;
    }

    png_ptr->io_ptr = io_ptr;
    png_ptr->read_data_fn = read_func;

    png_set_sig_bytes(png_ptr, SIG_BYTES);      /* we already read the 8 signature bytes */

    png_read_info(png_ptr, info_ptr);   /* read all PNG info up to image data */

    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
        NULL, NULL, NULL);

    /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
     * transparency chunks to full alpha channel; strip 16-bit-per-sample
     * images to 8 bits per sample; and convert grayscale to RGB[A]
     * this may be sub-optimal but this simplifies implementation */

    png_set_expand(png_ptr);
    png_set_tRNS_to_alpha(png_ptr);
    png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
    png_set_strip_16(png_ptr);
    png_set_gray_to_rgb(png_ptr);

    if (png_get_gAMA(png_ptr, info_ptr, &gamma))
        png_set_gamma(png_ptr, 2.2, gamma);

    png_read_update_info(png_ptr, info_ptr);

    rowbytes = png_get_rowbytes(png_ptr, info_ptr);

    if (!SAFE_TO_ALLOC(rowbytes, height)) {
        goto done;
    }

    if ((image_data = (unsigned char *) malloc(rowbytes * height)) == NULL) {
        goto done;
    }

    if (!SAFE_TO_ALLOC(height, sizeof(png_bytep))) {
        goto done;
    }
    if ((row_pointers = (png_bytepp) malloc(height * sizeof(png_bytep)))
            == NULL) {
        goto done;
    }

    for (i = 0; i < height; ++i)
        row_pointers[i] = image_data + i * rowbytes;

    png_read_image(png_ptr, row_pointers);

    SplashCleanup(splash);

    splash->width = width;
    splash->height = height;

    if (!SAFE_TO_ALLOC(splash->width, splash->imageFormat.depthBytes)) {
        goto done;
    }
    stride = splash->width * splash->imageFormat.depthBytes;

    if (!SAFE_TO_ALLOC(splash->height, stride)) {
        goto done;
    }
    splash->frameCount = 1;
    splash->frames = (SplashImage *)
        malloc(sizeof(SplashImage) * splash->frameCount);

    if (splash->frames == NULL) {
        goto done;
    }

    splash->loopCount = 1;
    splash->frames[0].bitmapBits = malloc(stride * splash->height);
    if (splash->frames[0].bitmapBits == NULL) {
        free(splash->frames);
        goto done;
    }
    splash->frames[0].delay = 0;

    /* FIXME: sort out the real format */
    initFormat(&srcFormat, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
    srcFormat.byteOrder = BYTE_ORDER_MSBFIRST;

    initRect(&srcRect, 0, 0, width, height, 1, rowbytes,
        image_data, &srcFormat);
    initRect(&dstRect, 0, 0, width, height, 1, stride,
        splash->frames[0].bitmapBits, &splash->imageFormat);
    convertRect(&srcRect, &dstRect, CVT_COPY);

    SplashInitFrameShape(splash, 0);

    png_read_end(png_ptr, NULL);
    success = 1;

  done:
    free(row_pointers);
    free(image_data);
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
    return success;
}

int
SplashDecodePngStream(Splash * splash, SplashStream * stream)
{
    unsigned char sig[SIG_BYTES];
    int success = 0;

    stream->read(stream, sig, SIG_BYTES);
    if (!png_check_sig(sig, SIG_BYTES)) {
        goto done;
    }
    success = SplashDecodePng(splash, my_png_read_stream, stream);

  done:
    return success;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dkc.ucfr"
    android:installLocation="auto"
    android:versionCode="2"
    android:versionName="2.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19"  />

    <application android:hardwareAccelerated="true"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.dkc.ucfr.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>


text:
Create a new Kerberos principal with a password or an optional keytab.

## Example

```js
const {$status} = await nikita.krb5.addprinc({
  admin: {
    password: 'pass',
    principal: 'me/admin@MY_REALM',
    server: 'localhost'
  },
  keytab: '/etc/security/keytabs/my.service.keytab',
  gid: 'myservice',
  principal: 'myservice/my.fqdn@MY.REALM',
  randkey: true,
  uid: 'myservice'
})
console.info(`Principal was created or modified: ${$status}`)
```

## Schema definitions

    definitions =
      config:
        type: 'object'
        properties:
          'admin':
            $ref: 'module://@nikitajs/krb5/src/execute#/definitions/config/properties/admin'
          'keytab':
            type: 'string'
            description: '''
            Path to the file storing key entries.
            '''
          'password':
            type: 'string'
            description: '''
            Password associated to this principal.
            '''
          'password_sync':
            type: 'boolean'
            default: false
            description: '''
            Wether the password should be created if the principal already exists.
            '''
          'principal':
            type: 'string'
            description: '''
            Principal to be created.
            '''
          'randkey':
            type: 'boolean'
            description: '''
            Generate a random key.
            '''
        required: ['admin', 'principal']
        oneOf: [
          {required: ['password']}
          {required: ['randkey']}
        ]

## Handler

    handler = ({config}) ->
      # Normalize realm and principal for later usage of config
      config.admin.realm ?= config.admin.principal.split('@')[1] if /.*@.*/.test config.admin?.principal
      config.principal = "#{config.principal}@#{config.admin.realm}" unless /^\S+@\S+$/.test config.principal
      # Start execution
      {$status} = await @krb5.execute
        $shy: true
        admin: config.admin
        command: "getprinc #{config.principal}"
        grep: new RegExp "^.*#{utils.regexp.escape config.principal}$"
      unless $status
        await @krb5.execute
          $retry: 3
          admin: config.admin
          command: if config.password
          then "addprinc -pw #{config.password} #{config.principal}"
          else "addprinc -randkey #{config.principal}"
      if config.password and config.password_sync
        cache_name = "/tmp/nikita_#{Math.random()}" # Ticket cache location
        await @krb5.execute
          $retry: 3
          # Test the user password
          # On success, write the ticket to a temporary location before cleanup
          $unless_execute: "if ! echo #{config.password} | kinit '#{config.principal}' -c '#{cache_name}'; then exit 1; else kdestroy -c '#{cache_name}'; fi"
          admin: config.admin
          command: "cpw -pw #{config.password} #{config.principal}"
      return unless !!config.keytab
      await @krb5.ktadd config

## Exports

    module.exports =
      handler: handler
      metadata:
        global: 'krb5'
        definitions: definitions

## Dependencies

    utils = require '@nikitajs/core/lib/utils'
    {mutate} = require 'mixme'


text:
import numpy as np

from nested_sampling.utils.rotations import vector_random_uniform_hypersphere

class Harmonic(object):
    def __init__(self, ndim):
        self.ndim = ndim

    def get_energy(self, x):
        assert len(x) == self.ndim
        return 0.5 * x.dot(x)

    def get_random_configuration(self, radius=10.):
        """ return a random vector sampled uniformly from within a hypersphere of dimensions self.ndim"""
        x = vector_random_uniform_hypersphere(self.ndim) * radius
        return x


text:
package org.apache.geronimo.st.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.util.SocketUtil;

/**
 * @version $Rev$ $Date$
 */
public class ModuleArtifactMapper {

	private static ModuleArtifactMapper instance = new ModuleArtifactMapper();

	private static final String FILE_NAME = "servermodule.info";

	ServerEntries serverEntries = null;

	private ModuleArtifactMapper() {
		if (serverEntries == null)
			serverEntries = new ServerEntries();
		load();
	}

	public static ModuleArtifactMapper getInstance() {
		return instance;
	}

	public void addEntry(IServer server, IProject project, String configId) {

		if (!SocketUtil.isLocalhost(server.getHost()))
			return;

		File runtimeLoc = server.getRuntime().getLocation().toFile();
		Map artifactEntries = (Map) serverEntries.get(runtimeLoc);
		if (artifactEntries == null) {
			artifactEntries = new HashMap();
			serverEntries.put(runtimeLoc, artifactEntries);
		}

		artifactEntries.put(project.getName(), configId);
	}

	public void removeEntry(IServer server, IModule module) {

		if (!SocketUtil.isLocalhost(server.getHost()))
			return;

		File runtimeLoc = server.getRuntime().getLocation().toFile();
		Map artifactEntries = (Map) serverEntries.get(runtimeLoc);
		if (artifactEntries != null) {
			artifactEntries.remove(module.getName());
		}
	}

	public String resolve(IServer server, IModule module) {
		Map artifactEntries = (Map) serverEntries.get(server.getRuntime().getLocation().toFile());
		if (artifactEntries != null && module != null) {
		    if(module.getProject() != null) {
		        return (String) artifactEntries.get(module.getProject().getName());
		    } else {
		        return (String) artifactEntries.get(module.getName());
		    }

		}
		return null;
	}

	public void save() {
		ObjectOutput output = null;
		try {
			IPath dest = Activator.getDefault().getStateLocation().append(FILE_NAME);
			OutputStream file = new FileOutputStream(dest.toFile());
			OutputStream buffer = new BufferedOutputStream(file);
			output = new ObjectOutputStream(buffer);
			String xml = serverEntries.toXML();
			output.writeObject(xml);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void load() {
		ObjectInput input = null;
		try {
			IPath dest = Activator.getDefault().getStateLocation().append(FILE_NAME);
			if (dest.toFile().exists()) {
				InputStream file = new FileInputStream(dest.toFile());
				InputStream buffer = new BufferedInputStream(file);
				input = new ObjectInputStream(buffer);
				String xml = (String) input.readObject();
				serverEntries.loadXML(xml);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// This Inner class is the result of removing XStream.  ModuleArtifactMapper
	// was the only class using it so it seemed silly to have two extra jar
	// files (xpp3.jar and xstream.jar) just for one class.
	// this class is a HashMap
	// keys are the files
	// entries are the Maps of artifact entries
	// this is all saved/loaded to .plugins/org.apache.geronimo.st.core/servermodule.info
    protected class ServerEntries extends HashMap {
        static final long serialVersionUID = 0;

        protected void loadXML (String xml) {
            if (xml == null || xml.length() == 0)
                return;

            String projectName, configId;
            int fileEndPos, nomapStartPos, mapStartPos, mapEndPos, stringStartPos, stringEndPos;
            int fileStartPos = xml.indexOf("<file>", 0);
            Map artifactEntries;
            while (fileStartPos > -1) {
                fileEndPos = xml.indexOf("</file>", fileStartPos);
                File runtimeLoc = new File(xml.substring(fileStartPos + 6, fileEndPos));

                nomapStartPos = xml.indexOf("<map/>", fileEndPos);
                mapStartPos = xml.indexOf("<map>", fileEndPos);
                artifactEntries = new HashMap();
                // have projects on the server
                if ((nomapStartPos == -1) || (nomapStartPos > mapStartPos)) {
                    mapEndPos = xml.indexOf("</map>", mapStartPos);
                    stringStartPos = xml.indexOf("<string>", mapStartPos);
                    while ((stringStartPos > -1) && (stringStartPos < mapEndPos)) {
                        stringEndPos = xml.indexOf("</string>", stringStartPos);
                        projectName = xml.substring(stringStartPos + 8, stringEndPos);
                        stringStartPos = xml.indexOf("<string>", stringEndPos);
                        stringEndPos = xml.indexOf("</string>", stringStartPos);
                        configId = xml.substring(stringStartPos + 8, stringEndPos);
                        artifactEntries.put(projectName, configId);
                        stringStartPos = xml.indexOf("<string>", stringEndPos);
                    }
                }
                // if no projects on the server, it is ok to put an empty HashMap
                this.put (runtimeLoc, artifactEntries);

                fileStartPos = xml.indexOf("<file>", fileEndPos);
            }
        }

        protected String toXML () {
            String xmlString = "";
            if (!isEmpty()) {
                xmlString = "<map>\n  <entry>\n";

                Object[] serverKeySet = keySet().toArray();
                for (int i = 0; i < serverKeySet.length; i++) {
                    xmlString += "    <file>" + serverKeySet[i] + "</file>\n";
                    Map projectMap = (Map)get(serverKeySet[i]);
                    if (projectMap == null || projectMap.size() == 0) {
                        xmlString += "    <map/>\n";
                    }
                    else {
                        xmlString += "    <map>\n";
                        Object[] projectKeySet = projectMap.keySet().toArray();
                        for (int j = 0; j < projectKeySet.length; j++)
                        {
                             xmlString += "      <entry>\n";
                             xmlString += "        <string>" + (String)projectKeySet[j] + "</string>\n";
                             xmlString += "        <string>" + (String)projectMap.get(projectKeySet[j]) + "</string>\n";
                             xmlString += "      </entry>\n";
                        }
                        xmlString += "    </map>\n";
                    }
                }
                xmlString += "  </entry>\n</map>";
            }
            return xmlString;
        }
    }
}


text:
#if !defined(BOOST_SPIRIT_BINARY_MAY_08_2007_0906AM)
#define BOOST_SPIRIT_BINARY_MAY_08_2007_0906AM

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once      // MS compatible compilers support #pragma once
#endif

#include <boost/spirit/home/qi/binary/binary.hpp>
#include <boost/spirit/home/qi/binary/meta_grammar.hpp>

#endif


text:
using System;
using System.Web.Mvc;

namespace CookieMVC.Web.Security
{
    public class RequireSecureConnectionAttribute : RequireHttpsAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.HttpContext.Request.IsLocal)
            {
                return;
            }

            base.OnAuthorization(filterContext);
        }
    }
}


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

namespace Ccr.Core.Collections
{
	[Serializable]
  public struct BijectiveIsomorphicMorphism<TA, TB>
    : IBijectiveMorphism<TA, TB>
  {
    public TA A { get; }

    public TB B { get; }

    public BijectiveIsomorphicMorphism<TB, TA> InverseMorphism
    {
      get => new BijectiveIsomorphicMorphism<TB, TA>(B, A);
    }

    IBijectiveMorphism<TB, TA> IBijectiveMorphism<TA, TB>.BijectiveInverse
    {
      get => InverseMorphism;
    }

    IIsomorphicMorphism<TB, TA> IIsomorphicMorphism<TA, TB>.IsomorphicInverse
    {
      get => InverseMorphism;
    }

    public BijectiveIsomorphicMorphism(TA a, TB b)
    {
      A = a;
      B = b;
    }

    public static implicit operator KeyValuePair<TA, TB>(
      BijectiveIsomorphicMorphism<TA, TB> @this)
    {
      return new KeyValuePair<TA, TB>(
        @this.A,
        @this.B);
    }

    public static implicit operator BijectiveIsomorphicMorphism<TA, TB>(
      KeyValuePair<TA, TB> @this)
    {
      return new BijectiveIsomorphicMorphism<TA, TB>(
        @this.Key,
        @this.Value);
    }

    public TB Evaluate(TA a)
    {
      return B;
    }

    public TA EvaluateInverse(TB b)
    {
      return A;
    }

    public override string ToString()
    {
      return $"[{A}, {B}]";
    }
  }
}


text:
<?php

/*
	Begin Boilerplate Admin panel.
*/

/*	Define Boilerplate URI */
	define('BP_THEME_URL', get_template_directory_uri());

/*
	There are essentially 5 sections to this:
	1)	Add "Boilerplate Admin" link to left-nav Admin Menu & callback function for clicking that menu link
	2)	Add Admin Page CSS if on the Admin Page
	3)	Add "Boilerplate Admin" Page options
	4)	Create functions to add above elements to pages
	5)	Add Boilerplate options to page as requested
*/

/*	1)	Add "Boilerplate Admin" link to left-nav Admin Menu & callback function for clicking that menu link */

	//	Add option if in Admin Page
	if ( ! function_exists( 'create_boilerplate_admin_page' ) ):
		function create_boilerplate_admin_page() {
			add_theme_page('Boilerplate Admin', 'Boilerplate Admin', 'administrator', 'boilerplate-admin', 'build_boilerplate_admin_page');
		}
		add_action('admin_menu', 'create_boilerplate_admin_page');
	endif; // create_boilerplate_admin_page

	//	You get this if you click the left-column "Boilerplate Admin" (added above)
	if ( ! function_exists( 'build_boilerplate_admin_page' ) ):
		function build_boilerplate_admin_page() {
		?>

Boilerplate Admin

So, there's actually a tremendous amount going on here.  If you're not familiar with HTML5 Boilerplate or the Starkers theme (upon which this theme is based) you should check them out.

Choose below which options you want included in your site.

The clumsiest part of this plug-in is dealing with the CSS files.  Check the <a href="<?php echo BP_THEME_URL ?>/readme.txt">Read Me file for details on how I suggest handling them.

				<form method="post" action="options.php" enctype="multipart/form-data">
					<?php settings_fields('plugin_options'); /* very last function on this page... */ ?>
					<?php do_settings_sections('boilerplate-admin'); /* let's get started! */?>

<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>">

				</form>

		<?php
		}
	endif; // build_boilerplate_admin_page

/*	2)	Add Admin Page CSS if on the Admin Page */
	if ( ! function_exists( 'admin_register_head' ) ):
		function admin_register_head() {
			echo '<link rel="stylesheet" href="' .BP_THEME_URL. '/boilerplate-admin/admin-style.css">'.PHP_EOL;
		}
		add_action('admin_head', 'admin_register_head');
	endif; // admin_register_head

/*	3)	Add "Boilerplate Admin" Page options */
	//	Register form elements
	if ( ! function_exists( 'register_and_build_fields' ) ):
		function register_and_build_fields() {
			register_setting('plugin_options', 'plugin_options', 'validate_setting');
			add_settings_section('main_section', '', 'section_cb', 'boilerplate-admin');
			add_settings_field('toolbar', 'IE6 Image Toolbar?:', 'toolbar_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('google_chrome', 'IE-edge / Google Chrome?:', 'google_chrome_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('google_verification', 'Google Verification?:', 'google_verification_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('viewport', 'iThings use full zoom?:', 'viewport_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('favicon', 'Got Favicon?:', 'favicon_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('favicon_ithing', 'Got iThing Favicon?', 'favicon_ithing_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('ie_css', 'IE CSS?:', 'ie_css_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('modernizr_js', 'Modernizr JS?:', 'modernizr_js_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('respond_js', 'Respond JS?:', 'respond_js_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('jquery_js', 'jQuery JS?:', 'jquery_js_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('plugins_js', 'jQuery Plug-ins JS?:', 'plugins_js_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('site_js', 'Site-specific JS?:', 'site_js_setting', 'boilerplate-admin', 'main_section');
			add_settings_field('cache_buster', 'Cache-Buster?:', 'cache_buster_setting', 'boilerplate-admin', 'main_section');
		}
		add_action('admin_init', 'register_and_build_fields');
	endif; // register_and_build_fields

	//	Add Admin Page validation
	if ( ! function_exists( 'validate_setting' ) ):
		function validate_setting($plugin_options) {
			$keys = array_keys($_FILES);
			$i = 0;
			foreach ( $_FILES as $image ) {
				// if a files was upload
				if ($image['size']) {
					// if it is an image
					if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) {
						$override = array('test_form' => false);
						// save the file, and store an array, containing its location in $file
						$file = wp_handle_upload( $image, $override );
						$plugin_options[$keys[$i]] = $file['url'];
					} else {
						// Not an image.
						$options = get_option('plugin_options');
						$plugin_options[$keys[$i]] = $options[$logo];
						// Die and let the user know that they made a mistake.
						wp_die('No image was uploaded.');
					}
				} else { // else, the user didn't upload a file, retain the image that's already on file.
					$options = get_option('plugin_options');
					$plugin_options[$keys[$i]] = $options[$keys[$i]];
				}
				$i++;
			}
			return $plugin_options;
		}
	endif; // validate_setting

	//	Add Admin Page options

	//	in case you need it...
	if ( ! function_exists( 'section_cb' ) ):
		function section_cb() {}
	endif; // section_cb

	//	callback fn for toolbar
	if ( ! function_exists( 'toolbar_setting' ) ):
		function toolbar_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['toolbar']) && $options['toolbar']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[toolbar]" value="true" ' .$checked. '/>';
			echo '
Kill the IE6 Image Toolbar that appears when users hover over images on your site.
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<meta http-equiv="imagetoolbar" content="false">';
		}
	endif; // toolbar_setting

	//	callback fn for google_chrome
	if ( ! function_exists( 'google_chrome_setting' ) ):
		function google_chrome_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['google_chrome']) && $options['google_chrome']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[google_chrome]" value="true" ' .$checked. '/>';
			echo '
Force the most-recent IE rendering engine or users with Google Chrome Frame installed to see your site using Google Frame.
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">';
		}
	endif; // google_chrome_setting

	//	callback fn for google_verification
	if ( ! function_exists( 'google_verification_setting' ) ):
		function google_verification_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['google_verification']) && $options['google_verification'] && $options['google_verification_account'] && $options['google_verification_account'] !== 'XXXXXXXXX...') ? 'checked="checked" ' : '';
			$account = (isset($options['google_verification_account']) && $options['google_verification_account']) ? $options['google_verification_account'] : 'XXXXXXXXX...';
			$msg = ($account === 'XXXXXXXXX...') ? ', where XXXXXXXXX... will be replaced with the code you insert above' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[google_verification]" value="true" ' .$checked. '/>';
			echo '
Add Google Verificaton code to the <head> of all your pages.
';
			echo '
To include Google Verificaton, select this option and include your Verificaton number here:
';
			echo '<input type="text" size="40" name="plugin_options[google_verification_account]" value="'.$account.'" onfocus="javascript:if(this.value===\'XXXXXXXXX...\'){this.select();}">
';
			echo '
Selecting this option will add the following code to the <head> of your pages'.$msg.'
';
			echo '<meta name="google-site-verification" content="'.$account.'">';
		}
	endif; // google_verification_setting

	//	callback fn for viewport
	if ( ! function_exists( 'viewport_setting' ) ):
		function viewport_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['viewport']) && $options['viewport']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[viewport]" value="true" ' .$checked. '/>';
			echo '
Force iThings to show site at full-zoom, instead of trying to show the entire page.
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<meta name="viewport" content="width=device-width">';
		}
	endif; // viewport_setting

	//	callback fn for favicon
	if ( ! function_exists( 'favicon_setting' ) ):
		function favicon_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['favicon']) && $options['favicon']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[favicon]" value="true" ' .$checked. '/>';
			echo '
If you plan to use a favicon for your site, place the "favicon.ico" file in the root directory of your site.
';
			echo '
If the file is in the right location, you don\'t really need to select this option, browsers will automatically look there and no additional code will be added to your pages.
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<link rel="shortcut icon" href="/favicon.ico">';
		}
	endif; // favicon_setting

	//	callback fn for favicon_ithing
	if ( ! function_exists( 'favicon_ithing_setting' ) ):
		function favicon_ithing_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['favicon_ithing']) && $options['favicon_ithing']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[favicon_ithing]" value="true" ' .$checked. '/>';
			echo '
To allow iThing users to add an icon for your site to their Home screen, place the "apple-touch-icon.png" file in the root directory of your site.
';
			echo '
If the file is in the right location, you don\'t really need to select this option, browsers will automatically look there and no additional code will be added to your pages.
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<link rel="apple-touch-icon" href="/apple-touch-icon.png">';
			echo '<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">';
			echo '<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">';
			echo '<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">';
		}
	endif; // favicon_ithing_setting

	//	callback fn for ie_css
	if ( ! function_exists( 'ie_css_setting' ) ):
		function ie_css_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['ie_css']) && $options['ie_css']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[ie_css]" value="true" ' .$checked. '/>';
			echo '
If you would like to add a IE-specific CSS file, Boilerplate provides a starter file located in:
';
			echo '' .BP_THEME_URL. '/css/ie-starter.css';
			echo '
I recommend adding any custom IE-specific CSS to this file and either copying from the starter file or using an @import to add the starter file rather than editing the starter file itself.  This will help to avoid your changes being overwritten during upgrades.
';
			echo '
And remember, you don\'t need IE-specific hacks if you activate the IE-Conditional <html> above, because you can target IE specifically by using the IE classes that are being added to <html>.  Sweet!
';
			echo '
Selecting this option will add the following code to the <head> of your pages:
';
			echo '<!--[if IE ]><link rel="stylesheet" href="' .BP_THEME_URL. '/css/ie.css"><![endif]-->';
		}
	endif; // ie_css_setting

	//	callback fn for modernizr_js
	if ( ! function_exists( 'modernizr_js_setting' ) ):
		function modernizr_js_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['modernizr_js']) && $options['modernizr_js']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[modernizr_js]" value="true" ' .$checked. '/>';
			echo '
Modernizr is a JS library that appends classes to the <html> that indicate whether the user\'s browser is capable of handling advanced CSS, like "cssreflections" or "no-cssreflections".  It\'s a really handy way to apply varying CSS techniques, depending on the user\'s browser\'s abilities, without resorting to CSS hacks.
';
			echo '
Selecting this option will add the following code to the <head> of your pages (note the lack of a version, when you\'re ready to upgrade, simply copy/paste the new version into the file below, and your site is ready to go!):
';
			echo '<script src="' .BP_THEME_URL. '/js/modernizr.js"></script>';
			echo '
Note: If you do not include Modernizr, the IEShiv JS will be added to accommodate the HTML5 elements used in Boilerplate in weaker browsers:
';
			echo '<!--[if lt IE 9]>';
			echo '	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js" onload="window.ieshiv=true;"></script>';
			echo '	<script>!window.ieshiv && document.write(unescape(\'%3Cscript src="' .BP_THEME_URL. '/js/ieshiv.js"%3E%3C/script%3E\'))</script>';
			echo '<![endif]-->';
		}
	endif; // modernizr_js_setting

	//	callback fn for respond_js
	if ( ! function_exists( 'respond_js_setting' ) ):
		function respond_js_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['respond_js']) && $options['respond_js']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[respond_js]" value="true" ' .$checked. '/>';
			echo '
Respond.js is a JS library that helps IE<=8 understand @media queries, specifically min-width and max-width, allowing you to more reliably implement responsive design across all browsers.
';
			echo '
Selecting this option will add the following code to the <head> of your pages (note the lack of a version, when you\'re ready to upgrade, simply copy/paste the new version into the file below, and your site is ready to go!):
';
			echo '<script src="' .BP_THEME_URL. '/js/respond.js"></script>';
		}
	endif; // respond_js_setting

	//	callback fn for jquery_js
	if ( ! function_exists( 'jquery_js_setting' ) ):
		function jquery_js_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['jquery_js']) && $options['jquery_js']) ? 'checked="checked" ' : '';
			$version = (isset($options['jquery_version']) && $options['jquery_version'] && $options['jquery_version'] !== '') ? $options['jquery_version'] : '1.7.1';
			$inhead = (isset($options['jquery_head']) && $options['jquery_head']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[jquery_js]" value="true" ' .$checked. '/>';
			echo '
jQuery is a JS library that aids greatly in developing high-quality JavaScript quickly and efficiently.
';
			echo '
Selecting this option will add the following code to your pages just before the </body>:
';
			echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/'.$version.'/jquery.min.js"></script>';
			echo '<script>!window.jQuery && document.write(unescape(\'%3Cscript src="'.BP_THEME_URL.'/js/jquery.js"%3E%3C/script%3E\'))</script>';
			echo '
<input class="check-field" type="checkbox" name="plugin_options[jquery_head]" value="true" ' .$inhead. '/>';
			echo 'Note: Best-practices recommend that you load JS as close to the </body> as possible.  If for some reason you would prefer jQuery and jQuery plug-ins to be in the <head>, please select this option.
';
			echo '
The above code first tries to download jQuery from Google\'s CDN (which might be available via the user\'s browser cache).  If this is not successful, it uses the theme\'s version.
';
			echo '
Note: This plug-in tries to keep current with the most recent version of jQuery.  If for some reason you would prefer to use another version, please indicate that version:
';
			echo '<input type="text" size="6" name="plugin_options[jquery_version]" value="'.$version.'"> (see all versions available via Google\'s CDN)
';
		}
	endif; // jquery_js_setting

	//	callback fn for plugins_js
	if ( ! function_exists( 'plugins_js_setting' ) ):
		function plugins_js_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['plugins_js']) && $options['plugins_js']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[plugins_js]" value="true" ' .$checked. '/>';
			echo '
If you choose to use any jQuery plug-ins, I recommend downloading and concatenating them together in a single JS file, as below.  This will reduce your site\'s HTTP Requests, making your site a better experience.
';
			echo '
Selecting this option will add the following code to your pages just before the </body>:
';
			echo '<script type=\'text/javascript\' src=\'' .BP_THEME_URL. '/js/plug-in.js?ver=x\'></script>';
			echo '
(The single quotes and no-longer-necessary attributes are from WP, would like to fix that... maybe next update...)
';
			echo '
Note: If you do not include jQuery, this file will not be added to the page.
';
		}
	endif; // plugins_js_setting

	//	callback fn for site_js
	if ( ! function_exists( 'site_js_setting' ) ):
		function site_js_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['site_js']) && $options['site_js']) ? 'checked="checked" ' : '';
			echo '<input class="check-field" type="checkbox" name="plugin_options[site_js]" value="true" ' .$checked. '/>';
			echo '
If you would like to add your own site JavaScript file, Boilerplate provides a starter file located in:
';
			echo '' .BP_THEME_URL. '/js/script-starter.js';
			echo '
Add what you want to that file and select this option.
';
			echo '
Selecting this option will add the following code to your pages just before the </body>:
';
			echo '<script type=\'text/javascript\' src=\'' .BP_THEME_URL. '/js/script-starter.js?ver=x\'></script>';
			echo '
(The single quotes and no-longer-necessary attributes are from WP, would like to fix that... maybe next update...)
';
		}
	endif; // site_js_setting

	//	callback fn for cache_buster
	if ( ! function_exists( 'cache_buster_setting' ) ):
		function cache_buster_setting() {
			$options = get_option('plugin_options');
			$checked = (isset($options['cache_buster']) && $options['cache_buster']) ? 'checked="checked" ' : '';
			$version = (isset($options['cache_buster_version']) && $options['cache_buster_version']) ? $options['cache_buster_version'] : '1';
			echo '<input class="check-field" type="checkbox" name="plugin_options[cache_buster]" value="true" ' .$checked. '/>';
			echo '
To force browsers to fetch a new version of a file, versus one it might already have cached, you can add a "cache buster" to the end of your CSS and JS files.  ';
			echo 'To increment the cache buster version number, type something here:
';
			echo '<input type="text" size="4" name="plugin_options[cache_buster_version]" value="'.$version.'">
';
			echo '
Selecting this option will add the following code to the end of all of your CSS and JS file names on all of your pages:
';
			echo '?ver='.$version.'';
		}
	endif; // cache_buster_setting

/*	4)	Create functions to add above elements to pages */

	//	$options['toolbar']
	if ( ! function_exists( 'add_toolbar' ) ):
		function add_toolbar() {
			echo '<meta http-equiv="imagetoolbar" content="false">'.PHP_EOL;
		}
	endif; // add_toolbar

	//	$options['google_chrome']
	if ( ! function_exists( 'add_google_chrome' ) ):
		function add_google_chrome() {
			echo '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">'.PHP_EOL;
		}
	endif; // add_google_chrome

	//	$options['google_verification']
	if ( ! function_exists( 'add_google_verification' ) ):
		function add_google_verification() {
			$options = get_option('plugin_options');
			$account = $options['google_verification_account'];
			echo '<meta name="google-site-verification" content="'.$account.'">'.PHP_EOL;
		}
	endif; // add_google_verification

	//	$options['viewport']
	if ( ! function_exists( 'add_viewport' ) ):
		function add_viewport() {
			echo '<meta name="viewport" content="width=device-width">'.PHP_EOL;
		}
	endif; // add_viewport

	//	$options['favicon']
	if ( ! function_exists( 'add_favicon' ) ):
		function add_favicon() {
			echo '<link rel="shortcut icon" href="/favicon.ico">'.PHP_EOL;
		}
	endif; // add_favicon

	//	$options['favicon_ithing']
	if ( ! function_exists( 'add_favicon_ithing' ) ):
		function add_favicon_ithing() {
			echo '<link rel="apple-touch-icon" href="/apple-touch-icon.png">'.PHP_EOL;
			echo '<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">'.PHP_EOL;
			echo '<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">'.PHP_EOL;
			echo '<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">'.PHP_EOL;
		}
	endif; // add_favicon_ithing

	//	$options['ie_css'];
	if ( ! function_exists( 'add_ie_stylesheet' ) ):
		function add_ie_stylesheet() {
			$cache = cache_buster();
			echo ''.PHP_EOL;
		}
	endif; // add_ie_stylesheet

	//	$options['modernizr_js']
	if ( ! function_exists( 'add_modernizr_script' ) ):
		function add_modernizr_script() {
			$cache = cache_buster();
			wp_deregister_script( 'ieshiv' ); // get rid of IEShiv if it somehow got called too (IEShiv is included in Modernizr)
			wp_deregister_script( 'modernizr' ); // get rid of any native Modernizr
			echo ''.PHP_EOL;
		}
	endif; // add_modernizr_script

	//	$options['ieshiv_script']
	if ( ! function_exists( 'add_ieshiv_script' ) ):
		function add_ieshiv_script() {
			$cache = cache_buster();
			echo ''.PHP_EOL;
		}
	endif; // add_ieshiv_script

	//	$options['respond_js']
	if ( ! function_exists( 'add_respond_script' ) ):
		function add_respond_script() {
			$cache = cache_buster();
			echo ''.PHP_EOL;
		}
	endif; // add_respond_script

	//	$options['jquery_js']
	if ( ! function_exists( 'add_jquery_script' ) ):
		function add_jquery_script() {
			$cache = cache_buster();
			$options = get_option('plugin_options');
			$version = ($options['jquery_version']) ? $options['jquery_version'] : '1.7.1';
			wp_deregister_script( 'jquery' ); // get rid of WP's jQuery
			echo ''.PHP_EOL; // try getting from CDN
			echo ''.PHP_EOL; // fallback to local if CDN fails
		}
	endif; // add_jquery_script

	//	$options['plugins_js']
	if ( ! function_exists( 'add_plugin_script' ) ):
		function add_plugin_script() {
			$cache = cache_buster();
			echo ''.PHP_EOL;
		}
	endif; // add_plugin_script

	//	$options['site_js']
	if ( ! function_exists( 'add_site_script' ) ):
		function add_site_script() {
			$cache = cache_buster();
			echo ''.PHP_EOL;
		}
	endif; // add_site_script

	//	$options['cache_buster']
	if ( ! function_exists( 'cache_buster' ) ):
		function cache_buster() {
			$options = get_option('plugin_options');
			return (isset($options['cache_buster']) && $options['cache_buster']) ? '?ver='.$options['cache_buster_version'] : '';
		}
	endif; // cache_buster

/*	5)	Add Boilerplate options to page as requested */
		if (!is_admin() ) {

			// get the options
			$options = get_option('plugin_options');

			// check if each option is set (meaning it exists) and check if it is true (meaning it was checked)
			if (isset($options['toolbar']) && $options['toolbar']) {
				// if yes to both, apply option
				add_action('wp_print_styles', 'add_toolbar');
			}

			if (isset($options['google_chrome']) && $options['google_chrome']) {
				add_action('wp_print_styles', 'add_google_chrome');
			}

			if (isset($options['google_verification']) && $options['google_verification'] && $options['google_verification_account'] && $options['google_verification_account'] !== 'XXXXXXXXX...') {
				add_action('wp_print_styles', 'add_google_verification');
			}

			if (isset($options['viewport']) && $options['viewport']) {
				add_action('wp_print_styles', 'add_viewport');
			}

			if (isset($options['favicon']) && $options['favicon']) {
				add_action('wp_print_styles', 'add_favicon');
			}

			if (isset($options['favicon_ithing']) && $options['favicon_ithing']) {
				add_action('wp_print_styles', 'add_favicon_ithing');
			}

			if (isset($options['modernizr_js']) && $options['modernizr_js']) {
				add_action('wp_print_styles', 'add_modernizr_script');
			} else {
				// if Modernizr isn't selected, add IEShiv inside an IE Conditional Comment
				add_action('wp_print_styles', 'add_ieshiv_script');
			}

			if (isset($options['respond_js']) && $options['respond_js']) {
				add_action('wp_print_styles', 'add_respond_script');
			}

			if (isset($options['ie_css']) && $options['ie_css']) {
				add_action('wp_print_styles', 'add_ie_stylesheet');
			}

			if (isset($options['jquery_js']) && $options['jquery_js'] && isset($options['jquery_version']) && $options['jquery_version'] && $options['jquery_version'] !== '') {
				// check if should be loaded in  or at end of
				$hook = (isset($options['jquery_head']) && $options['jquery_head']) ? 'wp_print_styles' : 'wp_footer';
				add_action($hook, 'add_jquery_script');
			}
			// for jQuery plug-ins, make sure jQuery was also set
			if (isset($options['jquery_js']) && $options['jquery_js'] && isset($options['plugins_js']) && $options['plugins_js']) {
				// check if should be loaded in  or at end of
				$hook = (isset($options['jquery_head']) && $options['jquery_head']) ? 'wp_print_styles' : 'wp_footer';
				add_action($hook, 'add_plugin_script');
			}

			if (isset($options['site_js']) && $options['site_js']) {
				add_action('wp_footer', 'add_site_script');
			}

		} // if (!is_admin() )

?>


text:
pagetitle: Of the sacraments, part 5
date: February 19, 2020
prev_url: /westminster-daily/11/17/
prev_date: Nov 17
this_url: /westminster-daily/11/18/
short_date: "1118"
this_date: Nov 18
next_url: /westminster-daily/11/19/
next_date: Nov 19
---

#### Confession of Faith

##### Chapter 27: Of the Sacraments

The sacraments of the old testament, in regard of the spiritual things thereby signified and exhibited, were, for substance, the same with those of the new.[^fnref:wcf1]

[^fnref:wcf1]:

1 Corinthians 10:1-4

10:1 For I want you to know, brothers, that our fathers were all under the cloud, and all passed through the sea, and all were baptized into Moses in the cloud and in the sea, and all ate the same spiritual food, and all drank the same spiritual drink. For they drank from the spiritual Rock that followed them, and the Rock was Christ.  (ESV)


text:
extern std::string FLAGS_jlog_out;
extern bool FLAGS_jlog_suppress_log;

namespace jlog_internal {
double get_current_time_sec();
long get_memory_usage();

struct json_node {
  virtual ~json_node() {};
  virtual void print(std::ostream &os, int depth, bool last) = 0;
};

struct json_parent : json_node {
  std::vector<std::string> keys;
  std::map<std::string, json_node*> children;

  virtual void print(std::ostream &os, int depth, bool last) {
    os << "{" << std::endl;
    for (size_t i = 0; i < keys.size(); ++i) {
      os << std::string(depth + 2, ' ') << "\"" << keys[i] << "\": ";
      children[keys[i]]->print(os, depth + 2, i + 1 == keys.size());
    }
    os << std::string(depth, ' ')
       << (last ? "}" : "},")
       << std::endl;
  }
};

template<typename value_t> struct json_leaf : json_node {
  std::string value;

  virtual void set_value(value_t v) {
    std::stringstream ss;
    ss << v;
    ss >> value;
  }

  virtual void print(std::ostream &os, int, bool last) {
    os << "\"" << value << (last ? "\"" : "\",") << std::endl;
  }
};

template<typename value_t> struct json_leaf_numerical : json_node {
  value_t value;

  virtual void set_value(value_t v) {
    value = v;
  }

  virtual void print(std::ostream &os, int, bool last) {
    os << value << (last ? "" : ",") << std::endl;
  }
};

template<> struct json_leaf<unsigned long long> : json_leaf_numerical<unsigned long long> {};
template<> struct json_leaf<long long> : json_leaf_numerical<long long> {};
template<> struct json_leaf<unsigned long> : json_leaf_numerical<unsigned long> {};
template<> struct json_leaf<long> : json_leaf_numerical<long> {};
template<> struct json_leaf<unsigned int> : json_leaf_numerical<unsigned int> {};
template<> struct json_leaf<int> : json_leaf_numerical<int> {};
template<> struct json_leaf<unsigned short> : json_leaf_numerical<unsigned short> {};
template<> struct json_leaf<short> : json_leaf_numerical<short> {};
template<> struct json_leaf<long double> : json_leaf_numerical<long double> {};
template<> struct json_leaf<double> : json_leaf_numerical<double> {};
template<> struct json_leaf<float> : json_leaf_numerical<float> {};

template<> struct json_leaf<bool> : json_node {
  bool value;

  virtual void set_value(bool v) {
    value = v;
  }

  virtual void print(std::ostream &os, int, bool last) {
    os << (value ? "true" : "false") << (last ? "" : ",") << std::endl;
  }
};

struct json_array : json_node {
  std::vector<json_node*> children;

  virtual void print(std::ostream &os, int depth, bool last) {
    os << "[" << std::endl;
    for (size_t i = 0; i < children.size(); ++i) {
      os << std::string(depth + 2, ' ');
      children[i]->print(os, depth + 2, i + 1 == children.size());
    }
    os << std::string(depth, ' ')
       << (last ? "]" : "],")
       << std::endl;
  }
};

class jlog {
 public:
  template<typename value_t>
  static void jlog_put(const char *path, value_t value,
                       bool glog) {
    if (instance_.filename_.empty() && !instance_.already_warned_) {
      std::cerr << "WARNING: Logging without calling JLOG_INIT is written to STDOUT" << std::endl;
      instance_.already_warned_ = true;
    }

    if (instance_.nested_glog_flag_ && glog) {
      LOG() << path << " = " << value << std::endl;
    }

    json_node *&jn = instance_.reach_path(path);
    json_leaf<value_t> *jl = new json_leaf<value_t>;
    jl->set_value(value);
    jn = jl;
  }

  template<typename value_t>
  static void jlog_add(const char *path, value_t value,
                       bool glog) {
    if (instance_.filename_.empty() && !instance_.already_warned_) {
      std::cerr << "WARNING: Logging without calling JLOG_INIT is written to STDOUT" << std::endl;
      instance_.already_warned_ = true;
    }

    if (instance_.nested_glog_flag_ && glog) {
      LOG() << path << " = " << value << std::endl;
    }

    json_node *&jn = instance_.reach_path(path);
    if (jn == NULL) jn = new json_array;
    json_array *ja = dynamic_cast<json_array*>(jn);
    assert(ja);
    json_leaf<value_t> *jl = new json_leaf<value_t>;
    jl->set_value(value);
    ja->children.push_back(jl);
  }

  static void init(int argc, char **argv) {
    const char *slash = strrchr(argv[0], '/');
    instance_.program_name_ = slash ? slash + 1 : argv[0];

    struct utsname u;
    if (0 != uname(&u)) {
      *u.nodename = '\0';
    }

    time_t timestamp = time(NULL);
    struct ::tm tm_time;
    localtime_r(&timestamp, &tm_time);

    std::ostringstream os;
    os.fill('0');
    os << instance_.program_name_ << "."
       << u.nodename << "."
       // << getenv("USER") << "."
       << "jlog."
       << std::setw(2) << (1900 + tm_time.tm_year) % 100
       << std::setw(2) << 1+tm_time.tm_mon
       << std::setw(2) << tm_time.tm_mday
       << '-'
       << std::setw(2) << tm_time.tm_hour
       << std::setw(2) << tm_time.tm_min
       << std::setw(2) << tm_time.tm_sec
       << '.'
       << getpid();

    instance_.filename_ = os.str();
    LOG() << "JLOG: " << instance_.filename_ << std::endl;

    jlog_put("run.program", instance_.program_name_, true);
    for (int i = 0; i < argc; ++i) {
      jlog_add("run.args", argv[i], true);
    }
    jlog_put("run.machine", u.nodename, true);
    {
      char buf[256];
      strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &tm_time);
      jlog_put("run.date", buf, true);
    }
    jlog_put("run.user", getenv("USER"), true);
    jlog_put("run.pid", getpid(), true);

    instance_.start_time_ = get_current_time_sec();
  }

 private:
  static std::ostream &LOG() {
    if (FLAGS_jlog_suppress_log) {
      return null_ostream;
    }
    time_t timestamp = time(NULL);
    struct ::tm tm_time;
    localtime_r(&timestamp, &tm_time);

    std::cerr.fill('0');
    std::cerr
        << '['
        << std::setw(2) << 1+tm_time.tm_mon
        << std::setw(2) << tm_time.tm_mday
        << ' '
        << std::setw(2) << tm_time.tm_hour << ':'
        << std::setw(2) << tm_time.tm_min << ':'
        << std::setw(2) << tm_time.tm_sec << "] ";
    return std::cerr;
  }

  jlog() : already_warned_(false), nested_glog_flag_(true) {
    current_ = &root_;
  }

  ~jlog() {
    if (filename_.empty()) {
      if (!root_.children.empty()) {
        root_.print(std::cout, 0, true);
      }
    } else {
      jlog_put("run.time", get_current_time_sec() - start_time_, true);
      jlog_put("run.memory", get_memory_usage(), true);

      if (0 != system(("mkdir -p " + FLAGS_jlog_out).c_str())) {
        perror("mkdir");
      }
      std::ofstream ofs((FLAGS_jlog_out + "/" + filename_).c_str());
      if (!ofs) {
        perror("ofstream");
        LOG() << "JLOG: Failed to open output file, write to STDERR" << std::endl;
        root_.print(std::cout, 0, true);
      }
      root_.print(ofs, 0, true);
      LOG() << "JLOG: " << FLAGS_jlog_out + "/" + filename_ << std::endl;

      std::ostringstream os;
      std::string linkname = FLAGS_jlog_out + "/" + std::string(program_name_);

      if (0 != system(("rm -rf " + linkname).c_str())) {
        perror("rm");
      }
      if (0 != symlink(filename_.c_str(), linkname.c_str())) {
        perror("symlink");
      }
    }
  }

  json_node *&reach_path(const char *path) {
    std::string s(path);
    assert(!s.empty());
    for (size_t i = 0; i < s.length(); ++i) {
      if (s[i] == '.') s[i] = ' ';
    }
    std::istringstream iss(s);

    json_node **jn = &current_;
    for (std::string t; iss >> t; ) {
      if (*jn == NULL) *jn = new json_parent();
      json_parent *jp = dynamic_cast<json_parent*>(*jn);
      assert(jp != NULL);
      if (jp->children[t] == NULL) jp->keys.push_back(t);
      jn = &jp->children[t];
      assert(jn);
    }

    return *jn;
  }

  json_parent root_;
  json_node *current_;
  bool already_warned_;
  bool nested_glog_flag_;

  static std::ostream null_ostream;

  const char *program_name_;
  std::string filename_;
  double start_time_;

  static jlog instance_;

  friend class jlog_opener;
  friend class jlog_add_opener;
};

class jlog_opener {
 public:
  jlog_opener(bool add, const char *path, bool glog = true) {
    if (add == false) {
      prev_ = jlog::instance_.current_;
      json_node *& jn = jlog::instance_.reach_path(path);
      if (jn == NULL) jn = new json_parent;
      jlog::instance_.current_ = jn;
    } else {
      prev_ = jlog::instance_.current_;
      json_node *& jn = jlog::instance_.reach_path(path);
      if (jn == NULL) jn = new json_array;
      json_array *ja = dynamic_cast<json_array*>(jn);
      assert(ja);
      ja->children.push_back(new json_parent);
      jlog::instance_.current_ = ja->children.back();
    }

    prev_glog_flag_ = jlog::instance_.nested_glog_flag_;
    jlog::instance_.nested_glog_flag_ = glog;
  }

  ~jlog_opener() {
    jlog::instance_.current_ = prev_;
    jlog::instance_.nested_glog_flag_ = prev_glog_flag_;
  }

  operator bool() {
    return false;
  }

 private:
  json_node *prev_;
  bool prev_glog_flag_;
};

class jlog_benchmarker {
 public:
  jlog_benchmarker(bool add, const char *path, bool glog = true)
      : path_(path), add_(add), glog_(glog) {
    start_ = get_current_time_sec();
  }

  ~jlog_benchmarker() {
    double r = get_current_time_sec() - start_;
    if (add_) {
      jlog::jlog_add(path_, r, glog_);
    } else {
      jlog::jlog_put(path_, r, glog_);
    }
  }

  operator bool() {
    return false;
  }

 private:
  const char *path_;
  bool add_;
  double start_;
  bool glog_;
};
}  // namespace jlog_internal

#define JLOG_OPEN(...)                                              \
  if (jlog_internal::jlog_opener o__                                \
      = jlog_internal::jlog_opener(false, __VA_ARGS__)); else

#define JLOG_ADD_OPEN(...)                                          \
  if (jlog_internal::jlog_opener o__                                \
      = jlog_internal::jlog_opener(true, __VA_ARGS__)); else

#define JLOG_PUT_BENCHMARK(...)                                     \
  if (jlog_internal::jlog_benchmarker o__                           \
      = jlog_internal::jlog_benchmarker(false, __VA_ARGS__)); else

#define JLOG_ADD_BENCHMARK(...)                                     \
  if (jlog_internal::jlog_benchmarker o__                           \
      = jlog_internal::jlog_benchmarker(true, __VA_ARGS__)); else

template<typename value_t>
inline void JLOG_PUT(const char *path, value_t value, bool glog = true) {
  jlog_internal::jlog::jlog_put(path, value, glog);
}

template<typename value_t>
inline void JLOG_ADD(const char *path, value_t value, bool glog = true) {
  jlog_internal::jlog::jlog_add(path, value, glog);
}

void JLOG_INIT(int *argc, char **argv);

#endif  // JLOG_H_


text:
/*!
\page test_report Test Report

- \link com::caoym::WinRobotTest JUnit Test Cases \endlink
- XP x86 Test Report
- Vista x86 Test Report
- Win7 x86 Test Report
- Win7 x64 Test Report
*/


text:
"""
Created on 2012-12-11

@author: qcg
"""
import os
import platform
import logging

if platform.platform().startswith('Windows'):
    logging_file = os.path.join(os.getenv('HOMEDRIVE'),
                                os.getenv('HOMEPATH'),
                                'test.log')
else:
    logging_file = os.path.join(os.getenv('HOME'), 'test.log')
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] %(message)s',
    filename=logging_file,
    filemode='a',
)
# test
logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")