text:
KISSY.add('sammy/rendercontext', function(S, Sammy, Node){
  var $ = Node.all
  var SammyRenderCtx = Sammy.RenderContext = function(event_context){
    this.event_context    = event_context
    this.callbacks        = []
    this.previous_content = null
    this.content          = null
    this.next_engine      = false
    this.waiting          = false
  }

  S.extend(SammyRenderCtx, {
    // The "core" of the `RenderContext` object, adds the `callback` to the
    // queue. If the context is `waiting` (meaning an async operation is happening)
    // then the callback will be executed in order, once the other operations are
    // complete. If there is no currently executing operation, the `callback`
    // is executed immediately.
    //
    // The value returned from the callback is stored in `content` for the
    // subsequent operation. If you return `false`, the queue will pause, and
    // the next callback in the queue will not be executed until `next()` is
    // called. This allows for the guaranteed order of execution while working
    // with async operations.
    //
    // If then() is passed a string instead of a function, the string is looked
    // up as a helper method on the event context.
    //
    // ### Example
    //
    //      this.get('#/', function() {
    //        // initialize the RenderContext
    //        // Even though `load()` executes async, the next `then()`
    //        // wont execute until the load finishes
    //        this.load('myfile.txt')
    //            .then(function(content) {
    //              // the first argument to then is the content of the
    //              // prev operation
    //              $('#main').html(content);
    //            });
    //      });
    //
    then: function(callback) {
      if (!S.isFunction(callback)) {
        // if a string is passed to then, assume we want to call
        // a helper on the event context in its context
        if (typeof callback === 'string' && callback in this.event_context) {
          var helper = this.event_context[callback]
          callback = function(content) {
            return helper.apply(this.event_context, [content])
          }
        } else {
          return this
        }
      }
      var context = this
      if (this.waiting) {
        this.callbacks.push(callback)
      } else {
        this.wait()
        window.setTimeout(function() {
          var returned = callback.apply(context, [context.content, context.previous_content])
          if (returned !== false) {
            context.next(returned)
          }
        }, 0)
      }
      return this
    },

    // Pause the `RenderContext` queue. Combined with `next()` allows for async
    // operations.
    //
    // ### Example
    //
    //        this.get('#/', function() {
    //          this.load('mytext.json')
    //              .then(function(content) {
    //                var context = this,
    //                    data    = JSON.parse(content);
    //                // pause execution
    //                context.wait();
    //                // post to a url
    //                $.post(data.url, {}, function(response) {
    //                  context.next(JSON.parse(response));
    //                });
    //              })
    //              .then(function(data) {
    //                // data is json from the previous post
    //                $('#message').text(data.status);
    //              });
    //        });
    wait: function() {
      this.waiting = true
    },

    // Resume the queue, setting `content` to be used in the next operation.
    // See `wait()` for an example.
    next: function(content) {
      this.waiting = false
      if (typeof content !== 'undefined') {
        this.previous_content = this.content
        this.content = content
      }
      if (this.callbacks.length > 0) {
        this.then(this.callbacks.shift())
      }
    },

    // Load a template into the context.
    // The `location` can either be a string specifying the remote path to the
    // file, a jQuery object, or a DOM element.
    //
    // No interpolation happens by default, the content is stored in
    // `content`.
    //
    // In the case of a path, unless the option `{cache: false}` is passed the
    // data is stored in the app's `templateCache()`.
    //
    // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
    // This is useful for nesting templates as part of the initial page load wrapped
    // in invisible elements or `<script>` tags. With template paths, the template
    // engine is looked up by the extension. For DOM/jQuery embedded templates,
    // this isnt possible, so there are a couple of options:
    //
    //  * pass an `{engine:}` option.
    //  * define the engine in the `data-engine` attribute of the passed node.
    //  * just store the raw template data and use `interpolate()` manually
    //
    // If a `callback` is passed it is executed after the template load.
    load: function(location, options, callback) {
      var context = this
      return this.then(function() {
        var should_cache, cached, is_json, location_array
        if (_isFunction(options)) {
          callback = options
          options = {}
        } else {
          options = $.extend({}, options)
        }
        if (callback) { this.then(callback) }
        if (typeof location === 'string') {
          // it's a path
          is_json      = (location.match(/\.json$/) || options.json)
          should_cache = is_json ? options.cache === true : options.cache !== false
          context.next_engine = context.event_context.engineFor(location)
          delete options.cache
          delete options.json
          if (options.engine) {
            context.next_engine = options.engine
            delete options.engine
          }
          if (should_cache && (cached = this.event_context.app.templateCache(location))) {
            return cached
          }
          this.wait()
          $.ajax($.extend({
            url: location,
            data: {},
            dataType: is_json ? 'json' : 'text',
            type: 'get',
            success: function(data) {
              if (should_cache) {
                context.event_context.app.templateCache(location, data)
              }
              context.next(data)
            }
          }, options))
          return false
        } else {
          // it's a dom/jQuery
          if (location.nodeType) {
            return location.innerHTML
          }
          if (location.selector) {
            // it's a jQuery
            context.next_engine = location.attr('data-engine')
            if (options.clone === false) {
              return location.remove()[0].innerHTML.toString()
            } else {
              return location[0].innerHTML.toString()
            }
          }
        }
      })
    },

    // Load partials
    //
    // ### Example
    //
    //      this.loadPartials({mypartial: '/path/to/partial'});
    //
    loadPartials: function(partials) {
      var name
      if(partials) {
        this.partials = this.partials || {}
        for(name in partials) {
          (function(context, name) {
            context.load(partials[name])
                   .then(function(template) {
                     this.partials[name] = template
                   })
          })(this, name)
        }
      }
      return this
    },

    // `load()` a template and then `interpolate()` it with data.
    //
    // can be called with multiple different signatures:
    //
    //      this.render(callback);
    //      this.render('/location');
    //      this.render('/location', {some: data});
    //      this.render('/location', callback);
    //      this.render('/location', {some: data}, callback);
    //      this.render('/location', {some: data}, {my: partials});
    //      this.render('/location', callback, {my: partials});
    //      this.render('/location', {some: data}, callback, {my: partials});
    //
    // ### Example
    //
    //      this.get('#/', function() {
    //        this.render('mytemplate.template', {name: 'test'});
    //      });
    //
    render: function(location, data, callback, partials) {
      if (S.isFunction(location) && !data) {
        // invoked as render(callback)
        return this.then(location)
      } else {
        if(S.isFunction(data)) {
          // invoked as render(location, callback, [partials])
          partials = callback
          callback = data
          data = null
        } else if(callback && !S.isFunction(callback)) {
          // invoked as render(location, data, partials)
          partials = callback
          callback = null
        }

        return this.loadPartials(partials)
                   .load(location)
                   .interpolate(data, location)
                   .then(callback)
      }
    },

    // `render()` the `location` with `data` and then `swap()` the
    // app's `$element` with the rendered content.
    partial: function(location, data, callback, partials) {
      if (S.isFunction(callback)) {
        // invoked as partial(location, data, callback, [partials])
        return this.render(location, data, partials).swap(callback)
      } else if (S.isFunction(data)) {
        // invoked as partial(location, callback, [partials])
        return this.render(location, {}, callback).swap(data)
      } else {
        // invoked as partial(location, data, [partials])
        return this.render(location, data, callback).swap()
      }
    },

    // defers the call of function to occur in order of the render queue.
    // The function can accept any number of arguments as long as the last
    // argument is a callback function. This is useful for putting arbitrary
    // asynchronous functions into the queue. The content passed to the
    // callback is passed as `content` to the next item in the queue.
    //
    // ### Example
    //
    //     this.send($.getJSON, '/app.json')
    //         .then(function(json) {
    //           $('#message).text(json['message']);
    //          });
    //
    //
    send: function() {
      var context = this,
          args = S.makeArray(arguments),
          fun  = args.shift()

      if (S.isArray(args[0])) { args = args[0] }

      return this.then(function(content) {
        args.push(function(response) { context.next(response) })
        context.wait()
        fun.apply(fun, args)
        return false
      })
    },

    // iterates over an array, applying the callback for each item item. the
    // callback takes the same style of arguments as `jQuery.each()` (index, item).
    // The return value of each callback is collected as a single string and stored
    // as `content` to be used in the next iteration of the `RenderContext`.
    collect: function(array, callback, now) {
      var context = this
      var coll = function() {
        if (S.isFunction(array)) {
          callback = array
          array = this.content
        }
        var contents = [], doms = false
        S.each(array, function(item, i) {
          var returned = callback.apply(context, [i, item])
          if (returned.jquery && returned.length == 1) {
            returned = returned[0]
            doms = true
          }
          contents.push(returned)
          return returned
        })
        return doms ? contents : contents.join('')
      }
      return now ? coll() : this.then(coll)
    },

    // loads a template, and then interpolates it for each item in the `data`
    // array. If a callback is passed, it will call the callback with each
    // item in the array _after_ interpolation
    renderEach: function(location, name, data, callback) {
      if (S.isArray(name)) {
        callback = data
        data = name
        name = null
      }
      return this.load(location).then(function(content) {
          var rctx = this
          if (!data) {
            data = S.isArray(this.previous_content) ? this.previous_content : []
          }
          if (callback) {
            S.each(data, function(value, i) {
              var idata = {}, engine = this.next_engine || location
              if (name) {
                idata[name] = value
              } else {
                idata = value
              }
              callback(value, rctx.event_context.interpolate(content, idata, engine))
            })
          } else {
            return this.collect(data, function(i, value) {
              var idata = {}, engine = this.next_engine || location
              if (name) {
                idata[name] = value
              } else {
                idata = value
              }
              return this.event_context.interpolate(content, idata, engine)
            }, true)
          }
      })
    },

    // uses the previous loaded `content` and the `data` object to interpolate
    // a template. `engine` defines the templating/interpolation method/engine
    // that should be used. If `engine` is not passed, the `next_engine` is
    // used. If `retain` is `true`, the final interpolated data is appended to
    // the `previous_content` instead of just replacing it.
    interpolate: function(data, engine, retain) {
      var context = this
      return this.then(function(content, prev) {
        if (!data && prev) { data = prev }
        if (this.next_engine) {
          engine = this.next_engine
          this.next_engine = false
        }
        var rendered = context.event_context.interpolate(content, data, engine, this.partials)
        return retain ? prev + rendered : rendered
      })
    },

    // Swap the return contents ensuring order. See `Application#swap`
    swap: function(callback) {
      return this.then(function(content) {
        this.event_context.swap(content, callback)
        return content
      }).trigger('changed', {})
    },

    // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
    appendTo: function(selector) {
      return this.then(function(content) {
        $(selector).append(content)
      }).trigger('changed', {})
    },

    // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
    prependTo: function(selector) {
      return this.then(function(content) {
        $(selector).prepend(content)
      }).trigger('changed', {})
    },

    // Replaces the `$(selector)` using `html()` with the previously loaded
    // `content`
    replace: function(selector) {
      return this.then(function(content) {
        $(selector).html(content)
      }).trigger('changed', {})
    },

    // trigger the event in the order of the event context. Same semantics
    // as `Sammy.EventContext#trigger()`. If data is omitted, `content`
    // is sent as `{content: content}`
    trigger: function(name, data) {
      return this.then(function(content) {
        if (typeof data == 'undefined') { data = {content: content} }
        this.event_context.trigger(name, data)
        return content
      });
    }

  })

  return SammyRenderCtx
}, {
  requires: ['sammy/base', 'Node']
})


text:
title:  "Openstack Nova Migrate Error SSH Key"
header:
  image: /assets/images/y4azyntou5ybeulcquqx.jpg
date:  2017-01-03
tags:
  - openstack
  - nova
description: ''
categories:
  - Virtual
---
{% highlight python %}
   ERROR oslo_messaging.rpc.server ResizeError: Resize error: not able to execute ssh command: Unexpected error while running command.
   ERROR oslo_messaging.rpc.server Command: ssh -o BatchMode=yes <compute_host_address> mkdir -p /var/lib/nova/instances/<instance-id>
{% endhighlight %}

It's possible for you to get those errors while you migrate your instance from one host (hypervisor/compute) to another host (hypervisor/compute). Those errors appears because by default nova service create user nova on system for Daemons only with nologin.

{% highlight python %}
nova:x:162:162:OpenStack Nova Daemons:/var/lib/nova:/sbin/nologin
{% endhighlight %}

Then, while ```nova migrate``` command working, source host (hypervisor/compute) will do an ssh onto destination host for some of nova works. To solve this problem, we had to copy ssh-credential across compute host.

1. Run __setenforce 0__ to put SELinux into permissive mode.
2. Enable login abilities for the nova user:
   ```# usermod -s /bin/bash nova```
3. as root, give nova user password, for __ssh-copy-id__ works later
   ```# passwd nova```
   then switch to nova account:
   ```# su nova```
4. Generate ssh-key for nova user
   ```$ ssh-keygen -t rsa```
5. Repeat step 1-4 for all nova users in each compute nodes
6. As nova user Copy SSH-Key to every compute nodes
   ```$ ssh-copy-id <compute-nodes-destinations>```
7. Try to ssh, it must be automatically login without password
   ```$ ssh <compute-nodes-destinations>```

Try for ```nova migrate``` again, and see for any further errors.

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Lightswitch : MonoBehaviour
{
    [SerializeField] private Light mObjLight;

    // check if somthing enters the trigger
    void OnTriggerEnter(Collider other)
    {
        // if its the Player
        if (other.gameObject.tag == "Player")
        {
            // turn on the light
            mObjLight.enabled = true;
        }
    }
    // check if somthing leaves the trigger
    void OnTriggerExit(Collider other)
    {
        // if its the Player
        if (other.gameObject.tag == "Player")
        {
            // turn off the light
            mObjLight.enabled = false;
        }
    }

}


text:
package org.springframework.boot.actuate.endpoint.web.annotation;

import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.Operation;
import org.springframework.boot.actuate.endpoint.web.PathMappedEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Information describing an endpoint that can be exposed over Spring MVC or Spring
 * WebFlux. Mappings should be discovered directly from {@link #getController()} and
 * {@link #getOperations()} should always return an empty collection.
 *
 * @author Phillip Webb
 * @since 2.0.0
 */
public interface ExposableControllerEndpoint extends ExposableEndpoint<Operation>, PathMappedEndpoint {

	/**
	 * Return the source controller that contains {@link RequestMapping @RequestMapping}
	 * methods.
	 * @return the source controller
	 */
	Object getController();

}


text:
package main

import "os"

func main() {
	os.Stderr.WriteString(`compilebench: stale compilebench

This program is rsc.io/compilebench.
You should be using golang.org/x/tools/cmd/compilebench.
Suggestion:

	rm -r $GOPATH/src/rsc.io/compilebench
	go get -u golang.org/x/tools/cmd/compilebench

`)
	os.Exit(2)
}


text:
#include "Rendering/VulkanRenderPassOLD.hpp"

#include "Rendering/Image.hpp"
#include "Rendering/VulkanRenderDeviceOLD.hpp"

using namespace crimild;
using namespace crimild::vulkan;

crimild::Bool RenderPassManager::bind( RenderPass *renderPass ) noexcept
{
    if ( validate( renderPass ) ) {
        return true;
    }

    CRIMILD_LOG_DEBUG( "Binding Vulkan Render Pass: ", renderPass->getName() );

    auto renderDevice = getRenderDevice();
    auto swapchain = renderDevice->getSwapchain();
    auto imageCount = swapchain->getImages().size();
    auto extent = utils::getExtent( renderPass->extent, renderDevice );

    auto createAttachmentImage = [ & ]( Attachment *attachment ) {
        auto image = crimild::alloc< Image >();
        if ( attachment->imageView != nullptr ) {
            if ( attachment->imageView->image != nullptr ) {
                image = attachment->imageView->image;
            }
        }
        image->extent = {
            .scalingMode = ScalingMode::FIXED,
            .width = crimild::Real32( extent.width ),
            .height = crimild::Real32( extent.height ),
        };
        image->format = attachment->format;
        image->setMipLevels( 1 ); // only 1 mip level is allowed for framebuffer's images
        return image;
    };

    auto createAttachmentImageView = [ & ]( Attachment *attachment ) {
        auto imageView = attachment->imageView != nullptr ? attachment->imageView : crimild::alloc< ImageView >();
        imageView->type = ImageView::Type::IMAGE_VIEW_2D;
        imageView->image = createAttachmentImage( attachment );
        imageView->format = imageView->image->format;
        return imageView;
    };

    auto colorReferences = Array< VkAttachmentReference >();
    auto depthStencilReferences = Array< VkAttachmentReference >();

    bool hasPresentation = false;

    // This render pass supports presentation if and only if there is AT MOST one color attachment.
    // This might change in the future.
    auto supportsPresentation =
        renderPass->attachments
            .filter(
                []( auto att ) {
                    return att->isPresentation() && !utils::formatIsDepthStencil( att->format );
                }
            )
            .size()
        <= 1;

    auto attachments = renderPass->attachments.map(
        [ &, idx = 0u ]( auto const &attachment ) mutable {
            // This is a presentation attachment only if no other operation reads from it
            auto isPresentation = supportsPresentation && attachment->isPresentation();
            if ( !isPresentation ) {
                // Create an image view for this attachemnt
                // TODO: Have a pool of image views instead?
                attachment->imageView = createAttachmentImageView( crimild::get_ptr( attachment ) );
            }

            auto format = attachment->format;
            auto initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
            auto finalLayout = VK_IMAGE_LAYOUT_GENERAL;

            if ( utils::formatIsDepthStencil( format ) ) {
                depthStencilReferences.add(
                    VkAttachmentReference {
                        .attachment = idx++,
                        .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
                    }
                );
                finalLayout = isPresentation ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
            } else {
                colorReferences.add(
                    VkAttachmentReference {
                        .attachment = idx++,
                        .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                    }
                );
                hasPresentation |= isPresentation;
                finalLayout = isPresentation ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
            }

            // 1. Write only: LoadOp::CLEAR or LoadOp::DONT_CARE
            // 2. Read-Write: LoadOp::LOAD
            // 3. Read only: LoadOp::LOAD?

            auto loadOp = attachment->isWrittenBefore( renderPass ) ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_CLEAR;

            return VkAttachmentDescription {
                .format = utils::getFormat( renderDevice, attachment->format ),
                .samples = VK_SAMPLE_COUNT_1_BIT,
                .loadOp = loadOp,
                .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
                .stencilLoadOp = utils::formatIsDepthStencil( attachment->format ) ? loadOp : VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .initialLayout = initialLayout,
                .finalLayout = finalLayout,
            };
        }
    );

    auto subpass = VkSubpassDescription {
        .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
        .inputAttachmentCount = 0,
        .pInputAttachments = nullptr,
        .colorAttachmentCount = crimild::UInt32( colorReferences.size() ),
        .pColorAttachments = colorReferences.getData(),
        .pResolveAttachments = nullptr,
        .pDepthStencilAttachment = !depthStencilReferences.empty() ? depthStencilReferences.getData() : nullptr,
        .preserveAttachmentCount = 0,
        .pPreserveAttachments = nullptr,
    };

    auto dependencies = std::vector< VkSubpassDependency > {
        {
            .srcSubpass = VK_SUBPASS_EXTERNAL,
            .dstSubpass = 0,
            .srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // hasPresentation ? VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
            .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
            .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,                                                  // hasPresentation ? VK_ACCESS_MEMORY_READ_BIT : VK_ACCESS_SHADER_READ_BIT,
            .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // hasPresentation ? VkAccessFlags( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
            .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT,
        },
        {
            .srcSubpass = 0,
            .dstSubpass = VK_SUBPASS_EXTERNAL,
            .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
            .dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,                                        // hasPresentation ? VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
            .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // hasPresentation ? VkAccessFlags( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) : VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
            .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,                                                  // hasPresentation ? VK_ACCESS_MEMORY_READ_BIT : VK_ACCESS_SHADER_READ_BIT,
            .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT,
        }
    };

    auto createInfo = VkRenderPassCreateInfo {
        .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
        .attachmentCount = static_cast< crimild::UInt32 >( attachments.size() ),
        .pAttachments = attachments.getData(),
        .subpassCount = 1,
        .pSubpasses = &subpass,
        .dependencyCount = crimild::UInt32( dependencies.size() ),
        .pDependencies = dependencies.data(),
    };

    RenderPassBindInfo bindInfo;
    CRIMILD_VULKAN_CHECK(
        vkCreateRenderPass(
            renderDevice->handler,
            &createInfo,
            nullptr,
            &bindInfo.handler
        )
    );

    bindInfo.framebuffers.resize( imageCount );
    for ( auto i = 0l; i < imageCount; i++ ) {
        auto fbAttachments = renderPass->attachments.map( [ & ]( auto &att ) {
            if ( !supportsPresentation || !att->isPresentation() ) {
                return renderDevice->getBindInfo( crimild::get_ptr( att->imageView ) );
            }
            return renderDevice->getBindInfo( crimild::get_ptr( swapchain->getImageViews()[ i ] ) );
        } );

        auto createInfo = VkFramebufferCreateInfo {
            .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
            .renderPass = bindInfo.handler,
            .attachmentCount = crimild::UInt32( fbAttachments.size() ),
            .pAttachments = fbAttachments.getData(),
            .width = extent.width,
            .height = extent.height,
            .layers = 1,
        };

        CRIMILD_VULKAN_CHECK(
            vkCreateFramebuffer(
                renderDevice->handler,
                &createInfo,
                nullptr,
                &bindInfo.framebuffers[ i ]
            )
        );
    }

    if ( !renderPass->getName().empty() ) {
        utils::setObjectName(
            renderDevice->handler,
            UInt64( bindInfo.handler ),
            VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,
            renderPass->getName().c_str()
        );
    }

    setBindInfo( renderPass, bindInfo );

    return ManagerImpl::bind( renderPass );
}

crimild::Bool vulkan::RenderPassManager::unbind( RenderPass *renderPass ) noexcept
{
    if ( !validate( renderPass ) ) {
        return false;
    }

    CRIMILD_LOG_TRACE();

    auto renderDevice = getRenderDevice();

    auto info = getBindInfo( renderPass );

    if ( renderDevice != nullptr ) {
        info.framebuffers.each( [ & ]( auto &fb ) {
            vkDestroyFramebuffer( renderDevice->handler, fb, nullptr );
        } );
        if ( info.handler != VK_NULL_HANDLE ) {
            vkDestroyRenderPass( renderDevice->handler, info.handler, nullptr );
        }
    }

    removeBindInfo( renderPass );

    return ManagerImpl::unbind( renderPass );
}


text:
if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('..');
};

/*
  Test for issue #379
*/

var test = 422;

describe('Test '+test+' Test for JOINSTAR', function() {

  before(function(){
    alasql('CREATE DATABASE test'+test+';USE test'+test);
  });

  after(function(){
    alasql('DROP DATABASE test'+test);
  });

  it('1. Create tables',function(done){
    var ast = alasql.parse('SELECT * FROM table1 WHERE a = b AND a->fn(b->c) > 0');
    //console.log(JSON.stringify(ast.statements[0].where));
    done();
  });

});


text:
package com.github.ljtfreitas.restify.http.client.message.converter;

import java.lang.reflect.Type;

import com.github.ljtfreitas.restify.http.client.message.response.HttpResponseMessage;

public interface HttpMessageReader<T> extends HttpMessageConverter {

	public boolean canRead(Type type);

	public T read(HttpResponseMessage httpResponseMessage, Type expectedType) throws HttpMessageReadException;
}


text:
/**
 * @module gallery-widget-inherit-css
 */
(function (Y) {
    'use strict';

    var _Do = Y.Do,
        _Widget = Y.Widget,

        _AlterReturn = _Do.AlterReturn,

        _getClassName = Y.ClassNameManager.getClassName,

        _getSuperclassClassName = function () {
            var superclass = this.constructor.superclass,
                superclassClassName,
                superclassConstructor = superclass.constructor,
                superclassCssPrefix = superclassConstructor.CSS_PREFIX || _getClassName(superclassConstructor.NAME.toLowerCase());

            superclassClassName = superclassConstructor !== _Widget && _getSuperclassClassName.apply(superclass, arguments) || [];

            superclassClassName.push(superclass.getClassName.apply({
                _cssPrefix: superclassCssPrefix
            }, arguments));

            return superclassClassName;
        };

    /**
     * Allows a Widget subclass to inherit css from the superclass.
     * @class WidgetInheritCss
     * @constructor
     */
    Y.WidgetInheritCss = function () {
        _Do.after(function () {
            return new _AlterReturn('Added superclass class.', _Do.originalRetVal + ' ' + _getSuperclassClassName.apply(this, arguments).join(' '));
        }, this, 'getClassName', this);
    };
}(Y));


text:
package master

import (
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"

	"github.com/golang/glog"
)

// NewIPCache makes a new ip caching layer, which will get IP addresses from cp,
// and use clock for deciding when to re-get an IP address.
// Thread-safe.
//
// TODO: when we switch to go1.4, this class would be a good candidate for something
// that could be produced from a template and a type via `go generate`.
func NewIPCache(cp cloudprovider.Interface, clock util.Clock, ttl time.Duration) *ipCache {
	return &ipCache{
		cache: util.NewTimeCache(
			clock,
			ttl,
			func(host string) util.T {
				return getInstanceIPFromCloud(cp, host)
			},
		),
	}
}

type ipCache struct {
	cache util.TimeCache
}

// GetInstanceIP returns the IP address of host, from the cache
// if possible, otherwise it asks the cloud provider.
func (c *ipCache) GetInstanceIP(host string) string {
	return c.cache.Get(host).(string)
}

func getInstanceIPFromCloud(cloud cloudprovider.Interface, host string) string {
	if cloud == nil {
		return ""
	}
	instances, ok := cloud.Instances()
	if instances == nil || !ok {
		return ""
	}
	addr, err := instances.IPAddress(host)
	if err != nil {
		glog.Errorf("Error getting instance IP for %q: %v", host, err)
		return ""
	}
	return addr.String()
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// load header
$this->load->view('layouts/header');
?>

Edit Vendor Truck <a href="<?php echo site_url('Master/view_all_vendor_truck'); ?>" class="btn btn-default"> Back

                    Form Vendor Truck

                            <?php echo form_open(); ?>
                                <?php if(validation_errors()) { ?>

                                    <?php echo validation_errors(); ?>

                                <?php } ?>

                                <?php if(isset($error_var) && $error_var == "error") { ?>

                                    <?php echo $error_msg; ?>

                                <?php } ?>

                                <?php if($this->session->flashdata('success')) { ?>

                                    <?php echo $this->session->flashdata('success'); ?>

                                <?php } ?>

                                <?php if($this->session->flashdata('failed')) { ?>

                                    <?php echo $this->session->flashdata('failed'); ?>

                                <?php } ?>

                                            Contract
                                            <input type="text" name="contract_no" class="form-control" value="<?php echo $contract_no; ?>" readonly="true">

                                            Company
                                            <input type="text" class="form-control" readonly="true" name="company_id" value="<?php echo set_value('company_id', $company_id) ?>">

                                            Container Size
                                            <select name="container_size_id" class="form-control" readonly="true">
                                                <option <?php echo set_select('container_size_id', '', TRUE); ?>></option>
                                                <?php
                                                    foreach ($container_size as $key => $value) {?>
                                                        <option <?php if($container_size_id == $value->GENERAL_ID) {echo 'selected';} ?> value="<?php echo $value->GENERAL_ID; ?>" <?php echo set_select('container_size_id', $value->GENERAL_ID, FALSE); ?>><?php echo $value->GENERAL_DESCRIPTION; ?></option>
                                                    <?php }
                                                ?>
                                            </select>

                                            Container Type
                                            <select name="container_type_id" class="form-control" readonly="true">
                                                <option <?php echo set_select('container_type_id', '', TRUE); ?>></option>
                                                <?php
                                                    foreach ($container_type as $key => $value) {?>
                                                        <option <?php if($container_type_id == $value->GENERAL_ID) {echo 'selected';} ?> value="<?php echo $value->GENERAL_ID; ?>" <?php echo set_select('container_type_id', $value->GENERAL_ID, FALSE); ?>><?php echo $value->GENERAL_DESCRIPTION; ?></option>
                                                    <?php }
                                                ?>
                                            </select>

                                            Container Category
                                            <select name="container_category_id" class="form-control" readonly="true">
                                                <option <?php echo set_select('container_category_id', '', TRUE); ?>></option>
                                                <?php
                                                    foreach ($container_category as $key => $value) {?>
                                                        <option <?php if($container_category_id == $value->GENERAL_ID) {echo 'selected';} ?> value="<?php echo $value->GENERAL_ID; ?>" <?php echo set_select('container_category_id', $value->GENERAL_ID, FALSE); ?>><?php echo $value->GENERAL_DESCRIPTION; ?></option>
                                                    <?php }
                                                ?>
                                            </select>

                                            From QTY
                                            <input type="number" name="from_qty" class="form-control" readonly="true" value="<?php echo set_value('from_qty', $from_qty) ?>">

                                            To QTY
                                            <input type="number" name="to_qty" class="form-control" readonly="true" value="<?php echo set_value('to_qty', $to_qty) ?>">

                                            From Location
                                            <select readonly="true" name="from_location_id" class="form-control">
                                                <option <?php echo set_select('from_location_id', '', TRUE); ?>></option>
                                                <?php
                                                    foreach ($data_location as $key => $value) {?>
                                                        <option <?php if($from_location_id == $value->LOCATION_ID) {echo 'selected';} ?> value="<?php echo $value->LOCATION_ID; ?>" <?php echo set_select('from_location_id', $value->LOCATION_ID, FALSE); ?>><?php echo $value->LOCATION_NAME; ?></option>
                                                    <?php }
                                                ?>
                                            </select>

                                            To Location
                                            <select readonly="true" name="to_location_id" class="form-control">
                                                <option <?php echo set_select('to_location_id', '', TRUE); ?>></option>
                                                <?php
                                                    foreach ($data_location as $key => $value) {?>
                                                        <option <?php if($to_location_id == $value->LOCATION_ID) {echo 'selected';} ?> value="<?php echo $value->LOCATION_ID; ?>" <?php echo set_select('to_location_id', $value->LOCATION_ID, FALSE); ?>><?php echo $value->LOCATION_NAME; ?></option>
                                                    <?php }
                                                ?>
                                            </select>

                                            Currency
                                            <select class="form-control" name="buying_currency">
                                                <option <?php echo set_select('buying_currency', '', TRUE); ?>></option>
                                                <option <?php if($buying_currency == "IDR") {echo 'selected';} ?> value="IDR" <?php echo set_select('buying_currency', 'IDR', FALSE); ?>>IDR</option>
                                                <option <?php if($buying_currency == "USD") {echo 'selected';} ?> value="USD" <?php echo set_select('buying_currency', 'USD', FALSE); ?>>USD</option>
                                            </select>

                                            Amount
                                            <input type="number" name="buying_rate" class="form-control" value="<?php echo set_value('buying_rate', $buying_rate) ?>">

                                <button type="submit" id="btns" class="btn btn-primary">Save</button>
                                <a href="<?php echo site_url('Master/view_all_vendor_truck'); ?>" class="btn btn-default">Cancel
                            </form>

<?php
    $this->load->view('layouts/js.php');
?>

<?php
    $this->load->view('layouts/footer.php');
?>


text:
package org.axiom_tools.domain;

import java.util.*;
import java.io.Serializable;

import javax.persistence.*;
import javax.xml.bind.annotation.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.axiom_tools.storage.Surrogated;
import org.axiom_tools.storage.SurrogatedComposite;

/**
 * Contains contact information.
 */
@Entity
@Table(name = "CONTACT")
@XmlRootElement(name = "Contact", namespace = "##default")
@SuppressWarnings("unchecked")
public class Contact extends Surrogated<Contact> implements SurrogatedComposite, Serializable {

    private static final long serialVersionUID = 1001001L;
    private static final Logger Log = LoggerFactory.getLogger(Contact.class);
    private static final Contact SampleContact = new Contact();

    /**
     * Indicates a kind of contact.
     */
    public static enum Kind {

        HOME,
        WORK,
        MOBILE,
        BILLING,
        SHIPPING,
    } // Kind

    /**
     * Identifies a kind of contact ID.
     */
    public static enum Type {

        hash,
        email,
        phone,
    } // Type

    // component map indices for this composite
    private static final int AddressIndex = 0;
    private static final int EmailIndex = 1;
    private static final int PhoneIndex = 2;

    /**
     * A logger.
     *
     * @return a Logger
     */
    @Override
    protected Logger getLogger() {
        return Log;
    }

    /**
     * The available contact mechanisms.
     *
     * @return a ContactMechanism list
     */
    @XmlElement(name = "mechanisms")
    public List<ContactMechanism> getMechanisms() {
        ArrayList<ContactMechanism> results = new ArrayList();
        for (Kind addressType : addresses.keySet()) {
            results.add(ContactMechanism.with(addressType, addresses.get(addressType)));
        }

        for (Kind phoneType : phones.keySet()) {
            results.add(ContactMechanism.with(phoneType, phones.get(phoneType)));
        }

        for (Kind emailType : emails.keySet()) {
            results.add(ContactMechanism.with(emailType, emails.get(emailType)));
        }
        return results;
    }

    public void setMechanisms(List<ContactMechanism> mechanisms) {
        for (ContactMechanism mechanism : mechanisms) {
            if (mechanism.getMechanism() instanceof MailAddress) {
                updateAddress(Kind.valueOf(mechanism.getType()), (MailAddress) mechanism.getMechanism());
            }
            if (mechanism.getMechanism() instanceof EmailAddress) {
                updateEmail(Kind.valueOf(mechanism.getType()), (EmailAddress) mechanism.getMechanism());
            }
            if (mechanism.getMechanism() instanceof PhoneNumber) {
                updatePhone(Kind.valueOf(mechanism.getType()), (PhoneNumber) mechanism.getMechanism());
            }
        }
    }

    /**
     * Any components that are managed as maps.
     *
     * @return the component maps associated with this Contact
     */
    @Override
    public Object[] componentMaps() {
        Object[] results = {this.addresses, this.emails, this.phones};
        return results;
    }

    /**
     * Any street addresses associated with this contact.
     */
    @ManyToMany(
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL)
    @MapKeyEnumerated(EnumType.STRING)
    @MapKeyColumn(name = "kind", length = 10, nullable = false)
    private final Map<Kind, MailAddress> addresses = new HashMap<>();

    /**
     * Any phone numbers associated with this contact.
     */
    @OneToMany(
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    @MapKeyEnumerated(EnumType.STRING)
    @MapKeyColumn(name = "kind", length = 10, nullable = false)
    private final Map<Kind, PhoneNumber> phones = new HashMap<>();

    /**
     * Any email addresses associated with this contact.
     */
    @OneToMany(
            fetch = FetchType.EAGER,
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    @MapKeyEnumerated(EnumType.STRING)
    @MapKeyColumn(name = "kind", length = 10, nullable = false)
    private final Map<Kind, EmailAddress> emails = new HashMap<>();

    /**
     * Counts the number of saved contacts.
     *
     * @return a count, or zero
     */
    public static int count() {
        return (int) SampleContact.getStore().count();
    }

    /**
     * A count of the mail addresses associated with this contact.
     *
     * @return a count
     */
    public int countAddresses() {
        return this.addresses.size();
    }

    /**
     * A count of the phones associated with this contact.
     *
     * @return a count
     */
    public int countPhones() {
        return this.phones.size();
    }

    /**
     * A count of the email addresses associated with this contact.
     *
     * @return a count
     */
    public int countEmails() {
        return this.emails.size();
    }

    /**
     * Returns an address of a given kind.
     *
     * @param kind a kind of address
     * @return a StreetAddress, or null
     */
    public MailAddress getAddress(Kind kind) {
        return this.addresses.get(kind);
    }

    /**
     * Adds an address of a given kind.
     *
     * @param kind a kind of address
     * @param address a StreetAddress
     * @return this contact
     */
    public Contact withAddress(Kind kind, MailAddress address) {
        if (address == null) {
            return this;
        }
        updateAddress(kind, address);
        return this;
    }

    /**
     * Removes an address of a given kind.
     *
     * @param kind a kind of address
     * @return this contact
     */
    public Contact removeAddress(final Kind kind) {
        updateAddress(kind, null);
        return this;
    }

    /**
     * Returns a phone of a given kind.
     *
     * @param kind a kind of phone
     * @return a PhoneNumber, or null
     */
    public PhoneNumber getPhone(Kind kind) {
        return this.phones.get(kind);
    }

    /**
     * Adds a phone to this contact.
     *
     * @param kind a kind of phone
     * @param phone a phone
     * @return this contact
     */
    public Contact withPhone(Kind kind, PhoneNumber phone) {
        if (phone == null) {
            return this;
        }
        updatePhone(kind, phone);
        return this;
    }

    /**
     * Removes a phone from this contact.
     *
     * @param kind a kind of phone
     * @return this contact
     */
    public Contact removePhone(Kind kind) {
        updatePhone(kind, null);
        return this;
    }

    /**
     * Returns an email address of a given kind.
     *
     * @param kind a kind of email address
     * @return an EmailAddress, or null
     */
    public EmailAddress getEmail(Kind kind) {
        return this.emails.get(kind);
    }

    /**
     * Adds an email address of a given kind.
     *
     * @param kind a kind of email address
     * @param email an email address
     * @return this contact
     */
    public Contact withEmail(Kind kind, EmailAddress email) {
        if (email == null) {
            return this;
        }
        updateEmail(kind, email);
        return this;
    }

    /**
     * Removes an email address of a given kind.
     *
     * @param kind a kind of email address
     * @return this contact
     */
    public Contact removeEmail(final Kind kind) {
        updateEmail(kind, null);
        return this;
    }

    /**
     * Describes this contact and its components.
     */
    @Override
    public void describe() {
        super.describe();
        for (Kind addressType : addresses.keySet()) {
            addresses.get(addressType).describe(addressType);
        }

        for (Kind phoneType : phones.keySet()) {
            phones.get(phoneType).describe(phoneType);
        }

        for (Kind emailType : emails.keySet()) {
            emails.get(emailType).describe(emailType);
        }
    }

    private void updateAddress(Kind kind, MailAddress address) {
        if (address == null) {
            this.addresses.remove(kind);
        } else {
            this.addresses.put(kind, address);
        }
    }

    private void updatePhone(Kind kind, PhoneNumber phoneNumber) {
        if (phoneNumber == null) {
            this.phones.remove(kind);
        } else {
            this.phones.put(kind, phoneNumber);
        }
    }

    private void updateEmail(Kind kind, EmailAddress emailAddress) {
        if (emailAddress == null) {
            this.emails.remove(kind);
        } else {
            this.emails.put(kind, emailAddress);
        }
    }

} // Contact


text:
package io.jboot.support.seata;

import io.jboot.app.config.annotation.ConfigModel;
import io.jboot.utils.StrUtil;

@ConfigModel(prefix = "jboot.seata")
public class SeataConfig {

    private boolean enable;
    private String applicationId;
    private String txServiceGroup;
    private String failureHandler;
    private int mode = 1;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public String getApplicationId() {
        return applicationId;
    }

    public void setApplicationId(String applicationId) {
        this.applicationId = applicationId;
    }

    public String getTxServiceGroup() {
        return txServiceGroup;
    }

    public void setTxServiceGroup(String txServiceGroup) {
        this.txServiceGroup = txServiceGroup;
    }

    public String getFailureHandler() {
        return failureHandler;
    }

    public void setFailureHandler(String failureHandler) {
        this.failureHandler = failureHandler;
    }

    public int getMode() {
        return mode;
    }

    public void setMode(int mode) {
        this.mode = mode;
    }

    public boolean isConfigOk() {
        return StrUtil.isNotBlank(applicationId) && StrUtil.isNotBlank(txServiceGroup);
    }
}


text:
package org.skywalking.apm.collector.core.define;

/**
 * @author peng-yongsheng
 */
public interface Loader<T> {
    T load() throws DefineException;
}


text:
/**
 *	bug.ctrl.js
 */

class BugCtrl {

	constructor($scope, BugServ) {

		this.id = $scope.id;
		this.title = $scope.title;
		this.severity = $scope.severity;
		this.product = $scope.product;
		this.version = $scope.version;
		this.component = $scope.component;
		this.classification = $scope.classification;
		this.statusCode = $scope.statusCode;
		this.statusName = $scope.statusName;
		this.lastUpdate = $scope.lastUpdate;

		this.deleteBug = function (id) {
			if (!id) return;
			BugServ.deleteBug(id);
		};
	}
}

export default BugCtrl;


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

package org.brixcms.workspace;

import javax.jcr.RepositoryException;

/**
 * Generic unchecked jcr-related exception
 *
 * @author ivaynberg
 */
public class JcrException extends RuntimeException {
// ------------------------------ FIELDS ------------------------------

    private static final long serialVersionUID = 1L;

// --------------------------- CONSTRUCTORS ---------------------------

    public JcrException(RepositoryException cause) {
        super("Error accessing repository", cause);
    }
}


text:
package org.apache.calcite.rel.core;

import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.AbstractRelNode;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelInput;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelShuttle;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.ImmutableIntList;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Relational operator that returns the contents of a table.
 */
public abstract class TableScan extends AbstractRelNode {
  //~ Instance fields --------------------------------------------------------

  /**
   * The table definition.
   */
  protected final RelOptTable table;

  //~ Constructors -----------------------------------------------------------

  protected TableScan(RelOptCluster cluster, RelTraitSet traitSet,
      RelOptTable table) {
    super(cluster, traitSet);
    this.table = table;
    if (table.getRelOptSchema() != null) {
      cluster.getPlanner().registerSchema(table.getRelOptSchema());
    }
  }

  /**
   * Creates a TableScan by parsing serialized output.
   */
  protected TableScan(RelInput input) {
    this(input.getCluster(), input.getTraitSet(), input.getTable("table"));
  }

  //~ Methods ----------------------------------------------------------------

  @Override public double estimateRowCount(RelMetadataQuery mq) {
    return table.getRowCount();
  }

  @Override public RelOptTable getTable() {
    return table;
  }

  @Override public List<RelCollation> getCollationList() {
    return table.getCollationList();
  }

  @Override public RelOptCost computeSelfCost(RelOptPlanner planner,
      RelMetadataQuery mq) {
    double dRows = table.getRowCount();
    double dCpu = dRows + 1; // ensure non-zero cost
    double dIo = 0;
    return planner.getCostFactory().makeCost(dRows, dCpu, dIo);
  }

  @Override public RelDataType deriveRowType() {
    return table.getRowType();
  }

  /** Returns an identity projection for the given table. */
  public static ImmutableIntList identity(RelOptTable table) {
    return ImmutableIntList.identity(table.getRowType().getFieldCount());
  }

  /** Returns an identity projection. */
  public ImmutableIntList identity() {
    return identity(table);
  }

  @Override public RelWriter explainTerms(RelWriter pw) {
    return super.explainTerms(pw)
        .item("table", table.getQualifiedName());
  }

  /**
   * Projects a subset of the fields of the table, and also asks for "extra"
   * fields that were not included in the table's official type.
   *
   *
The default implementation assumes that tables cannot do either of
   * these operations, therefore it adds a {@link Project} that projects
   * {@code NULL} values for the extra fields, using the
   * {@link RelBuilder#project(Iterable)} method.
   *
   *
Sub-classes, representing table types that have these capabilities,
   * should override.

   *
   * @param fieldsUsed  Bitmap of the fields desired by the consumer
   * @param extraFields Extra fields, not advertised in the table's row-type,
   *                    wanted by the consumer
   * @param relBuilder Builder used to create a Project
   * @return Relational expression that projects the desired fields
   */
  public RelNode project(ImmutableBitSet fieldsUsed,
      Set<RelDataTypeField> extraFields,
      RelBuilder relBuilder) {
    final int fieldCount = getRowType().getFieldCount();
    if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount))
        && extraFields.isEmpty()) {
      return this;
    }
    final List<RexNode> exprList = new ArrayList<>();
    final List<String> nameList = new ArrayList<>();
    final RexBuilder rexBuilder = getCluster().getRexBuilder();
    final List<RelDataTypeField> fields = getRowType().getFieldList();

    // Project the subset of fields.
    for (int i : fieldsUsed) {
      RelDataTypeField field = fields.get(i);
      exprList.add(rexBuilder.makeInputRef(this, i));
      nameList.add(field.getName());
    }

    // Project nulls for the extra fields. (Maybe a sub-class table has
    // extra fields, but we don't.)
    for (RelDataTypeField extraField : extraFields) {
      exprList.add(
          rexBuilder.ensureType(
              extraField.getType(),
              rexBuilder.constantNull(),
              true));
      nameList.add(extraField.getName());
    }

    return relBuilder.push(this).project(exprList, nameList).build();
  }

  @Override public RelNode accept(RelShuttle shuttle) {
    return shuttle.visit(this);
  }
}

// End TableScan.java


text:
drop SEQUENCE item_seq;
--SET SERVEROUTPUT ON;
DECLARE
   max_sk NUMBER;
BEGIN
   SELECT max(i_item_sk)+1 INTO max_sk FROM item;
   dbms_output.put_line('max item sk '||max_sk);
   EXECUTE IMMEDIATE 'CREATE SEQUENCE item_seq INCREMENT BY 1 START WITH '||max_sk||' ORDER';
END;

.

run;


text:
using xwalk::RuntimeContext;

namespace xwalk {
namespace application {

const base::FilePath::CharType kApplicationsDir[] =
    FILE_PATH_LITERAL("applications");

ApplicationService::ApplicationService(RuntimeContext* runtime_context)
    : runtime_context_(runtime_context),
      app_store_(new ApplicationStore(runtime_context)) {
}

ApplicationService::~ApplicationService() {
}

bool ApplicationService::Install(const base::FilePath& path, std::string* id) {
  if (!file_util::PathExists(path))
    return false;

  const base::FilePath data_dir =
      runtime_context_->GetPath().Append(kApplicationsDir);

  // Make sure the kApplicationsDir exists under data_path, otherwise,
  // the installation will always fail because of moving application
  // resources into an invalid directory.
  if (!file_util::DirectoryExists(data_dir) &&
      !file_util::CreateDirectory(data_dir))
    return false;

  base::FilePath unpacked_dir;
  std::string app_id;
  if (!file_util::DirectoryExists(path)) {
    scoped_refptr<XPKExtractor> extractor = XPKExtractor::Create(path);
    if (extractor)
      app_id = extractor->GetPackageID();

    if (app_id.empty()) {
      LOG(ERROR) << "XPK file is invalid.";
      return false;
    }

    if (app_store_->Contains(app_id)) {
      *id = app_id;
      LOG(INFO) << "Already installed: " << app_id;
      return true;
    }

    base::FilePath temp_dir;
    extractor->Extract(&temp_dir);
    unpacked_dir = data_dir.AppendASCII(app_id);
    if (file_util::DirectoryExists(unpacked_dir) &&
        !file_util::Delete(unpacked_dir, true))
      return false;
    if (!file_util::Move(temp_dir, unpacked_dir))
      return false;
  } else {
    unpacked_dir = path;
  }

  std::string error;
  scoped_refptr<Application> application =
      LoadApplication(unpacked_dir,
                      app_id,
                      Manifest::COMMAND_LINE,
                      &error);
  if (!application) {
    LOG(ERROR) << "Error during application installation: " << error;
    return false;
  }

  if (app_store_->AddApplication(application)) {
    LOG(INFO) << "Installed application with id: " << application->ID()
              << " successfully.";
    *id = application->ID();
    return true;
  }

  LOG(ERROR) << "Application with id " << application->ID()
             << " couldn't be installed.";
  return false;
}

bool ApplicationService::Uninstall(const std::string& id) {
  if (!app_store_->RemoveApplication(id)) {
    LOG(ERROR) << "Cannot uninstall application with id " << id
               << "; application is not installed.";
    return false;
  }

  const base::FilePath resources =
      runtime_context_->GetPath().Append(kApplicationsDir).AppendASCII(id);
  if (file_util::DirectoryExists(resources) &&
      !file_util::Delete(resources, true)) {
    LOG(ERROR) << "Error occurred while trying to remove application with id "
               << id << "; Cannot remove all resources.";
    return false;
  }
  return true;
}

bool ApplicationService::Launch(const std::string& id) {
  scoped_refptr<const Application> application =
      app_store_->GetApplicationByID(id);
  if (!application) {
    LOG(ERROR) << "Application with id " << id << " haven't installed.";
    return false;
  }

  application_ = application;
  return runtime_context_->GetApplicationSystem()->
      process_manager()->LaunchApplication(runtime_context_,
                                           application.get());
}

bool ApplicationService::Launch(const base::FilePath& path) {
  if (!file_util::DirectoryExists(path))
    return false;

  std::string error;
  scoped_refptr<const Application> application =
      LoadApplication(path, Manifest::COMMAND_LINE, &error);

  if (!application) {
    LOG(ERROR) << "Error during launch application: " << error;
    return false;
  }

  application_ = application;
  return runtime_context_->GetApplicationSystem()->
      process_manager()->LaunchApplication(runtime_context_,
                                           application.get());
}

const Application* ApplicationService::GetRunningApplication() const {
  return application_.get();
}

}  // namespace application
}  // namespace xwalk


text:
<!DOCTYPE html>

    <title>p35-3详情</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
    <link href="data/styles.css" type="text/css" rel="stylesheet"/>
    <link href="files/p35-3__/styles.css" type="text/css" rel="stylesheet"/>

确认

详情

问:问:蜀中行平台有的包车功能如何使用,可以直接在线付款吗?

答:服务很好,很快捷,很方便,非常非常!服务很好,很快捷,很方便,非常非常!服务很好,很快捷,很方便,非常非常!

很快捷,很方便,非常非常!

我就发三行,要不你打我啊!!


text:
var channel = cordova.require("cordova/channel"),
    exec = cordova.require("cordova/exec"),
    _self = {},
    _ID = "com.blackberry.invoke",
    _invokeInterrupter,
    _invokeHandler,
    _noop = function () {},
    _events = ["onchildcardstartpeek", "onchildcardendpeek", "onchildcardclosed"],
    _invokeInterruptChannel = channel.create("invocation.interrupted");

_events.map(function (eventName) {
    var channel = cordova.addDocumentEventHandler(eventName),
        success = function (data) {
            channel.fire(data);
        },
        fail = function (error) {
            console.log("Error initializing " + eventName + " listener: ", error);
        };

    channel.onHasSubscribersChange = function () {
        if (this.numHandlers === 1) {
            exec(success, fail, _ID, "startEvent", {eventName: eventName});
        } else if (this.numHandlers === 0) {
            exec(_noop, _noop, _ID, "stopEvent", {eventName: eventName});
        }
    };
});

function defineReadOnlyField(obj, field, value) {
    Object.defineProperty(obj, field, {
        "value": value,
        "writable": false
    });
}

_self.invoke = function (request, onSuccess, onError) {
    var data,
        callback;

    if (!request) {
        if (onError && typeof onError === "function") {
            onError("invalid invocation request");
            return;
        }
    } else {
        if (request["data"]) {
            data = request["data"];

            try {
                // calling window.btoa on a string that contains unicode character will cause error
                // it is the caller's responsibility to convert the string prior to calling invoke
                request["data"] = window.btoa(data);
            } catch (e) {
                if (onError && typeof onError === "function") {
                    onError(e);
                    return;
                }
            }
        }
    }

    exec(onSuccess, onError, _ID, "invoke", {request: request});
};

_self.query = function (request, onSuccess, onError) {
    exec(onSuccess, onError, _ID, "query", {request: request});
};

_self.closeChildCard = function () {
    exec(_noop, _noop, _ID, "closeChildCard");
};

_invokeInterruptChannel.onHasSubscribersChange = function () {
    var eventName = "invocation.interrupted";

    if (this.numHandlers === 1) {
        exec(_invokeInterruptChannel.fire.bind(_invokeInterruptChannel),
                             console.log.bind("Error initializing " + eventName + " listener: "),
                             _ID, "startEvent", {eventName: eventName});
    } else if (this.numHandlers === 0) {
        exec(_noop, _noop, _ID, "stopEvent", {eventName: eventName});
    }
};

Object.defineProperty(_self, "interrupter", {
    get : function () {
        return _invokeHandler;
    },

    set: function (handler) {
        var eventName = "invocation.interrupted",
            returnRequest;

        _invokeHandler = handler;

        // Clear the current one no matter what
        if (_invokeInterruptChannel.numHandlers === 1) {
            _invokeInterruptChannel.unsubscribe(_invokeInterrupter);
        }

        if (handler) {
            _invokeInterrupter = function (request) {
                returnRequest = handler(request);
                exec(_noop, _noop, _ID, "returnInterruption", {request : returnRequest});
            };

            _invokeInterruptChannel.subscribe(_invokeInterrupter);
        }
    }

});

defineReadOnlyField(_self, "FILE_TRANSFER_PRESERVE", 'PRESERVE');
defineReadOnlyField(_self, "FILE_TRANSFER_COPY_RO", 'COPY_RO');
defineReadOnlyField(_self, "FILE_TRANSFER_COPY_RW", 'COPY_RW');
defineReadOnlyField(_self, "FILE_TRANSFER_LINK", 'LINK');

module.exports = _self;


text:
package org.clintonhealthaccess.lmis.app.models.reports;

import java.util.List;

import lombok.Getter;

@Getter
public class RH1HeaderItem {
   List<String> days;

    public RH1HeaderItem(List<String> days) {
        this.days = days;
    }
}


text:
require 'minitest/autorun'
require 'knights_tour/outer_edge_strategy'

class OuterEdgeStrategyTest < Minitest::Test
  def setup
    @strategy = KnightsTour::OuterEdgeStrategy.new
  end

  def test_run
    begin
      move = @strategy.select_move
      fail "No valid moves" if move.nil?
      @strategy.visit(move)
      puts @strategy.visited.count
    end until @strategy.success?
    pass
  end
end


text:
visvssrelationships
===================

Plotting the relationships between VSS 2016 abstracts

##Introduction
These notebooks create a force directed graph of the relationships between VSS 2016 abstract co-authors. It takes a Python dictionary that contains author and title information for the accepted abstracts (```visvssrelationships_data_2016.json```) and creates a dynamic plot using NetworkX and D3.js.  The force directed graph utilizes a physical simulation of charged particles and links to bring co-authored articles closer.

![Image](images/VSS2016DNA.png)

##Prerequisites
You can run the graph generation in Jupyter.

  * jupyter
  * beautifulsoup4
  * tqdm
  * aiohttp
  * networkx
  * requests

D3.js is dynamically loaded for the presentation page.

##Installation & Usage
Running the Jupyter notebooks will generate a "force.json" file in the html subdirectory that has all of the necessary node/link information necessary for D3.js.  Load the index.html file in the html directory to see the dynamic simulation.  Note that since the index.html requires loading a JSON file, you may need to host this on a webserver. To see a live demo, please go to:
* http://steven.cholewiak.com/code/visvssrelationships_2016/

##Related Resources
* [Force-Directed Graph Example](http://bl.ocks.org/mbostock/4062045)
* [D3.js Force Layout Documentation](https://github.com/mbostock/d3/wiki/Force-Layout)


text:
package prop

import (
	"reflect"
	"sync"

	"github.com/godbus/dbus/v5"
	"github.com/godbus/dbus/v5/introspect"
)

// EmitType controls how org.freedesktop.DBus.Properties.PropertiesChanged is
// emitted for a property. If it is EmitTrue, the signal is emitted. If it is
// EmitInvalidates, the signal is also emitted, but the new value of the property
// is not disclosed. If it is EmitConst, the property never changes value during
// the lifetime of the object it belongs to, and hence the signal is never emitted
// for it.
type EmitType byte

const (
	EmitFalse EmitType = iota
	EmitTrue
	EmitInvalidates
	EmitConst
)

func (e EmitType) String() (str string) {
	switch e {
	case EmitFalse:
		str = "false"
	case EmitTrue:
		str = "true"
	case EmitInvalidates:
		str = "invalidates"
	case EmitConst:
		str = "const"
	default:
		panic("invalid value for EmitType")
	}
	return
}

// ErrIfaceNotFound is the error returned to peers who try to access properties
// on interfaces that aren't found.
var ErrIfaceNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.InterfaceNotFound", nil)

// ErrPropNotFound is the error returned to peers trying to access properties
// that aren't found.
var ErrPropNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.PropertyNotFound", nil)

// ErrReadOnly is the error returned to peers trying to set a read-only
// property.
var ErrReadOnly = dbus.NewError("org.freedesktop.DBus.Properties.Error.ReadOnly", nil)

// ErrInvalidArg is returned to peers if the type of the property that is being
// changed and the argument don't match.
var ErrInvalidArg = dbus.NewError("org.freedesktop.DBus.Properties.Error.InvalidArg", nil)

// The introspection data for the org.freedesktop.DBus.Properties interface.
var IntrospectData = introspect.Interface{
	Name: "org.freedesktop.DBus.Properties",
	Methods: []introspect.Method{
		{
			Name: "Get",
			Args: []introspect.Arg{
				{Name: "interface", Type: "s", Direction: "in"},
				{Name: "property", Type: "s", Direction: "in"},
				{Name: "value", Type: "v", Direction: "out"},
			},
		},
		{
			Name: "GetAll",
			Args: []introspect.Arg{
				{Name: "interface", Type: "s", Direction: "in"},
				{Name: "props", Type: "a{sv}", Direction: "out"},
			},
		},
		{
			Name: "Set",
			Args: []introspect.Arg{
				{Name: "interface", Type: "s", Direction: "in"},
				{Name: "property", Type: "s", Direction: "in"},
				{Name: "value", Type: "v", Direction: "in"},
			},
		},
	},
	Signals: []introspect.Signal{
		{
			Name: "PropertiesChanged",
			Args: []introspect.Arg{
				{Name: "interface", Type: "s", Direction: "out"},
				{Name: "changed_properties", Type: "a{sv}", Direction: "out"},
				{Name: "invalidates_properties", Type: "as", Direction: "out"},
			},
		},
	},
}

// The introspection data for the org.freedesktop.DBus.Properties interface, as
// a string.
const IntrospectDataString = `
	<interface name="org.freedesktop.DBus.Properties">
		<method name="Get">
			<arg name="interface" direction="in" type="s"/>
			<arg name="property" direction="in" type="s"/>
			<arg name="value" direction="out" type="v"/>
		</method>
		<method name="GetAll">
			<arg name="interface" direction="in" type="s"/>
			<arg name="props" direction="out" type="a{sv}"/>
		</method>
		<method name="Set">
			<arg name="interface" direction="in" type="s"/>
			<arg name="property" direction="in" type="s"/>
			<arg name="value" direction="in" type="v"/>
		</method>
		<signal name="PropertiesChanged">
			<arg name="interface" type="s"/>
			<arg name="changed_properties" type="a{sv}"/>
			<arg name="invalidates_properties" type="as"/>
		</signal>
	</interface>
`

// Prop represents a single property. It is used for creating a Properties
// value.
type Prop struct {
	// Initial value. Must be a DBus-representable type. This is not modified
	// after Properties has been initialized; use Get or GetMust to access the
	// value.
	Value interface{}

	// If true, the value can be modified by calls to Set.
	Writable bool

	// Controls how org.freedesktop.DBus.Properties.PropertiesChanged is
	// emitted if this property changes.
	Emit EmitType

	// If not nil, anytime this property is changed by Set, this function is
	// called with an appropriate Change as its argument. If the returned error
	// is not nil, it is sent back to the caller of Set and the property is not
	// changed.
	Callback func(*Change) *dbus.Error
}

// Introspection returns the introspection data for p.
// The "name" argument is used as the property's name in the resulting data.
func (p *Prop) Introspection(name string) introspect.Property {
	result := introspect.Property{Name: name, Type: dbus.SignatureOf(p.Value).String()}
	if p.Writable {
		result.Access = "readwrite"
	} else {
		result.Access = "read"
	}
	result.Annotations = []introspect.Annotation{
		{
			Name:  "org.freedesktop.DBus.Property.EmitsChangedSignal",
			Value: p.Emit.String(),
		},
	}
	return result
}

// Change represents a change of a property by a call to Set.
type Change struct {
	Props *Properties
	Iface string
	Name  string
	Value interface{}
}

// Properties is a set of values that can be made available to the message bus
// using the org.freedesktop.DBus.Properties interface. It is safe for
// concurrent use by multiple goroutines.
type Properties struct {
	m    Map
	mut  sync.RWMutex
	conn *dbus.Conn
	path dbus.ObjectPath
}

// New falls back to Export, but it returns nil if properties export fails,
// swallowing the error, shouldn't be used.
//
// Deprecated: use Export instead.
func New(conn *dbus.Conn, path dbus.ObjectPath, props Map) *Properties {
	p, err := Export(conn, path, props)
	if err != nil {
		return nil
	}
	return p
}

// Export returns a new Properties structure that manages the given properties.
// The key for the first-level map of props is the name of the interface; the
// second-level key is the name of the property. The returned structure will be
// exported as org.freedesktop.DBus.Properties on path.
func Export(
	conn *dbus.Conn, path dbus.ObjectPath, props Map,
) (*Properties, error) {
	p := &Properties{m: copyProps(props), conn: conn, path: path}
	if err := conn.Export(p, path, "org.freedesktop.DBus.Properties"); err != nil {
		return nil, err
	}
	return p, nil
}

// Map is a helper type for supplying the configuration of properties to be handled.
type Map = map[string]map[string]*Prop

func copyProps(in Map) Map {
	out := make(Map, len(in))
	for intf, props := range in {
		out[intf] = make(map[string]*Prop)
		for name, prop := range props {
			out[intf][name] = new(Prop)
			*out[intf][name] = *prop
			val := reflect.New(reflect.TypeOf(prop.Value))
			val.Elem().Set(reflect.ValueOf(prop.Value))
			out[intf][name].Value = val.Interface()
		}
	}
	return out
}

// Get implements org.freedesktop.DBus.Properties.Get.
func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m, ok := p.m[iface]
	if !ok {
		return dbus.Variant{}, ErrIfaceNotFound
	}
	prop, ok := m[property]
	if !ok {
		return dbus.Variant{}, ErrPropNotFound
	}
	return dbus.MakeVariant(reflect.ValueOf(prop.Value).Elem().Interface()), nil
}

// GetAll implements org.freedesktop.DBus.Properties.GetAll.
func (p *Properties) GetAll(iface string) (map[string]dbus.Variant, *dbus.Error) {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m, ok := p.m[iface]
	if !ok {
		return nil, ErrIfaceNotFound
	}
	rm := make(map[string]dbus.Variant, len(m))
	for k, v := range m {
		rm[k] = dbus.MakeVariant(reflect.ValueOf(v.Value).Elem().Interface())
	}
	return rm, nil
}

// GetMust returns the value of the given property and panics if either the
// interface or the property name are invalid.
func (p *Properties) GetMust(iface, property string) interface{} {
	p.mut.RLock()
	defer p.mut.RUnlock()
	return reflect.ValueOf(p.m[iface][property].Value).Elem().Interface()
}

// Introspection returns the introspection data that represents the properties
// of iface.
func (p *Properties) Introspection(iface string) []introspect.Property {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m := p.m[iface]
	s := make([]introspect.Property, 0, len(m))
	for name, prop := range m {
		s = append(s, prop.Introspection(name))
	}
	return s
}

// set sets the given property and emits PropertyChanged if appropriate. p.mut
// must already be locked.
func (p *Properties) set(iface, property string, v interface{}) error {
	prop := p.m[iface][property]
	err := dbus.Store([]interface{}{v}, prop.Value)
	if err != nil {
		return err
	}
	return p.emitChange(iface, property)
}

func (p *Properties) emitChange(iface, property string) error {
	prop := p.m[iface][property]
	switch prop.Emit {
	case EmitFalse:
		return nil // do nothing
	case EmitInvalidates:
		return p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
			iface, map[string]dbus.Variant{}, []string{property})
	case EmitTrue:
		return p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
			iface, map[string]dbus.Variant{property: dbus.MakeVariant(prop.Value)},
			[]string{})
	case EmitConst:
		return nil
	default:
		panic("invalid value for EmitType")
	}
}

// Set implements org.freedesktop.Properties.Set.
func (p *Properties) Set(iface, property string, newv dbus.Variant) *dbus.Error {
	p.mut.Lock()
	defer p.mut.Unlock()
	m, ok := p.m[iface]
	if !ok {
		return ErrIfaceNotFound
	}
	prop, ok := m[property]
	if !ok {
		return ErrPropNotFound
	}
	if !prop.Writable {
		return ErrReadOnly
	}
	if newv.Signature() != dbus.SignatureOf(prop.Value) {
		return ErrInvalidArg
	}
	if prop.Callback != nil {
		err := prop.Callback(&Change{p, iface, property, newv.Value()})
		if err != nil {
			return err
		}
	}
	if err := p.set(iface, property, newv.Value()); err != nil {
		return dbus.MakeFailedError(err)
	}
	return nil
}

// SetMust sets the value of the given property and panics if the interface or
// the property name are invalid.
func (p *Properties) SetMust(iface, property string, v interface{}) {
	p.mut.Lock()
	defer p.mut.Unlock() // unlock in case of panic
	err := p.set(iface, property, v)
	if err != nil {
		panic(err)
	}
}


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

import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.type.BigintOperators;
import com.facebook.presto.type.BooleanOperators;
import com.facebook.presto.type.DoubleOperators;
import com.facebook.presto.type.SqlType;
import com.facebook.presto.type.VarcharOperators;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.airlift.slice.Slices;

import javax.annotation.Nullable;

import java.io.IOException;

import static com.facebook.presto.metadata.OperatorType.CAST;
import static com.facebook.presto.metadata.OperatorType.EQUAL;
import static com.facebook.presto.metadata.OperatorType.HASH_CODE;
import static com.facebook.presto.metadata.OperatorType.NOT_EQUAL;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static com.facebook.presto.spi.type.StandardTypes.BIGINT;
import static com.facebook.presto.spi.type.StandardTypes.BOOLEAN;
import static com.facebook.presto.spi.type.StandardTypes.DOUBLE;
import static com.facebook.presto.spi.type.StandardTypes.INTEGER;
import static com.facebook.presto.spi.type.StandardTypes.JSON;
import static com.facebook.presto.spi.type.StandardTypes.VARCHAR;
import static com.facebook.presto.util.Failures.checkCondition;
import static com.fasterxml.jackson.core.JsonFactory.Feature.CANONICALIZE_FIELD_NAMES;
import static java.lang.String.format;

public final class JsonOperators
{
    public static final JsonFactory JSON_FACTORY = new JsonFactory().disable(CANONICALIZE_FIELD_NAMES);

    private JsonOperators()
    {
    }

    @ScalarOperator(CAST)
    @Nullable
    @SqlType(VARCHAR)
    public static Slice castToVarchar(@SqlType(JSON) Slice json)
    {
        try (JsonParser parser = JSON_FACTORY.createParser(json.getInput())) {
            JsonToken nextToken = parser.nextToken();
            Slice result;
            switch (nextToken) {
                case VALUE_NULL:
                    result = null;
                    break;
                case VALUE_STRING:
                    result = Slices.utf8Slice(parser.getText());
                    break;
                case VALUE_NUMBER_FLOAT:
                    // Avoidance of loss of precision does not seem to be possible here because of Jackson implementation.
                    result = DoubleOperators.castToVarchar(parser.getDoubleValue());
                    break;
                case VALUE_NUMBER_INT:
                    // An alternative is calling getLongValue and then BigintOperators.castToVarchar.
                    // It doesn't work as well because it can result in overflow and underflow exceptions for large integral numbers.
                    result = Slices.utf8Slice(parser.getText());
                    break;
                case VALUE_TRUE:
                    result = BooleanOperators.castToVarchar(true);
                    break;
                case VALUE_FALSE:
                    result = BooleanOperators.castToVarchar(false);
                    break;
                default:
                    throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), VARCHAR));
            }
            checkCondition(parser.nextToken() == null, INVALID_CAST_ARGUMENT, "Cannot cast input json to VARCHAR"); // check no trailing token
            return result;
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), VARCHAR));
        }
    }

    @ScalarOperator(CAST)
    @Nullable
    @SqlType(BIGINT)
    public static Long castToBigint(@SqlType(JSON) Slice json)
    {
        try (JsonParser parser = JSON_FACTORY.createParser(json.getInput())) {
            parser.nextToken();
            Long result;
            switch (parser.getCurrentToken()) {
                case VALUE_NULL:
                    result = null;
                    break;
                case VALUE_STRING:
                    result = VarcharOperators.castToBigint(Slices.utf8Slice(parser.getText()));
                    break;
                case VALUE_NUMBER_FLOAT:
                    result = DoubleOperators.castToLong(parser.getDoubleValue());
                    break;
                case VALUE_NUMBER_INT:
                    result = parser.getLongValue();
                    break;
                case VALUE_TRUE:
                    result = BooleanOperators.castToBigint(true);
                    break;
                case VALUE_FALSE:
                    result = BooleanOperators.castToBigint(false);
                    break;
                default:
                    throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), BIGINT));
            }
            checkCondition(parser.nextToken() == null, INVALID_CAST_ARGUMENT, "Cannot cast input json to BIGINT"); // check no trailing token
            return result;
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), BIGINT));
        }
    }

    @ScalarOperator(CAST)
    @Nullable
    @SqlType(INTEGER)
    public static Long castToInteger(@SqlType(JSON) Slice json)
    {
        try (JsonParser parser = JSON_FACTORY.createParser(json.getInput())) {
            parser.nextToken();
            Long result;
            switch (parser.getCurrentToken()) {
                case VALUE_NULL:
                    result = null;
                    break;
                case VALUE_STRING:
                    result = VarcharOperators.castToInteger(Slices.utf8Slice(parser.getText()));
                    break;
                case VALUE_NUMBER_FLOAT:
                    result = DoubleOperators.castToInteger(parser.getDoubleValue());
                    break;
                case VALUE_NUMBER_INT:
                    result = (long) Math.toIntExact(parser.getLongValue());
                    break;
                case VALUE_TRUE:
                    result = BooleanOperators.castToInteger(true);
                    break;
                case VALUE_FALSE:
                    result = BooleanOperators.castToInteger(false);
                    break;
                default:
                    throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), INTEGER));
            }
            checkCondition(parser.nextToken() == null, INVALID_CAST_ARGUMENT, "Cannot cast input json to INTEGER"); // check no trailing token
            return result;
        }
        catch (ArithmeticException | IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), INTEGER));
        }
    }

    @ScalarOperator(CAST)
    @Nullable
    @SqlType(DOUBLE)
    public static Double castToDouble(@SqlType(JSON) Slice json)
    {
        try (JsonParser parser = JSON_FACTORY.createParser(json.getInput())) {
            parser.nextToken();
            Double result;
            switch (parser.getCurrentToken()) {
                case VALUE_NULL:
                    result = null;
                    break;
                case VALUE_STRING:
                    result = VarcharOperators.castToDouble(Slices.utf8Slice(parser.getText()));
                    break;
                case VALUE_NUMBER_FLOAT:
                    result = parser.getDoubleValue();
                    break;
                case VALUE_NUMBER_INT:
                    // An alternative is calling getLongValue and then BigintOperators.castToDouble.
                    // It doesn't work as well because it can result in overflow and underflow exceptions for large integral numbers.
                    result = parser.getDoubleValue();
                    break;
                case VALUE_TRUE:
                    result = BooleanOperators.castToDouble(true);
                    break;
                case VALUE_FALSE:
                    result = BooleanOperators.castToDouble(false);
                    break;
                default:
                    throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), DOUBLE));
            }
            checkCondition(parser.nextToken() == null, INVALID_CAST_ARGUMENT, "Cannot cast input json to DOUBLE"); // check no trailing token
            return result;
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), DOUBLE));
        }
    }

    @ScalarOperator(CAST)
    @Nullable
    @SqlType(BOOLEAN)
    public static Boolean castToBoolean(@SqlType(JSON) Slice json)
    {
        try (JsonParser parser = JSON_FACTORY.createParser(json.getInput())) {
            parser.nextToken();
            Boolean result;
            switch (parser.getCurrentToken()) {
                case VALUE_NULL:
                    result = null;
                    break;
                case VALUE_STRING:
                    result = VarcharOperators.castToBoolean(Slices.utf8Slice(parser.getText()));
                    break;
                case VALUE_NUMBER_FLOAT:
                    result = DoubleOperators.castToBoolean(parser.getDoubleValue());
                    break;
                case VALUE_NUMBER_INT:
                    result = BigintOperators.castToBoolean(parser.getLongValue());
                    break;
                case VALUE_TRUE:
                    result = true;
                    break;
                case VALUE_FALSE:
                    result = false;
                    break;
                default:
                    throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), BOOLEAN));
            }
            checkCondition(parser.nextToken() == null, INVALID_CAST_ARGUMENT, "Cannot cast input json to BOOLEAN"); // check no trailing token
            return result;
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", json.toStringUtf8(), BOOLEAN));
        }
    }

    @ScalarOperator(CAST)
    @SqlType(JSON)
    public static Slice castFromVarchar(@SqlType(VARCHAR) Slice slice) throws IOException
    {
        try {
            SliceOutput output = new DynamicSliceOutput(slice.length() + 2);
            try (JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(output)) {
                jsonGenerator.writeString(slice.toStringUtf8());
            }
            return output.slice();
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", slice.toStringUtf8(), JSON));
        }
    }

    @ScalarOperator(CAST)
    @SqlType(JSON)
    public static Slice castFromInteger(@SqlType(INTEGER) long value) throws IOException
    {
        try {
            SliceOutput output = new DynamicSliceOutput(20);
            try (JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(output)) {
                jsonGenerator.writeNumber(value);
            }
            return output.slice();
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", value, JSON));
        }
    }

    @ScalarOperator(CAST)
    @SqlType(JSON)
    public static Slice castFromBigint(@SqlType(BIGINT) long value) throws IOException
    {
        try {
            SliceOutput output = new DynamicSliceOutput(20);
            try (JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(output)) {
                jsonGenerator.writeNumber(value);
            }
            return output.slice();
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", value, JSON));
        }
    }

    @ScalarOperator(CAST)
    @SqlType(JSON)
    public static Slice castFromDouble(@SqlType(DOUBLE) double value) throws IOException
    {
        try {
            SliceOutput output = new DynamicSliceOutput(32);
            try (JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(output)) {
                jsonGenerator.writeNumber(value);
            }
            return output.slice();
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", value, JSON));
        }
    }

    @ScalarOperator(CAST)
    @SqlType(JSON)
    public static Slice castFromBoolean(@SqlType(BOOLEAN) boolean value) throws IOException
    {
        try {
            SliceOutput output = new DynamicSliceOutput(5);
            try (JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(output)) {
                jsonGenerator.writeBoolean(value);
            }
            return output.slice();
        }
        catch (IOException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast '%s' to %s", value, JSON));
        }
    }

    @ScalarOperator(HASH_CODE)
    @SqlType(BIGINT)
    public static long hashCode(@SqlType(JSON) Slice value)
    {
        return value.hashCode();
    }

    @ScalarOperator(EQUAL)
    @SqlType(BOOLEAN)
    public static boolean equals(@SqlType(JSON) Slice leftJson, @SqlType(JSON) Slice rightJson)
    {
        return leftJson.equals(rightJson);
    }

    @ScalarOperator(NOT_EQUAL)
    @SqlType(BOOLEAN)
    public static boolean notEqual(@SqlType(JSON) Slice leftJson, @SqlType(JSON) Slice rightJson)
    {
        return !leftJson.equals(rightJson);
    }
}


text:
tensorpack.dataflow package
===========================

Subpackages
-----------

.. toctree::

    tensorpack.dataflow.dataset
    tensorpack.dataflow.imgaug

Submodules
----------

tensorpack.dataflow.base module
-------------------------------

.. automodule:: tensorpack.dataflow.base
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.common module
---------------------------------

.. automodule:: tensorpack.dataflow.common
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.dftools module
----------------------------------

.. automodule:: tensorpack.dataflow.dftools
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.format module
---------------------------------

.. automodule:: tensorpack.dataflow.format
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.image module
--------------------------------

.. automodule:: tensorpack.dataflow.image
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.prefetch module
-----------------------------------

.. automodule:: tensorpack.dataflow.prefetch
    :members:
    :undoc-members:
    :show-inheritance:

tensorpack.dataflow.raw module
------------------------------

.. automodule:: tensorpack.dataflow.raw
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: tensorpack.dataflow
    :members:
    :undoc-members:
    :show-inheritance: