text:
namespace T5Suite2
{
    partial class frmDecodeVIN
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textEdit1 = new DevExpress.XtraEditors.TextEdit();
            this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
            this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
            this.lblCarModel = new DevExpress.XtraEditors.LabelControl();
            this.lblEngineType = new DevExpress.XtraEditors.LabelControl();
            this.lblTurbo = new DevExpress.XtraEditors.LabelControl();
            this.lblMakeyear = new DevExpress.XtraEditors.LabelControl();
            this.labelControl6 = new DevExpress.XtraEditors.LabelControl();
            this.labelControl7 = new DevExpress.XtraEditors.LabelControl();
            this.labelControl8 = new DevExpress.XtraEditors.LabelControl();
            this.labelControl9 = new DevExpress.XtraEditors.LabelControl();
            this.labelControl10 = new DevExpress.XtraEditors.LabelControl();
            this.lblPlant = new DevExpress.XtraEditors.LabelControl();
            this.labelControl12 = new DevExpress.XtraEditors.LabelControl();
            this.lblSeries = new DevExpress.XtraEditors.LabelControl();
            this.labelControl14 = new DevExpress.XtraEditors.LabelControl();
            this.lblBody = new DevExpress.XtraEditors.LabelControl();
            this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
            ((System.ComponentModel.ISupportInitialize)(this.textEdit1.Properties)).BeginInit();
            this.SuspendLayout();
            //
            // textEdit1
            //
            this.textEdit1.Location = new System.Drawing.Point(83, 12);
            this.textEdit1.Name = "textEdit1";
            this.textEdit1.Size = new System.Drawing.Size(302, 20);
            this.textEdit1.TabIndex = 0;
            this.textEdit1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textEdit1_KeyDown);
            //
            // simpleButton1
            //
            this.simpleButton1.Location = new System.Drawing.Point(401, 9);
            this.simpleButton1.Name = "simpleButton1";
            this.simpleButton1.Size = new System.Drawing.Size(75, 23);
            this.simpleButton1.TabIndex = 1;
            this.simpleButton1.Text = "Decode";
            this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
            //
            // labelControl1
            //
            this.labelControl1.Location = new System.Drawing.Point(9, 16);
            this.labelControl1.Name = "labelControl1";
            this.labelControl1.Size = new System.Drawing.Size(56, 13);
            this.labelControl1.TabIndex = 2;
            this.labelControl1.Text = "VIN number";
            //
            // lblCarModel
            //
            this.lblCarModel.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblCarModel.Appearance.Options.UseForeColor = true;
            this.lblCarModel.Location = new System.Drawing.Point(196, 47);
            this.lblCarModel.Name = "lblCarModel";
            this.lblCarModel.Size = new System.Drawing.Size(12, 13);
            this.lblCarModel.TabIndex = 3;
            this.lblCarModel.Text = "---";
            //
            // lblEngineType
            //
            this.lblEngineType.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblEngineType.Appearance.Options.UseForeColor = true;
            this.lblEngineType.Location = new System.Drawing.Point(196, 66);
            this.lblEngineType.Name = "lblEngineType";
            this.lblEngineType.Size = new System.Drawing.Size(12, 13);
            this.lblEngineType.TabIndex = 4;
            this.lblEngineType.Text = "---";
            //
            // lblTurbo
            //
            this.lblTurbo.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblTurbo.Appearance.Options.UseForeColor = true;
            this.lblTurbo.Location = new System.Drawing.Point(196, 85);
            this.lblTurbo.Name = "lblTurbo";
            this.lblTurbo.Size = new System.Drawing.Size(12, 13);
            this.lblTurbo.TabIndex = 5;
            this.lblTurbo.Text = "---";
            //
            // lblMakeyear
            //
            this.lblMakeyear.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblMakeyear.Appearance.Options.UseForeColor = true;
            this.lblMakeyear.Location = new System.Drawing.Point(196, 104);
            this.lblMakeyear.Name = "lblMakeyear";
            this.lblMakeyear.Size = new System.Drawing.Size(12, 13);
            this.lblMakeyear.TabIndex = 6;
            this.lblMakeyear.Text = "---";
            //
            // labelControl6
            //
            this.labelControl6.Location = new System.Drawing.Point(83, 104);
            this.labelControl6.Name = "labelControl6";
            this.labelControl6.Size = new System.Drawing.Size(47, 13);
            this.labelControl6.TabIndex = 10;
            this.labelControl6.Text = "Makeyear";
            //
            // labelControl7
            //
            this.labelControl7.Location = new System.Drawing.Point(83, 85);
            this.labelControl7.Name = "labelControl7";
            this.labelControl7.Size = new System.Drawing.Size(28, 13);
            this.labelControl7.TabIndex = 9;
            this.labelControl7.Text = "Turbo";
            //
            // labelControl8
            //
            this.labelControl8.Location = new System.Drawing.Point(83, 66);
            this.labelControl8.Name = "labelControl8";
            this.labelControl8.Size = new System.Drawing.Size(57, 13);
            this.labelControl8.TabIndex = 8;
            this.labelControl8.Text = "Engine type";
            //
            // labelControl9
            //
            this.labelControl9.Location = new System.Drawing.Point(83, 47);
            this.labelControl9.Name = "labelControl9";
            this.labelControl9.Size = new System.Drawing.Size(48, 13);
            this.labelControl9.TabIndex = 7;
            this.labelControl9.Text = "Car model";
            //
            // labelControl10
            //
            this.labelControl10.Location = new System.Drawing.Point(83, 123);
            this.labelControl10.Name = "labelControl10";
            this.labelControl10.Size = new System.Drawing.Size(72, 13);
            this.labelControl10.TabIndex = 12;
            this.labelControl10.Text = "Assembly plant";
            //
            // lblPlant
            //
            this.lblPlant.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblPlant.Appearance.Options.UseForeColor = true;
            this.lblPlant.Location = new System.Drawing.Point(196, 123);
            this.lblPlant.Name = "lblPlant";
            this.lblPlant.Size = new System.Drawing.Size(12, 13);
            this.lblPlant.TabIndex = 11;
            this.lblPlant.Text = "---";
            //
            // labelControl12
            //
            this.labelControl12.Location = new System.Drawing.Point(83, 142);
            this.labelControl12.Name = "labelControl12";
            this.labelControl12.Size = new System.Drawing.Size(29, 13);
            this.labelControl12.TabIndex = 14;
            this.labelControl12.Text = "Series";
            //
            // lblSeries
            //
            this.lblSeries.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblSeries.Appearance.Options.UseForeColor = true;
            this.lblSeries.Location = new System.Drawing.Point(196, 142);
            this.lblSeries.Name = "lblSeries";
            this.lblSeries.Size = new System.Drawing.Size(12, 13);
            this.lblSeries.TabIndex = 13;
            this.lblSeries.Text = "---";
            //
            // labelControl14
            //
            this.labelControl14.Location = new System.Drawing.Point(83, 161);
            this.labelControl14.Name = "labelControl14";
            this.labelControl14.Size = new System.Drawing.Size(24, 13);
            this.labelControl14.TabIndex = 16;
            this.labelControl14.Text = "Body";
            //
            // lblBody
            //
            this.lblBody.Appearance.ForeColor = System.Drawing.Color.DarkBlue;
            this.lblBody.Appearance.Options.UseForeColor = true;
            this.lblBody.Location = new System.Drawing.Point(196, 161);
            this.lblBody.Name = "lblBody";
            this.lblBody.Size = new System.Drawing.Size(12, 13);
            this.lblBody.TabIndex = 15;
            this.lblBody.Text = "---";
            //
            // simpleButton2
            //
            this.simpleButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.simpleButton2.Location = new System.Drawing.Point(401, 191);
            this.simpleButton2.Name = "simpleButton2";
            this.simpleButton2.Size = new System.Drawing.Size(75, 23);
            this.simpleButton2.TabIndex = 17;
            this.simpleButton2.Text = "Close";
            //
            // frmDecodeVIN
            //
            this.AcceptButton = this.simpleButton1;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.simpleButton2;
            this.ClientSize = new System.Drawing.Size(488, 226);
            this.Controls.Add(this.simpleButton2);
            this.Controls.Add(this.labelControl14);
            this.Controls.Add(this.lblBody);
            this.Controls.Add(this.labelControl12);
            this.Controls.Add(this.lblSeries);
            this.Controls.Add(this.labelControl10);
            this.Controls.Add(this.lblPlant);
            this.Controls.Add(this.labelControl6);
            this.Controls.Add(this.labelControl7);
            this.Controls.Add(this.labelControl8);
            this.Controls.Add(this.labelControl9);
            this.Controls.Add(this.lblMakeyear);
            this.Controls.Add(this.lblTurbo);
            this.Controls.Add(this.lblEngineType);
            this.Controls.Add(this.lblCarModel);
            this.Controls.Add(this.labelControl1);
            this.Controls.Add(this.simpleButton1);
            this.Controls.Add(this.textEdit1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmDecodeVIN";
            this.ShowIcon = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "VIN decoder";
            this.Load += new System.EventHandler(this.frmDecodeVIN_Load);
            ((System.ComponentModel.ISupportInitialize)(this.textEdit1.Properties)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private DevExpress.XtraEditors.TextEdit textEdit1;
        private DevExpress.XtraEditors.SimpleButton simpleButton1;
        private DevExpress.XtraEditors.LabelControl labelControl1;
        private DevExpress.XtraEditors.LabelControl lblCarModel;
        private DevExpress.XtraEditors.LabelControl lblEngineType;
        private DevExpress.XtraEditors.LabelControl lblTurbo;
        private DevExpress.XtraEditors.LabelControl lblMakeyear;
        private DevExpress.XtraEditors.LabelControl labelControl6;
        private DevExpress.XtraEditors.LabelControl labelControl7;
        private DevExpress.XtraEditors.LabelControl labelControl8;
        private DevExpress.XtraEditors.LabelControl labelControl9;
        private DevExpress.XtraEditors.LabelControl labelControl10;
        private DevExpress.XtraEditors.LabelControl lblPlant;
        private DevExpress.XtraEditors.LabelControl labelControl12;
        private DevExpress.XtraEditors.LabelControl lblSeries;
        private DevExpress.XtraEditors.LabelControl labelControl14;
        private DevExpress.XtraEditors.LabelControl lblBody;
        private DevExpress.XtraEditors.SimpleButton simpleButton2;
    }
}


text:
/* global require, describe, it, before, after, beforeEach, afterEach */
'use strict';

var assert = require('chai').assert,
    request = require('request');

var savedLogLevel;

// NOTE: running tests with log level 'FATAL' to suppress logging during mock server tests.

describe('Error handling and misconfiguration', function () {
    var server = require('../index.js')(),
        port = 8000,
        url = 'http://localhost:' + port;

    it('should return 500 if no handlers', function (done) {
        server.clearHandlers();
        request.get(url, function (err, res, body) {
            assert(res.statusCode === 500);
            assert.include(body, 'Missing handler');
            done();
        });
    });

    it('should return 500 if handler throws error', function (done) {
        server.setHandler(function () { throw new Error('Dummy message: internal error'); });
        request.get(url, function (err, res, body) {
            assert(res.statusCode === 500);
            assert.include(body, 'Dummy message: internal error');
            done();
        });
    });

    before(function () {
        savedLogLevel = process.env.LOG_LEVEL;
        process.env.LOG_LEVEL = 'FATAL';
    });

    after(function () {
        process.env.LOG_LEVEL = savedLogLevel;
    });

    beforeEach(function (done) {
        server.listen(port, done);
    });

    afterEach(function (done) {
        server.close(done);
    });
});

redpajama_set_name: RedPajamaGithub


text:
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'

module Google
  module Apis
    module AppsactivityV1
      # Google Apps Activity API
      #
      # Provides a historical view of activity.
      #
      # @example
      #    require 'google/apis/appsactivity_v1'
      #
      #    Appsactivity = Google::Apis::AppsactivityV1 # Alias the module
      #    service = Appsactivity::AppsactivityService.new
      #
      # @see https://developers.google.com/google-apps/activity/
      class AppsactivityService < Google::Apis::Core::BaseService
        # @return [String]
        #  API key. Your API key identifies your project and provides you with API access,
        #  quota, and reports. Required unless you provide an OAuth 2.0 token.
        attr_accessor :key

        # @return [String]
        #  Available to use for quota purposes for server-side applications. Can be any
        #  arbitrary string assigned to a user, but should not exceed 40 characters.
        #  Overrides userIp if both are provided.
        attr_accessor :quota_user

        # @return [String]
        #  IP address of the site where the request originates. Use this if you want to
        #  enforce per-user limits.
        attr_accessor :user_ip

        def initialize
          super('https://www.googleapis.com/', 'appsactivity/v1/')
        end

        # Returns a list of activities visible to the current logged in user. Visible
        # activities are determined by the visiblity settings of the object that was
        # acted on, e.g. Drive files a user can see. An activity is a record of past
        # events. Multiple events may be merged if they are similar. A request is scoped
        # to activities from a given Google service using the source parameter.
        # @param [String] drive_ancestor_id
        #   Identifies the Drive folder containing the items for which to return
        #   activities.
        # @param [String] drive_file_id
        #   Identifies the Drive item to return activities for.
        # @param [String] grouping_strategy
        #   Indicates the strategy to use when grouping singleEvents items in the
        #   associated combinedEvent object.
        # @param [Fixnum] page_size
        #   The maximum number of events to return on a page. The response includes a
        #   continuation token if there are more events.
        # @param [String] page_token
        #   A token to retrieve a specific page of results.
        # @param [String] source
        #   The Google service from which to return activities. Possible values of source
        #   are:
        #   - drive.google.com
        # @param [String] user_id
        #   Indicates the user to return activity for. Use the special value me to
        #   indicate the currently authenticated user.
        # @param [String] fields
        #   Selector specifying which fields to include in a partial response.
        # @param [String] quota_user
        #   Available to use for quota purposes for server-side applications. Can be any
        #   arbitrary string assigned to a user, but should not exceed 40 characters.
        #   Overrides userIp if both are provided.
        # @param [String] user_ip
        #   IP address of the site where the request originates. Use this if you want to
        #   enforce per-user limits.
        # @param [Google::Apis::RequestOptions] options
        #   Request-specific options
        #
        # @yield [result, err] Result & error if block supplied
        # @yieldparam result [Google::Apis::AppsactivityV1::ListActivitiesResponse] parsed result object
        # @yieldparam err [StandardError] error object if request failed
        #
        # @return [Google::Apis::AppsactivityV1::ListActivitiesResponse]
        #
        # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
        # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
        # @raise [Google::Apis::AuthorizationError] Authorization is required
        def list_activities(drive_ancestor_id: nil, drive_file_id: nil, grouping_strategy: nil, page_size: nil, page_token: nil, source: nil, user_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
          command =  make_simple_command(:get, 'activities', options)
          command.response_representation = Google::Apis::AppsactivityV1::ListActivitiesResponse::Representation
          command.response_class = Google::Apis::AppsactivityV1::ListActivitiesResponse
          command.query['drive.ancestorId'] = drive_ancestor_id unless drive_ancestor_id.nil?
          command.query['drive.fileId'] = drive_file_id unless drive_file_id.nil?
          command.query['groupingStrategy'] = grouping_strategy unless grouping_strategy.nil?
          command.query['pageSize'] = page_size unless page_size.nil?
          command.query['pageToken'] = page_token unless page_token.nil?
          command.query['source'] = source unless source.nil?
          command.query['userId'] = user_id unless user_id.nil?
          command.query['fields'] = fields unless fields.nil?
          command.query['quotaUser'] = quota_user unless quota_user.nil?
          command.query['userIp'] = user_ip unless user_ip.nil?
          execute_or_queue_command(command, &block)
        end

        protected

        def apply_command_defaults(command)
          command.query['key'] = key unless key.nil?
          command.query['quotaUser'] = quota_user unless quota_user.nil?
          command.query['userIp'] = user_ip unless user_ip.nil?
        end
      end
    end
  end
end


text:
set -ex

# CocoaPods requires the terminal to be using UTF-8 encoding.
export LANG=en_US.UTF-8

cd "$(dirname "$0")"

# Check that required tools are available.
hash pod 2>/dev/null || { echo >&2 "Cocoapods needs to be installed."; exit 1; }
hash xcodebuild 2>/dev/null || {
    echo >&2 "XCode command-line tools need to be installed."
    exit 1
}

# clean up pod cache and existing pods
rm -Rf Pods Podfile.lock CFStreamTests.xcworkspace
time pod cache clean --all

time pod install --verbose

# ios-test-cfstream-tests flakes sometimes because of missing files in gRPC-Core,
# add some log to help find out the root cause.
# TODO(yulinliang): Delete it after solving the issue.
if [ -d "./Pods/Headers/Public/gRPC-Core/grpc/impl/codegen" ]
then
    echo "grpc/impl/codegen/ has been imported."
    number_of_files=$(find Pods/Headers/Public/gRPC-Core/grpc/impl/codegen -name "*.h" | wc -l)
    echo "The number of files in Pods/Headers/Public/gRPC-Core/grpc/impl/codegen/ is $number_of_files"
else
    echo "Error: grpc/impl/codegen/ hasn't been imported."
fi


text:
package com.hoolay.animation.basic;

import android.graphics.drawable.Animatable;
import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.hoolay.animation.BaseFragment;
import com.hoolay.animation.R;

/*
本类只要演示了上传动画、声音动画、loading动画

loading动画实现方式:
    1>使用Frame动画可以实现,因为没有找到那么多图片所以本类中没有实现.可以参考上传动画;
    2>使用animated-rotate实现,但是效果不佳,不能定义frameCount.
      白色部分(最白的那一帧)始终在一个位置,不会走动.[仔细看下第一个loading]
      而且旋转一圈后,还有细微的停顿感
    3>使用RotationAnimation实现, 自定义interpolator. 效果也不错

    总结: 最差的是第一种方式, 需要的图片比较多. 实际项目中可以使用方式3,一张图片搞定,效果也不错!
 */

/**
 * Created by chiclaim on 2016/06/14
 */
public class ViewAnimationFrameFragment extends BaseFragment {

    private ImageView ivUpload, ivLoading, ivLoading2, ivSound;
    private ProgressView ivLoading3;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_view_animation_frame;
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        view.findViewById(R.id.btn_start_upload).setOnClickListener(this);
        view.findViewById(R.id.btn_start_sound).setOnClickListener(this);
        view.findViewById(R.id.btn_start_loading).setOnClickListener(this);
        view.findViewById(R.id.btn_start_loading2).setOnClickListener(this);
        ivUpload = (ImageView) view.findViewById(R.id.iv_upload);
        ivSound = (ImageView) view.findViewById(R.id.iv_sound);
        ivLoading = (ImageView) view.findViewById(R.id.iv_loading);
        ivLoading2 = (ImageView) view.findViewById(R.id.iv_loading2);
        ivLoading3 = (ProgressView) view.findViewById(R.id.iv_loading3);
        ivLoading3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_start_upload:
                ivUpload.setBackgroundResource(R.drawable.frame_animation_upload);
                AnimationDrawable uploadAnimation = (AnimationDrawable) ivUpload.getBackground();
                uploadAnimation.start();
                break;
            case R.id.btn_start_sound:
                ivSound.setBackgroundResource(R.drawable.frame_animation_sound);
                AnimationDrawable uploadAnimation2 = (AnimationDrawable) ivSound.getBackground();
                uploadAnimation2.start();
                break;
            case R.id.btn_start_loading:
                ivLoading.setBackgroundResource(R.drawable.rotation_animation1);
                Animatable uploadAnimation1 = (Animatable) ivLoading.getBackground();
                uploadAnimation1.start();
                break;

            case R.id.btn_start_loading2:
                Animation a = AnimationUtils.loadAnimation(getContext(),
                        R.anim.rotation_animation2);
                a.setInterpolator(new android.view.animation.Interpolator() {
                    //总共有多少帧(具体根据图片来设置)
                    private final int frameCount = 12;
                    @Override
                    public float getInterpolation(float input) {
                        return (float) Math.floor(input * frameCount) / frameCount;
                    }
                });
                a.setDuration(1500);
                ivLoading2.startAnimation(a);
                break;
            case R.id.iv_loading3:
                ivLoading3.toggleAnimation();
                break;
        }
    }

}


text:
#include <stdio.h>
#include <unistd.h>
#include "stdlib.h"
#include "string.h"
#include "icp.h"
#include "topics.h"
#include "mqtt.h"
#include "dbg.h"

volatile MQTTAsync 			*p_client;

/**
 * Print out the packet content.
 * @param p_packet Pointer to the packet.
 */
uint8_t print_packet( icp_packet_t *p_packet ) {
	int i = 0;

	if (p_packet == NULL) {
		SENTINEL("Packet is NULL");
	}

	printf("Packet content:\n");
	printf("   destination[%02X]:\t%s\n", p_packet->destination, mac_addrs[p_packet->destination]);
	printf("        source[%02X]:\t%s\n", p_packet->source, mac_addrs[p_packet->source]);
	printf("            received:\t%hu\n", p_packet->receive_timestamp);
	printf("  data_len[%02X %02X]:\t%d\n", p_packet->data_length >> 8, (uint8_t)(p_packet->data_length & 0x00FF), p_packet->data_length);
	printf("               data:\t");
	for (i=0; i < p_packet->data_length+1; i++) {
		putchar( i ? ' ': '[' );
		printf("%02X", p_packet->data[i]);
	}
	printf("] \"");
	for (i=0; i < p_packet->data_length+1; i++) {
		putchar( p_packet->data[i] );
	}
	puts("\"");

	return 0;

error:
	return -1;

}

uint8_t icp_bytes_out_cb( const uint8_t* output_byte_array, buf_index_t array_len ) {
	int i = 0;
	MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
	sent = FALSE;

	ICP_CHECK_MEM(output_byte_array);
	ICP_CHECK_WARN(array_len != 0, "array_len, 0")

	ICP_LOG_INFO("Outputting %d bytes", array_len);
	ICP_DEBUG_({
		printf("[ ");
		for (i=0; i < array_len; i++) {
			printf("%02X ", output_byte_array[i]);
		}
		puts("]");
	});
	pubmsg.payload = (char*)output_byte_array;
	pubmsg.payloadlen = array_len;
	pubmsg.qos = QOS;
	pubmsg.retained = 0;

	ICP_CHECK_MEM(p_client);
	sendmsg(*p_client, topic_names[TOPIC_PRIM_RS485], &pubmsg);

	while(!sent);

	icp_notify_bytes_out_finished();

	ICP_DEBUG("Returning: %d", array_len);
	return array_len;

error:
	return 0;
}

uint8_t icp_packet_received_cb( icp_packet_t *new_packet ) {
	ICP_CHECK_MEM(new_packet);
	print_packet( new_packet );
	return 0;
error:
	return -1;
}

uint8_t icp_error_cb( icp_error_t error, uint8_t* packet_data, buf_index_t packet_length ) {
	char error_names[][50] = {"ICP_SUCCESS", "ICP_BUSY", "ICP_INVALID_PARAMETERS", "ICP_TOO_SHORT_PACKET", "ICP_TOO_SHORT_PAYLOAD", "ICP_ESCAPE_ERROR", "ICP_FAWLTY_CHECKSUM", "ICP_WRONG_RECIPIENT", "ICP_QUEUE_FULL", "ICP_GOT_NACK", "ICP_PACKET_RECEIVED_OUT_OF_ORDER", "ICP_PACKET_COULD_NOT_BE_DELIVERED", "ICP_QUEUE_LOCKED"};

	ICP_CHECK_MEM(packet_data);
	ICP_CHECK_WARN(packet_length != 0, "packet_length, 0");

	if (error >= NUM_OF_ERROR_CODES){
		ICP_LOG_ERR("Unknown error : %d", error);
	}
	else{
		ICP_LOG_ERR("%s", error_names[error]);
	}
	return 0;

error:
	return -1;
}

icp_time_t icp_get_time_cb( void ) {
	return 1;
}

uint8_t icp_notify_packet_ack_cb( void ) {
	// MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
	// char str[64] = "ACTIVE by ";
	// strcat (str, mac_addrs[local_mac_addr]);
	// uint8_t timeout = 0;
	// sent = FALSE;

	// pubmsg.payload = (char*)str;
	// pubmsg.payloadlen = strlen(str);
	// pubmsg.qos = QOS;
	// pubmsg.retained = 0;

	// sendmsg(*p_client, topic_names[TOPIC_PRIM_ACCESS_OUT], &pubmsg);

	// while (g_access == INACTIVE && timeout < 10){
	// 	sleep(1);
	// 	timeout++; // TODO should this be part of ICP ??
	// }

	LOG_INFO("I got ACK. My last packet has been transmitted");

	return ICP_SUCCESS;
}

uint8_t icp_set_access_sig_cb( void ) {
	MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
	char str[64] = "ACTIVE by ";
	strcat (str, mac_addrs[local_mac_addr]);
	uint8_t timeout = 0;
	sent = FALSE;

	pubmsg.payload = (char*)str;
	pubmsg.payloadlen = strlen(str);
	pubmsg.qos = QOS;
	pubmsg.retained = 0;

	sendmsg(*p_client, topic_names[TOPIC_PRIM_ACCESS_OUT], &pubmsg);

	while (g_access == INACTIVE && timeout < 10){
		sleep(1);
		timeout++; // TODO should this be part of ICP ??
	}

	return line_is_mine ? ICP_SUCCESS : ICP_BUSY;
}

uint8_t icp_clear_access_sig_cb( void ) {
	MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
	char str[64] = "INACTIVE  by ";
	strcat (str, mac_addrs[local_mac_addr]);
	sent = FALSE;

	pubmsg.payload = (char*)str;
	pubmsg.payloadlen = strlen(str);
	pubmsg.qos = QOS;
	pubmsg.retained = 0;

	sendmsg(*p_client, topic_names[TOPIC_PRIM_ACCESS_OUT], &pubmsg);

	while (g_access == ACTIVE);

	return ICP_SUCCESS;
}

uint8_t icp_get_access_sig_cb( void ) {
	return g_access;
}

uint8_t icp_listen_for_ack_cb( bool_t enable ) {
	listen_for_ack = enable;
	return ICP_SUCCESS;
}

uint8_t icp_set_shudup_sig_cb( void ) {
	return ICP_SUCCESS;
}

uint8_t icp_clear_shudup_sig_cb( void ) {
	return ICP_SUCCESS;
}

uint8_t icp_get_shudup_sig_cb( void ) {
	return INACTIVE;
}

struct timespec orwl_gettime(void)  {
  // be more careful in a multithreaded environement
  if (!orwl_timestart) {
    mach_timebase_info_data_t tb = { 0 };
    mach_timebase_info(&tb);
    orwl_timebase = tb.numer;
    orwl_timebase /= tb.denom;
    orwl_timestart = mach_absolute_time();
  }
  struct timespec t;
  double diff = (mach_absolute_time() - orwl_timestart) * orwl_timebase;
  t.tv_sec = diff * ORWL_NANO;
  t.tv_nsec = diff - (t.tv_sec * ORWL_GIGA);
  return t;
}

static char result[64];

char *gettime_s(void) {
  struct timespec t = orwl_gettime();
  sprintf(result, "%lu.%09lu sec", t.tv_sec, t.tv_nsec);
  return result;
}

icp_time_t local_time_ms;
int32_t local_time_ns;

icp_time_t gettime(void) {
  struct timespec t = orwl_gettime();
  local_time_ns = (t.tv_sec / ORWL_GIGA) + t.tv_nsec;
  local_time_ms = (icp_time_t) (local_time_ns * ORWL_NANO2MILLI);
  return local_time_ms;
}

void synctime(void) {
	LOG_INFO("Reseting time");
	orwl_timebase = 0.0;
	orwl_timestart = 0;
	mach_timebase_info_data_t tb = { 0 };
    mach_timebase_info(&tb);
    orwl_timebase = tb.numer;
    orwl_timebase /= tb.denom;
    orwl_timestart = mach_absolute_time();
	LOG_INFO("Time reset!");
    return;
}

#ifdef SYSDEBUG
bool_t g_sys_enable_debug_output = TRUE;
bool_t g_sys_enable_err_output= TRUE;
bool_t g_sys_enable_warn_output= TRUE;
bool_t g_sys_enable_info_output= TRUE;
uint8_t sys_enable_debug_output( uint8_t enabled ) {
    LOG_INFO("Setting g_sys_enable_debug_output to %d", enabled);
    g_sys_enable_debug_output = enabled;
    return 0;
}
uint8_t sys_enable_err_output( uint8_t enabled ) {
    LOG_INFO("Setting g_sys_enable_err_output to %d", enabled);
    g_sys_enable_err_output = enabled;
    return 0;
}
uint8_t sys_enable_warn_output( uint8_t enabled ) {
    LOG_INFO("Setting g_sys_enable_warn_output to %d", enabled);
    g_sys_enable_warn_output = enabled;
    return 0;
}
uint8_t sys_enable_all_output( uint8_t enabled ) {
    sys_enable_debug_output( enabled );
    sys_enable_err_output( enabled );
    sys_enable_warn_output( enabled );
    sys_enable_info_output( enabled );
    return 0;
}
uint8_t sys_enable_info_output( uint8_t enabled ) {
    LOG_INFO("Setting g_sys_enable_info_output to %d", enabled);
    g_sys_enable_info_output = enabled;
    return 0;
}
#else
uint8_t sys_enable_debug_output( uint8_t enabled ) { return 0;}
uint8_t sys_enable_err_output( uint8_t enabled ) { return 0;}
uint8_t sys_enable_warn_output( uint8_t enabled ) { return 0;}
uint8_t sys_enable_info_output( uint8_t enabled ) { return 0;}
uint8_t sys_enable_all_output( uint8_t enabled ) { return 0;}
#endif

int main( int argc, const char* argv[] ){
	MQTTAsync 					client;
	MQTTAsync_connectOptions 	conn_opts = MQTTAsync_connectOptions_initializer;
	MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;

	int 			rc = ICP_SUCCESS;
	char 			s_topic[128];
	icp_config_t 	conf;

	printf("\n\n\n\n\n\n");

	// MQTT setup, connection and subscribe's
	p_client = &client;
	CHECK_MEM(p_client);
	MQTTAsync_create(&client, ADDRESS, mac_addrs[local_mac_addr], MQTTCLIENT_PERSISTENCE_NONE, NULL);
	MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL);

	conn_opts.keepAliveInterval = 20;
	conn_opts.cleansession = 1;
	conn_opts.onSuccess = onConnect;
	conn_opts.onFailure = onConnectFailure;
	conn_opts.context = client;
	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS){
		MQTT_DEBUG("Failed to start connect, return code %d", rc);
		exit(-1);
	}
	while	(!connected);

	subscribe(client, topic_names[TOPIC_TEST]);
	subscribe(client, topic_names[TOPIC_PRIM_ACCESS]);
	subscribe(client, topic_names[TOPIC_PRIM_GPINTL]);
	subscribe(client, topic_names[TOPIC_PRIM_SHUDUP]);
	subscribe(client, topic_names[TOPIC_PRIM_RS485]);
	subscribe(client, topic_names[TOPIC_SEC_ACCESS]);
	subscribe(client, topic_names[TOPIC_SEC_GPINTL]);
	subscribe(client, topic_names[TOPIC_SEC_SHUDUP]);
	subscribe(client, topic_names[TOPIC_SEC_RS485]);
	subscribe(client, topic_names[TOPIC_SIMULATOR_BASE]);
	strcpy(s_topic, topic_names[TOPIC_SIMULATOR_BASE]);
	strcat(s_topic, mac_addrs[local_mac_addr]);
	subscribe(client, s_topic);
	while	(!(subscribed==11));
	sim_topic = s_topic;

	if (finished)
		goto exit;

	mqtt_enable_debug_output(FALSE);
	icp_enable_debug_output(TRUE);
	sys_enable_debug_output(TRUE);

reset:
	// ICP setup
	icp_init_conf_struct( &conf );
	conf.bytes_out_cb 		= icp_bytes_out_cb;
	conf.packet_received_cb = icp_packet_received_cb;
	conf.error_cb 			= icp_error_cb;
	conf.get_time_cb 		= icp_get_time_cb;
	conf.notify_packet_ack_cb 		= icp_notify_packet_ack_cb;

	conf.set_access_sig_cb 	= icp_set_access_sig_cb;
	conf.clear_access_sig_cb = icp_clear_access_sig_cb;
	conf.get_access_sig_cb 	= icp_get_access_sig_cb;

	conf.set_shudup_sig_cb 	= icp_set_shudup_sig_cb;
	conf.clear_shudup_sig_cb = icp_clear_shudup_sig_cb;
	conf.get_shudup_sig_cb 	= icp_get_shudup_sig_cb;
	conf.get_time_cb 	= gettime;

	CHECK_ERR_RE(icp_init( &conf ), ICP_SUCCESS, "Could not initialize ICP");

	DEBUG("Running...");

	// icp_packet_t packet = ICP_packet_initializer;
	// CHECK_ERR_RE(print_packet(NULL), -1, "failed with p_packet=NULL");
	// CHECK_ERR_RE(print_packet(&packet), 0, "failed with valid args");

	// char str[64];
 	// 	CHECK_ERR_RE(icp_bytes_out_cb( (const uint8_t *)NULL, 10, NULL), 0, "failed with output_byte_array=NULL");
 	// 	CHECK_ERR_RE(icp_bytes_out_cb( (const uint8_t *)str, 0, NULL), 0, "failed with array_len=0");

 	// 	strcpy(str, "Hello");
 	// 	CHECK_ERR_RE(icp_bytes_out_cb( (const uint8_t *)str, 10, NULL), 10, "failed");

 	// 	strcpy(str, "Hello");
 	// 	CHECK_ERR_RE(icp_bytes_out_cb( (const uint8_t *)str, strlen(str), NULL), (int)strlen(str), "failed with valid args");

	// CHECK_ERR_RE(icp_packet_received_cb(NULL, NULL), -1, "failed with p_packet=NULL");
	// CHECK_ERR_RE(icp_packet_received_cb(&packet, NULL), 0, "failed with valid args");

	// CHECK_ERR_RE(icp_error_cb(ICP_SUCCESS, packet.data, packet.data_length, NULL), -1, "failed with invalid packet");
	// packet.data = (uint8_t *)&str;
	// CHECK_ERR_RE(icp_error_cb(ICP_WRONG_RECIPIENT, packet.data, packet.data_length, NULL), 0, "failed with valid args");

	// while(TRUE);

	while (TRUE) {

		if (bytes_in){
			bytes_in = FALSE;
			DEBUG("bytes_in was TRUE with %d bytes ", payload_in_len)
			icp_bytes_in( (const uint8_t *)payload_in, payload_in_len );
		}

		if (update_now){
			icp_update();
			update_now = FALSE;
		}

		if (reset_flag){
			LOG_INFO("Reseting system...");
			reset_flag = FALSE;
			goto reset;
		}
		sleep(1);

	}

	disc_opts.onSuccess = onDisconnect;
	if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS){
		MQTT_DEBUG("Failed to start disconnect, return code %d", rc);
		exit(-1);
	}
 	while	(!connected);

error:

exit:
	MQTTAsync_destroy(&client);
 	return rc;
}


text:
[jvm]
Content
@[JvmName](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-name/index.html)(name = "charLiteral")

fun [char](char.md)(char: [Char](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-char/index.html)): [Literal](-literal/index.md)


text:
/**
 * File: css/order/checkout.css
 * @author Zeakis George <zeageorge@gmail.com>
 */

#order_container{
    font-size: large;
}

#orderSummary{
}

#totals {
    position: absolute;
    font-size: x-large;
}

#msg{
    color:red;
    font-size: large;
}

#orderForm2 input[type="submit"]{
    font-size: x-large;
}


text:
package cn.fmachine.leetcode.medium;

import cn.fmachine.leetcode.utility.TreeNode;

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

/**
 * BinaryTreeInorderTraversal
 * <p>
 * Given a binary tree, return the inorder traversal of its nodes' values.
 * For example: Given binary tree {1,null,2,3}
 * return [1,3,2]
 *
 * @author XIN MING
 * @since 3/15/16
 */
public class BinaryTreeInorderTraversal {
    List<Integer> resultList = new ArrayList<Integer>();

    public List<Integer> inorderTraversal(TreeNode root) {
        if (null == root) return resultList;
        if (null != root.left)
            inorderTraversal(root.left);
        resultList.add(root.val);
        if (null != root.right)
            inorderTraversal(root.right);
        return resultList;
    }
}


text:
Ext2.namespace('Kwf.Component');
Kwf.Component.Pages = Ext2.extend(Ext2.Panel, {
    initComponent : function()
    {
        this.actions = {};
        this.componentConfigs = {};

        this.pageButtonMenu = new Ext2.menu.Menu({
            items    : [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('copy'),
                this.getAction('paste'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview')
            ]
        });
        this.pageButton = new Ext2.Toolbar.Button({
            cls     : 'x2-btn-text-icon bmenu',
            text    : trlKwf('Page'),
            menu    : this.pageButtonMenu,
            icon    : '/assets/silkicons/page.png',
            disabled: true
        });

        this.treePanel = new Kwf.Auto.TreePanel({
            controllerUrl: '/admin/component/pages',
            title       : trlKwf('Page tree'),
            region      : 'west',
            split       : true,
            width       : 300,
            collapsible : true,
            minSize     : 200,
            maxSize     : 600,
            autoScroll: true,
            tbar: []
        });

        var tbar = this.treePanel.getTopToolbar();
        tbar.add(this.pageButton);

        tbar.add('-');
        tbar.add(trlKwf('Search: '));

        var filter = new Kwf.Auto.Filter.Text({name: 'text', 'paramName': 'query'});
        filter.on('filter', function(f, params) {
            this.applyBaseParams(params);
            this.reload();
        }, this.treePanel);
        filter.getToolbarItem().each(function(i) {
            tbar.add(i);
        });

        tbar.add('->');
        tbar.add(this.treePanel.getAction('reload'));

        this.treePanel.onMoved = function (response) {
            this.tree.getRootNode().reload();
        };

        this.contentTabPanel = new Ext2.TabPanel({
            region      : 'center'
        });
        this.contentTabPanel.on('render', function() {
            this.contentTabPanel.strip.setHeight(24);
        }, this);

        this.layout = 'border';
        this.items = [this.treePanel, this.contentTabPanel];

        Kwf.Component.Pages.superclass.initComponent.call(this);

        this.treePanel.on('loaded', this.onTreePanelLoaded, this);
        this.setupEditform();

        this.editActions = {};
    },
    setupEditform : function ()
    {
       this.editDialog = new Kwf.Auto.Form.Window({
            width: 620,
            height: 700,
            controllerUrl: '/admin/component/page'
        });
        this.editDialog.on('datachange', function(test) {
            this.treePanel.tree.root.reload();
        }, this);
        this.editDialog.on('renderform', function() {
            var component = this.editDialog.getAutoForm().findField('component');
            if (component && component.formsForComponent) {
                //initially hide all to avoid flickr
                this.editDialog.getAutoForm().cascade(function(i) {
                    if (i.showDependingOnComponent) {
                        i.disableRecursive(); //to disable validation
                        i.hide();
                    }
                }, this);
                component.on('changevalue', function() {
                    //hide/show forms depending on selected component
                    this.editDialog.getAutoForm().cascade(function(i) {
                        var showForms = component.formsForComponent[component.getValue()] || [];
                        if (i.showDependingOnComponent) {
                            if (showForms.indexOf(i.name) !== -1) {
                                i.show();
                                i.enableRecursive();
                            } else {
                                i.disableRecursive(); //to disable validation
                                i.hide();
                            }
                        }
                    }, this);
                }, this);
            }
        }, this);
    },

    onTreePanelLoaded : function(tree)
    {
        tree.loader.on('load', function(tree, node, response) {
            var result = Ext2.decode(response.responseText);
            Ext2.applyIf(this.componentConfigs, result.componentConfigs);
        }, this);

        this.contextMenu = new Ext2.menu.Menu({
             items: [
                '-',
                this.getAction('properties'),
                this.getAction('add'),
                this.getAction('delete'),
                this.getAction('copy'),
                this.getAction('paste'),
                this.getAction('visible'),
                this.getAction('makeHome'),
                this.getAction('preview')
            ]
        });

        tree.on('click', this.treeSelectionchange, this);
        tree.on('contextmenu', function (node) {
            node.select();
            this.treeSelectionchange(node);
            this.contextMenu.show(node.ui.getAnchor());
        }, this);

        tree.on('dblclick', function (o, e) {
            var i = this.contextMenu.items.first();
            if (i && i.handler) {
                i.handler.call(i.scope, i, e);
            }
        }, this);

    },

    treeSelectionchange : function (node) {
        if (!node) return;
        var data = node.attributes;

        if (data.disabled) {
            this.pageButton.disable();
        } else {
            this.pageButton.enable();
        }

        for (var action in data.actions) {
            if (data.actions[action]) {
                this.getAction(action).enable();
            } else {
                this.getAction(action).disable();
            }
        }

        this.contextMenu.items.each(function(i) {
            if (i.initialConfig.actionKey) {
                this.contextMenu.remove(i);
            }
        }, this);
        this.pageButtonMenu.items.each(function(i) {
            if (i.initialConfig.actionKey) {
                this.pageButtonMenu.remove(i);
            }
        }, this);
        var actionsAdded = 0;
        data.editComponents.each(function(editComponent) {
            var editKey = editComponent.componentId;
            var actionKey = editComponent.componentClass+'-'+editComponent.type;
            if (!this.editActions[editKey+actionKey]) {
                this.editActions[editKey+actionKey] = new Ext2.Action({
                    text    : this.componentConfigs[actionKey].title,
                    handler : function (o, e) {
                        var node = this.treePanel.tree.getSelectionModel().getSelectedNode();
                        node.attributes.editComponents.each(function(editComponent) {
                            if (editComponent.componentId+editComponent.componentClass+'-'+editComponent.type == o.editKey+o.actionKey) {
                                this.loadComponent({
                                    id: editComponent.componentId,
                                    componentClass: editComponent.componentClass,
                                    type: editComponent.type,
                                    text: node.text,
                                    icon: node.attributes.bIcon,
                                    editComponents: node.attributes.editComponents,
                                    pageId: node.attributes.id
                                });
                                return false;
                            }
                        }, this);
                    },
                    icon    : this.componentConfigs[actionKey].icon,
                    cls     : 'x2-btn-text-icon',
                    scope   : this,
                    actionKey: actionKey,
                    editKey: editKey
                });
            }
            this.editActions[editKey+actionKey].setDisabled(data.disabled);
            this.contextMenu.insert(actionsAdded, new Ext2.menu.Item(this.editActions[editKey+actionKey]));
            this.pageButtonMenu.insert(actionsAdded, new Ext2.menu.Item(this.editActions[editKey+actionKey]));
            actionsAdded++;
        }, this);
    },

    loadComponent: function(data)
    {
        var panel = this.contentTabPanel.getItem('page'+data.pageId);
        if (!panel) {
            panel = this.createComponentPanel(data);
            this.contentTabPanel.add(panel);
        }
        this.contentTabPanel.setActiveTab(panel);

        panel.applyBaseParams({
            id: data.id
        });
        panel.mainComponentText = data.text;
        panel.mainComponentIcon = data.icon;
        panel.load({
            componentClass: data.componentClass,
            type: data.type,
            editComponents: data.editComponents
        });
    },

    createComponentPanel: function(data)
    {
        var panel = new Kwf.Component.ComponentPanel({
            id          : 'page'+data.pageId,
            title       : data.text,
            closable    : true,
            autoLoad    : false,
            componentConfigs : this.componentConfigs
        });
        return panel;
    },

    _removeEditDialogForm: function()
    {
        var form = this.editDialog.getAutoForm();
        if (form.formPanel) {
            form.remove(form.formPanel, true);
            this.editDialog.getAutoForm().formPanel = null;
        }
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'properties') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Page properties'),
                handler : function () {
                    this._removeEditDialogForm();
                    var node = this.treePanel.tree.selModel.selNode;
                    this.editDialog.getAutoForm().setBaseParams({});
                    this.editDialog.showEdit(node.id);
                },
                icon    : '/assets/silkicons/page_gear.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'add') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Add new child page'),
                handler : function () {
                    this._removeEditDialogForm();
                    var node = this.treePanel.tree.selModel.selNode;
                    this.editDialog.getAutoForm().setBaseParams({
                        parent_id: node.id
                    });
                    this.editDialog.showAdd();
                },
                icon    : '/assets/silkicons/page_add.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'delete') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Delete Page'),
                handler : function() {
                    this.treePanel.onDelete();
                },
                icon    : '/assets/silkicons/page_delete.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'copy') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Copy Page'),
                handler : function() {
                    this.onCopy();
                },
                icon    : '/assets/silkicons/page_copy.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'paste') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Paste Page'),
                handler : function() {
                    this.onPaste();
                },
                icon    : '/assets/silkicons/page_paste.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'visible') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Show / Hide Page'),
                handler : function() {
                    this.treePanel.onVisible();
                },
                icon    : '/assets/fx_invisible/silkicons/page.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'makeHome') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Use as homepage'),
                handler : function (o, e) {
                    Ext2.Msg.show({
                        title: trlKwf('Use as homepage'),
                        msg: trlKwf('Attention! You are about to set the selected page as the homepage of your website. This may affect the entire website. Do you wish to proceed?'),
                        buttons: Ext2.Msg.YESNO,
                        icon: Ext2.MessageBox.WARNING,
                        fn: function(btn, text) {
                            if (btn == 'yes') {
                                Ext2.Ajax.request({
                                    url: '/admin/component/pages/json-make-home',
                                    success: function(r) {
                                        response = Ext2.decode(r.responseText);
                                        var oldhome = this.treePanel.tree.getNodeById(response.oldhome);
                                        oldhome.attributes.visible = response.oldhomeVisible;
                                        this.treePanel.setVisible(oldhome);
                                        oldhome.ui.iconNode.style.backgroundImage = 'url(/assets/silkicons/page.png)';
                                        var home = this.treePanel.tree.getNodeById(response.home);
                                        home.ui.iconNode.style.backgroundImage = 'url(/assets/silkicons/application_home.png)';
                                    },
                                    params: {id: this.treePanel.tree.getSelectionModel().getSelectedNode().id },
                                    scope: this
                                });
                            }
                        },
                        scope: this
                    });
                },
                icon    : '/assets/silkicons/application_home.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'expand') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Expand here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().expand(true); },
                icon    : '/assets/silkicons/bullet_add.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'collapse') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Collapse here'),
                handler : function () { this.treePanel.tree.getSelectionModel().getSelectedNode().collapse(true); },
                icon    : '/assets/silkicons/bullet_delete.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else if (type == 'preview') {
            this.actions[type] = new Ext2.Action({
                text    : trlKwf('Open preview'),
                handler : function () {
                    window.open('/admin/component/pages/open-preview?page_id='+
                                this.treePanel.getSelectedId());
                },
                icon    : '/assets/silkicons/page_white_magnify.png',
                cls     : 'x2-btn-text-icon',
                scope   : this
            });
        } else {
            throw 'unknown action-type: ' + type;
        }
        return this.actions[type];
    },

    onCopy: function(o, e) {
        Ext2.Ajax.request({
            url: this.treePanel.controllerUrl + '/json-copy',
            params: Ext2.apply({id:this.treePanel.getSelectedId()}, this.treePanel.getBaseParams()),
            mask: this.el,
            success: function(response, options, result) {
            },
            scope: this
        });
    },

    onPaste: function() {
        Ext2.Ajax.request({
            url: this.treePanel.controllerUrl + '/json-paste',
            params: Ext2.apply({id:this.treePanel.getSelectedId()}, this.treePanel.getBaseParams()),
            timeout: 5*60*1000,
            progress: true,
            progressTitle : trlKwf('Paste Page'),
            showCancel: false,
            success: function(response, options, result) {
                this.treePanel.reload();
            },
            scope: this
        });
    }

});

Ext2.reg('kwf.component.pages', Kwf.Component.Pages);


text:
<?php

// connexion bdd
if (!isset($bdd)) {
	include(__DIR__ . '/../common/connexion_sql.php');
}

// si c'est une requête ajax
if (!empty($_POST)) {
	// fichier de cache
	$cacheContent = __DIR__ . '/cache/pedit_cache_text_content.php';
	// $cacheType = __DIR__ . '/cache/pedit_cache_text_type.php';
	// si le cache existe on le supprime
	if (file_exists($cacheContent)) {
		unlink($cacheContent);
	}
	// if (file_exists($cacheType)) {
	// 	unlink($cacheType);
	// }
	// On update la BDD
	try {
		$req = $bdd->prepare('UPDATE text SET textContent = :textContent WHERE textId = :textId');
		$req->execute(array(
			'textContent' => $_POST['textContent'],
			'textId' => $_POST['textId']
		));
		$req->closeCursor();

		// GOOD
		echo 1;
	}
	catch (Exception $e) {
		echo 'Erreur catched : ',  $e->getMessage();
	}
}


text:
require 'rails_helper'
require 'models/concerns/emailable'
require 'models/concerns/nameable'

RSpec.describe SlackMembershipSubmission, type: :model do
  let(:subject) { build(:slack_membership_submission) }

  it "is valid from the factory" do
    expect(subject).to be_valid
  end

  it_behaves_like "a emailable concern"
  it_behaves_like "a nameable concern"

  describe "validations" do
    it { should validate_presence_of(:first_name) }
    it { should validate_presence_of(:last_name) }

    it { should allow_value("").for(:website_url) }
    it { should allow_value("http://web.site").for(:website_url) }
    it { should allow_value("https://web.site").for(:website_url) }
    it { should_not allow_value("https://web").for(:website_url) }
    it { should_not allow_value("sftp://ftp.site").for(:website_url) }

    it { should allow_value("").for(:github_url) }
    it { should allow_value("http://github.com/johndoe").for(:github_url) }
    it { should allow_value("https://github.com/johndoe").for(:github_url) }
    it { should_not allow_value("https://notgithub.com/johndoe").for(:github_url) }

    it { should allow_value("").for(:linkedin_url) }
    it { should allow_value("http://linkedin.com/in/johndoe").for(:linkedin_url) }
    it { should allow_value("https://linkedin.com/in/johndoe").for(:linkedin_url) }
    it { should allow_value("https://www.linkedin.com/in/johndoe").for(:linkedin_url) }
    it { should_not allow_value("https://notlinkedin.com/johndoe").for(:linkedin_url) }

    it { should validate_presence_of(:introduction) }
  end

  it "sets status to pending on create" do
    subject.save!
    expect(subject.status).to eq "pending"
  end

  describe "#approve_and_invite!" do
    pending
  end

  describe "#ip_address_location" do
    it "returns nil if ip_address is nil" do
      subject.ip_address = nil
      expect(subject.ip_address_location).to eq nil
    end

    it "returns nil if ip_address is private" do
      subject.ip_address = "127.0.0.1"
      expect(subject.ip_address_location).to eq nil
    end

    it "returns location string if ip_address is valid" do
      subject.ip_address = "73.11.237.17"
      expect(subject.ip_address_location).to eq "Olympia, WA, United States"
    end

  end
end


text:
package JFlex;

import java.io.File;

/**
 * Performs simple semantic analysis on regular expressions.
 *
 * (used for checking if trailing contexts are legal)
 *
 * @author Gerwin Klein
 * @version JFlex 1.4.1, $Revision: 1.2 $, $Date: 2007/11/16 20:11:30 $
 */
public final class SemCheck {

  // stored globally since they are used as constants in all checks
  private static Macros macros;
  private static char maxChar;

  /**
   * Performs semantic analysis for all expressions.
   *
   * Currently: illegal lookahead check only
   * [fixme: more checks possible]
   *
   * @param rs   the reg exps to be checked
   * @param m    the macro table (in expanded form)
   * @param max  max character of the used charset (for negation)
   * @param f    the spec file containing the rules [fixme]
   */
  public static void check(RegExps rs, Macros m, char max, File f) {
    macros = m;
    maxChar = max;

    int num = rs.getNum();
    for (int i = 0; i < num; i++) {
      RegExp r = rs.getRegExp(i);
      RegExp l = rs.getLookAhead(i);

      if (!checkLookAhead(r,l)) {
        Out.warning(f, ErrorMessages.LOOKAHEAD_ERROR, rs.getLine(i), -1);
      }
    }
  }

  /**
   * Checks for illegal lookahead expressions.
   *
   * Lookahead in JFlex only works when the first expression has fixed
   * length or when the intersection of the last set of the first expression
   * and the first set of the second expression is empty.
   *
   * FIXME: this check is much too weak
   *
   *
   * @param r1   first regexp
   * @param r2   second regexp (the lookahead)
   *
   * @return true iff JFlex can generate code for the lookahead expression
   */
  private static boolean checkLookAhead(RegExp r1, RegExp r2) {
    return r2 == null || length(r1) > 0;
  }

  /**
   * Returns length if expression has fixed length, -1 otherwise.
   *
   * Negation operators are treated as always variable length.
   */
  private static int length(RegExp re) {
    RegExp2 r;

    switch (re.type) {

    case sym.BAR: {
      r = (RegExp2) re;
      int l1 = length(r.r1);
      if (l1 < 0) return -1;
      int l2 = length(r.r2);

      if (l1 == l2)
        return l1;
      else
        return -1;
    }

    case sym.CONCAT: {
      r = (RegExp2) re;
      int l1 = length(r.r1);
      if (l1 < 0) return -1;
      int l2 = length(r.r2);
      if (l2 < 0) return -1;
      return l1+l2;
    }

    case sym.STAR:
    case sym.PLUS:
    case sym.QUESTION:
      return -1;

    case sym.CCLASS:
    case sym.CCLASSNOT:
    case sym.CHAR:
    case sym.CHAR_I:
      return 1;

    case sym.STRING:
    case sym.STRING_I: {
      String content = (String) ((RegExp1) re).content;
      return content.length();
    }

    case sym.TILDE:
    case sym.BANG:
       // too hard to caculate at this level, use safe approx
      return -1;

    case sym.MACROUSE:
      return length(macros.getDefinition((String) ((RegExp1) re).content));
    }

    throw new Error("Unknown expression type "+re.type+" in "+re);   //$NON-NLS-1$ //$NON-NLS-2$
  }
}


text:
Use Azure WebJobs to implement timer jobs that can access SharePoint Online.

 **Last modified:** April 20, 2015

 _**Applies to:** apps for SharePoint | SharePoint 2013 | SharePoint Online_

 **In this article**

 [Create and run a console application as an Azure WebJob](#sectionSection0)

 [Create an organization account](#sectionSection1)

 [Create and set up the console application](#sectionSection2)

 [Add code to the console application](#sectionSection3)

 [Publish your console application as an Azure WebJob](#sectionSection4)

 [Run and verify your Azure WebJob](#runandverify)

 [Additional resources](#bk_addresources)

 **Provided by:**
Tobias Zimmergren

Implement timer job functionality using  [Microsoft Azure WebJobs](http://azure.microsoft.com/documentation/articles/websites-webjobs-resources/) or Windows Task Scheduler to perform tasks in SharePoint Online. A timer job is a repetitive, scheduled, background process that runs in SharePoint to perform certain tasks. For example, you may want a timer job to copy data entered in a SharePoint list to a database. In SharePoint Online, you cannot deploy farm solutions, which is how timer jobs were deployed in the past. To implement similar timer job functionality in SharePoint Online, you need to run a console application as an Azure WebJob. The console application accesses SharePoint Online using the client-side object model (CSOM). This article presents the basic concepts involved in deploying console applications as Azure WebJobs to run and access your SharePoint Online sites and content.

**Note**  You can [view this article](https://msdn.microsoft.com/EN-US/library/dn986826.aspx) in the [Solutions guidance](https://msdn.microsoft.com/en-us/library/dn904529.aspx) node on MSDN.

## Create and run a console application as an Azure WebJob

To set up your console application to run as an Azure WebJob, you need to:

1. Create an organization account for the Azure WebJob to use to access your SharePoint sites and content.

2. Create and set up the console application.

3. Add code to the console application.

4. Publish your console application as an Azure WebJob.

5. Run and verify your Azure WebJob.

## Create an organization account

You need to create an account for the Azure WebJob to use when accessing SharePoint sites and content. For more information, see  [Add users individually to Office 365-Admin Help](https://support.office.microsoft.com/article/Add-users-individually-to-Office-365---Admin-Help-1970f7d6-03b5-442f-b385-5880b9c256ec). When the Azure WebJob runs, the  **Modified By** field stores and displays the value entered in **Display name** of the organization account. Ensure you choose a display name that your users can easily identify as the account used by the Azure WebJob for accessing SharePoint.

## Create and set up the console application

To create a console application to run as an Azure WebJob, perform the following steps:

1. Create a new console application project by:

      1. In Visual Studio, choose  **New Project** > **Visual C#** > **Console Application** > **OK**.

  2. After the console application is created, choose  **Tools** > **NuGet Package Manager** > **Manage NuGet Packages for Solution...** > **Online** > **All**.

  3. Search for  **App for SharePoint Web Toolkit**.

  4. Choose  **Install**, then choose  **OK**.

  5. Choose  **Close**.

  6. Verify that SharePointContext.cs and TokenHelper.cs were added to the console application project.

2. Save your account information in the app.config by adding the  **appSettings** element shown. Change **SPOAccount** and **SPOPassword** to the user name and password of the organization account you created previously.

  ```XML
  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <startup>
   <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 </startup>
 <appSettings>
   <add key="SPOAccount" value="admin@contoso.onmicrosoft.com"/>
   <add key="SPOPassword" value="Contoso"/>
 </appSettings>
</configuration>

  ```

    **Caution**  App.config stores the organization account's username and password in clear text. This method is used for demonstration purposes only, and should not be used in your production deployment of your Azure WebJobs. We recommend encrypting the password, or authenticating using OAuth with access tokens. For more information, see Kirk Evans blog post on  [Building a SharePoint App as a Timer Job](http://blogs.msdn.com/b/kaevans/archive/2014/03/02/building-a-sharepoint-app-as-a-timer-job.aspx).

## Add code to the console application

In Program.cs, add the following code to the console application.

**Note**  The code in this article is provided as-is, without warranty of any kind, either express or implied, including any implied warranties of fitness for a particular purpose, merchantability, or non-infringement.

1. Add  **using** statements.

  ```C#
  using Microsoft.SharePoint.Client;
using System.Security;
using System.Configuration;
  ```

2. Add the following methods to your class:

      -  **Main** signs into your SharePoint site, and then uses the CSOM to perform tasks on your site or content. This code sample uses the CSOM to find a list and output the total number of items that are in the list to the console window. When using Azure WebJobs, you can see the console window output in the WebJob Run Details, which is explained in [Run and verify your Azure WebJob](ea962814-e430-424b-b45f-4bcda7fe9eab.md#runandverify).

  -  **GetSPOSecureStringPassword** reads your password from app.config.

  -  **GetSPOAccountName** reads your username from app.config.

  ```C#
   static void Main(string[] args)
        {
            using (ClientContext context = new ClientContext("https://contoso.sharepoint.com"))
            {
                // Use default authentication mode.
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());

                // Add your CSOM code to perform tasks on your sites and content.

                try
                {
                    List objList = context.Web.Lists.GetByTitle("Docs");
                    context.Load(objList);
                    context.ExecuteQuery();

                    if (objList != null && objList.ItemCount > 0)
                    {
                        Console.WriteLine(objList.Title.ToString() + " has " + objList.ItemCount + " items.");
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERROR: " + ex.Message);
                    Console.WriteLine("ERROR: " + ex.Source);
                    Console.WriteLine("ERROR: " + ex.StackTrace);
                    Console.WriteLine("ERROR: " + ex.InnerException);

                }
            }

        }

 private static SecureString GetSPOSecureStringPassword()
  {
      try
      {
          Console.WriteLine("Entered GetSPOSecureStringPassword.");
          var secureString = new SecureString();
          foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
          {
              secureString.AppendChar(c);
          }
          Console.WriteLine("Constructed the secure password.");

          return secureString;
      }
      catch
      {
          throw;
      }
  }

  private static string GetSPOAccountName()
  {
      try
      {
          Console.WriteLine("Entered GetSPOAccountName.");
          return ConfigurationManager.AppSettings["SPOAccount"];
      }
      catch
      {
          throw;
      }
   }

  ```

## Publish your console application as an Azure WebJob

When you are finished developing your console application, you need to deploy the console application as an Azure WebJob. To deploy your console application as an Azure WebJob, you can:

- Upload your binaries to an Azure Web App, and create an Azure WebJob using the  [Microsoft Azure Portal](https://portal.azure.com/). The binaries for your Visual Studio project can be found in the bin/Debug or bin/Release folders of your Visual Studio project. To create the Azure Web App and upload the binaries, follow the steps in  [Create an ASP.NET web app in Azure App Service](http://azure.microsoft.com/documentation/articles/web-sites-dotnet-get-started/). To create your on demand, continuous, or scheduled Azure WebJob, see  [Run Background tasks with WebJobs](http://azure.microsoft.com/documentation/articles/web-sites-create-web-jobs/).

- Publish your Azure WebJob from Visual Studio. For more information, see  [Enable WebJobs deployment without a web project](http://azure.microsoft.com/documentation/articles/websites-dotnet-deploy-webjobs/#convertnolink).

## Run and verify your Azure WebJob

After completing all the previous steps, your Azure WebJob should be running and performing tasks in your Office 365 subscription. At times, you may need to perform maintenance or troubleshoot your Azure WebJobs. To verify that your Azure WebJob is running:

- If your Azure WebJob updated a SharePoint item, like a list item, the  **Modified By** field displays the organization account that the Azure WebJob used to access SharePoint.

- Review the WebJob Details logs for your Azure WebJob. The WebJob Details logs lets you review when a job ran, the success or failure of a job run, any output from the WebJob (for example, when Console.WriteLine was called), and other details of the job run. For more information, see the section View the job history on  [Run Background tasks with WebJobs](http://azure.microsoft.com/documentation/articles/web-sites-create-web-jobs/).

## Additional resources

-  [Office 365 development patterns and practices solution guidance](https://msdn.microsoft.com/library/dn904529%28v=office.15%29.aspx).

-  [Create a .NET WebJob in Azure App Service](http://azure.microsoft.com/documentation/articles/websites-dotnet-webjobs-sdk-get-started/).

-  [Azure WebJobs resources](http://azure.microsoft.com/documentation/articles/websites-webjobs-resources/).


text:
require "rack"
require 'rack/handler/webrick'
require 'line/bot'

module Ruboty
  module Adapters
    class LineBot < Base
      env :LINE_CHANNEL_ID,          "LINE Channel ID"
      env :LINE_CHANNEL_SECRET,      "LINE Channel Secret"
      env :LINE_CHANNEL_MID,         "LINE Channel MID"
      env :LINE_SERVER_BIND_ADDRESS, "Bind address (default: 0.0.0.0)",   :optional => true
      env :LINE_SERVER_PORT,         "Port         (default: 4567)",      :optional => true
      env :LINE_SERVER_ENDPOINT,     "Endpoint     (default: /callback)", :optional => true

      def run
        init
        serve
        main_loop
      end

      def init
        @queue = Queue.new
        @cached_contacts = {}
      end

      def say(message)
        client.send_text(
          to_mid: message[:original][:from_mid],
          text:   message[:body],
        )
      end

      private

      def client
        @client ||= Line::Bot::Client.new do |config|
          config.channel_id     = channel_id
          config.channel_secret = channel_secret
          config.channel_mid    = channel_mid
        end
      end

      def serve
        Thread.new do
          server.start
        end
        Thread.abort_on_exception = true
      end

      def server
        return @server if @server

        @server = WEBrick::HTTPServer.new({
          BindAddress: bind_address,
          Port:        port,
          Logger:      Ruboty.logger,
        })
        @server.mount(endpoint, Rack::Handler::WEBrick, lambda(&method(:callback)))

        @server
      end

      def callback(env)
        req = Rack::Request.new(env)

        unless req.request_method == 'POST'
          return [404, {}, ['Not found']]
        end

        signature = req.env['HTTP_X_LINE_CHANNELSIGNATURE']

        unless client.validate_signature(req.body.read, signature)
          return [400, {}, ['Bad Request']]
        end

        @queue.enq(req.env)

        [204, {}, []]
      end

      def main_loop
        loop do
          request_from_queue.data.each do |event|
            next unless event.content.is_a?(Line::Bot::Message::Text)

            keys = [:id, :from_mid, :to_mid, :from_channel_id, :to_channel_id, :event_type, :created_time, :content]
            message = keys.each_with_object({}) {|key, hash| hash[key] = event.send(key) }

            unless contact = @cached_contacts[message[:from_mid]]
              contact = client.get_user_profile(message[:from_mid]).contacts.first
              @cached_contacts.update({
                contact.mid => {
                  mid:            contact.mid,
                  display_name:   contact.display_name,
                  picture_url:    contact.picture_url,
                  status_message: contact.status_message,
                }
              })
              contact = @cached_contacts[contact.mid]
            end

            message.update(
              body:      message[:content].content[:text],
              from:      message[:from_mid],
              from_name: contact[:display_name],
              to:        message[:to_mid],
              type:      message[:event_type],
            )
            Ruboty.logger.debug('Received:' + message.inspect)
            robot.receive(message)
          end
        end
      end

      def request_from_queue
        rack_raw_env = @queue.deq
        Line::Bot::Receive::Request.new(rack_raw_env)
      end

      def channel_id
        ENV['LINE_CHANNEL_ID']
      end

      def channel_secret
        ENV['LINE_CHANNEL_SECRET']
      end

      def channel_mid
        ENV['LINE_CHANNEL_MID']
      end

      def bind_address
        ENV['WEBHOOK_BIND_ADDRESS'] || '0.0.0.0'
      end

      def port
        ENV['WEBHOOK_PORT'] || '4567'
      end

      def endpoint
        ENV['WEBHOOK_ENDPOINT'] || '/callback'
      end
    end
  end
end


text:
Fieldtrip Decision Tree Plugin
==============================

Decision Tree is a plugin for creating questionnaires that follow a tree structure.

## Editor Markup

```html
<div class="fieldcontain" id="fieldcontain-dtree-1" data-fieldtrip-type="dtree">
    <fieldset>
        <label for="fieldcontain-dtree-1">Decision Tree Label</label>
        <div class="button-wrapper button-dtree"></div>
        <input type="hidden" data-dtree="decision_tree.json">
    </fieldset>
</div>
```


text:
"""General python utility functions."""

import contextlib
import functools
import os
import shutil
import subprocess as sp
import tempfile

import numpy as np

def compose(*fs):
  composition = lambda f, g: lambda x: f(g(x))
  identity = lambda x: x
  return functools.reduce(composition, fs, identity)

def maybe(x, f):
  """Returns [f(x)], unless f(x) raises an exception. In that case, []."""
  try:
    result = f(x)
    output = [result]
  # pylint:disable=broad-except
  except Exception:
    # pylint:enable=broad-except
    output = []
  return output

@contextlib.contextmanager
def py2_temporary_directory():
  d = tempfile.mkdtemp()
  try:
    yield d
  finally:
    shutil.rmtree(d)

@contextlib.contextmanager
def x11_server():
  """Generates a headless x11 target to use."""
  idx = np.random.randint(10, 10000)
  prev_display_name = os.environ['DISPLAY']
  x11 = sp.Popen('Xvfb :%i' % idx, shell=True)
  os.environ['DISPLAY'] = ':%i' % idx
  try:
    yield idx
  finally:
    x11.kill()
    os.environ['DISPLAY'] = prev_display_name

def merge(x, y):
  z = x.copy()
  z.update(y)
  return z

def merge_into(x, ys):
  out = []
  for y in ys:
    out.append(merge(x, y))
  return out


text:
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// 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.

/**
 * @fileoverview Defines a class for parsing JSON using eval.
 */

goog.provide('goog.json.EvalJsonProcessor');

goog.require('goog.json');
goog.require('goog.json.Processor');
goog.require('goog.json.Serializer');

/**
 * A class that parses and stringifies JSON using eval (as implemented in
 * goog.json).
 * Adapts {@code goog.json} to the {@code goog.json.Processor} interface.
 *
 * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during
 *     serialization.
 * @param {?boolean=} opt_useUnsafeParsing Whether to use goog.json.unsafeParse
 *     for parsing. Safe parsing is very slow on large strings. On the other
 *     hand, unsafe parsing uses eval() without checking whether the string is
 *     valid, so it should only be used if you trust the source of the string.
 * @constructor
 * @implements {goog.json.Processor}
 * @final
 */
goog.json.EvalJsonProcessor = function(opt_replacer, opt_useUnsafeParsing) {
  /**
   * @type {goog.json.Serializer}
   * @private
   */
  this.serializer_ = new goog.json.Serializer(opt_replacer);

  /**
   * @type {function(string): *}
   * @private
   */
  this.parser_ = opt_useUnsafeParsing ? goog.json.unsafeParse : goog.json.parse;
};

/** @override */
goog.json.EvalJsonProcessor.prototype.stringify = function(object) {
  return this.serializer_.serialize(object);
};

/** @override */
goog.json.EvalJsonProcessor.prototype.parse = function(s) {
  return this.parser_(s);
};


text:
package org.apache.spark.sql.streaming.ui

import java.net.URLEncoder
import java.nio.charset.StandardCharsets.UTF_8
import javax.servlet.http.HttpServletRequest

import scala.collection.mutable
import scala.xml.Node

import org.apache.commons.text.StringEscapeUtils

import org.apache.spark.internal.Logging
import org.apache.spark.sql.streaming.ui.UIUtils._
import org.apache.spark.ui.{PagedDataSource, PagedTable, UIUtils => SparkUIUtils, WebUIPage}
import org.apache.spark.util.Utils

private[ui] class StreamingQueryPage(parent: StreamingQueryTab)
    extends WebUIPage("") with Logging {

  override def render(request: HttpServletRequest): Seq[Node] = {
    val content = generateStreamingQueryTable(request)
    SparkUIUtils.headerSparkPage(request, "Streaming Query", content, parent)
  }

  private def generateStreamingQueryTable(request: HttpServletRequest): Seq[Node] = {
    val (activeQueries, inactiveQueries) =
      parent.store.allQueryUIData.partition(_.summary.isActive)

    val content = mutable.ListBuffer[Node]()
    // show active queries table only if there is at least one active query
    if (activeQueries.nonEmpty) {
      // scalastyle:off
      content ++=

            Active Streaming Queries ({activeQueries.length})

         ++

              {queryTable(activeQueries, request, "active")}

      // scalastyle:on
    }
    // show active queries table only if there is at least one completed query
    if (inactiveQueries.nonEmpty) {
      // scalastyle:off
      content ++=

            Completed Streaming Queries ({inactiveQueries.length})

         ++

              {queryTable(inactiveQueries, request, "completed")}

      // scalastyle:on
    }
    content
  }

  private def queryTable(data: Seq[StreamingQueryUIData], request: HttpServletRequest,
      tableTag: String): Seq[Node] = {

    val isActive = if (tableTag.contains("active")) true else false
    val page = Option(request.getParameter(s"$tableTag.page")).map(_.toInt).getOrElse(1)

    try {
      new StreamingQueryPagedTable(
        request,
        parent,
        data,
        tableTag,
        isActive,
        SparkUIUtils.prependBaseUri(request, parent.basePath),
        "StreamingQuery"
      ).table(page)
    } catch {
      case e@(_: IllegalArgumentException | _: IndexOutOfBoundsException) =>

Error while rendering execution table:

            {Utils.exceptionString(e)}

    }
  }
}

private[ui] class StreamingQueryPagedTable(
    request: HttpServletRequest,
    parent: StreamingQueryTab,
    data: Seq[StreamingQueryUIData],
    tableTag: String,
    isActive: Boolean,
    basePath: String,
    subPath: String) extends PagedTable[StructuredStreamingRow] {

  private val (sortColumn, sortDesc, pageSize) = getTableParameters(request, tableTag, "Start Time")
  private val parameterPath = s"$basePath/$subPath/?${getParameterOtherTable(request, tableTag)}"
  private val encodedSortColumn = URLEncoder.encode(sortColumn, UTF_8.name())

  override def tableId: String = s"$tableTag-table"

  override def tableCssClass: String =
    "table table-bordered table-sm table-striped table-head-clickable table-cell-width-limited"

  override def pageSizeFormField: String = s"$tableTag.pageSize"

  override def pageNumberFormField: String = s"$tableTag.page"

  override def pageLink(page: Int): String = {
    parameterPath +
      s"&$pageNumberFormField=$page" +
      s"&$tableTag.sort=$encodedSortColumn" +
      s"&$tableTag.desc=$sortDesc" +
      s"&$pageSizeFormField=$pageSize" +
      s"#$tableTag"
  }

  override def goButtonFormPath: String =
    s"$parameterPath&$tableTag.sort=$encodedSortColumn&$tableTag.desc=$sortDesc#$tableTag"

  override def dataSource: PagedDataSource[StructuredStreamingRow] =
    new StreamingQueryDataSource(data, sortColumn, sortDesc, pageSize, isActive)

  override def headers: Seq[Node] = {
    val headerAndCss: Seq[(String, Boolean, Option[String])] = {
      Seq(
        ("Name", true, None),
        ("Status", true, None),
        ("ID", true, None),
        ("Run ID", true, None),
        ("Start Time", true, None),
        ("Duration", true, None),
        ("Avg Input /sec", true, None),
        ("Avg Process /sec", true, None),
        ("Latest Batch", true, None)) ++ {
        if (!isActive) {
          Seq(("Error", false, None))
        } else {
          Nil
        }
      }
    }
    isSortColumnValid(headerAndCss, sortColumn)

    headerRow(headerAndCss, sortDesc, pageSize, sortColumn, parameterPath, tableTag, tableTag)
  }

  override def row(query: StructuredStreamingRow): Seq[Node] = {
    val streamingQuery = query.streamingUIData
    val statisticsLink = "%s/%s/statistics?id=%s"
      .format(SparkUIUtils.prependBaseUri(request, parent.basePath), parent.prefix,
        streamingQuery.summary.runId)

    def details(detail: Any): Seq[Node] = {
      if (isActive) {
        return Seq.empty[Node]
      }
      val detailString = detail.asInstanceOf[String]
      val isMultiline = detailString.indexOf('\n') >= 0
      val summary = StringEscapeUtils.escapeHtml4(
        if (isMultiline) detailString.substring(0, detailString.indexOf('\n')) else detailString
      )
      val details = SparkUIUtils.detailsUINode(isMultiline, detailString)
      {summary}{details}
    }

      {UIUtils.getQueryName(streamingQuery)}
      {UIUtils.getQueryStatus(streamingQuery)}
      {streamingQuery.summary.id}
      {streamingQuery.summary.runId}
      {SparkUIUtils.formatDate(streamingQuery.summary.startTimestamp)}
      {SparkUIUtils.formatDurationVerbose(query.duration)}
      {withNoProgress(streamingQuery, {"%.2f".format(query.avgInput)}, "NaN")}
      {withNoProgress(streamingQuery, {"%.2f".format(query.avgProcess)}, "NaN")}
      {withNoProgress(streamingQuery, {streamingQuery.lastProgress.batchId}, "NaN")}
      {details(streamingQuery.summary.exception.getOrElse("-"))}

  }
}

private[ui] case class StructuredStreamingRow(
    duration: Long,
    avgInput: Double,
    avgProcess: Double,
    streamingUIData: StreamingQueryUIData)

private[ui] class StreamingQueryDataSource(
    uiData: Seq[StreamingQueryUIData],
    sortColumn: String,
    desc: Boolean,
    pageSize: Int,
    isActive: Boolean) extends PagedDataSource[StructuredStreamingRow](pageSize) {

  // convert StreamingQueryUIData to StreamingRow to provide required data for sorting and sort it
  private val data = uiData.map(streamingRow).sorted(ordering(sortColumn, desc))

  override def dataSize: Int = data.size

  override def sliceData(from: Int, to: Int): Seq[StructuredStreamingRow] = data.slice(from, to)

  private def streamingRow(uiData: StreamingQueryUIData): StructuredStreamingRow = {
    val duration = if (isActive) {
      System.currentTimeMillis() - uiData.summary.startTimestamp
    } else {
      withNoProgress(uiData, {
        val endTimeMs = uiData.lastProgress.timestamp
        parseProgressTimestamp(endTimeMs) - uiData.summary.startTimestamp
      }, 0)
    }

    val avgInput = (uiData.recentProgress.map(p => withNumberInvalid(p.inputRowsPerSecond)).sum /
      uiData.recentProgress.length)

    val avgProcess = (uiData.recentProgress.map(p =>
      withNumberInvalid(p.processedRowsPerSecond)).sum / uiData.recentProgress.length)

    StructuredStreamingRow(duration, avgInput, avgProcess, uiData)
  }

  private def ordering(sortColumn: String, desc: Boolean): Ordering[StructuredStreamingRow] = {
    val ordering: Ordering[StructuredStreamingRow] = sortColumn match {
      case "Name" => Ordering.by(row => UIUtils.getQueryName(row.streamingUIData))
      case "Status" => Ordering.by(row => UIUtils.getQueryStatus(row.streamingUIData))
      case "ID" => Ordering.by(_.streamingUIData.summary.id)
      case "Run ID" => Ordering.by(_.streamingUIData.summary.runId)
      case "Start Time" => Ordering.by(_.streamingUIData.summary.startTimestamp)
      case "Duration" => Ordering.by(_.duration)
      case "Avg Input /sec" => Ordering.by(_.avgInput)
      case "Avg Process /sec" => Ordering.by(_.avgProcess)
      case "Latest Batch" => Ordering.by(_.streamingUIData.lastProgress.batchId)
      case unknownColumn => throw new IllegalArgumentException(s"Unknown Column: $unknownColumn")
    }
    if (desc) {
      ordering.reverse
    } else {
      ordering
    }
  }
}


text:
<!DOCTYPE html>

        <title>Babylon.js Specifications</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="author" href="humans.txt" />

        <meta property="og:title" content="Babylon.js: Powerful, Beautiful, Simple, Open - Web-Based 3D At Its Best" />
        <meta property="og:site_name" content="Babylon.js" />
        <meta property="og:url" content="https://www.babylonjs.com" />
        <meta property="og:description"
            content="Babylon.js is one of the world's leading WebGL-based graphics engines. From a new visual scene inspector, best-in-class physically-based rendering, countless performance optimizations, and much more, Babylon.js brings powerful, beautiful, simple, and open 3D to everyone on the web." />
        <meta property="og:type" content="website" />
        <meta property="og:image" content="https://www.babylonjs.com/assets/logo-babylonjs-social-twitter.png" />
        <meta property="og:locale" content="en_US" />

        <meta name="twitter:card" content="summary" />
        <meta name="twitter:url" content="https://www.babylonjs.com" />
        <meta name="twitter:title" content="Babylon.js: Powerful, Beautiful, Simple, Open - Web-Based 3D At Its Best" />
        <meta name="twitter:description"
            content="Babylon.js is one of the world's leading WebGL-based graphics engines. From a new visual scene inspector, best-in-class physically-based rendering, countless performance optimizations, and much more, Babylon.js brings powerful, beautiful, simple, and open 3D to everyone on the web." />
        <meta name="twitter:image" content="https://www.babylonjs.com/assets/logo-babylonjs-social-twitter.png" />
        <link rel="shortcut icon" href="/assets/favicon.ico">
        <link rel="icon" type="image/png" href="/assets/favicon.ico">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <link rel="stylesheet" href="https://use.typekit.net/cta4xsb.css">
        <link rel="stylesheet" href="/assets/styles/variables.css">
        <link rel="stylesheet" href="/assets/styles/upTriangleBlock.css">
        <link rel="stylesheet" href="/assets/styles/downTriangleBlock.css">
        <link rel="stylesheet" href="/assets/styles/header.css">
        <link rel="stylesheet" href="/assets/styles/footer.css">
        <link rel="stylesheet" href="/assets/styles/gallery.css">
        <link rel="stylesheet" href="/assets/styles/topBlock.css">
        <link rel="stylesheet" href="/assets/styles/carousel.css">
        <link rel="stylesheet" href="/assets/styles/textBlock.css">
        <link rel="stylesheet" href="/assets/styles/imageBlock.css">
        <link rel="stylesheet" href="/assets/styles/twoColumns.css">
        <link rel="stylesheet" href="/assets/styles/imageAndTextBlock.css">
        <link rel="stylesheet" href="/assets/styles/linkList.css">
        <link rel="stylesheet" href="/assets/styles/imageList.css">
        <link rel="stylesheet" href="/assets/styles/styles.css">
        <link rel="stylesheet" href="/assets/styles/mediaQueries.css">
        <link rel="author" href="humans.txt">

TOOLS

COMMUNITY

GAMES

E-COMMERCE

BABYLON NATIVE

LEARN

SPECIFICATIONS

RELEASE NOTES

GET

PLAYGROUND

SANDBOX

NODE MATERIAL EDITOR

DOCUMENTATION

EXPORTERS

SPECTOR.JS

FORUM

DEMOS

BABYLON NATIVE RUNTIME

BABYLON REACT NATIVE

DOCUMENTATION

VIDEOS

BLOG

            </video>

            </video>

            </video>

ENGINE SPECIFICATIONS

MAIN FEATURES

                    Transparent WebGL 1.0 /
                                        WebGL 2.0 /
                    WebGPU
                    support

                    Complete scene graph
                    with lights, cameras, materials, meshes, animations, audio & actions

                    Easy to use full featured viewer

                    Native host (iOS, Android, MacOS, Win32, UWP)

                    Native
                                        collisions
                    engine

                    Physics engine
                    (thanks to
                                        oimo.js
                    ammo.js
                    and
                                        cannon.js
                    integrations)

                    Scene picking

                    Support left and right handed systems

                    Anti-aliasing

                    Animations
                    engine

                    Particles
                    (both CPU and GPU)
                                        and
                                        Solid particles
                    Systems

                    Sprites
                    and 2D layers

                    Complete
                                        audio engine
                    based on Web Audio

                    Hardware accelerated
                                        GUI

                    Behaviors

                    Accelerated 2D controls

SHADERS / RENDERING

                    Node Material

                    Physically Based Rendering (PBR)

                    Clear coat

                    Sheen

                    Diffuse lighting and texture

                    Ambient lighting and texture

                    Specular lighting and texture

                    Opacity texture

                    Mirror texture

                    Emissive texture

                    Bump texture

                    Lightmap texture

                    Unlimited lights (points, directionals, spots, hemispherics)

                    Light texture projection

                    Skybox

                    Vertex color

                    Up to 8 bones per vertex

                    Morphing

                    Render target textures

                    Dynamic textures (2D canvas)

                    Reflection texture (Spheric, planar, cubic, projection and equirectangular)

                    Video textures (including from webcam)

                    Compressed (DDS, KTX, .basis) textures & TGA

                    360 photos and videos

                    Procedural textures library

                    Materials library

MESHES

                    Mesh cloning

                    Dynamic meshes

                    Decals

                    Height maps

                    Skeletons and bones

                    Parametric shapes (Ribbon, tubes, etc.)

                    Morph targets

                    Dynamic mesh simplification

                    Constructive Solid Geometries

OPTIMIZATIONS

                    Frustum clipping

                    Sub-meshes clipping

                    Hardware scaling

                    Occlusion queries

                    Selection octrees

                    Offline mode (Assets saved in IndexedDB)

                    Incremental loading

                    Binary compressed format

                    Hardware accelerated instances

                    Automatic scene optimizer

                    LOD (Level Of Details)

                    Meshes merging

                    Offscreen canvas

                    Engine sharing over multiple canvases

SPECIAL FX

                    Fog

                    Alpha blending

                    Alpha testing

                    Billboarding

                    Fullscreen mode

                    Shadow Maps and Exponentatial Shadow Maps (including soft shadows with PCF and PCSS)

                    Cascaded Shadow Maps

                    Post-processes

                    Depth of field

                    Image processing

                    Bloom

                    Grain

                    Anti aliasing

                    Sharpening

                    Screen space reflections

                    Rendering layers

                    Lens flares

                    Reflection Probes

                    Edges renderer

                    Multi-views

                    Highlights rendering

                    Glow layer

                    Navigation mesh and crowd of moving agents

CAMERAS

                    Universal camera (keyboard/touch/gamepad)

                    Arc rotate camera

                    Free camera

                    Touch camera

                    Virtual Joysticks camera

                    WebVR camera

                    Gamepad camera

                    VR Device Oriention camera for Cardboard

                    Follow camera

                    Anaglyph camera

EXPORTERS AND TOOLING

                    Exporters for glTF, OBJ and Babylon file formats

                    Importers for glTF, STL, OBJ and Babylon file formats

                    Support for drag'n'drop

                    Inspector

                    Assets manager

TOOLS INTEGRATION

FEATURED DEMOS

Marble Tower

by PirateJC

SharePoint Spaces

by Microsoft

US Masters

by ANGC

Adobe Dimension web export

by Adobe

Shell Shockers

by Fun Fetched

JigSpace

by JigSpace Inc.

Apartment Configurator

by Axeon Software

MORE

                    Forum
                    Contribute
                    Tutorials
                    Branding


text:
'use strict';

describe('Directive: DeviceEditableFields', function () {

  // load the directive's module
  beforeEach(module('ubirchAdminCrudApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<-device-editable-fields></-device-editable-fields>');
    element = $compile(element)(scope);
    expect(element.text()).toBe('this is the DeviceEditableFields directive');
  }));
});


text:
/* This file just contains a small glue function which fishes the
 * location of kernel etc out of linker script defined symbols, and
 * calls semi_loader functions to do the actual work of loading
 * and booting the kernel.
 */

#include <stdint.h>
#include "semihosting.h"
#include "semi_loader.h"

/* Linker script defined symbols for any preloaded kernel/initrd */
extern uint8_t fs_start, fs_end, kernel_entry, kernel_start, kernel_end;
/* Symbols defined by boot.S */
extern uint8_t kernel_cmd, kernel_cmd_end;

static struct loader_info loader;

#ifdef MACH_MPS
#define PLAT_ID 10000 /* MPS (temporary) */
#elif defined (VEXPRESS)
#define PLAT_ID 2272 /* Versatile Express */
#else
#define PLAT_ID 827 /* RealView/EB */
#endif

void c_start(void)
{
	/* Main C entry point */
	loader.kernel_size = (uint32_t)&kernel_end - (uint32_t)&kernel_start;
	loader.initrd_start = (uint32_t)&fs_start;
	loader.initrd_size = (uint32_t)&fs_end - (uint32_t)&fs_start;
	loader.kernel_entry = (uint32_t)&kernel_entry;
	if (loader.kernel_size) {
		loader.cmdline_start = (uint32_t)&kernel_cmd;
		loader.cmdline_size = &kernel_cmd_end - &kernel_cmd;
	}
	load_kernel(&loader);

	/* Start the kernel */
	if(loader.fdt_start) {
		boot_kernel(&loader, 0, -1, loader.fdt_start, 0);
	} else {
		boot_kernel(&loader, 0, PLAT_ID, loader.atags_start, 0);
	}

	semi_write0("[bootwrapper] ERROR: returned from boot_kernel\n");
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XLSLoader
{
    class VisaForLoader
    {
        public string VisaType { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime DueDate { get; set; }
        public int Days { get; set; }
        public int Entries { get; set; }
        public string EID { get; set; }
    }
}


text:
{% extends 'base/base.html' %}
{% block tabs %}
    {{ select_tab('LITINFANTOJUVS') }}
{% endblock %}