text:
package service

import (
	"fmt"
	"math/rand"
	"net"
	"net/http"
	"net/url"
	"strconv"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/rest"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/api/validation"
	"k8s.io/kubernetes/pkg/registry/endpoint"
	"k8s.io/kubernetes/pkg/registry/service/ipallocator"
	"k8s.io/kubernetes/pkg/registry/service/portallocator"
	"k8s.io/kubernetes/pkg/runtime"
	utilnet "k8s.io/kubernetes/pkg/util/net"
	"k8s.io/kubernetes/pkg/util/validation/field"
	"k8s.io/kubernetes/pkg/watch"
)

// ServiceRest includes storage for services and all sub resources
type ServiceRest struct {
	Service *REST
	Proxy   *ProxyREST
}

// REST adapts a service registry into apiserver's RESTStorage model.
type REST struct {
	registry         Registry
	endpoints        endpoint.Registry
	serviceIPs       ipallocator.Interface
	serviceNodePorts portallocator.Interface
	proxyTransport   http.RoundTripper
}

// NewStorage returns a new REST.
func NewStorage(registry Registry, endpoints endpoint.Registry, serviceIPs ipallocator.Interface,
	serviceNodePorts portallocator.Interface, proxyTransport http.RoundTripper) *ServiceRest {
	rest := &REST{
		registry:         registry,
		endpoints:        endpoints,
		serviceIPs:       serviceIPs,
		serviceNodePorts: serviceNodePorts,
		proxyTransport:   proxyTransport,
	}
	return &ServiceRest{
		Service: rest,
		Proxy:   &ProxyREST{ServiceRest: rest, ProxyTransport: proxyTransport},
	}
}

func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, error) {
	service := obj.(*api.Service)

	if err := rest.BeforeCreate(Strategy, ctx, obj); err != nil {
		return nil, err
	}

	// TODO: this should probably move to strategy.PrepareForCreate()
	releaseServiceIP := false
	defer func() {
		if releaseServiceIP {
			if api.IsServiceIPSet(service) {
				rs.serviceIPs.Release(net.ParseIP(service.Spec.ClusterIP))
			}
		}
	}()

	nodePortOp := portallocator.StartOperation(rs.serviceNodePorts)
	defer nodePortOp.Finish()

	if api.IsServiceIPRequested(service) {
		// Allocate next available.
		ip, err := rs.serviceIPs.AllocateNext()
		if err != nil {
			// TODO: what error should be returned here?  It's not a
			// field-level validation failure (the field is valid), and it's
			// not really an internal error.
			return nil, errors.NewInternalError(fmt.Errorf("failed to allocate a serviceIP: %v", err))
		}
		service.Spec.ClusterIP = ip.String()
		releaseServiceIP = true
	} else if api.IsServiceIPSet(service) {
		// Try to respect the requested IP.
		if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil {
			// TODO: when validation becomes versioned, this gets more complicated.
			el := field.ErrorList{field.Invalid(field.NewPath("spec", "clusterIP"), service.Spec.ClusterIP, err.Error())}
			return nil, errors.NewInvalid(api.Kind("Service"), service.Name, el)
		}
		releaseServiceIP = true
	}

	assignNodePorts := shouldAssignNodePorts(service)
	for i := range service.Spec.Ports {
		servicePort := &service.Spec.Ports[i]
		if servicePort.NodePort != 0 {
			err := nodePortOp.Allocate(int(servicePort.NodePort))
			if err != nil {
				// TODO: when validation becomes versioned, this gets more complicated.
				el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), servicePort.NodePort, err.Error())}
				return nil, errors.NewInvalid(api.Kind("Service"), service.Name, el)
			}
		} else if assignNodePorts {
			nodePort, err := nodePortOp.AllocateNext()
			if err != nil {
				// TODO: what error should be returned here?  It's not a
				// field-level validation failure (the field is valid), and it's
				// not really an internal error.
				return nil, errors.NewInternalError(fmt.Errorf("failed to allocate a nodePort: %v", err))
			}
			servicePort.NodePort = int32(nodePort)
		}
	}

	out, err := rs.registry.CreateService(ctx, service)
	if err != nil {
		err = rest.CheckGeneratedNameError(Strategy, err, service)
	}

	if err == nil {
		el := nodePortOp.Commit()
		if el != nil {
			// these should be caught by an eventual reconciliation / restart
			glog.Errorf("error(s) committing service node-ports changes: %v", el)
		}

		releaseServiceIP = false
	}

	return out, err
}

func (rs *REST) Delete(ctx api.Context, id string) (runtime.Object, error) {
	service, err := rs.registry.GetService(ctx, id)
	if err != nil {
		return nil, err
	}

	err = rs.registry.DeleteService(ctx, id)
	if err != nil {
		return nil, err
	}

	// TODO: can leave dangling endpoints, and potentially return incorrect
	// endpoints if a new service is created with the same name
	err = rs.endpoints.DeleteEndpoints(ctx, id)
	if err != nil && !errors.IsNotFound(err) {
		return nil, err
	}

	if api.IsServiceIPSet(service) {
		rs.serviceIPs.Release(net.ParseIP(service.Spec.ClusterIP))
	}

	for _, nodePort := range CollectServiceNodePorts(service) {
		err := rs.serviceNodePorts.Release(nodePort)
		if err != nil {
			// these should be caught by an eventual reconciliation / restart
			glog.Errorf("Error releasing service %s node port %d: %v", service.Name, nodePort, err)
		}
	}

	return &unversioned.Status{Status: unversioned.StatusSuccess}, nil
}

func (rs *REST) Get(ctx api.Context, id string) (runtime.Object, error) {
	return rs.registry.GetService(ctx, id)
}

func (rs *REST) List(ctx api.Context, options *api.ListOptions) (runtime.Object, error) {
	return rs.registry.ListServices(ctx, options)
}

// Watch returns Services events via a watch.Interface.
// It implements rest.Watcher.
func (rs *REST) Watch(ctx api.Context, options *api.ListOptions) (watch.Interface, error) {
	return rs.registry.WatchServices(ctx, options)
}

// Export returns Service stripped of cluster-specific information.
// It implements rest.Exporter.
func (rs *REST) Export(ctx api.Context, name string, opts unversioned.ExportOptions) (runtime.Object, error) {
	return rs.registry.ExportService(ctx, name, opts)
}

func (*REST) New() runtime.Object {
	return &api.Service{}
}

func (*REST) NewList() runtime.Object {
	return &api.ServiceList{}
}

func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) {
	service := obj.(*api.Service)
	if !api.ValidNamespace(ctx, &service.ObjectMeta) {
		return nil, false, errors.NewConflict(api.Resource("services"), service.Namespace, fmt.Errorf("Service.Namespace does not match the provided context"))
	}

	oldService, err := rs.registry.GetService(ctx, service.Name)
	if err != nil {
		return nil, false, err
	}

	// Copy over non-user fields
	// TODO: make this a merge function
	if errs := validation.ValidateServiceUpdate(service, oldService); len(errs) > 0 {
		return nil, false, errors.NewInvalid(api.Kind("Service"), service.Name, errs)
	}

	nodePortOp := portallocator.StartOperation(rs.serviceNodePorts)
	defer nodePortOp.Finish()

	assignNodePorts := shouldAssignNodePorts(service)

	oldNodePorts := CollectServiceNodePorts(oldService)

	newNodePorts := []int{}
	if assignNodePorts {
		for i := range service.Spec.Ports {
			servicePort := &service.Spec.Ports[i]
			nodePort := int(servicePort.NodePort)
			if nodePort != 0 {
				if !contains(oldNodePorts, nodePort) {
					err := nodePortOp.Allocate(nodePort)
					if err != nil {
						el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), nodePort, err.Error())}
						return nil, false, errors.NewInvalid(api.Kind("Service"), service.Name, el)
					}
				}
			} else {
				nodePort, err = nodePortOp.AllocateNext()
				if err != nil {
					// TODO: what error should be returned here?  It's not a
					// field-level validation failure (the field is valid), and it's
					// not really an internal error.
					return nil, false, errors.NewInternalError(fmt.Errorf("failed to allocate a nodePort: %v", err))
				}
				servicePort.NodePort = int32(nodePort)
			}
			// Detect duplicate node ports; this should have been caught by validation, so we panic
			if contains(newNodePorts, nodePort) {
				panic("duplicate node port")
			}
			newNodePorts = append(newNodePorts, nodePort)
		}
	} else {
		// Validate should have validated that nodePort == 0
	}

	// The comparison loops are O(N^2), but we don't expect N to be huge
	// (there's a hard-limit at 2^16, because they're ports; and even 4 ports would be a lot)
	for _, oldNodePort := range oldNodePorts {
		if !contains(newNodePorts, oldNodePort) {
			continue
		}
		nodePortOp.ReleaseDeferred(oldNodePort)
	}

	// Remove any LoadBalancerStatus now if Type != LoadBalancer;
	// although loadbalancer delete is actually asynchronous, we don't need to expose the user to that complexity.
	if service.Spec.Type != api.ServiceTypeLoadBalancer {
		service.Status.LoadBalancer = api.LoadBalancerStatus{}
	}

	out, err := rs.registry.UpdateService(ctx, service)

	if err == nil {
		el := nodePortOp.Commit()
		if el != nil {
			// problems should be fixed by an eventual reconciliation / restart
			glog.Errorf("error(s) committing NodePorts changes: %v", el)
		}
	}

	return out, false, err
}

// Implement Redirector.
var _ = rest.Redirector(&REST{})

// ResourceLocation returns a URL to which one can send traffic for the specified service.
func (rs *REST) ResourceLocation(ctx api.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "svcname", "svcname:port", or "scheme:svcname:port".
	svcScheme, svcName, portStr, valid := utilnet.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid service request %q", id))
	}

	// If a port *number* was specified, find the corresponding service port name
	if portNum, err := strconv.ParseInt(portStr, 10, 64); err == nil {
		svc, err := rs.registry.GetService(ctx, svcName)
		if err != nil {
			return nil, nil, err
		}
		found := false
		for _, svcPort := range svc.Spec.Ports {
			if int64(svcPort.Port) == portNum {
				// use the declared port's name
				portStr = svcPort.Name
				found = true
				break
			}
		}
		if !found {
			return nil, nil, errors.NewServiceUnavailable(fmt.Sprintf("no service port %d found for service %q", portNum, svcName))
		}
	}

	eps, err := rs.endpoints.GetEndpoints(ctx, svcName)
	if err != nil {
		return nil, nil, err
	}
	if len(eps.Subsets) == 0 {
		return nil, nil, errors.NewServiceUnavailable(fmt.Sprintf("no endpoints available for service %q", svcName))
	}
	// Pick a random Subset to start searching from.
	ssSeed := rand.Intn(len(eps.Subsets))
	// Find a Subset that has the port.
	for ssi := 0; ssi < len(eps.Subsets); ssi++ {
		ss := &eps.Subsets[(ssSeed+ssi)%len(eps.Subsets)]
		if len(ss.Addresses) == 0 {
			continue
		}
		for i := range ss.Ports {
			if ss.Ports[i].Name == portStr {
				// Pick a random address.
				ip := ss.Addresses[rand.Intn(len(ss.Addresses))].IP
				port := int(ss.Ports[i].Port)
				return &url.URL{
					Scheme: svcScheme,
					Host:   net.JoinHostPort(ip, strconv.Itoa(port)),
				}, rs.proxyTransport, nil
			}
		}
	}
	return nil, nil, errors.NewServiceUnavailable(fmt.Sprintf("no endpoints available for service %q", id))
}

// This is O(N), but we expect haystack to be small;
// so small that we expect a linear search to be faster
func contains(haystack []int, needle int) bool {
	for _, v := range haystack {
		if v == needle {
			return true
		}
	}
	return false
}

func CollectServiceNodePorts(service *api.Service) []int {
	servicePorts := []int{}
	for i := range service.Spec.Ports {
		servicePort := &service.Spec.Ports[i]
		if servicePort.NodePort != 0 {
			servicePorts = append(servicePorts, int(servicePort.NodePort))
		}
	}
	return servicePorts
}

func shouldAssignNodePorts(service *api.Service) bool {
	switch service.Spec.Type {
	case api.ServiceTypeLoadBalancer:
		return true
	case api.ServiceTypeNodePort:
		return true
	case api.ServiceTypeClusterIP:
		return false
	default:
		glog.Errorf("Unknown service type: %v", service.Spec.Type)
		return false
	}
}


text:
using System;
using System.Diagnostics.Contracts;

namespace System
{

    public class OperatingSystem
    {

        public PlatformID Platform
        {
          get;
        }

        public Version Version
        {
          get;
        }

        [Pure][Reads(ReadsAttribute.Reads.Owned)]
        public string ToString () {

          return default(string);
        }
        public object Clone () {

          return default(object);
        }
        public OperatingSystem (PlatformID platform, Version! version) {
            CodeContract.Requires(version != null);
          return default(OperatingSystem);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace NAttreid\Cms\Factories;

use Kdyby\Translation\Translator;
use Nette\ComponentModel\IContainer;
use Nette\SmartObject;
use Ublaboo\DataGrid\DataGrid;

/**
 * Tovaran datagridu
 *
 * @author Attreid <attreid@gmail.com>
 */
class DataGridFactory
{
	use SmartObject;

	/** @var array */
	private $config;

	/** @var Translator */
	private $translator;

	public function __construct(array $config, Translator $translator)
	{
		$this->translator = $translator;
		$this->config = $config;
	}

	/**
	 * @param IContainer $parent
	 * @param string $name
	 * @return DataGrid
	 */
	public function create(IContainer $parent = null, string $name = null): DataGrid
	{
		$grid = new DataGrid($parent, $name);

		$grid->setTranslator($this->translator);
		$grid->setItemsPerPageList($this->config['perPage']['list'], $this->config['perPage']['all']);
		$grid->setDefaultPerPage($this->config['perPage']['list'][0]);

		return $grid;
	}

}


text:
/**
 * Auth wrapper
 * @type {*|exports|module.exports}
 */
var fs = require ('fs');
var express = require ('express');
var app = require ('../app');
var user = require ('./models/User.js');
var jwt = require ('jsonwebtoken');

/**
 * provide basic verify function with callback of err/decoded returned
 * @param token
 * @param callback
 */

var verify = function (token, callback) {
	jwt.verify (token, app.get ('jwt-secret'), function (err, decoded) {
		callback (err, decoded);
	})

}
/**
 * protectCSRF ensure Fully Authentication check by ignoring cookies
 * Client must attached its token within post body, url or headers
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
var protectCSRF = function (req, res, next) {
	req.cookies.token = null;
	return next ();
}

/**
 * ensureAuth is a middleware which filter the json token for verifying login
 * @param req
 * @param res
 * @param next
 *
 * usage:
 * in router.js ---router.use('*some url*', auth.ensureAuth, *next middleware function*)
 * in next middleware ---var middleware = function(req, res, next){var authResult = req.body.auth}
 */
var ensureAuth = function (req, res, next) {
	//Get token from body or query or headers
	var token = req.body.token || req.query.token || req.headers['token'] || req.cookies.token;
	if (token) {
		return jwt.verify (token, app.get ('jwt-secret'), function (err, decoded) {
			if (err) {
				req.body.auth = {
					success: false,
					message: 'Invalid'
				};
				return next ();
			} else {
				req.body.auth = {
					success: true,
					decoded: decoded
				};
				return next ();
			}
		});
	} else {
		req.body.auth = {
			success: false,
			message: 'Null'
		};
		return next ();
	}

	// have not yet implemented else!!!!
};

/**
 * auth is a middleware provide function for login use and set authorization info
 * @param req
 * @param res
 * @param next
 * usage:
 * use like ensureAuth before login controller
 */
var setAuth = function (id, name) {
	var tmpuser = {};
	tmpuser.id = id;
	tmpuser.name = name

	//set token
	var token = jwt.sign (tmpuser, app.get ('jwt-secret'), {
		expiresIn: '30d'
	});
	return token;
};

module.exports.verify = verify;
module.exports.protectCSRF = protectCSRF;
module.exports.ensureAuth = ensureAuth;
module.exports.setAuth = setAuth;


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white" android:drawable="@mipmap/icon_bg_selected" android:state_checked="true" />
    <item android:color="@color/colorPrimary" android:drawable="@mipmap/icon_bg_normal" />
</selector>


text:
// Copyright 2017 The Kubernetes Dashboard Authors.
//
// 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.

import LoginSpec from './spec';

/** @final */
class TokenLoginController {
  /** @ngInject */
  constructor() {
    /** @export {!angular.Component} */
    this.loginOptionsCtrl;
    /** @export {boolean} */
    this.selected = false;
    /** @export {function({loginSpec: !backendApi.LoginSpec})} - Initialized from binding */
    this.onUpdate;
    /** @export {string} */
    this.token;
  }

  /** @export */
  $onInit() {
    this.loginOptionsCtrl.addOption(this);
  }

  /** @export */
  onTokenUpdate() {
    this.onUpdate({loginSpec: new LoginSpec({token: this.token})});
  }
}

/** @type {!angular.Component} */
export const tokenLoginComponent = {
  templateUrl: 'login/token.html',
  require: {
    'loginOptionsCtrl': '^kdLoginOptions',
  },
  bindings: {
    'title': '@',
    'onUpdate': '&',
  },
  controller: TokenLoginController,
};


text:
using aGrader.Properties;

namespace aGrader.IOForms
{
    public partial class OutputString : InputString
    {
        public OutputString()
        {
            InitializeComponent();
        }

        public OutputString(string text) : base(text)
        {

        }

        public override string ToString()
        {
            return string.Format(Resources.IOFDescription_OutputString, Text);
        }
    }
}


text:
@interface SKStoreProductViewController(BBlock)

typedef void (^SKStoreProductViewControllerBBlock)(SKStoreProductViewController *productViewController);

+ (id)productViewControllerWithDidFinishBlock:(SKStoreProductViewControllerBBlock)block;
- (id)initWithProductViewControllerWithDidFinishBlock:(SKStoreProductViewControllerBBlock)block;

@end


text:
// ----------------------------------------------------------------------------
// Copyright 2006-2010, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
//  2007/03/11  Martin D. Flynn
//     -Initial release
//  2007/06/30  Martin D. Flynn
//     -Added total row ('getTotalsDataIterator')
//  2007/12/13  Martin D. Flynn
//     -Added indication of partial data (ie. when 'limit' has been exceeded)
//  2007/01/10  Martin D. Flynn
//     -Fixed 'partial' indication when limit is '-1'
//  2009/05/01  Martin D. Flynn
//     -Removed "Totals" line from CSV generated output
// ----------------------------------------------------------------------------
package org.opengts.war.report.presentation;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.opengts.util.*;

import org.opengts.war.tools.*;
import org.opengts.war.report.*;

public class ReportBody
{

    // ------------------------------------------------------------------------

    private ReportTable         reportTable = null;

    private BodyRowTemplate     bodyRow     = null;

    private int                 rcdCount    = 0;
    private boolean             isPartial   = false;

    // ------------------------------------------------------------------------

    public ReportBody(ReportTable rptTable)
    {
        this(rptTable, null);
    }

    protected ReportBody(ReportTable rptTable, BodyRowTemplate br)
    {
        this.reportTable = rptTable;
        this.bodyRow     = (br != null)? br : new BodyRowTemplate(this.reportTable);
    }

    // ------------------------------------------------------------------------

    public int getRecordCount()
    {
        return this.rcdCount;
    }

    public boolean isPartial()
    {
        return this.isPartial;
    }

    // ------------------------------------------------------------------------

    private boolean _overLimit(ReportData rd)
    {

        /* check report limit */
        long rptLimit = rd.getReportLimit();
        long rptCount = this.rcdCount;
        if ((rptLimit > 0L) && (rptCount >= rptLimit)) {
            Print.logInfo("Partial report data (RecordCount): " + rptCount + " >= " + rptLimit);
            return true;
        }
        //Print.logInfo("RecordCount: %d/%d", rptCount, rptLimit);

        /* check selection limit (applicable only for EventData queries) */
        long selLimit = rd.getSelectionLimit();
        if (selLimit > 10L) { // don't count small selection limit (other "1 >= 1" will cause a partial indication)
            long selCount = rd.getMaximumEventDataCount();
            if ((selLimit > 0L) && (selCount >= selLimit)) {
                Print.logInfo("Partial report data (maxSelectionCount): " + selCount + " >= " + selLimit);
                return true;
            }
            //Print.logInfo("SelectionCount: %d/%d", selCount, selLimit);
        }

        /* not over limit */
        return false;

    }

    // ------------------------------------------------------------------------

    public void writeHTML(PrintWriter out, int level, ReportData report)
        throws ReportException
    {

        /* resulting state */
        this.isPartial = false;
        this.rcdCount = 0;

        /* HTML table body begin */
        out.print("<tbody>\n");

        /* report body */
        DBDataIterator data = report.getBodyDataIterator();
        if ((data != null) && data.hasNext()) {
            for (this.rcdCount = 0; data.hasNext(); this.rcdCount++) {
                DBDataRow dr = data.next();
                if (dr != null) {
                    this.bodyRow.writeHTML(out, level+1, this.rcdCount, false/*totals*/, dr);
                }
            }
            this.isPartial = this._overLimit(report);
        }

        /* report totals */
        DBDataIterator totals = report.getTotalsDataIterator();
        if ((totals != null) && totals.hasNext()) {
            for (int r = 0; totals.hasNext(); r++) {
                DBDataRow dr = totals.next();
                if (dr != null) {
                    this.bodyRow.writeHTML(out, level+1, r, true/*totals*/, dr);
                }
            }
        }

        /* HTML table body end */
        out.print("</tbody>\n");

    }

    // ------------------------------------------------------------------------

    public void writeXML(PrintWriter out, int level, ReportData report)
        throws ReportException
    {
        boolean isSoapRequest = report.isSoapRequest();
        String PFX1 = XMLTools.PREFIX(isSoapRequest, level * ReportTable.INDENT);

        /* resulting state */
        this.isPartial = false;
        this.rcdCount = 0;

        /* HTML table body begin */
        out.print(PFX1);
        out.print(XMLTools.startTAG(isSoapRequest,"ReportBody","",false,true));

        /* report body */
        DBDataIterator data = report.getBodyDataIterator();
        if ((data != null) && data.hasNext()) {
            for (this.rcdCount = 0; data.hasNext(); this.rcdCount++) {
                DBDataRow dr = data.next();
                if (dr != null) {
                    this.bodyRow.writeXML(out, level+1, this.rcdCount, false/*totals*/, dr);
                }
            }
            this.isPartial = this._overLimit(report);
        }

        /* report totals */
        DBDataIterator totals = report.getTotalsDataIterator();
        if ((totals != null) && totals.hasNext()) {
            for (int r = 0; totals.hasNext(); r++) {
                DBDataRow dr = totals.next();
                if (dr != null) {
                    this.bodyRow.writeXML(out, level+1, r, true/*totals*/, dr);
                }
            }
        }

        /* HTML table body end */
        out.print(PFX1);
        out.print(XMLTools.endTAG(isSoapRequest,"ReportBody",true));

    }

    // ------------------------------------------------------------------------

    private static final boolean INCLUDE_CSV_TOTALS = false;

    public void writeCSV(PrintWriter out, int level, ReportData report)
        throws ReportException
    {

        /* report body */
        this.isPartial = false;
        this.rcdCount = 0;
        DBDataIterator data = report.getBodyDataIterator();
        if ((data != null) && data.hasNext()) {
            for (this.rcdCount = 0; data.hasNext(); this.rcdCount++) {
                DBDataRow dr = data.next();
                if (dr != null) {
                    this.bodyRow.writeCSV(out, level+1, this.rcdCount, false/*totals*/, dr);
                }
            }
            this.isPartial = this._overLimit(report);
        }

        /* report totals */
        if (INCLUDE_CSV_TOTALS) {
            DBDataIterator totals = report.getTotalsDataIterator();
            if (totals != null) {
                for (int r = 0; totals.hasNext(); r++) {
                    DBDataRow dr = totals.next();
                    if (dr != null) {
                        this.bodyRow.writeCSV(out, level+1, r, true/*totals*/, dr);
                    }
                }
            }
        }

    }

    // ------------------------------------------------------------------------

}


text:
var discover = function( req, res ) {

	var commands =  {
			input : {
				fm: {
					name : 'Listen to FM',
					instructions : 'Enjoy the radio',
					endpoint : '/api/inputs/fm'
				},
				roku: {
					name : 'Use Roku',
					instructions: 'Grab that remote and enjoy',
					endpoint : '/api/inputs/roku'
				},
				phono: {
					name : 'Listen to Records',
					instructions: 'Start Playing that Vinyl',
					endpoint : '/api/inputs/phono'
				},
				tv: {
					name : "Watch Normal TV",
					instructions: "Use the TV remote",
					endpoint : '/api/inputs/tv'
				}

			},
			power : {
				on : {
					name : 'On',
					endpoint: '/api/power/on'
				},
				off : {
					name : 'Off',
					endpoint: '/api/power/off'
				}
			}
		}

	var response = {
			status : 'ok',
			'commands' : commands
		}
	res.send(response);
}

module.exports = discover;


text:
package org.killbill.billing.payment.provider;

import org.killbill.billing.platform.api.KillbillConfigSource;
import org.killbill.billing.util.glue.KillBillModule;
import org.killbill.clock.Clock;

import com.google.inject.name.Names;

public class MockPaymentProviderPluginModule extends KillBillModule {

    private final String instanceName;
    private final Clock clock;

    public MockPaymentProviderPluginModule(final String instanceName, final Clock clock, final KillbillConfigSource configSource) {
        super(configSource);
        this.instanceName = instanceName;
        this.clock = clock;
    }

    @Override
    protected void configure() {
        bind(MockPaymentProviderPlugin.class)
                .annotatedWith(Names.named(instanceName))
                .toProvider(new MockPaymentProviderPluginProvider(instanceName, clock))
                .asEagerSingleton();
    }
}


text:
int32_t
ipc_recv(envid_t *from_env_store, void *pg, int *perm_store)
{
	// LAB 4: Your code here.
	//panic("ipc_recv not implemented");
	if(from_env_store) *from_env_store = 0;

	if(perm_store) *perm_store = 0;

	if(!pg) pg = (void*)KERNBASE;

	int ret = sys_ipc_recv(pg);

	if(ret == 0 && from_env_store) *from_env_store = thisenv->env_ipc_from;

	if(ret == 0 && perm_store) *perm_store = thisenv->env_ipc_perm;
	return thisenv->env_ipc_value;
}

// Send 'val' (and 'pg' with 'perm', if 'pg' is nonnull) to 'toenv'.
// This function keeps trying until it succeeds.
// It should panic() on any error other than -E_IPC_NOT_RECV.
//
// Hint:
//   Use sys_yield() to be CPU-friendly.
//   If 'pg' is null, pass sys_ipc_try_send a value that it will understand
//   as meaning "no page".  (Zero is not the right value.)
void
ipc_send(envid_t to_env, uint32_t val, void *pg, int perm)
{
	// LAB 4: Your code here.
	//panic("ipc_send not implemented");
	if(!pg) pg = (void*)KERNBASE;

	int ret = -E_IPC_NOT_RECV;
	while(ret == -E_IPC_NOT_RECV){
		ret = sys_ipc_try_send(to_env, val, pg, perm);
		sys_yield();
	}
	if(ret != 0) panic("ipc_send error!");
}

// Find the first environment of the given type.  We'll use this to
// find special environments.
// Returns 0 if no such environment exists.
envid_t
ipc_find_env(enum EnvType type)
{
	int i;
	for (i = 0; i < NENV; i++)
		if (envs[i].env_type == type)
			return envs[i].env_id;
	return 0;
}


text:
/*! firebase-admin v4.2.1
    https://firebase.google.com/terms/ */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Renames properties on an object given a mapping from old to new property names.
 *
 * For example, this can be used to map underscore_cased properties to camelCase.
 *
 * @param {Object} obj The object whose properties to rename.
 * @param {Object} keyMap The mapping from old to new property names.
 */
function renameProperties(obj, keyMap) {
    Object.keys(keyMap).forEach(function (oldKey) {
        if (oldKey in obj) {
            var newKey = keyMap[oldKey];
            // The old key's value takes precedence over the new key's value.
            obj[newKey] = obj[oldKey];
            delete obj[oldKey];
        }
    });
}
exports.renameProperties = renameProperties;
/**
 * Defines a new read-only property directly on an object and returns the object.
 *
 * @param {Object} obj The object on which to define the property.
 * @param {string} prop The name of the property to be defined or modified.
 * @param {any} value The value associated with the property.
 *
 * @return {Object} The object that was passed to the function.
 */
function addReadonlyGetter(obj, prop, value) {
    Object.defineProperty(obj, prop, {
        value: value,
        // Make this property read-only.
        writable: false,
        // Include this property during enumeration of obj's properties.
        enumerable: true,
    });
}
exports.addReadonlyGetter = addReadonlyGetter;


text:
package butterknife;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.CLASS;

/**
 * Bind a field to the specified string resource ID.
 *

 * {@literal @}BindString(R.string.username_error) String usernameErrorText;
 *

 */
@Retention(CLASS) @Target(FIELD)
public @interface BindString {
  /** String resource ID to which the field will be bound. */
  int value();
}


text:
Neopixel example
================

Yes, it's near christmas. This is therefore the ideal time to do this, and
write this. This example shows how to use the Adafruit Neopixel library in
Pyxie.

Manually:
    1. Clone https://github.com/adafruit/Adafruit_NeoPixel
    2. Copy (or symlink) the directory into /usr/share/arduino/libraries
    3. Done.

TO BE DONE:

Less Manually:
    1. Clone https://github.com/sparkslabs/neopixel-packaging
    2. Run make
    3. Install adafruit-neopixel

Even less Manually - if you're using Ubuntu 16.04LTS
    1. Make sure you're using my ppa
    2. sudo apt-get install adafruit-neopixel


text:
require 'spec_helper'

describe Cynic::Renderer do
  path = "cynic/controller/index.html.erb"

  describe "#render" do
    let(:renderer) { Cynic::Renderer.new(path) }
    it "finds a file" do
      File.should_receive(:read).with("app/views/" + path).and_return('This is erb <%= "olleh".reverse %>')
      expect(renderer.body).to eq "This is erb hello"
    end

    it "finds a file with a layout" do
      Cynic::Renderer.any_instance.stub(:layout_file).and_return("Layout: <%= yield %> :file" )
      File.should_receive(:read).with("app/views/" + path).and_return('This is erb <%= "olleh".reverse %>')
      expect(renderer.body).to eq "Layout: This is erb hello :file"
    end
  end

  describe "controller" do
    let(:controller) { Cynic::Controller.new }
    before { controller.instance_variable_set(:@test, "Test")}
    let(:renderer) { Cynic::Renderer.new(path, controller) }

    it "assigns the cynic controllers instance methods" do
      expect(renderer.instance_variable_get(:@test)).to eq "Test"
    end
  end
end


text:
package web;

import com.codahale.metrics.ConsoleReporter;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.seleniumhq.selenium.fluent.monitors.CodaHaleMetricsMonitor;

import java.util.concurrent.TimeUnit;

public class WholeSuiteListener extends RunListener {

    @Override
    public void testRunFinished(Result result) throws Exception {
        super.testRunFinished(result);

        final ConsoleReporter reporter = ConsoleReporter.forRegistry(codahaleMetricsMonitor.getMetrics())
                .convertRatesTo(TimeUnit.MILLISECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .outputTo(System.out)
                .build();

        reporter.report();

    }

    public static final CodaHaleMetricsMonitor codahaleMetricsMonitor = new CodaHaleMetricsMonitor("com.paulhammant.fluentSeleniumExamples.");
}


text:
function varargout = fisher(varargin)
% VL_FISHER    Fisher vector feature encoding
%   ENC = VL_FISHER(X, MEANS, COVARIANCES, PRIORS) computes the Fisher
%   vector encoding of the vectors X relative to the Gaussian mixture
%   model with means MEANS, covariances COVARIANCES, and prior mode
%   probabilities PRIORS.
%
%   X has one column per data vector (e.g. a SIFT descriptor), and
%   MEANS and COVARIANCES one column per GMM component (covariance
%   matrices are assumed diagonal, hence these are simply the variance
%   of each data dimension). PRIORS has size equal to the number of
%   GMM components. All data must be of the same class, either SINGLE
%   or DOUBLE.
%
%   ENC is a vector of the same class of X of size equal to the
%   product of the data dimension and the number of components.
%
%   By default, the standard Fisher vector is computed. VL_FISHER()
%   accepts the following options:
%
%   Normalized::
%     If specified, L2 normalize the Fisher vector.
%
%   SquareRoot::
%     If specified, the signed square root function is applied to
%     ENC before normalization.
%
%   Improved::
%     If specified, compute the improved variant of the Fisher
%     Vector. This is equivalent to specifying the Normalized and
%     SquareRoot options.
%
%   Fast::
%     If specified, uses slightly less accurate computations but
%     significantly increase the speed in some cases (particularly
%     with a large number of Gaussian modes).
%
%   Verbose::
%     Increase the verbosity level (may be specified multiple times).
%
%   See: Fisher vectors, VL_HELP().
[varargout{1:nargout}] = vl_fisher(varargin{:});


text:
package org.spideruci.benchmark.spiderMath_TestNG;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class MultiplicationParamTest {

	@Test(dataProvider = "numberProvider")
	public void testMulti(int expt, int a, int b) {
		Assert.assertEquals(expt, Multiplication.multi(a, b));
	}

	@DataProvider
	public static Object[][] numberProvider() {
		return new Integer[][] { { 3, 1, 3 }, { 6, 2, 3 },};
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Arr. Brit. Pl. (London), Edn 3 4: 216 (1796)

#### Original name
Agaricus littoreus With.

### Remarks
null


text:
layout: post
microblog: true
audio:
photo:
date: 2018-04-08 14:21:08 -0700
guid: http://curt.micro.blog/2018/04/08/grilled-alaska-salmon.html
---
Grilled Alaska salmon with this [pineapple salsa](https://www.allrecipes.com/recipe/35157/pineapple-salsa/) was excellent. Easy to make, but lots of chopping and dicing.


text:
@interface OFNewAccountController : OFFormControllerHelper< OFCallbackable >
{
@private
	BOOL hasBeenDismissed;
	NSString* desiredName;
	UIView* loadingView;

    UIView* contentView;
	UIView* feintLogoLargeView;
    UILabel* appNameLabel;
    UITextField* nameEntryField;
    OFImageView* profileImageView;
	OFDefaultButton* acceptNameButton;
	UIButton* useDefaultNameButton;
	UIButton* alreadyHaveAccountButton;
	OFDelegate mOnCompletionDelegate;
	OFDelegate mOnCancelDelegate;
	BOOL hideNavigationBar;
	BOOL allowNavigatingBack;
	BOOL closeDashboardOnCompletion;
}

@property (nonatomic, retain) IBOutlet UIView* contentView;
@property (nonatomic, retain) IBOutlet UIView* feintLogoLargeView;
@property (nonatomic, retain) IBOutlet UILabel* appNameLabel;
@property (nonatomic, retain) IBOutlet UITextField* nameEntryField;
@property (nonatomic, retain) IBOutlet OFImageView* profileImageView;
@property (nonatomic, retain) IBOutlet OFDefaultButton* acceptNameButton;
@property (nonatomic, retain) IBOutlet UIButton* useDefaultNameButton;
@property (nonatomic, retain) IBOutlet UIButton* alreadyHaveAccountButton;
@property (nonatomic, assign) BOOL hideNavigationBar;
@property (nonatomic, assign) BOOL allowNavigatingBack;
@property (nonatomic, assign) BOOL closeDashboardOnCompletion;

- (IBAction)_useDefaultName;
- (IBAction)_alreadyCreatedAccount;
- (void)setCompleteDelegate:(OFDelegate&)completeDelegate;
- (void)setCancelDelegate:(OFDelegate&)cancelDelegate;
- (void)hideIntroFlowViews;
- (void)hideContentFrame;

- (void)showNameLoadingView:(NSString *)submittingText;
- (void)hideNameLoadingView;

@end


text:
silverstripe-news
=================

The [silverstripe-news](http://silverstripe.entidi.com/) module
implements two new page types for handling a typical basic news system:
*NewsHolder* (the folder containing related news) and *NewsPage* (the
page presenting a single news).

Every `NewsHolder` will have its own feed and by default it will render
its children (supposedly all `NewsPage` instances) in a `<dl>` list.

* Should work out-of-the-box.
* Ready to use templates compatible with the
  [silverstrap](http://dev.entidi.com/p/silverstrap/) theme.
* Atom 1.0 feed for every `NewsHolder` instance: it can be accessed by
  specificaly requesting an `application/atom+xml` mime type at the
  `NewsHolder` URL or by accessing the `feed` news underneath it, e.g.
  `http://mysite/news/feed/`.
* Back-end fully localized.
* Author customizable for every `NewsHolder` instance.
* Author customizable for every `NewsPage` instance.

Installation
------------

To install silverstripe-news you should proceed as usual: unpack or copy
the directory tree inside your SilverStripe root directory and do a
`/dev/build/?flush`.

If you use [composer](https://getcomposer.org/), you could just use the
following command instead:

    composer require entidi/silverstripe-news

Support
-------

This project has been developed by [ntd](mailto:ntd@entidi.it). Its
[home page](http://silverstripe.entidi.com/) is shared by other
[SilverStripe](http://www.silverstripe.org/) modules and themes.

To check out the code, report issues or propose enhancements, go to the
[dedicated tracker](http://dev.entidi.com/p/silverstripe-news).
Alternatively, you can do the same things by leveraging the official
[github repository](https://github.com/ntd/silverstripe-news).


text:
import {Component, OnDestroy, OnInit} from '@angular/core';

import { SpinnerService } from './spinner.service';

@Component({
  selector: 'toh-spinner',
  template: '
spinner
'
})

export class SpinnerComponent implements OnDestroy, OnInit {
  constructor(private spinnerService: SpinnerService) { }

  ngOnInit() { }

  ngOnDestroy() { }
}


text:
@import UIKit;

@interface GVViewController : UIViewController

@end


text:
package io.nats.client.support;

import io.nats.client.Message;
import io.nats.client.Options;

import java.time.Duration;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;

public class NatsRequestCompletableFuture extends CompletableFuture<Message> {
    private static final long SAFE_TO_CONSIDER_ORPHANED = Duration.ofMinutes(10).toMillis();
    private static final long TIMEOUT_PADDING = Options.DEFAULT_CONNECTION_TIMEOUT.toMillis(); // currently 2 seconds

    private final boolean cancelOn503;
    private final long timeOutAfter;
    private boolean wasCancelledClosing;
    private boolean wasCancelledTimedOut;

    public NatsRequestCompletableFuture(boolean cancelOn503, Duration timeout) {
        this.cancelOn503 = cancelOn503;
        if (timeout == null) {
            timeOutAfter = System.currentTimeMillis() + SAFE_TO_CONSIDER_ORPHANED;
        }
        else {
            timeOutAfter = System.currentTimeMillis() + timeout.toMillis() + TIMEOUT_PADDING;
        }
    }

    public void cancelClosing() {
        wasCancelledClosing = true;
        completeExceptionally(new CancellationException("Future cancelled, connection closing."));
    }

    public void cancelTimedOut() {
        wasCancelledTimedOut = true;
        completeExceptionally(new CancellationException("Future cancelled, response not registered in time, likely due to server disconnect."));
    }

    public boolean isCancelOn503() {
        return cancelOn503;
    }

    public boolean hasExceededTimeout() {
        return System.currentTimeMillis() > timeOutAfter;
    }

    public boolean wasCancelledClosing() {
        return wasCancelledClosing;
    }

    public boolean wasCancelledTimedOut() {
        return wasCancelledTimedOut;
    }
}


text:
<!DOCTYPE HTML>

        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">

Nothing here yet


text:
def match(command, settings):
    return (command.script == 'ls'
            or command.script.startswith('ls ')
            and not ('ls -' in command.script))

def get_new_command(command, settings):
    command = command.script.split(' ')
    command[0] = 'ls -lah'
    return ' '.join(command)


text:
test('SpriteSheet', function() {

	var img = new Image();
	img.src = 'test/assets/jars-sprite.jpg';

	var spritesheet = new Gear.SpriteSheet({
		framerate: 20,
		image: img,
		frame: {
			width: 30,
			height: 42,
			regX: 0,
			regY: 0
		},
		animations: {
			jump: {
				frames: [
					{ idx: 0 },
					{ idx: 7 }
				]
			}
		}
	});

	ok(spritesheet instanceof Gear.SpriteSheet, 'spritesheet is a SpriteSheet');
	// ok(spritesheet._animations.length, 'spritesheet has animations');
	// ok(_.isObject(spritesheet._data) && _.size(spritesheet._data), 'spritesheet has populated data');
	// ok(spritesheet.framerate === 20, 'spritesheet has framerate set');
	// ok(spritesheet._numFrames === 7, 'spritesheet has set count');
	// ok(spritesheet._image instanceof Image, 'spritesheet has an image');

	// ok(spritesheet2._numFrames === 12, 'spritesheet can determine count correctly');
});


text:
#ifndef HASHMAP_H
#define HASHMAP_H

#ifndef HASHMAP_INITIAL_CAPACITY
#define HASHMAP_INITIAL_CAPACITY 32 ///< default hashmap init capacity
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * @file  hashmap.h
 * @brief Generic Hashmap
 */

/**
 * @brief hashmap entry structure
 */
struct hashmap_entry {
    char *key;   ///< entry search key
    void *value; ///< entry value
};

/**
 * @brief main hashmap structure
 */
struct hashmap {
    int capacity;                 ///< actual max capacity of hashmap
    int size;                     ///< actual fill of hashmap
    struct hashmap_entry *values; ///< array of entries
};

/**
 * @brief Free hash table.
 *
 * Uses free.
 * \param table pointer to hashmap struct
 */
void hashmap_free(struct hashmap **table, void (*value_free)(void *ptr));

/**
 * @brief Insert value into hash table. If *table is NULL, allocate new hashmap.
 *
 * Insert using quadratic probing as collision strategy.
 * Double capacity when size > (0.7 * capacity).
 * \param table pointer to the pointer of the hashmap struct
 * \param key key string
 * \param value pointer to payload/value
 */
void *hashmap_put(struct hashmap **table, const char *key, void *value);

/**
 * @brief Get value from hash table.
 *
 * If table is NULL, NULL is returned for any key.
 * \param table pointer to hashmap struct
 * \param key key string
 */
void *hashmap_get(struct hashmap *const *table, const char *key);

/**
 * @brief Update a hash table with another hash table.
 *
 * This function updates a given hash table by merging in the other hash table.
 * The values of equal keys are overwritten with the values of the other hash
 * table.
 * \param table_a pointer to the pointer of the hash table
 * \param table_b pointer of the hash table to be merged
 */
void hashmap_update(struct hashmap **table_a, struct hashmap *table_b);

#endif /* HASHTABLE_H */


text:
/* Groupname entry hung off a member_entry node. */
struct grouplist {
	char *groupname;
	struct grouplist *next;
};

/* Entry in the cooked member list hash table. */
struct member_entry {
	char *key;
	char *domain;
	struct grouplist *groups;
	struct member_entry *next;
};

/* Entry in the raw netgroup table. */
struct group_entry {
	char *key;
	char *data;
	struct group_entry *next;
};

/* Table size (chosen arbitrarily). Not too big, not too small. */
#define TABLESIZE 256
#define HASH_MASK 0x000000FF

#define LINSIZ 1024 * 10

extern void store(struct group_entry ** , char *, char *);
extern void mstore(struct member_entry ** , char *, char *, char *);
extern char *lookup(struct group_entry **, char *);
extern void __endnetgrent(void);
extern void __setnetgrent(char *);
extern int __getnetgrent(char **, char **, char **);


text:
define(['js/jquery',
        'text!/templates/index-entry-template.htm'
        ], function(jq, entryTemplate) {

        function init() {
            console.log('blogjs loaded')
        }

    return {
        'init': init
    }
});


text:
/**
 * Simple JavaScript Inheritance
 * By [John Resig](http://ejohn.org/)
 * MIT Licensed.
 * @ignore
 */
// Inspired by base2 and Prototype
(function() {
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  /**
   * @class Class
   *   The base Class implementation (does nothing).
   *
   * This is [John Resig's "simple JavaScript inheritance" library](http://ejohn.org/blog/simple-javascript-inheritance/).
   *
   * Define a new class with Class#extend:
   *
   *      var MyClass = Class.extend({
   *        // This is the constructor.
   *        init: function() {
   *          // this._super is the parent object's method.
   *          this._super.apply(this, arguments);
   *        },
   *        // This is a custom method.
   *        myMethod: function() {
   *          alert('hi');
   *        },
   *      });
   *      var myInstance = new MyClass();
   *      alert(myInstance instanceof MyClass); // true
   *      var MyChildClass = MyClass.extend({
   *        // Overrides the parent method.
   *        myMethod: function() {
   *          alert('hi there');
   *        },
   *      });
   *      var myChild = new MyChildClass();
   *      alert(myChild instanceof MyChildClass && myChild instanceof myClass); // true
   *      myChild.myMethod(); // hi there
   */
  this.Class = function() {};

  /**
   * Create a new Class that inherits from this class.
   */
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();


text:
<!-- Copyright 2017 MarkLogic Corporation.  All Rights Reserved. -->
<metadata>
  <title>forest-info</title>
  <description>
    <div>
      polyfill for ml9 forestinfo
    </div>
  </description>
  <method name="GET"/>
</metadata>


text:
'use strict';

function getTuneInMetadata(uri, serviceType) {
  return `<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"
        xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
        <item id="F00092020s${uri}" parentID="L" restricted="true"><dc:title>tunein</dc:title><upnp:class>object.item.audioItem.audioBroadcast</upnp:class>
        <desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON${serviceType}_</desc></item></DIDL-Lite>`;
}

function tuneIn(player, values) {
  const action = values[0];
  const tuneInUri = values[1];
  const encodedTuneInUri = encodeURIComponent(tuneInUri);
  const sid = player.system.getServiceId('TuneIn');
  const metadata = getTuneInMetadata(encodedTuneInUri, player.system.getServiceType('TuneIn'));
  const uri = `x-sonosapi-stream:s${encodedTuneInUri}?sid=${sid}&flags=8224&sn=0`;

  if (!tuneInUri) {
    return Promise.reject('Expected TuneIn station id');
  }

  if (action == 'play') {
    return player.coordinator.setAVTransport(uri, metadata)
      .then(() => player.coordinator.play());
  }

  return Promise.reject('TuneIn only handles the {play} action');
}

module.exports = function (api) {
  api.registerAction('tunein', tuneIn);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <last-access-at type="datetime">2010-04-02T01:34:59+00:00</last-access-at>
  <count type="integer">2</count>
  <timeframe-limit type="integer">15</timeframe-limit>
  <max-calls type="integer">40</max-calls>
  <lockout-seconds type="integer">5</lockout-seconds>
</hash>


text:
/*
 * blockAndthread.c
 * A "driver" program that calls a routine (i.e. a kernel)
 * that executes on the GPU.  The kernel fills two int arrays
 * with the block ID and the thread ID
 *
 * Note: the kernel code is found in the file 'blockAndThread.cu'
 * compile both driver code and kernel code with nvcc, as in:
 * 			nvcc blockAndThread.c blockAndThread.cu
 */

#include <stdio.h>
#define SIZEOFARRAY 64

// The function fillArray is in the file blockAndThread.cu
extern void fillArray(int *blockId, int *threadId, int size);

int main (int argc, char *argv[])
{
   // Declare arrays and initialize to 0
   int blockId[SIZEOFARRAY];
   int threadId[SIZEOFARRAY];
   int i;
   for (i=0; i < SIZEOFARRAY; i++) {
      blockId[i]=0;
      threadId[i]=0;
   }

   // Print the initial arrays
   printf ("Initial state of the array blockId:\n");
   for (i=0; i < SIZEOFARRAY; i++) {
      printf ("%d ", blockId[i]);
   }
   printf ("\n");
   printf ("Initial state of the array threadId:\n");
   for (i=0; i < SIZEOFARRAY; i++) {
      printf ("%d ", threadId[i]);
   }
   printf ("\n");

   // Call the function that will call the GPU function
   fillArray (blockId, threadId, SIZEOFARRAY);

   // Again, print the arrays
   printf ("Final state of the array blockId:\n");
   for (i=0; i < SIZEOFARRAY; i++) {
      printf ("%d ", blockId[i]);
   }
   printf ("\n");
      printf ("Initial state of the array threadId:\n");
   for (i=0; i < SIZEOFARRAY; i++) {
      printf ("%d ", threadId[i]);
   }
   printf ("\n");

   return 0;
}


text:
package com.project;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;

@SuppressLint("SimpleDateFormat")
public class ByTime extends Activity {

	String myDate, phone_no, sms;
	String strDate;
	AudioManager am;
	int count=0;
	AlertDialog alertDialog;
	Intent intent;

	public class A implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch(arg0.getId())
			{
				case R.id.btnc:
					if(strDate.equals(myDate))
					{
						am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
						//am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
						switch (am.getRingerMode())
						{
					    	case AudioManager.RINGER_MODE_SILENT:
					    		am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
					    		break;
					    	case AudioManager.RINGER_MODE_NORMAL:
					    		am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
					    		break;
					    	default:
					    		am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
						}
					}
					count=1;
					break;

				case R.id.btncs:
					showPopUp2();
					count=2;
					if(strDate.equals(myDate))
					{
						Intent it=new Intent(Intent.ACTION_CALL);
						it.setData(Uri.parse("tel:" + phone_no));
						startActivity(it);
					}
					break;
				case R.id.btnsms:
					showPopUp3();
					count=3;
					if(strDate.equals(myDate))
					{
						SmsManager smsManager = SmsManager.getDefault();
						smsManager.sendTextMessage(phone_no, null, sms, null, null);
					}
					break;
			}
		}
	}

	Button b1,b2,b3;
	EditText e1,e2;
	TimePicker tp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_by_time);
		b1=(Button)findViewById(R.id.btnc);
		b2=(Button)findViewById(R.id.btncs);
		b3=(Button)findViewById(R.id.btnsms);
		e1=(EditText)findViewById(R.id.editText1);
		tp=(TimePicker)findViewById(R.id.timePicker1);
		b1.setOnClickListener(new A());
		b2.setOnClickListener(new A());
		b3.setOnClickListener(new A());
		final Handler handler=new Handler();
		Timer time =new Timer();
		TimerTask tm=new TimerTask() {
			public void run() {
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Calendar c = Calendar.getInstance();
						SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
						strDate = sdf.format(c.getTime());
						myDate=tp.getCurrentHour().toString()+":"+tp.getCurrentMinute().toString();
						if(count==1)
						{
							if(strDate.equals(myDate))
							{
								count=10;
								am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
								am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
								//else  am.setRingerMode(AudioManager.RINGER_MODE_NORMAL
							}
						}
						if(count==2)
						{
							if(strDate.equals(myDate))
							{
								count=10;
								Intent it=new Intent(Intent.ACTION_CALL);
								it.setData(Uri.parse("tel:"+phone_no));
								startActivity(it);
							}
						}
						else if(count==3)
						{
							if(strDate.equals(myDate))
							{
								Intent itt=new Intent(Intent.ACTION_SEND);
								itt.setData(Uri.parse("sms:"+phone_no));
								startActivity(itt);
							}
						}
					}
				});
			}
		};
		time.schedule(tm,0,50);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch(item.getItemId()) {
		    case R.id.home_page:
		    	intent = new Intent(this, HomePageActivity.class);
		        startActivity(intent);
		        return true;
		    case R.id.greetings:
		    	alertDialog = new AlertDialog.Builder(this).setMessage(R.string.greetings_text).create();
		    	alertDialog.setTitle("Greetings");
		    	alertDialog.show();
		        return true;
		    case R.id.feedback:
		    	intent = new Intent(this, Feedback.class);
		        startActivity(intent);
		        return true;
		    case R.id.credits:
		    	alertDialog = new AlertDialog.Builder(this).setMessage(R.string.credits_text).create();
		    	alertDialog.setTitle("Credits");
		    	alertDialog.show();
		        return true;
		    default:
		    	return super.onOptionsItemSelected(item);
	    }
	}

	private void showPopUp2() {
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle("Set Number");
		helpBuilder.setMessage("Enter the number");
		final EditText input = new EditText(this);

		input.setSingleLine();
		input.setText("");
		helpBuilder.setView(input);
			helpBuilder.setPositiveButton("Set", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing but close the dialog
				phone_no=input.getText().toString();
			}
		});
		helpBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing
			}
		});
		// Remember, create doesn't show the dialog
		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}

	private void showPopUp3() {
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
		helpBuilder.setTitle("SMS");
		// helpBuilder.setMessage("Enter the number");
		final EditText number = new EditText(this);
		final EditText message=new EditText(this);

		helpBuilder.setView(number);
		helpBuilder.setView(message);

		message.setHint("Enter Message");

		helpBuilder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing but close the dialog
				phone_no=number.getText().toString();
				sms=message.getText().toString();
				showPopUp2();
			}
		});

		helpBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing
			}
		});
		// Remember, create doesn't show the dialog
		AlertDialog helpDialog = helpBuilder.create();
		helpDialog.show();
	}
}


text:
package com.headwire.aem.tooling.intellij.ui;

import com.headwire.aem.tooling.intellij.explorer.SlingMavenModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.hash.HashMap;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.MavenPropertiesPanel;
import org.jetbrains.idea.maven.model.MavenArchetype;
import org.jetbrains.idea.maven.model.MavenId;
import org.jetbrains.idea.maven.project.MavenEnvironmentForm;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenUtil;

import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Sergey Evdokimov
 */
public class ArchetypePropertiesStep extends ModuleWizardStep {

    public static final String NAME_PLACEHOLDER = "$name$";
    public static final String NAME_FOR_FOLDER_PLACEHOLDER = "$nameForFolder$";
    public static final String ARTIFACT_ID_PLACEHOLDER = "$artifactId$";
    private final Project myProjectOrNull;
    private final SlingMavenModuleBuilder myBuilder;

    private JPanel myMainPanel;
    private JPanel myEnvironmentPanel;
    private JPanel myPropertiesPanel;
    private JTextField artifactName;
    private JCheckBox doFillIn;

    private MavenEnvironmentForm myEnvironmentForm;
    private MavenPropertiesPanel myMavenPropertiesPanel;

    private Map<String, String> myAvailableProperties = new HashMap<String, String>();
    private Map<String, String> requiredProperties = new java.util.HashMap<String, String>();

    public ArchetypePropertiesStep(@Nullable Project project, SlingMavenModuleBuilder builder) {
        myProjectOrNull = project;
        myBuilder = builder;

        initComponents();
    }

    private void initComponents() {
        myEnvironmentForm = new MavenEnvironmentForm();

        Project project = myProjectOrNull == null ? ProjectManager.getInstance().getDefaultProject() : myProjectOrNull;
        myEnvironmentForm.getData(MavenProjectsManager.getInstance(project).getGeneralSettings().clone());

        myEnvironmentPanel.add(myEnvironmentForm.createComponent(), BorderLayout.CENTER);

        //AS TODO: If we keep on using the archetype properties we might add a description to the Required Properties
        //AS TODO: but then we need to copy this class over and add the description to the dialog.
        myMavenPropertiesPanel = new MavenPropertiesPanel(myAvailableProperties);
        myPropertiesPanel.add(myMavenPropertiesPanel);

        doFillIn.setSelected(true);
        artifactName.addKeyListener(
            new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent keyEvent) {
                    super.keyReleased(keyEvent);
                    if(doFillIn.isSelected()) {
                        updateProperties();
                    }
                }
            }
        );
        artifactName.addFocusListener(
            new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent focusEvent) {
                    super.focusLost(focusEvent);
                    if(doFillIn.isSelected()) {
                        updateProperties();
                    }
                }
            }
        );
    }

    @Override
    public void updateStep() {
        SlingMavenModuleBuilder.ArchetypeTemplate archetypeTemplate = myBuilder.getArchetypeTemplate();
        MavenArchetype archetype = archetypeTemplate.getMavenArchetype();

        Map<String, String> props = new LinkedHashMap<String, String>();

        MavenId projectId = myBuilder.getProjectId();

        props.put("groupId", projectId.getGroupId());
        props.put("artifactId", projectId.getArtifactId());
        props.put("version", projectId.getVersion());

        props.put("archetypeGroupId", archetype.groupId);
        props.put("archetypeArtifactId", archetype.artifactId);
        props.put("archetypeVersion", archetype.version);
        if (archetype.repository != null) props.put("archetypeRepository", archetype.repository);
        myMavenPropertiesPanel.setDataFromMap(props);

        //Add any props from the Builder
        requiredProperties = archetypeTemplate.getRequiredProperties();
        updateProperties();
    }

    private void updateProperties() {
        MavenId projectId = myBuilder.getProjectId();
        Map<String, String> props = myMavenPropertiesPanel.getDataAsMap();
        for(Map.Entry<String, String> entry: requiredProperties.entrySet()) {
            String propValue = entry.getValue();
            if(StringUtil.isNotEmpty(propValue)) {
                if(propValue.contains(NAME_PLACEHOLDER)) {
                    propValue = propValue.replace(NAME_PLACEHOLDER, artifactName.getText());
                } else if(propValue.contains(NAME_FOR_FOLDER_PLACEHOLDER)) {
                    propValue = propValue.replace(NAME_FOR_FOLDER_PLACEHOLDER, artifactName.getText().toLowerCase().replaceAll("[^a-zA-Z]", ""));
                } else if(propValue.contains(ARTIFACT_ID_PLACEHOLDER)) {
                    propValue = propValue.replace(ARTIFACT_ID_PLACEHOLDER, projectId.getArtifactId());
                }
            }
            props.put(entry.getKey(), propValue);
        }

        myMavenPropertiesPanel.setDataFromMap(props);
    }

    @Override
    public JComponent getComponent() {
        return myMainPanel;
    }

    @Override
    public boolean isStepVisible() {
        return myBuilder.getArchetypeTemplate() != null;
    }

    @Override
    public boolean validate() throws ConfigurationException {
        File mavenHome = MavenUtil.resolveMavenHomeDirectory(myEnvironmentForm.getMavenHome());
        if (mavenHome == null) {
            throw new ConfigurationException("Maven home directory is not specified");
        }

        if (!MavenUtil.isValidMavenHome(mavenHome)) {
            throw new ConfigurationException("Maven home directory is invalid: " + mavenHome);
        }

        return true;
    }

    @Override
    public void updateDataModel() {
        myBuilder.setEnvironmentForm(myEnvironmentForm);
        myBuilder.setPropertiesToCreateByArtifact(myMavenPropertiesPanel.getDataAsMap());
    }

    @Override
    public String getHelpId() {
        return "New_Projects_from_Scratch_Maven_Settings_Page";
    }
}


text:
package babybear.akbquiz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

@SuppressLint("NewApi")
public class CalendarEditor extends Activity {

	// 系统日历相关数据库的Uri
	private static Uri calanderUri;
	private static Uri calanderEventUri;
	private static Uri calanderRemiderUri;

	// 系统日历相关数据库的常量

	private static String KEY_CALLER_IS_SYNCADAPTER;

	private static String KEY_CALENDAR_NAME; // TEXT
	private static String KEY_CALENDAR_DISPLAY_NAME; // TEXT
	private static String KEY_CALENDAR_ACCOUNT_NAME; // TEXT
	private static String KEY_CALENDAR_ACCOUNT_TYPE; // TEXT
	private static String KEY_CALENDAR_CALENDAR_COLOR; // INTEGER (color value)
	private static String KEY_CALENDAR_ACCESS_LEVEL; // INTEGER
	private static String KEY_CALENDAR_OWNER_ACCOUNT;// String
	private static String VALUE_CALENDAR_ACCOUNT_TYPE; // TEXT
	private static int VALUE_CALENDAR_ACCESS_LEVEL;

	private static String KEY_EVENT_TITLE; // TEXT
	private static String KEY_EVENT_DESCRIPTION; // TEXT
	private static String KEY_EVENT_COLOR; // INTEGER
	private static String KEY_EVENT_ALL_DAY; // INTEGER
	private static String KEY_EVENT_CALENDAR_ID; // INTEGER
	private static String KEY_EVENT_RRULE; // TEXT
	private static String KEY_EVENT_TIMEZONE;// TEXT
	private static String KEY_EVENT_DTSTART; // INTEGER (long millis)
	private static String KEY_EVENT_DTEND; // INTEGER (long millis)
	private static String KEY_REMINDER_EVENT_ID; // INTEGER (foreign key to the
													// Events table)
	private static String KEY_REMINDER_MINUTES; // INTEGER
	private static String KEY_REMINDER_METHOD; // INTEGER
	private static int VALUE_REMINDER_METHOD; // INTEGER

	// 根据不同的系统版本设置不同的常量
	static {
		if (Build.VERSION.SDK_INT >= 14) {
			calanderUri = android.provider.CalendarContract.Calendars.CONTENT_URI;
			calanderEventUri = android.provider.CalendarContract.Events.CONTENT_URI;
			calanderRemiderUri = android.provider.CalendarContract.Reminders.CONTENT_URI;

			KEY_CALLER_IS_SYNCADAPTER = android.provider.CalendarContract.CALLER_IS_SYNCADAPTER;
			KEY_CALENDAR_NAME = android.provider.CalendarContract.Calendars.NAME;
			KEY_CALENDAR_DISPLAY_NAME = android.provider.CalendarContract.Calendars.CALENDAR_DISPLAY_NAME;
			KEY_CALENDAR_ACCOUNT_NAME = android.provider.CalendarContract.Calendars.ACCOUNT_NAME;
			KEY_CALENDAR_ACCOUNT_TYPE = android.provider.CalendarContract.Calendars.ACCOUNT_TYPE;
			KEY_CALENDAR_CALENDAR_COLOR = android.provider.CalendarContract.Calendars.CALENDAR_COLOR;
			KEY_CALENDAR_ACCESS_LEVEL = android.provider.CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL;
			KEY_CALENDAR_OWNER_ACCOUNT = android.provider.CalendarContract.Calendars.OWNER_ACCOUNT;
			VALUE_CALENDAR_ACCOUNT_TYPE = android.provider.CalendarContract.ACCOUNT_TYPE_LOCAL;
			VALUE_CALENDAR_ACCESS_LEVEL = android.provider.CalendarContract.Calendars.CAL_ACCESS_OWNER;

			KEY_EVENT_TITLE = android.provider.CalendarContract.Events.TITLE;
			KEY_EVENT_DESCRIPTION = android.provider.CalendarContract.Events.DESCRIPTION;
			KEY_EVENT_COLOR = android.provider.CalendarContract.Events.EVENT_COLOR;
			KEY_EVENT_ALL_DAY = android.provider.CalendarContract.Events.ALL_DAY;
			KEY_EVENT_CALENDAR_ID = android.provider.CalendarContract.Events.CALENDAR_ID;
			KEY_EVENT_RRULE = android.provider.CalendarContract.Events.RRULE;
			KEY_EVENT_TIMEZONE = android.provider.CalendarContract.Events.EVENT_TIMEZONE;
			KEY_EVENT_DTSTART = android.provider.CalendarContract.Events.DTSTART;
			KEY_EVENT_DTEND = android.provider.CalendarContract.Events.DTEND;

			KEY_REMINDER_EVENT_ID = android.provider.CalendarContract.Reminders.EVENT_ID;
			KEY_REMINDER_MINUTES = android.provider.CalendarContract.Reminders.MINUTES;
			KEY_REMINDER_METHOD = android.provider.CalendarContract.Reminders.METHOD;
			VALUE_REMINDER_METHOD = android.provider.CalendarContract.Reminders.METHOD_DEFAULT;
		} else {
			if (Build.VERSION.SDK_INT >= 8) {
				calanderUri = Uri.parse("content://com.android.calendar/calendars");
				calanderEventUri = Uri.parse("content://com.android.calendar/events");
				calanderRemiderUri = Uri.parse("content://com.android.calendar/reminders");

			} else {
				calanderUri = Uri.parse("content://calendar/calendars");
				calanderEventUri = Uri.parse("content://calendar/events");
				calanderRemiderUri = Uri.parse("content://calendar/reminders");
			}
			KEY_CALLER_IS_SYNCADAPTER = "caller_is_syncadapter";

			KEY_CALENDAR_NAME = "name";
			KEY_CALENDAR_DISPLAY_NAME = "calendar_displayName";
			KEY_CALENDAR_ACCOUNT_NAME = "account_name";
			KEY_CALENDAR_ACCOUNT_TYPE = "account_type";
			KEY_CALENDAR_CALENDAR_COLOR = "calendar_color";
			KEY_CALENDAR_ACCESS_LEVEL = "calendar_access_level";
			KEY_CALENDAR_OWNER_ACCOUNT = "ownerAccount";
			VALUE_CALENDAR_ACCOUNT_TYPE = "LOCAL";
			VALUE_CALENDAR_ACCESS_LEVEL = 700;

			KEY_EVENT_TITLE = "title";
			KEY_EVENT_DESCRIPTION = "description";
			KEY_EVENT_COLOR = "eventColor";
			KEY_EVENT_ALL_DAY = "allDay";
			KEY_EVENT_RRULE = "rrule";
			KEY_EVENT_TIMEZONE = "eventTimezone";
			KEY_EVENT_CALENDAR_ID = "calendar_id";
			KEY_EVENT_DTSTART = "dtstart";

			KEY_REMINDER_EVENT_ID = "event_id";
			KEY_REMINDER_MINUTES = "minutes";
			KEY_REMINDER_METHOD = "method";
			VALUE_REMINDER_METHOD = 0;
		}
	}

	// 一些其他键
	private static String KEY_GROUP_TITLE = "group";
	private static String KEY_CHILD_TITLE = "child";
	private static String KEY_CHILD_NAME = "name";
	private static String KEY_CHILD_BIRTH = "birthday";
	private static String KEY_CHILD_ADDED = "isadded";

	// 设置文件及其Editor
	private SharedPreferences sp_cfg;
	private SharedPreferences.Editor editor_cfg;

	// 所有日历 及 选择的日历的ID
	private int calendarId = -1;
	private ArrayList<ContentValues> calList;

	// 格式化数据库中生日用到
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
			Locale.getDefault());

	// ExpandableListView 及其 适配器
	private ExpandableListView memberList;
	private MemberGroupListAdapter memberListAdapter;

	// Group 和 childList列表
	private ArrayList<Map<String, String>> groupList = new ArrayList<Map<String, String>>();
	private ArrayList<ArrayList<Map<String, String>>> childList = new ArrayList<ArrayList<Map<String, String>>>();

	// 保存已添加的成员
	private Map<String, HashMap<String, String>> settings;

	// 强制删除模式
	private boolean forceClear = false;
	private int forceClearCounter = 0;

	private ContentResolver cr;
	private Database db;
	private Handler handler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendar_editor);

		Log.d("CalendarEditor", calanderUri.toString());

		db = new Database(this, Database.DBName_quiz);
		cr = getContentResolver();
		sp_cfg = getSharedPreferences("config", Context.MODE_PRIVATE);
		editor_cfg = sp_cfg.edit();

		calendarId = sp_cfg.getInt(Database.KEY_calendar_id, -1);

		// 这里是调试用代码

		// Cursor cur = cr.query(calanderEventUri, null, null, null, null);
		// cur.moveToFirst();
		//
		// while (cur.moveToNext()) {
		// Log.d("",
		// "_id = "
		// + cur.getInt(cur.getColumnIndex("_id"))
		// + " title = "
		// + cur.getString(cur.getColumnIndex(KEY_EVENT_TITLE)));
		// }
		// cur.close();

		// cr.delete(calanderEventUri.buildUpon().appendPath(""+37).build(),
		// null, null);
		// cr.delete(calanderEventUri.buildUpon().appendPath(""+42).build(),
		// null, null);

		init();
	}

	// 初始化 settings 和两个List的数据 以及widget
	private void init() {
		// widget 初始化
		OnClickListener l = new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (v.getId() != R.id.clear) {
					if (forceClear) {
						forceClear = false;
					}
				}
				switch (v.getId()) {
				case R.id.back:
					finish();
					break;
				case R.id.clear:
					if (forceClear) {
						if (forceClearCounter > 3) {
							forceClear();
						} else {

							forceClearCounter++;
							Toast.makeText(CalendarEditor.this,
									getString(R.string.calendar_forceclear,
											4 - forceClearCounter),
									Toast.LENGTH_SHORT).show();
						}
					} else {
						clearAll();
					}
					break;
				case R.id.calendar_editor_choose:
					getCalander();
					break;
				}
			};
		};
		findViewById(R.id.back).setOnClickListener(l);
		findViewById(R.id.clear).setOnClickListener(l);
		findViewById(R.id.calendar_editor_choose).setOnClickListener(l);

		((Button) findViewById(R.id.clear)).setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				if (v.getId() == R.id.clear) {
					forceClear = true;
				}

				return false;
			}
		});

		memberList = (ExpandableListView) findViewById(R.id.member_list);

		// 检查是否支持
		Cursor cur = cr.query(calanderUri, null, null, null, null);
		if (cur == null) {
			findViewById(R.id.not_support).setVisibility(View.VISIBLE);
			return;
		}
		cur.close();
		cur = cr.query(calanderEventUri, null, null, null, null);
		if (cur == null) {
			findViewById(R.id.not_support).setVisibility(View.VISIBLE);
			return;
		}
		cur.close();

		// 成员ArrayList 初始化

		HashMap<String, String> group1 = new HashMap<String, String>();
		group1.put(KEY_GROUP_TITLE, Database.GroupName_AKB48);
		groupList.add(group1);

		HashMap<String, String> group2 = new HashMap<String, String>();
		group2.put(KEY_GROUP_TITLE, Database.GroupName_SKE48);
		groupList.add(group2);
		HashMap<String, String> group3 = new HashMap<String, String>();
		group3.put(KEY_GROUP_TITLE, Database.GroupName_NMB48);
		groupList.add(group3);
		HashMap<String, String> group4 = new HashMap<String, String>();
		group4.put(KEY_GROUP_TITLE, Database.GroupName_HKT48);
		groupList.add(group4);
		HashMap<String, String> group5 = new HashMap<String, String>();
		group5.put(KEY_GROUP_TITLE, Database.GroupName_NGZK46);
		groupList.add(group5);
		HashMap<String, String> group6 = new HashMap<String, String>();
		group6.put(KEY_GROUP_TITLE, Database.GroupName_JKT48);
		groupList.add(group6);
		HashMap<String, String> group7 = new HashMap<String, String>();
		group7.put(KEY_GROUP_TITLE, Database.GroupName_SNH48);
		groupList.add(group7);

		for (int i = 0; i < groupList.size(); i++) {
			childList.add(new ArrayList<Map<String, String>>());

		}

		new Thread() {
			@Override
			public void run() {
				loadSetting();

				ArrayList<ContentValues> memberInfo = db.infoQery();
				Log.d("", "member info got");
				for (int i = 0; i < memberInfo.size(); i++) {
					ContentValues info = memberInfo.get(i);
					String str = info.getAsString("birthday");
					if (str == null) {
						continue;
					}
					String tGroup = info.getAsString(KEY_GROUP_TITLE);
					for (int j = 0; j < groupList.size(); j++) {
						if (groupList.get(j)
								.get(KEY_GROUP_TITLE)
								.equalsIgnoreCase(tGroup)) {
							HashMap<String, String> map = new HashMap<String, String>();

							String name = info.getAsString("name");
							String team = info.getAsString("team");
							map.put(KEY_CHILD_TITLE, (team == null ? ""
									: ("Team " + team + " ")) + name);
							map.put(KEY_CHILD_NAME, name);
							map.put(KEY_CHILD_BIRTH,
									info.getAsString("birthday"));
							map.put(KEY_EVENT_TITLE,
									getString(R.string.calendar_event_title,
											name));

							String color = getString(R.color.groupcolor_akb48);
							switch (j) {
							case 0:
								break;
							case 1:
								color = getString(R.color.groupcolor_ske48);
								break;
							case 2:
								color = getString(R.color.groupcolor_nmb48);
								break;
							case 3:
								color = getString(R.color.groupcolor_hkt48);
								break;
							case 4:
								color = getString(R.color.groupcolor_ngzk46);
								break;
							case 5:
								color = getString(R.color.groupcolor_jkt48);
								break;
							case 6:
								color = getString(R.color.groupcolor_snh48);
								break;
							}

							map.put(KEY_EVENT_COLOR, color);
							if (settings != null && settings.containsKey(name)) {
								map.put(KEY_CHILD_ADDED, "true");
							} else {
								map.put(KEY_CHILD_ADDED, "false");
							}

							String comefrom = info.getAsString("comefrom");
							map.put(KEY_EVENT_DESCRIPTION,
									(tGroup == null ? "" : tGroup)
											+ (team == null ? ""
													: getString(R.string.calendar_event_Team,
															"",
															team))
											+ (comefrom == null ? ""
													: getString(R.string.calendar_event_comefrom,
															comefrom))
											+ getString(R.string.calendar_event_title,
													name));
							childList.get(j).add(map);
							break;
						}
					}
				}
				memberListAdapter = new MemberGroupListAdapter(CalendarEditor.this,
						groupList,
						KEY_GROUP_TITLE,
						R.layout.member_list_group,
						R.id.textGroup,
						childList,
						KEY_CHILD_TITLE,
						R.layout.member_list_child,
						R.id.textChild,
						KEY_CHILD_ADDED,
						R.id.isAdded);
				handler.post(new Runnable() {
					@Override
					public void run() {
						memberList.setAdapter(memberListAdapter);
						memberList.setOnChildClickListener(listener);
						findViewById(R.id.calendar_editor_loading).setVisibility(View.GONE);
					}

				});
			}
		}.start();

	}

	@Override
	public void onStart() {
		super.onStart();

		// 设置自定义背景
		if (sp_cfg.getBoolean(Database.KEY_use_custom_background, false)) {
			findViewById(R.id.calender_editor_body).setBackgroundDrawable(Drawable.createFromPath(Environment.getExternalStorageDirectory()
					.getPath()
					+ "/Android/data/" + getPackageName() + "/custom_bg.png"));
		}

	}

	/**
	 * 加载设置 (有哪些成员的生日信息已被添加)
	 */
	private void loadSetting() {
		Log.d("", sp_cfg.getString(Database.KEY_events_added, "{}"));
		try {
			JSONObject events = new JSONObject(sp_cfg.getString(Database.KEY_events_added,
					"{}"));
			if (events.length() == 0) {
				return;
			}
			settings = new HashMap<String, HashMap<String, String>>();

			Log.d("", "get : '" + events.toString() + "' from config");
			for (Iterator<?> it = events.keys(); it.hasNext();) {
				String key = (String) it.next();
				JSONObject item = events.getJSONObject(key);
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("id", Integer.toString(item.getInt("_id")));
				map.put("uri", item.getString("uri"));
				settings.put(key, map);
				Log.d("", "add " + key + " : " + map + "in to settings ");
			}

		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存设置 (有哪些成员的生日信息已被添加)
	 */
	private void saveSetting() {

		JSONObject obj = new JSONObject();
		try {
			if (settings != null && settings.size() > 0) {
				Set<String> keySet = settings.keySet();
				for (String key : keySet) {
					JSONObject item = new JSONObject(settings.get(key));
					obj.put(key, item);
				}
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		Log.d("", obj.toString());
		editor_cfg.putString(Database.KEY_events_added, obj.toString());
		editor_cfg.commit();

	}

	/**
	 * 向日历添加一个生日
	 *
	 * @param groupPosition 从OnChildClickListener中获取的groupPosition
	 * @param childPosition 从OnChildClickListener中获取的childPosition
	 */
	private void addBirthday(int groupPosition, int childPosition) {
		if (calendarId == -1) {
			Toast.makeText(this,
					R.string.calendar_err_choose,
					Toast.LENGTH_LONG).show();
			getCalander();
			return;
		}
		String str = childList.get(groupPosition)
				.get(childPosition)
				.get(KEY_CHILD_BIRTH);
		if (str == null || str == "") {
			Toast.makeText(this,
					R.string.calendar_err_noinfo,
					Toast.LENGTH_LONG).show();
			return;
		}

		Map<String, String> member = childList.get(groupPosition)
				.get(childPosition);
		HashMap<String, String> map = insertEvent(calendarId, member, true);

		if (map != null) {
			Map<String, String> child = memberListAdapter.getChild(groupPosition,
					childPosition);
			child.put(KEY_CHILD_ADDED, Boolean.toString(true));
			memberListAdapter.notifyDataSetChanged();

			if (settings == null) {
				settings = new HashMap<String, HashMap<String, String>>();
			}
			settings.put(member.get(KEY_CHILD_NAME), map);
			saveSetting();
		}

	}

	//
	/**
	 * 移除名字为一个成员的Event
	 *
	 * @param name 成员名
	 * @param groupPosition 从OnChildClickListener中获取的groupPosition
	 * @param childPosition 从OnChildClickListener中获取的childPosition
	 */
	protected void removeBirthday(String name,
			int groupPosition,
			int childPosition) {
		Uri uri = Uri.parse(settings.get(name).get("uri"));
		int counter = cr.delete(uri, null, null);
		if (counter > 0) {
			Map<String, String> child = memberListAdapter.getChild(groupPosition,
					childPosition);
			child.put(KEY_CHILD_ADDED, Boolean.toString(false));
			memberListAdapter.notifyDataSetChanged();

			Toast.makeText(this, R.string.calendar_deleted, Toast.LENGTH_SHORT)
					.show();
			settings.remove(name);
			saveSetting();
		}
	}

	/**
	 * 向用户请求一个可用日历的ID 直接设置到calendarId
	 */
	private void getCalander() {
		Cursor cur = cr.query(calanderUri, new String[] { "_id",
				KEY_CALENDAR_NAME,
				KEY_CALENDAR_DISPLAY_NAME }, null, null, null);
		calList = new ArrayList<ContentValues>();
		ArrayList<String> items = new ArrayList<String>();
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			while (cur.moveToNext()) {
				ContentValues t = new ContentValues();
				DatabaseUtils.cursorRowToContentValues(cur, t);
				items.add(cur.getString(cur.getColumnIndex(KEY_CALENDAR_DISPLAY_NAME)));
				calList.add(t);
			}
		}
		cur.close();

		DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() {
			int tid = -1;

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				if (arg1 == DialogInterface.BUTTON_POSITIVE) {
					calendarId = tid;
					editor_cfg.putInt(Database.KEY_calendar_id, calendarId);
					editor_cfg.commit();
					return;
				}
				if (arg1 == DialogInterface.BUTTON_NEGATIVE) {
					return;
				}

				tid = calList.get(arg1).getAsInteger("_id");
			}

		};

		AlertDialog.Builder calchooser_builder = new AlertDialog.Builder(this);
		calchooser_builder.setTitle(R.string.calendar_choose_witch)
				.setPositiveButton(android.R.string.ok, l)
				.setNegativeButton(android.R.string.cancel, l)
				.setSingleChoiceItems(items.toArray(new String[items.size()]),
						-1,
						l);
		calchooser_builder.create().show();

	}

	/**
	 * 添加一个Event
	 *
	 * @param calId 日历ID
	 * @param member 成员及Event信息
	 * @param makeReminder 是否添加提醒
	 * @return 添加的Event的ID及Uri
	 */
	private HashMap<String, String> insertEvent(int calId,
			Map<String, String> member,
			boolean makeReminder) {
		int id = -1;
		ContentValues event = new ContentValues();

		try {
			Date birthday = fmt.parse(member.get(KEY_CHILD_BIRTH));
			// birthday.setHours(birthday.getHours() + 12);
			Calendar c = Calendar.getInstance();
			c.setTime(birthday);
			Log.d("", member.get(KEY_CHILD_BIRTH)
					+ " to Calendar and toString " + c.toString());
			event.put(KEY_EVENT_CALENDAR_ID, calId);
			event.put(KEY_EVENT_TITLE, member.get(KEY_EVENT_TITLE));
			event.put(KEY_EVENT_DESCRIPTION, member.get(KEY_EVENT_DESCRIPTION));
			event.put(KEY_EVENT_COLOR,
					Color.parseColor(member.get(KEY_EVENT_COLOR)));
			event.put(KEY_EVENT_DTSTART, c.getTimeInMillis()
					+ c.getTimeZone().getRawOffset());
			event.put(KEY_EVENT_ALL_DAY, 1);
			event.put(KEY_EVENT_RRULE, "FREQ=YEARLY");
			event.put(KEY_EVENT_TIMEZONE, c.getTimeZone().getID());
			birthday.setYear(birthday.getYear() + 100);
			event.put(KEY_EVENT_DTEND, birthday.getTime());

		}
		catch (ParseException e) {
			Toast.makeText(this,
					R.string.calendar_err_decodefail,
					Toast.LENGTH_LONG).show();
			e.printStackTrace();
			return null;
		}

		Uri eventUri = cr.insert(calanderEventUri, event);
		id = Integer.parseInt(eventUri.getLastPathSegment());
		if (id == -1) {
			Toast.makeText(this,
					R.string.calendar_err_addfail,
					Toast.LENGTH_SHORT).show();
			return null;
		}
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("uri", eventUri.toString());
		map.put("_id", Integer.toString(id));

		Toast.makeText(this, R.string.calendar_add_success, Toast.LENGTH_SHORT)
				.show();
		// if (makeReminder) {
		// insertReminder(id);
		// }
		return map;
	}

	/**
	 * 添加一个提醒
	 * 全天事件没有提醒 弃用
	 *
	 * @param eventId 事件ID
	 * @return 提醒ID
	 */
	@Deprecated
	private int insertReminder(int eventId) {
		if (eventId == -1) {
			return -1;
		}
		ContentValues reminder = new ContentValues();
		reminder.put(KEY_REMINDER_EVENT_ID, eventId);
		reminder.put(KEY_REMINDER_MINUTES, 10);
		reminder.put(KEY_REMINDER_METHOD, VALUE_REMINDER_METHOD);
		int id = -1;
		Uri eventUri = cr.insert(calanderRemiderUri, reminder);
		id = Integer.parseInt(eventUri.getLastPathSegment());
		return id;
	}

	/**
	 * 清除所有本应用添加的事件
	 */
	private void clearAll() {
		if(settings==null)return;
		Set<String> keys = settings.keySet();
		int count = 0;
		for (String key : keys) {
			String uri = settings.get(key).get("uri");
			count += cr.delete(Uri.parse(uri), null, null);
		}
		settings.clear();
		saveSetting();
		Toast.makeText(this,
				getString(R.string.calendar_clear_echo, count),
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 强行删除可能是本应用添加的所有事件
	 * 适用于设置文件丢失
	 */
	private void forceClear() {
		int counter = cr.delete(calanderEventUri, "`" + KEY_EVENT_DESCRIPTION
				+ "` like \"%%"
				+ getString(R.string.calendar_event_title, "%%") + "\"", null);
		Toast.makeText(this,
				getString(R.string.calendar_clear_echo, counter),
				Toast.LENGTH_SHORT).show();
		}

	/**
	 * ExpandableListView用到的 OnChildClickListener
	 */
	private OnChildClickListener listener = new OnChildClickListener() {

		@Override
		public boolean onChildClick(ExpandableListView parent,
				View view,
				int groupPosition,
				int childPosition,
				long id) {
			Boolean isChecked = Boolean.parseBoolean(memberListAdapter.getChild(groupPosition,
					childPosition)
					.get(KEY_CHILD_ADDED));
			if (isChecked) {
				String name = memberListAdapter.getChild(groupPosition,
						childPosition).get(KEY_CHILD_NAME);
				removeBirthday(name, groupPosition, childPosition);
			} else {
				addBirthday(groupPosition, childPosition);
			}
			Log.d("", "group : " + groupPosition + " child : " + childPosition
					+ " been clicked");
			return false;
		}
	};

}


text:
        	<?php foreach ($products as $products_item): ?>

<?php echo $products_item['price']; ?>

<a href="<?php echo site_url('products/'.$products_item['slug']); ?>"><?php echo $products_item['title']; ?>

<?php echo $products_item['description']; ?>

15 reviews

            <?php endforeach; ?>


text:
package com.cnpc.framework.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * Created by billJiang on 2017/6/6.
 * e-mail:475572229@qq.com  qq:475572229
 */
public class JsonObjectMapper extends ObjectMapper {
    private static final long serialVersionUID = 1L;

    public JsonObjectMapper() {
        super();
        // 空值处理为空串
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                jg.writeString("");
            }
        });

        //this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }
}


text:
//
//  RecognitionResult.h
//  CardRecognizer
//
//  Created by Vladimir Tchernitski on 11/01/16.
//  Copyright © 2016 Vladimir Tchernitski. All rights reserved.
//

#ifndef RecognitionResult_h
#define RecognitionResult_h

#include "IRecognitionResult.h"

class CRecognitionResult : public IRecognitionResult
{

public:
    CRecognitionResult();

    virtual ~CRecognitionResult();

public:

    virtual void Reset();

    virtual shared_ptr<INeuralNetworkResultList> GetNumberResult() const;
    virtual shared_ptr<INeuralNetworkResultList> GetDateResult() const;
    virtual shared_ptr<INeuralNetworkResultList> GetNameResult() const;
    virtual RecognitionStatus GetRecognitionStatus() const;
    virtual cv::Mat GetCardImage() const;
    virtual cv::Rect GetNumberRect() const;
    virtual cv::Rect GetDateRect() const;
    virtual std::string GetPostprocessedName() const;

    virtual void SetNumberResult(shared_ptr<INeuralNetworkResultList> result);
    virtual void SetDateResult(shared_ptr<INeuralNetworkResultList> result);
    virtual void SetNameResult(shared_ptr<INeuralNetworkResultList> result);
    virtual void SetRecognitionStatus(RecognitionStatus status);
    virtual void SetCardImage(cv::Mat cardImage);
    virtual void SetNumberRect(cv::Rect numberRect);
    virtual void SetDateRect(cv::Rect dateRect);
    virtual void SetPostprocessedName(std::string name);

private:

    shared_ptr<INeuralNetworkResultList> _numberResult;
    shared_ptr<INeuralNetworkResultList> _dateResult;
    shared_ptr<INeuralNetworkResultList> _nameResult;
    RecognitionStatus _recognitionStatus;
    cv::Mat _cardImage;
    cv::Rect _numberRect;
    cv::Rect _dateRect;

    std::string _postprocessedName;
};

#endif /* RecognitionResult_h */


text:
<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 14.11.2016
 * Time: 20:23
 */

namespace app\models;

use yii\db\ActiveRecord;
use yii;

class Levels extends ActiveRecord
{
    public function getUsers() //declaring relations
    {
        // we use table USERS_ON_LEVELS to merge two tables
        return $this->hasMany(Users::className(),["id" => "user_id"]) // "id" of Users to "users_id" of Users_on_levels
            ->viaTable("users_on_levels",["level_id"=>"id"]) // "level_id" of Users_on_levels to "id" of Levels
            ->all();
    }

}


text:
/**
 @file  types.h
 @brief type definitions for ENet
*/
#ifndef __ENET_TYPES_H__
#define __ENET_TYPES_H__

typedef unsigned char enet_uint8;   /**< unsigned 8-bit type  */
typedef unsigned short enet_uint16;   /**< unsigned 16-bit type */
typedef unsigned int enet_uint32;  /**< unsigned 32-bit type */

#endif /* __ENET_TYPES_H__ */


text:
package org.uberfire.client.screens.popup;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Label;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchPopup;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.mvp.PlaceRequest;

/**
 * An example popup
 */
@WorkbenchPopup(identifier = "MySimplePopUp")
public class SimplePopUp {

    @Inject
    private PlaceManager placeManager;

    private PlaceRequest place;

    private final VerticalPanel view = new VerticalPanel();
    private Label l;
    private TextBox t;
    private Button b;

    @PostConstruct
    public void setup() {
        l = new Label( "Click to close" );
        t = new TextBox();
        b = new Button( "Close" );
        b.addClickHandler( new ClickHandler() {

            @Override
            public void onClick( final ClickEvent event ) {
                placeManager.closePlace( place );
            }
        } );
        view.add( l );
        view.add( t );
        view.add( b );
    }

    @OnStartup
    public void onStartup( final PlaceRequest place ) {
        this.place = place;
        b.setFocus( true );
    }

    @WorkbenchPartTitle
    public String getTitle() {
        return "SimplePopUp says \"Hello\"";
    }

    @WorkbenchPartView
    public Widget getView() {
        return view;
    }

}


text:
class CreateTechnologies < ActiveRecord::Migration
  def change
    create_table :technologies do |t|
      t.string :name
      t.string :website

      t.timestamps null: false
    end
  end
end


text:
/** tslint:disable */
// Typings reference file, you can add your own global typings here
// https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html

///<reference path="Path2D.d.ts"/>

export declare module 'katex' {

  interface KatexOptions {
    /**
     * If true the math will be rendered in display mode, which will put the math in display
     * style (so \int and \sum are large, for example), and will center the math on the page
     * on its own line. If false the math will be rendered in inline mode. (default: false)
     */
    displayMode?: boolean
    /**
     * throwOnError: boolean. If true, KaTeX will throw a ParseError when it encounters an
     * unsupported command. If false, KaTeX will render the unsupported command as text in
     * the color given by errorColor. (default: true)
     */
    throwOnError?: boolean
    /**
     * errorColor: string. A color string given in the format "#XXX" or "#XXXXXX". This
     * option determines the color which unsupported commands are rendered in.
     * (default: #cc0000)
     */
    errorColor?: string
  }

  export const render: (str: string, element: HTMLElement, options?: KatexOptions) => void
  export const renderToString: (str: string, options?: KatexOptions) => string

}