text:
// Copyright 2017, EMC, Inc

'use strict';

var di = require('di');

module.exports = RestJobFactory;
di.annotate(RestJobFactory, new di.Provide('Job.Redfish.Alert.Enable'));

di.annotate(RestJobFactory, new di.Inject(
    'Job.Base',
    'Logger',
    '_',
    'Assert',
    'Promise',
    'Util',
    'HttpTool',
    'Services.Waterline',
    'Services.Configuration'));

function RestJobFactory(BaseJob,
                        Logger,
                        _,
                        assert,
                        Promise,
                        util,
                        HttpTool,
                        waterline,
                        configuration){
    var logger = Logger.initialize(RestJobFactory);

    /**
     * The interface that runs Rest Job from tasks
     * @constructor
     */
    function RestJob(options, context, taskId){
        var self = this;
        self.options = options;
        self.context = context;

        RestJob.super_.call(self, logger, options, context, taskId);
        self.restClient = new HttpTool();
    }

    util.inherits(RestJob, BaseJob);

    RestJob.prototype._run = function run(){
        var self = this;
        return new Promise.resolve()
            .then(function(){
                return updateOptions(self);
            })
            .then(function(setup){
                logger.debug("setting up the redfish alert subcription");
                return self.restClient.setupRequest(setup);
            })
            .then(function(){
                logger.debug("Running The rest call for redfish subscription");
                return self.restClient.runRequest();
            })
            .then(function(data){
                self.context.restData = data;
                self._done();
            })
            .catch(function(err){
                logger.error("Found error during HTTP request.", {error: err});
                self._done(err);
            });
    };

    function updateOptions(obj){
        logger.debug("Setting up the values in order to post RackHD subscribtion");
        //user entered values always take precedence
        var httpSetup = obj.options;

        httpSetup.method = obj.options.data.method || "POST";
        httpSetup.data.Protocol = obj.options.data.Protocol || "Redfish";
        httpSetup.data.Context = obj.options.data.Context || "RackhHD Subscription";
        httpSetup.data.EventTypes = obj.options.data.EventTypes ||
            ["ResourceAdded", "StatusChange", "Alert"];

        if (obj.options.data.Destination){
            httpSetup.data.Destination = obj.options.data.Destination;
        }else{
            var ip = configuration.get("rackhdPublicIp");
            var httpsPort = configuration.get("httpEndpoints")[1].port;
            httpSetup.data.Destination = "https://" + ip + ":"+
                httpsPort + "/api/2.0/notification/alerts";
        }

        //Getting the http credentials
        if (obj.options.credential &&
            obj.options.credential.password &&
            obj.options.credential.username){
            httpSetup.credential.username  = obj.options.credential.username;
            httpSetup.credential.password  = obj.options.credential.password;
            httpSetup.url = obj.options.url;

            return httpSetup;
        }else{
            return waterline.obms.findByNode(obj.context.target, 'redfish-obm-service', true)
                .then(function(obm){
                    if (!obm){
                        throw new Error("Couldn't find redfish obm  setting for node " +
                            obj.context.target);
                    }
                    else{
                        httpSetup.credential = {};
                        httpSetup.credential.username  = obm.config.user;
                        httpSetup.credential.password  = obm.config.password;
                        httpSetup.url =  obj.options.url || "https://" + obm.config.host +
                            "/redfish/v1/EventService/Subscriptions";
                        return httpSetup;
                    }
                });
        }
    }
    return RestJob;
}


text: YYText、SDWebImage、TYAttributedLabel 框架学习

redpajama_set_name: RedPajamaGithub


text:
var api_client;
$(function () {
     api_client = new API();
    api_client.getEndpoints(getEndpointsCallback);
    $('.help_popup').popover({ trigger: "hover" });
    $('#new-api-name').change(fillApiLevelEndpointNames);
    $('#new-api-version').change(fillApiLevelEndpointNames);

});
   function showHideCreateEndpoint(obj){
            var elementName = obj.name;
            var type = elementName.substring(elementName.lastIndexOf('-')+1,elementName.length);
            var level = $('input[name='+elementName+']:checked').val();
          var endpoint = {'type':type};
          if(level =="global"){
            $('#create-new-endpoint-'+type).addClass('hidden');
            $('#select-global-endpoint-'+type).removeClass('hidden');
          }else{
            $('#select-global-endpoint-'+type).addClass('hidden');
            $('#create-new-endpoint-'+type).removeClass('hidden');
          }
          $('#endpoint-config-'+type).val(endpoint);
   }

function getEndpointsCallback(response){
    var data = response.obj.list;
    if(data.length == 0){
        $('#no-global-endpoint-message-production').removeClass('hidden');
        $('#no-global-endpoint-message-sandbox').removeClass('hidden');
        $('#global-endpoint-production').addClass('hidden');
        $('#global-endpoint-sandbox').addClass('hidden');
    }else{
        $('#no-global-endpoint-message-production').addClass('hidden');
        $('#no-global-endpoint-message-sandbox').addClass('hidden');
        $('#global-endpoint-production').removeClass('hidden');
        $('#global-endpoint-sandbox').removeClass('hidden');
        for(var i in data){
            var name = data[i].name;
            var id = data[i].id;
            var selectChild = "<option title='"+name+"' data-content='"+name+"
' value='"+id+"'>"+name+"</option>";
            $('#global-endpoint-sandbox').append(selectChild);
            $('#global-endpoint-production').append(selectChild);
        }
    }
 }
function fillApiLevelEndpointNames(){
    var apiName = $('#new-api-name').val();
    var version = $('#new-api-version').val();
    $("input[name='endpoint-name']").each(function() {
       var elementName = this.id;
       var type = elementName.substring(elementName.lastIndexOf('-')+1,elementName.length);
       var endpointName =apiName + ' -- ' + version + ' -- ' + type.toUpperCase()+ ' -- Endpoint';
       this.value = endpointName;
    });
}


text:
class AddInfoToPlayer < ActiveRecord::Migration[5.0]
  def change
    add_column :players, :first_name, :string
    add_column :players, :last_name, :string
    add_column :players, :is_super, :string
  end
end


text:
// Copyright 2014 Serilog Contributors
//
// 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.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Json;

namespace Serilog.Sinks.Splunk
{
    /// <summary>
    /// A sink that logs to Splunk over Udp
    /// </summary>
    public class SplunkViaUdpSink : ILogEventSink, IDisposable
    {
        Socket _socket;
        JsonFormatter _jsonFormatter;

        /// <summary>
        /// Creates an instance of the Splunk UDP Sink
        /// </summary>
        /// <param name="hostAddress">The Splunk Host</param>
        /// <param name="port">The UDP port configured in Splunk</param>
        /// <param name="formatProvider">Optional format provider</param>
        public SplunkViaUdpSink(IPAddress hostAddress, int port, IFormatProvider formatProvider = null)
        {
            _socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            _socket.Connect(hostAddress, port);

            _jsonFormatter = new JsonFormatter(renderMessage: true, formatProvider: formatProvider);
        }

        /// <summary>
        /// Creates an instance of the Splunk UDP Sink
        /// </summary>
        /// <param name="host">The Splunk Host</param>
        /// <param name="port">The UDP port configured in Splunk</param>
        /// <param name="formatProvider">Optional format provider</param>
        public SplunkViaUdpSink(string host, int port, IFormatProvider formatProvider = null)
        {
            _socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            _socket.Connect(host, port);

            _jsonFormatter = new JsonFormatter(renderMessage: true, formatProvider: formatProvider);
        }

        /// <inheritdoc/>
        public void Emit(LogEvent logEvent)
        {
            var sw = new StringWriter();

            _jsonFormatter.Format(logEvent, sw);

            var message = sw.ToString();

            _socket.Send(Encoding.UTF8.GetBytes(message));
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            _socket.Close();
            _socket.Dispose();
        }
    }
}


text:
/* {{{ SapiResponse Argument Info */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getVersion_args, 0, 0, IS_STRING, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setVersion_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, version, IS_STRING, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getCode_args, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setCode_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, code, IS_LONG, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getHeaders_args, 0, 0, IS_ARRAY, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setHeader_args, 0, 2, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, label, IS_STRING, 0)
    ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_addHeader_args, 0, 2, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, label, IS_STRING, 0)
    ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_unsetHeader_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, label, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getHeader_args, 0, 1, IS_STRING, 1)
    ZEND_ARG_TYPE_INFO(0, label, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_hasHeader_args, 0, 1, _IS_BOOL, 0)
    ZEND_ARG_TYPE_INFO(0, label, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_unsetHeaders_args, 0, 0, SapiResponseInterface, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getCookie_args, 0, 1, IS_ARRAY, 1)
    ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_hasCookie_args, 0, 1, _IS_BOOL, 0)
    ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getCookies_args, 0, 0, IS_ARRAY, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setCookie_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
    ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
    ZEND_ARG_INFO(0, expires_or_options)
    ZEND_ARG_TYPE_INFO(0, path, IS_STRING, 0)
    ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
    ZEND_ARG_TYPE_INFO(0, secure, _IS_BOOL, 0)
    ZEND_ARG_TYPE_INFO(0, httponly, _IS_BOOL, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_unsetCookie_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_unsetCookies_args, 0, 0, SapiResponseInterface, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(SapiResponseInterface_getContent_args, 0, 0, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setContent_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_INFO(0, content)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_addHeaderCallback_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(SapiResponseInterface_setHeaderCallbacks_args, 0, 1, SapiResponseInterface, 0)
    ZEND_ARG_TYPE_INFO(0, callbacks, IS_ARRAY, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(SapiResponseInterface_getHeaderCallbacks_args, 0, 0, IS_ARRAY, 1)
ZEND_END_ARG_INFO()
/* }}} Argument Info */


text:
namespace Bookmarks.Web.RequestModels
{
    using Bookmarks.Data.Models;
    using Bookmarks.Web.Infrastructure.Mapping;

    public class WebSiteRequestModel : IMapFrom<Website>
    {
        public string Name { get; set; }

        public string FaviconBase64String { get; set; }
    }
}


text:
"""Test helpers"""

import datetime
import imaplib
import sys
import unittest

from imap_cli import search
from imap_cli import tests

class SearchTests(unittest.TestCase):
    def setUp(self):
        imaplib.IMAP4_SSL = tests.ImapConnectionMock()

    def test_basic_search(self):
        self.imap_account = imaplib.IMAP4_SSL()

        assert search.create_search_criterion() == ['ALL']

    def test_combine_search_criterion(self):
        self.imap_account = imaplib.IMAP4_SSL()

        date = datetime.datetime(1989, 1, 3)
        mail_address = 'user@example.tld'
        search_criterion = [
            search.create_search_criterion_by_date(date, relative='BEFORE'),
            search.create_search_criterion_by_mail_address(mail_address,
                                                           header_name='TO'),
        ]

        imap_request = search.combine_search_criterion(search_criterion)
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='AND')
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='OR')
        assert imap_request == 'OR BEFORE 03-Jan-1989 TO "user@example.tld"'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='NOT')
        assert imap_request == 'NOT BEFORE 03-Jan-1989 TO "user@example.tld"'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='WRONG')
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")'

    def test_create_search_criteria_by_date(self):
        self.imap_account = imaplib.IMAP4_SSL()

        date = datetime.datetime(1989, 1, 3)
        search_criterion = search.create_search_criterion(date=date)
        assert search_criterion == ['SINCE 03-Jan-1989']

        search_criterion = search.create_search_criterion_by_date(
            date, relative='BEFORE')
        assert search_criterion == 'BEFORE 03-Jan-1989'

        search_criterion = search.create_search_criterion_by_date(
            date, relative='ON')
        assert search_criterion == 'ON 03-Jan-1989'

        search_criterion = search.create_search_criterion_by_date(
            date, relative='SINCE')
        assert search_criterion == 'SINCE 03-Jan-1989'

        search_criterion = search.create_search_criterion_by_date(
            date, relative='BEFORE', sent=True)
        assert search_criterion == 'SENTBEFORE 03-Jan-1989'

        search_criterion = search.create_search_criterion_by_date(
            date, relative='ON', sent=True)
        assert search_criterion == 'SENTON 03-Jan-1989'

        search_criterion = search.create_search_criterion_by_date(
            date, relative='SINCE', sent=True)
        assert search_criterion == 'SENTSINCE 03-Jan-1989'

    def test_create_search_criteria_by_header(self):
        self.imap_account = imaplib.IMAP4_SSL()

        search_criterion = search.create_search_criterion_by_header(
            "FROM", "user@example.tld")
        assert search_criterion == 'HEADER FROM user@example.tld'

    def test_create_search_criterion_by_mail_address(self):
        self.imap_account = imaplib.IMAP4_SSL()

        mail_address = 'user@example.tld'
        search_criterion = search.create_search_criterion(address=mail_address)
        assert search_criterion == ['FROM "user@example.tld"']

        search_criterion = search.create_search_criterion_by_mail_address(
            mail_address, header_name='WRONG')
        assert search_criterion == 'FROM "user@example.tld"'

        search_criterion = search.create_search_criterion_by_mail_address(
            mail_address, header_name='CC')
        assert search_criterion == 'CC "user@example.tld"'

        search_criterion = search.create_search_criterion_by_mail_address(
            mail_address, header_name='BCC')
        assert search_criterion == 'BCC "user@example.tld"'

        search_criterion = search.create_search_criterion_by_mail_address(
            mail_address, header_name='TO')
        assert search_criterion == 'TO "user@example.tld"'

    def test_create_search_criteria_by_size(self):
        self.imap_account = imaplib.IMAP4_SSL()

        size = 3141592
        search_criterion = search.create_search_criterion(size=size)
        assert search_criterion == ['LARGER "3141592"']

        search_criterion = search.create_search_criterion_by_size(
            size, relative='SMALLER')
        assert search_criterion == 'SMALLER "3141592"'

        search_criterion = search.create_search_criterion_by_size(
            size, relative='LARGER')
        assert search_criterion == 'LARGER "3141592"'

        search_criterion = search.create_search_criterion_by_size(
            size, relative='Anything')
        assert search_criterion == 'LARGER "3141592"'

    def test_create_search_criterion_by_subject(self):
        self.imap_account = imaplib.IMAP4_SSL()

        subject = 'subject searched'
        search_criterion = search.create_search_criterion(subject=subject)
        assert search_criterion == ['SUBJECT "subject searched"']

        search_criterion = search.create_search_criterion_by_subject(subject)
        assert search_criterion == 'SUBJECT "subject searched"'

    def test_create_search_criteria_by_tag(self):
        self.imap_account = imaplib.IMAP4_SSL()

        tags = ['seen']
        search_criterion = search.create_search_criterion(tags=tags)
        assert search_criterion == ['SEEN']

        tags = ['testTag']
        search_criterion = search.create_search_criterion(tags=tags)
        assert search_criterion == ['KEYWORD "testTag"']

        tags = ['seen', 'testTag']
        search_criterion = search.create_search_criterion(tags=tags)
        assert search_criterion == ['(SEEN KEYWORD "testTag")']

        tags = []
        search_criterion = search.create_search_criterion(tags=tags)
        assert search_criterion == ['']

    def test_create_search_criteria_by_text(self):
        self.imap_account = imaplib.IMAP4_SSL()

        text = 'CONTENT'
        search_criterion = search.create_search_criterion(text=text)
        assert search_criterion == ['BODY "CONTENT"']

    def test_create_search_criteria_by_uid(self):
        self.imap_account = imaplib.IMAP4_SSL()

        uid = 42
        search_criterion = search.create_search_criterion_by_uid(uid)
        assert search_criterion == 'UID 42'

    def test_display_empty_mail_tree(self):
        self.imap_account = imaplib.IMAP4_SSL()
        assert list(search.display_mail_tree(self.imap_account, [])) == []

    def test_execute_simple_search(self):
        self.imap_account = imaplib.IMAP4_SSL()

        assert search.fetch_uids(self.imap_account) == ['1']

    def test_fetch_mails_info(self):
        self.imap_account = imaplib.IMAP4_SSL()

        reference_mails_info = [{
            'from': u'exampleFrom <example@from.org>',
            'to': u'exampleTo <example@to.org>',
            'subject': u'Mocking IMAP Protocols',
            'id': u'1',
            'flags': [u'\\Seen', u'NonJunk'],
            'date': u'Tue, 03 Jan 1989 09:42:34 +0200',
            'uid': u'1',
        }]
        assert list(search.fetch_mails_info(
            self.imap_account)) == reference_mails_info
        assert list(search.fetch_mails_info(
            self.imap_account, mail_set="42 24")) == reference_mails_info

        self.imap_account.error = True
        assert list(search.fetch_mails_info(self.imap_account)) == []

    def test_fetch_uids(self):
        self.imap_account = imaplib.IMAP4_SSL()

        assert list(search.fetch_uids(self.imap_account)) == ['1']

    def test_fetch_threads(self):
        self.imap_account = imaplib.IMAP4_SSL()

        assert list(search.fetch_threads(self.imap_account)) == [[[1], [2]],
                                                                 [3, 4]]
        threads = search.fetch_threads(
            self.imap_account,
            search_criterion=['BODY "CONTENT"'],
        )
        assert list(threads) == [[[1], [2]], [3, 4]]

    def test_search_cli_tools(self):
        sys.argv = ['imap-cli-search', '-c', 'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '--thread', '-c', 'wrong-config.ini']
        assert search.main() == 1

        sys.argv = ['imap-cli-search', '--thread', '-c', 'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-t testTag -T testText', '-c',
                    'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-t testTag,test2Tag -T testText', '-c',
                    'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-d', '2014-03-13', '-c',
                    'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-d', '201403-13', '-c',
                    'config-example.ini']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-a', 'user@exemple.org']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-f', '{from}']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-l', '10']
        assert search.main() == 0

        sys.argv = ['imap-cli-search', '-l', '0']
        assert search.main() == 1


text:
<?php

/**
 * sfSympalMenuItemGroup form.
 *
 * @package    elf-ekb.ru
 * @subpackage form
 * @author     Cluster Studio <clusterstudio@gmail.com>
 * @version    SVN: $Id: sfDoctrinePluginFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class sfSympalMenuItemGroupForm extends PluginsfSympalMenuItemGroupForm
{
  public function configure()
  {
  }
}


text:
template <class Ty> struct Vector  {
  void growStorageBy();
};
template <class T> __attribute__((noinline)) void Vector<T>::growStorageBy() {
}
void foo() {
 Vector<int> strs;
 strs.growStorageBy();
}

// CHECK: attributes [[NI]] = { noinline nounwind{{.*}} }


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

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

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent( ) {
			this.lblSearch = new System.Windows.Forms.Label();
			this.cmbSearchText = new TypeAheadControl.TypeAheadCombo();
			this.SuspendLayout();
			//
			// lblSearch
			//
			this.lblSearch.AutoSize = true;
			this.lblSearch.Location = new System.Drawing.Point(33, 15);
			this.lblSearch.Name = "lblSearch";
			this.lblSearch.Size = new System.Drawing.Size(41, 13);
			this.lblSearch.TabIndex = 1;
			this.lblSearch.Text = "Search";
			//
			// cmbSearchText
			//
			this.cmbSearchText.CurrentItem = null;
			this.cmbSearchText.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
			this.cmbSearchText.FormattingEnabled = true;
			this.cmbSearchText.Location = new System.Drawing.Point(80, 12);
			this.cmbSearchText.Name = "cmbSearchText";
			this.cmbSearchText.Size = new System.Drawing.Size(335, 21);
			this.cmbSearchText.TabIndex = 0;
			//
			// TypeAheadDemo
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(465, 83);
			this.Controls.Add(this.lblSearch);
			this.Controls.Add(this.cmbSearchText);
			this.Name = "TypeAheadDemo";
			this.Text = "Type Ahead Demo";
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private TypeAheadControl.TypeAheadCombo cmbSearchText;
		private System.Windows.Forms.Label lblSearch;
	}
}


text:
# Typesafe Config Extensions

Libraries supporting [Typesafe Config](https://github.com/typesafehub/config).

This project's release artifacts are available in the Maven
[Central Repository](http://search.maven.org/#search%7Cga%7C1%7Cg%3Aedu.gatech.gtri.typesafeconfig-extensions).

## Components

### Factory

**typesafeconfig-factory** provides a `ConfigFactory` class with which you can clearly and
concisely express how you want all sources of configuration data to be aggregated.

```
import edu.gatech.gtri.typesafeconfigextensions.factory.*;
import static edu.gatech.gtri.typesafeconfigextensions.factory.ConfigFactory.*;
```

A standard configuration loader can be defined as follows.

```
ConfigFactory standard = emptyConfigFactory()
     .bindDefaults()
     .withSources(
         classpathResource("reference"),
         classpathResource("application"),
         systemProperties()
     ).fromLowestToHighestPrecedence();
```

`reference.conf` classpath resources are overridden by `application.conf`, and both are
overridden by system properties.

Suppose we also want to load configuration from `/etc/exampleApp.conf`, sandwiched in the
precedence order between the classpath configs and the system properties. The previous factory
can be adapted to this requirement.

```
java.nio.file.Path path = java.nio.file.Paths.get("/etc/exampleApp");

ConfigFactory custom = standard
    .insertSource(configFile().byPath(path))
    .withHigherPrecedenceThan(classpathResource("application"));
```

Suppose we don't want to use a fixed filesystem path, but would rather let the user of our
application decide where to put their config file.

To support this scenario, `ConfigFactory` repeats its loading process twice so that values
from the first `Config` can be used to load *even more configuration* on the second go.
This allows us to load a file *by key*:

```
ConfigFactory custom2 = standard
    .insertSource(configFile().byKey("exampleApp.config.file"))
    .withHigherPrecedenceThan(classpathResource("application"));
```

Now someone can launch your application with the JVM flag
`-DexampleApp.config.file=$HOME/myAppSettings`, and the contents of
`$HOME/myAppSettings.conf` will be loaded into the configuration.

#### Maven dependency

```
<dependency>
  <groupId>edu.gatech.gtri.typesafeconfig-extensions</groupId>
  <artifactId>typesafeconfig-factory</artifactId>
  <version>1.1</version>
</dependency>
```

### JNDI

**typesafeconfig-jndi** converts a JNDI context into a `Config` object so you'll never have
to deal with the `javax.naming` API again.

```
import javax.naming.Context;
import static edu.gatech.gtri.typesafeconfigextensions.jndi.JndiContexts.*;
```

To convert from `javax.naming.Context` to `Config`:

```
Context someContext = /* ... */;
Config config = context(someContext).toConfig();
```

To just retrieve a JNDI variable named `abc` from the initial context:

```
String configValue = jndiContext().toConfig().getString("abc");
```

#### Maven dependency

```
<dependency>
  <groupId>edu.gatech.gtri.typesafeconfig-extensions</groupId>
  <artifactId>typesafeconfig-jndi</artifactId>
  <version>1.1</version>
</dependency>
```

### For Webapps

**typesafeconfig-for-webapps** defines a standard `ConfigFactory` for servlet-based
web applications.

```
import edu.gatech.gtri.typesafeconfigextensions.forwebapps.WebappConfigs.*;
```

```
ServletContext servletContext = /* ... */;
ConfigFactory factory = webappConfigFactory(servletContext);
```

This factory loads these configuration sources, in order from highest to lowest precedence:

* System properties
* File: `JNDI(webapp.config.directory)/[servlet context path]`
* File: `${webapp.config.directory}/[servlet context path]`
* File: `JNDI(webapp.config.file)`
* File: `${webapp.config file}`
* Classpath resource: `application.conf`
* Classpath resource: `reference.conf`

`JNDI(x)` refers to the JNDI variable named `x`, `[servlet context path]` is the value of
`servletContext.getContextPath()`, and `${x}` denotes the value of the `Config` at path `x`.

You might set up `server.xml` in a Tomcat installation like this, for example:

```
<Context path="/myApplication/apiServer" docBase="/users/chris/myAppApiServer">
  <Environment name="webapp.config.directory" type="java.lang.String" value="${CATALINA_BASE}/conf"/>
</Context>
```

(`CATALINA_BASE` is an environment variable pointing to the path of the Tomcat installation.)

This web application's `ConfigFactory` would then include configuration loaded from
`$CATALINA_BASE/conf/myApplication/apiServer.conf`.

#### Maven dependency

```
<dependency>
  <groupId>edu.gatech.gtri.typesafeconfig-extensions</groupId>
  <artifactId>typesafeconfig-for-webapps</artifactId>
  <version>1.1</version>
</dependency>
```

### For Scala

**typesafeconfig-for-scala** adds some sugar to help use the Config library in Scala.

```
import edu.gatech.gtri.typesafeconfigextensions.forscala._
```

```
val a = "A { B: C }, D: E".toConfig          // A { B: C }, D: E
val b = ("A" -> 7).toConfig                  // A: 7
val c = Seq("A" -> 4, "B" -> "C").toConfig   // A: 4, B: C
val d = c ++ b                               // A: 7, B: C
val e = b + ("F" -> "G")                     // A: 7, F: G
val f = a - "A"                              // D: E
```

#### SBT dependency

```
libraryDependencies += "edu.gatech.gtri.typesafeconfig-extensions" %
                       "typesafeconfig-for-scala_2.10" % "1.1"
```

## Information for developers

### Build scripts

`./sbt` to launch the build tool (SBT).

`./checkstyle` to run Checkstyle.

### Deploying

#### Setting up SBT

Add your Sonatype login to `~/.sbt/0.13/sonatype.sbt`:

```
credentials += Credentials(
  "Sonatype Nexus Repository Manager", "oss.sonatype.org",
  "your-username", "your-password")
```

Optionally, include the passphrase for the PGP key.

```
pgpPassphrase := Some("your-pgp-passphrase".toArray)
```

#### Publishing to Sonatype

`./sbt publish`

This creates a staging repository at
https://oss.sonatype.org/index.html#stagingRepositories

*Close* the staging repository.

If all is well, you can then *Release* the repository.


text:
var JSONStream = require('JSONStream')
  , websocket = require('websocket-stream')
  , wstream = websocket('ws://localhost:8080')
  , parser = JSONStream.parse([true])
  , stringify = JSONStream.stringify()
  , emitIO = require('../../.')()
// create an emitter from incoming stream
  , ev = emitIO(parser)
// create an outgoing stream from that emitter
  , emitStream = emitIO(ev)

wstream.pipe(parser)

emitStream.pipe(stringify).pipe(wstream)

ev.on('server ok', function (t) {
    console.log('server ok: ' + t)
})

ev.emit('client message' ,'this is a message from the client')


text:
"""Tests for BatchNorm Bijector."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib import distributions
from tensorflow.contrib.distributions.python.ops import test_util
from tensorflow.contrib.distributions.python.ops.bijectors.batch_normalization import BatchNormalization
from tensorflow.contrib.distributions.python.ops.bijectors.invert import Invert
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.layers import normalization
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variables
from tensorflow.python.ops.distributions import normal as normal_lib
from tensorflow.python.ops.distributions import transformed_distribution as transformed_distribution_lib
from tensorflow.python.platform import test
from tensorflow.python.training import adam

class BatchNormTest(test_util.VectorDistributionTestHelpers,
                    test.TestCase):

  def _reduction_axes(self, input_shape, event_dims):
    if isinstance(event_dims, int):
      event_dims = [event_dims]
    ndims = len(input_shape)
    # Convert event_dims to non-negative indexing.
    event_dims = list(event_dims)
    for idx, x in enumerate(event_dims):
      if x < 0:
        event_dims[idx] = ndims + x
    return tuple(i for i in range(ndims) if i not in event_dims)

  def testForwardInverse(self):
    """Tests forward and backward passes with different event shapes.

    input_shape: Tuple of shapes for input tensor.
    event_dims: Tuple of dimension indices that will be normalized.
    training: Boolean of whether bijector runs in training or inference mode.
    """
    params = [
        ((5*2, 4), [-1], False),
        ((5, 2, 4), [-1], False),
        ((5, 2, 4), [1, 2], False),
        ((5, 2, 4), [0, 1], False),
        ((5*2, 4), [-1], True),
        ((5, 2, 4), [-1], True),
        ((5, 2, 4), [1, 2], True),
        ((5, 2, 4), [0, 1], True)
    ]
    for input_shape, event_dims, training in params:
      x_ = np.arange(5 * 4 * 2).astype(np.float32).reshape(input_shape)
      with self.test_session() as sess:
        x = constant_op.constant(x_)
        # When training, memorize the exact mean of the last
        # minibatch that it normalized (instead of moving average assignment).
        layer = normalization.BatchNormalization(
            axis=event_dims, momentum=0., epsilon=0.)
        batch_norm = BatchNormalization(
            batchnorm_layer=layer, training=training)
        # Minibatch statistics are saved only after norm_x has been computed.
        norm_x = batch_norm.inverse(x)
        with ops.control_dependencies(batch_norm.batchnorm.updates):
          moving_mean = array_ops.identity(batch_norm.batchnorm.moving_mean)
          moving_var = array_ops.identity(batch_norm.batchnorm.moving_variance)
          denorm_x = batch_norm.forward(array_ops.identity(norm_x))
          fldj = batch_norm.forward_log_det_jacobian(
              x, event_ndims=len(event_dims))
          # Use identity to invalidate cache.
          ildj = batch_norm.inverse_log_det_jacobian(
              array_ops.identity(denorm_x), event_ndims=len(event_dims))
        variables.global_variables_initializer().run()
        # Update variables.
        norm_x_ = sess.run(norm_x)
        [
            norm_x_,
            moving_mean_,
            moving_var_,
            denorm_x_,
            ildj_,
            fldj_,
        ] = sess.run([
            norm_x,
            moving_mean,
            moving_var,
            denorm_x,
            ildj,
            fldj,
        ])
        self.assertEqual("batch_normalization", batch_norm.name)

        reduction_axes = self._reduction_axes(input_shape, event_dims)
        keepdims = len(event_dims) > 1

        expected_batch_mean = np.mean(
            x_, axis=reduction_axes, keepdims=keepdims)
        expected_batch_var = np.var(x_, axis=reduction_axes, keepdims=keepdims)

        if training:
          # When training=True, values become normalized across batch dim and
          # original values are recovered after de-normalizing.
          zeros = np.zeros_like(norm_x_)
          self.assertAllClose(np.mean(zeros, axis=reduction_axes),
                              np.mean(norm_x_, axis=reduction_axes))

          self.assertAllClose(expected_batch_mean, moving_mean_)
          self.assertAllClose(expected_batch_var, moving_var_)
          self.assertAllClose(x_, denorm_x_, atol=1e-5)
          # Since moving statistics are set to batch statistics after
          # normalization, ildj and -fldj should match.
          self.assertAllClose(ildj_, -fldj_)
          # ildj is computed with minibatch statistics.
          expected_ildj = np.sum(np.log(1.) - .5 * np.log(
              expected_batch_var + batch_norm.batchnorm.epsilon))
          self.assertAllClose(expected_ildj, ildj_)
        else:
          # When training=False, moving_mean, moving_var remain at their
          # initialized values (0., 1.), resulting in no scale/shift (a small
          # shift occurs if epsilon > 0.)
          self.assertAllClose(x_, norm_x_)
          self.assertAllClose(x_, denorm_x_, atol=1e-5)
          # ildj is computed with saved statistics.
          expected_ildj = np.sum(
              np.log(1.) - .5 * np.log(1. + batch_norm.batchnorm.epsilon))
          self.assertAllClose(expected_ildj, ildj_)

  def testMaximumLikelihoodTraining(self):
    # Test Maximum Likelihood training with default bijector.
    with self.test_session() as sess:
      base_dist = distributions.MultivariateNormalDiag(loc=[0., 0.])
      batch_norm = BatchNormalization(training=True)
      dist = transformed_distribution_lib.TransformedDistribution(
          distribution=base_dist,
          bijector=batch_norm)
      target_dist = distributions.MultivariateNormalDiag(loc=[1., 2.])
      target_samples = target_dist.sample(100)
      dist_samples = dist.sample(3000)
      loss = -math_ops.reduce_mean(dist.log_prob(target_samples))
      with ops.control_dependencies(batch_norm.batchnorm.updates):
        train_op = adam.AdamOptimizer(1e-2).minimize(loss)
        moving_mean = array_ops.identity(batch_norm.batchnorm.moving_mean)
        moving_var = array_ops.identity(batch_norm.batchnorm.moving_variance)
      variables.global_variables_initializer().run()
      for _ in range(3000):
        sess.run(train_op)
      [
          dist_samples_,
          moving_mean_,
          moving_var_
      ] = sess.run([
          dist_samples,
          moving_mean,
          moving_var
      ])
      self.assertAllClose([1., 2.], np.mean(dist_samples_, axis=0), atol=5e-2)
      self.assertAllClose([1., 2.], moving_mean_, atol=5e-2)
      self.assertAllClose([1., 1.], moving_var_, atol=5e-2)

  def testLogProb(self):
    with self.test_session() as sess:
      layer = normalization.BatchNormalization(epsilon=0.)
      batch_norm = BatchNormalization(batchnorm_layer=layer, training=False)
      base_dist = distributions.MultivariateNormalDiag(loc=[0., 0.])
      dist = transformed_distribution_lib.TransformedDistribution(
          distribution=base_dist,
          bijector=batch_norm,
          validate_args=True)
      samples = dist.sample(int(1e5))
      # No volume distortion since training=False, bijector is initialized
      # to the identity transformation.
      base_log_prob = base_dist.log_prob(samples)
      dist_log_prob = dist.log_prob(samples)
      variables.global_variables_initializer().run()
      base_log_prob_, dist_log_prob_ = sess.run([base_log_prob, dist_log_prob])
      self.assertAllClose(base_log_prob_, dist_log_prob_)

  def testMutuallyConsistent(self):
    # BatchNorm bijector is only mutually consistent when training=False.
    dims = 4
    with self.test_session() as sess:
      layer = normalization.BatchNormalization(epsilon=0.)
      batch_norm = BatchNormalization(batchnorm_layer=layer, training=False)
      dist = transformed_distribution_lib.TransformedDistribution(
          distribution=normal_lib.Normal(loc=0., scale=1.),
          bijector=batch_norm,
          event_shape=[dims],
          validate_args=True)
      self.run_test_sample_consistent_log_prob(
          sess_run_fn=sess.run,
          dist=dist,
          num_samples=int(1e5),
          radius=2.,
          center=0.,
          rtol=0.02)

  def testInvertMutuallyConsistent(self):
    # BatchNorm bijector is only mutually consistent when training=False.
    dims = 4
    with self.test_session() as sess:
      layer = normalization.BatchNormalization(epsilon=0.)
      batch_norm = Invert(
          BatchNormalization(batchnorm_layer=layer, training=False))
      dist = transformed_distribution_lib.TransformedDistribution(
          distribution=normal_lib.Normal(loc=0., scale=1.),
          bijector=batch_norm,
          event_shape=[dims],
          validate_args=True)
      self.run_test_sample_consistent_log_prob(
          sess_run_fn=sess.run,
          dist=dist,
          num_samples=int(1e5),
          radius=2.,
          center=0.,
          rtol=0.02)

if __name__ == "__main__":
  test.main()


text:
@interface PodsDummy_ARNTransitionAnimator : NSObject
@end
@implementation PodsDummy_ARNTransitionAnimator
@end


text:
package org.broad.igv.track;

import org.broad.igv.feature.Exon;
import org.broad.igv.feature.IExon;
import org.broad.igv.feature.IGVFeature;
import org.broad.igv.renderer.SelectableFeatureRenderer;
import htsjdk.tribble.Feature;

import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.Set;

/**
 * A FeatureTrack designed for selecting features/exons. Created to support Sashimi plot
 * window
 * User: jacob
 * Date: 2013-Jan-28
 */
public class SelectableFeatureTrack extends FeatureTrack {

    protected Set<IExon> selectedExons = new HashSet<IExon>();

    public SelectableFeatureTrack() {
    }

    public SelectableFeatureTrack(FeatureTrack geneTrack) {
        super(geneTrack);
        this.setRendererClass(SelectableFeatureRenderer.class);
    }

    @Override
    public boolean handleDataClick(TrackClickEvent te) {
        MouseEvent e = te.getMouseEvent();
        Feature f = getFeatureAtMousePosition(te);

        //We allow any of these modifier keys for multi-select
        if (!e.isShiftDown() && !e.isControlDown() && !e.isMetaDown()) {
            clearSelectedExons();
        }

        boolean foundExon = false;
        if (f != null && f instanceof IGVFeature) {
            selectedFeature = (IGVFeature) f;
            double location = te.getFrame().getChromosomePosition(e);
            if (selectedFeature.getExons() != null) {
                for (Exon exon : selectedFeature.getExons()) {
                    if (location >= exon.getStart() && location < exon.getEnd()) {
                        selectedExons.add(exon);
                        foundExon = true;
                        break;
                    }
                }
            }
        }

        ((SelectableFeatureRenderer) getRenderer()).setSelectedExons(selectedExons);

        return foundExon;
    }

    private void clearSelectedExons() {
        this.selectedExons.clear();
    }

    public Set<IExon> getSelectedExons() {
        return selectedExons;
    }
}


text:
namespace ax {
namespace NodeEditor {

//------------------------------------------------------------------------------
struct NodeId;
struct LinkId;
struct PinId;

//------------------------------------------------------------------------------
enum class SaveReasonFlags: uint32_t
{
    None       = 0x00000000,
    Navigation = 0x00000001,
    Position   = 0x00000002,
    Size       = 0x00000004,
    Selection  = 0x00000008,
    User       = 0x00000010
};

inline SaveReasonFlags operator |(SaveReasonFlags lhs, SaveReasonFlags rhs) { return static_cast<SaveReasonFlags>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs)); }
inline SaveReasonFlags operator &(SaveReasonFlags lhs, SaveReasonFlags rhs) { return static_cast<SaveReasonFlags>(static_cast<uint32_t>(lhs) & static_cast<uint32_t>(rhs)); }

using ConfigSaveSettings     = bool   (*)(const char* data, size_t size, SaveReasonFlags reason, void* userPointer);
using ConfigLoadSettings     = size_t (*)(char* data, void* userPointer);

using ConfigSaveNodeSettings = bool   (*)(NodeId nodeId, const char* data, size_t size, SaveReasonFlags reason, void* userPointer);
using ConfigLoadNodeSettings = size_t (*)(NodeId nodeId, char* data, void* userPointer);

using ConfigSession          = void   (*)(void* userPointer);

struct Config
{
    const char*             SettingsFile;
    ConfigSession           BeginSaveSession;
    ConfigSession           EndSaveSession;
    ConfigSaveSettings      SaveSettings;
    ConfigLoadSettings      LoadSettings;
    ConfigSaveNodeSettings  SaveNodeSettings;
    ConfigLoadNodeSettings  LoadNodeSettings;
    void*                   UserPointer;

    Config()
        : SettingsFile("NodeEditor.json")
        , BeginSaveSession(nullptr)
        , EndSaveSession(nullptr)
        , SaveSettings(nullptr)
        , LoadSettings(nullptr)
        , SaveNodeSettings(nullptr)
        , LoadNodeSettings(nullptr)
        , UserPointer(nullptr)
    {
    }
};

//------------------------------------------------------------------------------
enum class PinKind
{
    Input,
    Output
};

//------------------------------------------------------------------------------
enum StyleColor
{
    StyleColor_Bg,
    StyleColor_Grid,
    StyleColor_NodeBg,
    StyleColor_NodeBorder,
    StyleColor_HovNodeBorder,
    StyleColor_SelNodeBorder,
    StyleColor_NodeSelRect,
    StyleColor_NodeSelRectBorder,
    StyleColor_HovLinkBorder,
    StyleColor_SelLinkBorder,
    StyleColor_LinkSelRect,
    StyleColor_LinkSelRectBorder,
    StyleColor_PinRect,
    StyleColor_PinRectBorder,
    StyleColor_Flow,
    StyleColor_FlowMarker,
    StyleColor_GroupBg,
    StyleColor_GroupBorder,

    StyleColor_Count
};

enum StyleVar
{
    StyleVar_NodePadding,
    StyleVar_NodeRounding,
    StyleVar_NodeBorderWidth,
    StyleVar_HoveredNodeBorderWidth,
    StyleVar_SelectedNodeBorderWidth,
    StyleVar_PinRounding,
    StyleVar_PinBorderWidth,
    StyleVar_LinkStrength,
    StyleVar_SourceDirection,
    StyleVar_TargetDirection,
    StyleVar_ScrollDuration,
    StyleVar_FlowMarkerDistance,
    StyleVar_FlowSpeed,
    StyleVar_FlowDuration,
    StyleVar_PivotAlignment,
    StyleVar_PivotSize,
    StyleVar_PivotScale,
    StyleVar_PinCorners,
    StyleVar_PinRadius,
    StyleVar_PinArrowSize,
    StyleVar_PinArrowWidth,
    StyleVar_GroupRounding,
    StyleVar_GroupBorderWidth,
};

struct Style
{
    ImVec4  NodePadding;
    float   NodeRounding;
    float   NodeBorderWidth;
    float   HoveredNodeBorderWidth;
    float   SelectedNodeBorderWidth;
    float   PinRounding;
    float   PinBorderWidth;
    float   LinkStrength;
    ImVec2  SourceDirection;
    ImVec2  TargetDirection;
    float   ScrollDuration;
    float   FlowMarkerDistance;
    float   FlowSpeed;
    float   FlowDuration;
    ImVec2  PivotAlignment;
    ImVec2  PivotSize;
    ImVec2  PivotScale;
    float   PinCorners;
    float   PinRadius;
    float   PinArrowSize;
    float   PinArrowWidth;
    float   GroupRounding;
    float   GroupBorderWidth;
    ImVec4  Colors[StyleColor_Count];

    Style()
    {
        NodePadding             = ImVec4(8, 8, 8, 8);
        NodeRounding            = 12.0f;
        NodeBorderWidth         = 1.5f;
        HoveredNodeBorderWidth  = 3.5f;
        SelectedNodeBorderWidth = 3.5f;
        PinRounding             = 4.0f;
        PinBorderWidth          = 0.0f;
        LinkStrength            = 100.0f;
        SourceDirection         = ImVec2(1.0f, 0.0f);
        TargetDirection         = ImVec2(-1.0f, 0.0f);
        ScrollDuration          = 0.35f;
        FlowMarkerDistance      = 30.0f;
        FlowSpeed               = 150.0f;
        FlowDuration            = 2.0f;
        PivotAlignment          = ImVec2(0.5f, 0.5f);
        PivotSize               = ImVec2(0.0f, 0.0f);
        PivotScale              = ImVec2(1, 1);
        PinCorners              = ImDrawCornerFlags_All;
        PinRadius               = 0.0f;
        PinArrowSize            = 0.0f;
        PinArrowWidth           = 0.0f;
        GroupRounding           = 6.0f;
        GroupBorderWidth        = 1.0f;

        Colors[StyleColor_Bg]                 = ImColor( 80,  80,  90, 200);
        Colors[StyleColor_Grid]               = ImColor(240, 240, 240,  200);
        Colors[StyleColor_NodeBg]             = ImColor( 180,  180,  200, 200);
        Colors[StyleColor_NodeBorder]         = ImColor(30, 30, 30,  255);
        Colors[StyleColor_HovNodeBorder]      = ImColor( 50, 176, 255, 255);
        Colors[StyleColor_SelNodeBorder]      = ImColor(255, 176,  50, 255);
        Colors[StyleColor_NodeSelRect]        = ImColor(  5, 130, 255,  64);
        Colors[StyleColor_NodeSelRectBorder]  = ImColor(  5, 130, 255, 128);
        Colors[StyleColor_HovLinkBorder]      = ImColor( 50, 176, 255, 255);
        Colors[StyleColor_SelLinkBorder]      = ImColor(255, 176,  50, 255);
        Colors[StyleColor_LinkSelRect]        = ImColor(  5, 130, 255,  64);
        Colors[StyleColor_LinkSelRectBorder]  = ImColor(  5, 130, 255, 128);
        Colors[StyleColor_PinRect]            = ImColor( 60, 180, 255, 100);
        Colors[StyleColor_PinRectBorder]      = ImColor( 60, 180, 255, 128);
        Colors[StyleColor_Flow]               = ImColor(255, 128,  64, 255);
        Colors[StyleColor_FlowMarker]         = ImColor(255, 128,  64, 255);
        Colors[StyleColor_GroupBg]            = ImColor(  0,   0,   0, 160);
        Colors[StyleColor_GroupBorder]        = ImColor(255, 255, 255,  32);
    }
};

//------------------------------------------------------------------------------
struct EditorContext;

//------------------------------------------------------------------------------
void SetCurrentEditor(EditorContext* ctx);
EditorContext* GetCurrentEditor();
EditorContext* CreateEditor(const Config* config = nullptr);
void DestroyEditor(EditorContext* ctx);

Style& GetStyle();
const char* GetStyleColorName(StyleColor colorIndex);

void PushStyleColor(StyleColor colorIndex, const ImVec4& color);
void PopStyleColor(int count = 1);

void PushStyleVar(StyleVar varIndex, float value);
void PushStyleVar(StyleVar varIndex, const ImVec2& value);
void PushStyleVar(StyleVar varIndex, const ImVec4& value);
void PopStyleVar(int count = 1);

void Begin(const char* id, const ImVec2& size = ImVec2(0, 0));
void End();

void BeginNode(NodeId id);
void BeginPin(PinId id, PinKind kind);
void PinRect(const ImVec2& a, const ImVec2& b);
void PinPivotRect(const ImVec2& a, const ImVec2& b);
void PinPivotSize(const ImVec2& size);
void PinPivotScale(const ImVec2& scale);
void PinPivotAlignment(const ImVec2& alignment);
void EndPin();
void Group(const ImVec2& size);
void EndNode();

bool BeginGroupHint(NodeId nodeId);
ImVec2 GetGroupMin();
ImVec2 GetGroupMax();
ImDrawList* GetHintForegroundDrawList();
ImDrawList* GetHintBackgroundDrawList();
void EndGroupHint();

// TODO: Add a way to manage node background channels
ImDrawList* GetNodeBackgroundDrawList(NodeId nodeId);

bool Link(LinkId id, PinId startPinId, PinId endPinId, const ImVec4& color = ImVec4(1, 1, 1, 1), float thickness = 1.0f);

void Flow(LinkId linkId);

bool BeginCreate(const ImVec4& color = ImVec4(1, 1, 1, 1), float thickness = 1.0f);
bool QueryNewLink(PinId* startId, PinId* endId);
bool QueryNewLink(PinId* startId, PinId* endId, const ImVec4& color, float thickness = 1.0f);
bool QueryNewNode(PinId* pinId);
bool QueryNewNode(PinId* pinId, const ImVec4& color, float thickness = 1.0f);
bool AcceptNewItem();
bool AcceptNewItem(const ImVec4& color, float thickness = 1.0f);
void RejectNewItem();
void RejectNewItem(const ImVec4& color, float thickness = 1.0f);
void EndCreate();

bool BeginDelete();
bool QueryDeletedLink(LinkId* linkId, PinId* startId = nullptr, PinId* endId = nullptr);
bool QueryDeletedNode(NodeId* nodeId);
bool AcceptDeletedItem();
void RejectDeletedItem();
void EndDelete();

void SetNodePosition(NodeId nodeId, const ImVec2& editorPosition);
ImVec2 GetNodePosition(NodeId nodeId);
ImVec2 GetNodeSize(NodeId nodeId);
void CenterNodeOnScreen(NodeId nodeId);

void RestoreNodeState(NodeId nodeId);

void Suspend();
void Resume();
bool IsSuspended();

bool IsActive();

bool HasSelectionChanged();
int  GetSelectedObjectCount();
int  GetSelectedNodes(NodeId* nodes, int size);
int  GetSelectedLinks(LinkId* links, int size);
void ClearSelection();
void SelectNode(NodeId nodeId, bool append = false);
void SelectLink(LinkId linkId, bool append = false);
void DeselectNode(NodeId nodeId);
void DeselectLink(LinkId linkId);

bool DeleteNode(NodeId nodeId);
bool DeleteLink(LinkId linkId);

void NavigateToContent(float duration = -1);
void NavigateToSelection(bool zoomIn = false, float duration = -1);

bool ShowNodeContextMenu(NodeId* nodeId);
bool ShowPinContextMenu(PinId* pinId);
bool ShowLinkContextMenu(LinkId* linkId);
bool ShowBackgroundContextMenu();

void EnableShortcuts(bool enable);
bool AreShortcutsEnabled();

bool BeginShortcut();
bool AcceptCut();
bool AcceptCopy();
bool AcceptPaste();
bool AcceptDuplicate();
bool AcceptCreateNode();
int  GetActionContextSize();
int  GetActionContextNodes(NodeId* nodes, int size);
int  GetActionContextLinks(LinkId* links, int size);
void EndShortcut();

float GetCurrentZoom();

NodeId GetDoubleClickedNode();
PinId GetDoubleClickedPin();
LinkId GetDoubleClickedLink();
bool IsBackgroundClicked();
bool IsBackgroundDoubleClicked();

bool PinHadAnyLinks(PinId pinId);

ImVec2 GetScreenSize();
ImVec2 ScreenToCanvas(const ImVec2& pos);
ImVec2 CanvasToScreen(const ImVec2& pos);

//------------------------------------------------------------------------------
namespace Details {

template <typename T, typename Tag>
struct SafeType
{
    SafeType(T t)
        : m_Value(std::move(t))
    {
    }

    SafeType(const SafeType&) = default;

    template <typename T2, typename Tag2>
    SafeType(
        const SafeType
        <
            typename std::enable_if<!std::is_same<T, T2>::value, T2>::type,
            typename std::enable_if<!std::is_same<Tag, Tag2>::value, Tag2>::type
        >&) = delete;

    SafeType& operator=(const SafeType&) = default;

    explicit operator T() const { return Get(); }

    T Get() const { return m_Value; }

private:
    T m_Value;
};

template <typename Tag>
struct SafePointerType
    : SafeType<uintptr_t, Tag>
{
    static const Tag Invalid;

    using SafeType<uintptr_t, Tag>::SafeType;

    SafePointerType()
        : SafePointerType(Invalid)
    {
    }

    template <typename T = void> explicit SafePointerType(T* ptr): SafePointerType(reinterpret_cast<uintptr_t>(ptr)) {}
    template <typename T = void> T* AsPointer() const { return reinterpret_cast<T*>(this->Get()); }

    explicit operator bool() const { return *this != Invalid; }
};

template <typename Tag>
const Tag SafePointerType<Tag>::Invalid = { 0 };

template <typename Tag>
inline bool operator==(const SafePointerType<Tag>& lhs, const SafePointerType<Tag>& rhs)
{
    return lhs.Get() == rhs.Get();
}

template <typename Tag>
inline bool operator!=(const SafePointerType<Tag>& lhs, const SafePointerType<Tag>& rhs)
{
    return lhs.Get() != rhs.Get();
}

} // namespace Details

struct NodeId final: Details::SafePointerType<NodeId>
{
    using SafePointerType::SafePointerType;
};

struct LinkId final: Details::SafePointerType<LinkId>
{
    using SafePointerType::SafePointerType;
};

struct PinId final: Details::SafePointerType<PinId>
{
    using SafePointerType::SafePointerType;
};

//------------------------------------------------------------------------------
} // namespace Editor
} // namespace ax

//------------------------------------------------------------------------------
# endif // __IMGUI_NODE_EDITOR_H__


text:
package org.zstack.kvm;

import org.zstack.compute.host.HostReconnectTask;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.db.Q;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.utils.network.NetworkUtils;

import javax.persistence.Tuple;
import java.util.concurrent.TimeUnit;

public class KVMReconnectHostTask extends HostReconnectTask {
    public KVMReconnectHostTask(String uuid, NoErrorCompletion completion) {
        super(uuid, completion);
    }

    @Override
    protected CanDoAnswer canDoReconnect() {
        if (CoreGlobalProperty.UNIT_TEST_ON) {
            return CanDoAnswer.Ready;
        }

        Tuple t = Q.New(KVMHostVO.class).select(KVMHostVO_.managementIp, KVMHostVO_.port).eq(KVMHostVO_.uuid, uuid).findTuple();
        if (t == null) {
            return CanDoAnswer.NoReconnect;
        }

        String ip = t.get(0, String.class);
        int port = t.get(1, Integer.class);

        return NetworkUtils.isRemotePortOpen(ip, port, (int) TimeUnit.SECONDS.toMillis(2)) ?
                CanDoAnswer.Ready : CanDoAnswer.NotReady;
    }
}


text:
    <input ng-model="search.name" class="search-query" placeholder="Search" type="text" />

 0">
    <button class="btn" ng-class="allEnabled() ? 'btn-warning' : 'btn-success'" ng-click="toggleAll()">{{ allEnabled() ? 'Disable' : 'Enable' }}</button>

            <input type="checkbox" ng-model="allSelected" ng-change="toggleSelectAll(allSelected)">

          Check
          Target
          Command

            <input type="checkbox" ng-model="check.selected">

          {{ check.name }}{{ check.enabled ? '' : ' (disabled)' }}
          {{ check.target ? check.target : '__global__' }}
          {{ check.command.cmd }}


text:
@interface PagerViewController : UICollectionViewController

@end


text:
"use strict";

var app = require('../../../server/app');
var request = require('supertest').agent(app.listen());
var mockedBoard = require('../../mocks/board');

describe('Request board', function(){
  describe('GET /board', function(){
      it('should returns the board', function(done){
        request
            .get('/api/board')
            .expect(200)
            .expect(mockedBoard, done);
      });
  });
});


text:
Consider also that a reader may be a proxy for a remote reader.
A promise iterator be easily backed by a promise for a remote object.

```js
function RemotePromiseIterator(promise) {
    this.remoteIteratorPromise = promise.invoke("iterate");
}
RemotePromiseIterator.prototype.next = function (value) {
    return this.remoteIteratorPromise.invoke("next");
};

var remoteReader = remoteFilesystem.invoke("open", "primes.txt");
var reader = new RemotePromiseIterator(remoteReader);
reader.forEach(console.log);
```

Apart from `then` and `done`, promises provide methods like `get`, `call`, and
`invoke` to allow promises to be created from promises and for messages to be
pipelined to remote objects.
An `iterate` method should be a part of that protocol to allow values to be
streamed on demand over any message channel.


text:
require 'spree_core'
require 'spree_dotpay_pl/engine'


text:
package org.ovirt.engine.core.common.vdscommands;

import org.ovirt.engine.core.compat.Guid;

public class HSMTaskGuidBaseVDSCommandParameters extends VdsIdVDSCommandParametersBase {
    public HSMTaskGuidBaseVDSCommandParameters(Guid vdsId, Guid taskId) {
        super(vdsId);
        setTaskId(taskId);
    }

    private Guid privateTaskId;

    public Guid getTaskId() {
        return privateTaskId;
    }

    private void setTaskId(Guid value) {
        privateTaskId = value;
    }

    public HSMTaskGuidBaseVDSCommandParameters() {
        privateTaskId = Guid.Empty;
    }

    @Override
    public String toString() {
        return String.format("%s, taskId=%s", super.toString(), getTaskId());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 CloudBans (https://cloudbans.xyz)
  ~
  ~    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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>xyz.cloudbans</groupId>
    <artifactId>common</artifactId>
    <version>0.1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <licenses>
        <license>
            <name>GNU General Public License (GPL)</name>
            <url>http://www.gnu.org/licenses/gpl.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <distributionManagement>
        <snapshotRepository>
            <id>cloudbans-repo</id>
            <url>https://repo.cloudbans.xyz/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>cloudbans-repo</id>
            <url>https://repo.cloudbans.xyz/content/repositories/releases</url>
        </repository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package server

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/containers/storage"
	"github.com/kubernetes-incubator/cri-o/libkpod/sandbox"
	"github.com/kubernetes-incubator/cri-o/oci"
	"github.com/kubernetes-incubator/cri-o/pkg/annotations"
	runtimespec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/generate"
	"github.com/opencontainers/selinux/go-selinux/label"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"golang.org/x/sys/unix"
	"k8s.io/kubernetes/pkg/api/v1"
	pb "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime"
	"k8s.io/kubernetes/pkg/kubelet/leaky"
	"k8s.io/kubernetes/pkg/kubelet/network/hostport"
	"k8s.io/kubernetes/pkg/kubelet/types"
)

const (
	// PodInfraOOMAdj is the value that we set for oom score adj for
	// the pod infra container.
	// TODO: Remove this const once this value is provided over CRI
	// See https://github.com/kubernetes/kubernetes/issues/47938
	PodInfraOOMAdj int = -998
	// PodInfraCPUshares is default cpu shares for sandbox container.
	PodInfraCPUshares = 2
)

// privilegedSandbox returns true if the sandbox configuration
// requires additional host privileges for the sandbox.
func (s *Server) privilegedSandbox(req *pb.RunPodSandboxRequest) bool {
	securityContext := req.GetConfig().GetLinux().GetSecurityContext()
	if securityContext == nil {
		return false
	}

	if securityContext.Privileged {
		return true
	}

	namespaceOptions := securityContext.GetNamespaceOptions()
	if namespaceOptions == nil {
		return false
	}

	if namespaceOptions.HostNetwork ||
		namespaceOptions.HostPid ||
		namespaceOptions.HostIpc {
		return true
	}

	return false
}

// trustedSandbox returns true if the sandbox will run trusted workloads.
func (s *Server) trustedSandbox(req *pb.RunPodSandboxRequest) bool {
	kubeAnnotations := req.GetConfig().GetAnnotations()

	trustedAnnotation, ok := kubeAnnotations[annotations.TrustedSandbox]
	if !ok {
		// A sandbox is trusted by default.
		return true
	}

	return isTrue(trustedAnnotation)
}

func (s *Server) runContainer(container *oci.Container, cgroupParent string) error {
	if err := s.Runtime().CreateContainer(container, cgroupParent); err != nil {
		return err
	}
	if err := s.Runtime().StartContainer(container); err != nil {
		return err
	}
	return nil
}

var (
	conflictRE = regexp.MustCompile(`already reserved for pod "([0-9a-z]+)"`)
)

// RunPodSandbox creates and runs a pod-level sandbox.
func (s *Server) RunPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest) (resp *pb.RunPodSandboxResponse, err error) {
	s.updateLock.RLock()
	defer s.updateLock.RUnlock()

	logrus.Debugf("RunPodSandboxRequest %+v", req)
	var processLabel, mountLabel, resolvPath string
	// process req.Name
	kubeName := req.GetConfig().GetMetadata().Name
	if kubeName == "" {
		return nil, fmt.Errorf("PodSandboxConfig.Name should not be empty")
	}

	namespace := req.GetConfig().GetMetadata().Namespace
	attempt := req.GetConfig().GetMetadata().Attempt

	id, name, err := s.generatePodIDandName(req.GetConfig())
	if err != nil {
		if strings.Contains(err.Error(), "already reserved for pod") {
			matches := conflictRE.FindStringSubmatch(err.Error())
			if len(matches) != 2 {
				return nil, err
			}
			dupID := matches[1]
			if _, err := s.StopPodSandbox(ctx, &pb.StopPodSandboxRequest{PodSandboxId: dupID}); err != nil {
				return nil, err
			}
			if _, err := s.RemovePodSandbox(ctx, &pb.RemovePodSandboxRequest{PodSandboxId: dupID}); err != nil {
				return nil, err
			}
			id, name, err = s.generatePodIDandName(req.GetConfig())
			if err != nil {
				return nil, err
			}
		} else {
			return nil, err
		}
	}

	defer func() {
		if err != nil {
			s.ReleasePodName(name)
		}
	}()

	_, containerName, err := s.generateContainerIDandNameForSandbox(req.GetConfig())
	if err != nil {
		return nil, err
	}

	defer func() {
		if err != nil {
			s.ReleaseContainerName(containerName)
		}
	}()

	podContainer, err := s.StorageRuntimeServer().CreatePodSandbox(s.ImageContext(),
		name, id,
		s.config.PauseImage, "",
		containerName,
		req.GetConfig().GetMetadata().Name,
		req.GetConfig().GetMetadata().Uid,
		namespace,
		attempt,
		nil)
	if errors.Cause(err) == storage.ErrDuplicateName {
		return nil, fmt.Errorf("pod sandbox with name %q already exists", name)
	}
	if err != nil {
		return nil, fmt.Errorf("error creating pod sandbox with name %q: %v", name, err)
	}
	defer func() {
		if err != nil {
			if err2 := s.StorageRuntimeServer().RemovePodSandbox(id); err2 != nil {
				logrus.Warnf("couldn't cleanup pod sandbox %q: %v", id, err2)
			}
		}
	}()

	// TODO: factor generating/updating the spec into something other projects can vendor

	// creates a spec Generator with the default spec.
	g := generate.New()

	// setup defaults for the pod sandbox
	g.SetRootReadonly(true)
	if s.config.PauseCommand == "" {
		if podContainer.Config != nil {
			g.SetProcessArgs(podContainer.Config.Config.Cmd)
		} else {
			g.SetProcessArgs([]string{sandbox.PodInfraCommand})
		}
	} else {
		g.SetProcessArgs([]string{s.config.PauseCommand})
	}

	// set DNS options
	if req.GetConfig().GetDnsConfig() != nil {
		dnsServers := req.GetConfig().GetDnsConfig().Servers
		dnsSearches := req.GetConfig().GetDnsConfig().Searches
		dnsOptions := req.GetConfig().GetDnsConfig().Options
		resolvPath = fmt.Sprintf("%s/resolv.conf", podContainer.RunDir)
		err = parseDNSOptions(dnsServers, dnsSearches, dnsOptions, resolvPath)
		if err != nil {
			err1 := removeFile(resolvPath)
			if err1 != nil {
				err = err1
				return nil, fmt.Errorf("%v; failed to remove %s: %v", err, resolvPath, err1)
			}
			return nil, err
		}
		if err := label.Relabel(resolvPath, mountLabel, true); err != nil && err != unix.ENOTSUP {
			return nil, err
		}

		g.AddBindMount(resolvPath, "/etc/resolv.conf", []string{"ro"})
	}

	// add metadata
	metadata := req.GetConfig().GetMetadata()
	metadataJSON, err := json.Marshal(metadata)
	if err != nil {
		return nil, err
	}

	// add labels
	labels := req.GetConfig().GetLabels()

	// Add special container name label for the infra container
	labelsJSON := []byte{}
	if labels != nil {
		labels[types.KubernetesContainerNameLabel] = leaky.PodInfraContainerName
		labelsJSON, err = json.Marshal(labels)
		if err != nil {
			return nil, err
		}
	}

	// add annotations
	kubeAnnotations := req.GetConfig().GetAnnotations()
	kubeAnnotationsJSON, err := json.Marshal(kubeAnnotations)
	if err != nil {
		return nil, err
	}

	// set log directory
	logDir := req.GetConfig().LogDirectory
	if logDir == "" {
		logDir = filepath.Join(s.config.LogDir, id)
	}
	if err = os.MkdirAll(logDir, 0700); err != nil {
		return nil, err
	}
	// This should always be absolute from k8s.
	if !filepath.IsAbs(logDir) {
		return nil, fmt.Errorf("requested logDir for sbox id %s is a relative path: %s", id, logDir)
	}

	privileged := s.privilegedSandbox(req)

	securityContext := req.GetConfig().GetLinux().GetSecurityContext()
	if securityContext == nil {
		logrus.Warn("no security context found in config.")
	}

	processLabel, mountLabel, err = getSELinuxLabels(securityContext.GetSelinuxOptions(), privileged)
	if err != nil {
		return nil, err
	}

	// Don't use SELinux separation with Host Pid or IPC Namespace or privileged.
	if securityContext.GetNamespaceOptions().GetHostPid() || securityContext.GetNamespaceOptions().GetHostIpc() {
		processLabel, mountLabel = "", ""
	}
	g.SetProcessSelinuxLabel(processLabel)
	g.SetLinuxMountLabel(mountLabel)

	// create shm mount for the pod containers.
	var shmPath string
	if securityContext.GetNamespaceOptions().GetHostIpc() {
		shmPath = "/dev/shm"
	} else {
		shmPath, err = setupShm(podContainer.RunDir, mountLabel)
		if err != nil {
			return nil, err
		}
		defer func() {
			if err != nil {
				if err2 := unix.Unmount(shmPath, unix.MNT_DETACH); err2 != nil {
					logrus.Warnf("failed to unmount shm for pod: %v", err2)
				}
			}
		}()
	}

	err = s.setPodSandboxMountLabel(id, mountLabel)
	if err != nil {
		return nil, err
	}

	if err = s.CtrIDIndex().Add(id); err != nil {
		return nil, err
	}

	defer func() {
		if err != nil {
			if err2 := s.CtrIDIndex().Delete(id); err2 != nil {
				logrus.Warnf("couldn't delete ctr id %s from idIndex", id)
			}
		}
	}()

	// set log path inside log directory
	logPath := filepath.Join(logDir, id+".log")

	// Handle https://issues.k8s.io/44043
	if err := ensureSaneLogPath(logPath); err != nil {
		return nil, err
	}

	hostNetwork := securityContext.GetNamespaceOptions().GetHostNetwork()

	hostname, err := getHostname(id, req.GetConfig().Hostname, hostNetwork)
	if err != nil {
		return nil, err
	}
	g.SetHostname(hostname)

	trusted := s.trustedSandbox(req)
	g.AddAnnotation(annotations.Metadata, string(metadataJSON))
	g.AddAnnotation(annotations.Labels, string(labelsJSON))
	g.AddAnnotation(annotations.Annotations, string(kubeAnnotationsJSON))
	g.AddAnnotation(annotations.LogPath, logPath)
	g.AddAnnotation(annotations.Name, name)
	g.AddAnnotation(annotations.ContainerType, annotations.ContainerTypeSandbox)
	g.AddAnnotation(annotations.SandboxID, id)
	g.AddAnnotation(annotations.ContainerName, containerName)
	g.AddAnnotation(annotations.ContainerID, id)
	g.AddAnnotation(annotations.ShmPath, shmPath)
	g.AddAnnotation(annotations.PrivilegedRuntime, fmt.Sprintf("%v", privileged))
	g.AddAnnotation(annotations.TrustedSandbox, fmt.Sprintf("%v", trusted))
	g.AddAnnotation(annotations.ResolvPath, resolvPath)
	g.AddAnnotation(annotations.HostName, hostname)
	g.AddAnnotation(annotations.KubeName, kubeName)
	if podContainer.Config.Config.StopSignal != "" {
		// this key is defined in image-spec conversion document at https://github.com/opencontainers/image-spec/pull/492/files#diff-8aafbe2c3690162540381b8cdb157112R57
		g.AddAnnotation("org.opencontainers.image.stopSignal", podContainer.Config.Config.StopSignal)
	}

	created := time.Now()
	g.AddAnnotation(annotations.Created, created.Format(time.RFC3339Nano))

	portMappings := convertPortMappings(req.GetConfig().GetPortMappings())

	// setup cgroup settings
	cgroupParent := req.GetConfig().GetLinux().GetCgroupParent()
	if cgroupParent != "" {
		if s.config.CgroupManager == oci.SystemdCgroupsManager {
			if len(cgroupParent) <= 6 || !strings.HasSuffix(path.Base(cgroupParent), ".slice") {
				return nil, fmt.Errorf("cri-o configured with systemd cgroup manager, but did not receive slice as parent: %s", cgroupParent)
			}
			cgPath, err := convertCgroupFsNameToSystemd(cgroupParent)
			if err != nil {
				return nil, err
			}
			g.SetLinuxCgroupsPath(cgPath + ":" + "crio" + ":" + id)
			cgroupParent = cgPath
		} else {
			if strings.HasSuffix(path.Base(cgroupParent), ".slice") {
				return nil, fmt.Errorf("cri-o configured with cgroupfs cgroup manager, but received systemd slice as parent: %s", cgroupParent)
			}
			cgPath := filepath.Join(cgroupParent, scopePrefix+"-"+id)
			g.SetLinuxCgroupsPath(cgPath)
		}
	}

	sb, err := sandbox.New(id, namespace, name, kubeName, logDir, labels, kubeAnnotations, processLabel, mountLabel, metadata, shmPath, cgroupParent, privileged, trusted, resolvPath, hostname, portMappings)
	if err != nil {
		return nil, err
	}

	s.addSandbox(sb)
	defer func() {
		if err != nil {
			s.removeSandbox(id)
		}
	}()

	if err = s.PodIDIndex().Add(id); err != nil {
		return nil, err
	}

	defer func() {
		if err != nil {
			if err := s.PodIDIndex().Delete(id); err != nil {
				logrus.Warnf("couldn't delete pod id %s from idIndex", id)
			}
		}
	}()

	for k, v := range kubeAnnotations {
		g.AddAnnotation(k, v)
	}
	for k, v := range labels {
		g.AddAnnotation(k, v)
	}

	// extract linux sysctls from annotations and pass down to oci runtime
	safe, unsafe, err := SysctlsFromPodAnnotations(kubeAnnotations)
	if err != nil {
		return nil, err
	}
	for _, sysctl := range safe {
		g.AddLinuxSysctl(sysctl.Name, sysctl.Value)
	}
	for _, sysctl := range unsafe {
		g.AddLinuxSysctl(sysctl.Name, sysctl.Value)
	}

	// Set OOM score adjust of the infra container to be very low
	// so it doesn't get killed.
	g.SetProcessOOMScoreAdj(PodInfraOOMAdj)

	g.SetLinuxResourcesCPUShares(PodInfraCPUshares)

	// set up namespaces
	if hostNetwork {
		err = g.RemoveLinuxNamespace(string(runtimespec.NetworkNamespace))
		if err != nil {
			return nil, err
		}
	} else {
		// Create the sandbox network namespace
		if err = sb.NetNsCreate(); err != nil {
			return nil, err
		}

		defer func() {
			if err == nil {
				return
			}

			if netnsErr := sb.NetNsRemove(); netnsErr != nil {
				logrus.Warnf("Failed to remove networking namespace: %v", netnsErr)
			}
		}()

		// Pass the created namespace path to the runtime
		err = g.AddOrReplaceLinuxNamespace(string(runtimespec.NetworkNamespace), sb.NetNsPath())
		if err != nil {
			return nil, err
		}
	}

	if securityContext.GetNamespaceOptions().GetHostPid() {
		err = g.RemoveLinuxNamespace(string(runtimespec.PIDNamespace))
		if err != nil {
			return nil, err
		}
	}

	if securityContext.GetNamespaceOptions().GetHostIpc() {
		err = g.RemoveLinuxNamespace(string(runtimespec.IPCNamespace))
		if err != nil {
			return nil, err
		}
	}

	if !s.seccompEnabled {
		g.Spec().Linux.Seccomp = nil
	}

	saveOptions := generate.ExportOptions{}
	mountPoint, err := s.StorageRuntimeServer().StartContainer(id)
	if err != nil {
		return nil, fmt.Errorf("failed to mount container %s in pod sandbox %s(%s): %v", containerName, sb.Name(), id, err)
	}
	g.AddAnnotation(annotations.MountPoint, mountPoint)
	g.SetRootPath(mountPoint)

	hostnamePath := fmt.Sprintf("%s/hostname", podContainer.RunDir)
	if err := ioutil.WriteFile(hostnamePath, []byte(hostname+"\n"), 0644); err != nil {
		return nil, err
	}
	if err := label.Relabel(hostnamePath, mountLabel, true); err != nil && err != unix.ENOTSUP {
		return nil, err
	}
	g.AddBindMount(hostnamePath, "/etc/hostname", []string{"ro"})
	g.AddAnnotation(annotations.HostnamePath, hostnamePath)
	sb.AddHostnamePath(hostnamePath)

	container, err := oci.NewContainer(id, containerName, podContainer.RunDir, logPath, sb.NetNs(), labels, g.Spec().Annotations, kubeAnnotations, "", "", "", nil, id, false, false, false, sb.Privileged(), sb.Trusted(), podContainer.Dir, created, podContainer.Config.Config.StopSignal)
	if err != nil {
		return nil, err
	}
	container.SetSpec(g.Spec())
	container.SetMountPoint(mountPoint)

	sb.SetInfraContainer(container)

	var ip string
	ip, err = s.networkStart(hostNetwork, sb)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			s.networkStop(hostNetwork, sb)
		}
	}()

	g.AddAnnotation(annotations.IP, ip)
	sb.AddIP(ip)

	err = g.SaveToFile(filepath.Join(podContainer.Dir, "config.json"), saveOptions)
	if err != nil {
		return nil, fmt.Errorf("failed to save template configuration for pod sandbox %s(%s): %v", sb.Name(), id, err)
	}
	if err = g.SaveToFile(filepath.Join(podContainer.RunDir, "config.json"), saveOptions); err != nil {
		return nil, fmt.Errorf("failed to write runtime configuration for pod sandbox %s(%s): %v", sb.Name(), id, err)
	}

	if err = s.runContainer(container, sb.CgroupParent()); err != nil {
		return nil, err
	}

	s.addInfraContainer(container)

	s.ContainerStateToDisk(container)

	resp = &pb.RunPodSandboxResponse{PodSandboxId: id}
	logrus.Debugf("RunPodSandboxResponse: %+v", resp)
	return resp, nil
}

func convertPortMappings(in []*pb.PortMapping) []*hostport.PortMapping {
	if in == nil {
		return nil
	}
	out := make([]*hostport.PortMapping, len(in))
	for i, v := range in {
		out[i] = &hostport.PortMapping{
			HostPort:      v.HostPort,
			ContainerPort: v.ContainerPort,
			Protocol:      v1.Protocol(v.Protocol.String()),
			HostIP:        v.HostIp,
		}
	}
	return out
}

func getHostname(id, hostname string, hostNetwork bool) (string, error) {
	if hostNetwork {
		if hostname == "" {
			h, err := os.Hostname()
			if err != nil {
				return "", err
			}
			hostname = h
		}
	} else {
		if hostname == "" {
			hostname = id[:12]
		}
	}
	return hostname, nil
}

func (s *Server) setPodSandboxMountLabel(id, mountLabel string) error {
	storageMetadata, err := s.StorageRuntimeServer().GetContainerMetadata(id)
	if err != nil {
		return err
	}
	storageMetadata.SetMountLabel(mountLabel)
	return s.StorageRuntimeServer().SetContainerMetadata(id, storageMetadata)
}

func getSELinuxLabels(selinuxOptions *pb.SELinuxOption, privileged bool) (processLabel string, mountLabel string, err error) {
	if privileged {
		return "", "", nil
	}
	labels := []string{}
	if selinuxOptions != nil {
		if selinuxOptions.User != "" {
			labels = append(labels, "user:"+selinuxOptions.User)
		}
		if selinuxOptions.Role != "" {
			labels = append(labels, "role:"+selinuxOptions.Role)
		}
		if selinuxOptions.Type != "" {
			labels = append(labels, "type:"+selinuxOptions.Type)
		}
		if selinuxOptions.Level != "" {
			labels = append(labels, "level:"+selinuxOptions.Level)
		}
	}
	return label.InitLabels(labels)
}

func setupShm(podSandboxRunDir, mountLabel string) (shmPath string, err error) {
	shmPath = filepath.Join(podSandboxRunDir, "shm")
	if err = os.Mkdir(shmPath, 0700); err != nil {
		return "", err
	}
	shmOptions := "mode=1777,size=" + strconv.Itoa(sandbox.DefaultShmSize)
	if err = unix.Mount("shm", shmPath, "tmpfs", unix.MS_NOEXEC|unix.MS_NOSUID|unix.MS_NODEV,
		label.FormatMountLabel(shmOptions, mountLabel)); err != nil {
		return "", fmt.Errorf("failed to mount shm tmpfs for pod: %v", err)
	}
	return shmPath, nil
}

// convertCgroupFsNameToSystemd converts an expanded cgroupfs name to its systemd name.
// For example, it will convert test.slice/test-a.slice/test-a-b.slice to become test-a-b.slice
// NOTE: this is public right now to allow its usage in dockermanager and dockershim, ideally both those
// code areas could use something from libcontainer if we get this style function upstream.
func convertCgroupFsNameToSystemd(cgroupfsName string) (string, error) {
	// TODO: see if libcontainer systemd implementation could use something similar, and if so, move
	// this function up to that library.  At that time, it would most likely do validation specific to systemd
	// above and beyond the simple assumption here that the base of the path encodes the hierarchy
	// per systemd convention.
	return path.Base(cgroupfsName), nil
}


text:
layout: post
title: ASM——Java 字节码操控框架
categories: Java
description: Java 字节码操控框架。
keywords: ASM
---

jdk中的proxy必须基于接口,封装了asm的cglib没有这种限制。

## 关于ASM

ASM是一个Java字节码操纵框架,它能被用来动态生成类或者增强既有类的功能。ASM可以直接产生二进制class文件,也可以在类被加载入Java虚拟机之前动态改变类行为。

AOP一种较好的实现方式就是修改class文件织入逻辑,cglib正是通过ASM实现动态代理。 若想直接在字节码中增加内容,要对class文件结构和Java字节码有一定的了解,如方法和字段的描述符。(若要用复杂的逻辑需要ASM-Bytecode工具,会直接生成ASM代码)

| 标示字符                      | 含义                                |
|:--------------------------|:--------------------------------------|
| B  | 基本类型byte  |
| C  | 基本类型char  |
| I  | 基本类型int  |
| J  | 基本类型long  |
| Z  | 基本类型boolean |
| V  | 特殊类型void |
| L  | 对象类型,如Ljava/lang/String |

idea可以直接查看每个类的字节码。

![](/images/posts/java/ASM-bytecode.jpeg)

##  demo
demo用ASM实现删除类中的方法、改变类中的方法、加入aop

#### 原始的类:

```java
public class SrcClass {
	//要删除的方法
    public void change1() {
        System.out.println("i am change-one!");
    }

    public void change2() {
        System.out.println("i am change-two");
    }
}
```

#### 方法中要增加的逻辑
```java
System.out.println("i am new");
```

#### 要加载的aop方法

```java
public class AopContent {

    public static void content(){
        System.out.println("i am aop");
    }
}
```
最后相当于要把SrcClass变成

```java
public class SrcClass {
    public void change2() {
        System.out.println("i am new");
        System.out.println("i am aop");
        System.out.println("i am change-two");
    }
}
```

#### 安插 Aop、删除方法和修改方法的ASM代码

```java
public class AopMethodVisitor extends MethodVisitor implements Opcodes {

    public AopMethodVisitor(int i, MethodVisitor methodVisitor) {
        super(i, methodVisitor);
    }

    @Override
    public void visitCode() {
        super.visitCode();
        this.visitMethodInsn(INVOKESTATIC, "cn/qs/asm/AopContent", "content", "()V", false);
    }
}
```

```java
class DemoVisitor extends ClassVisitor implements Opcodes {

    public DemoVisitor(int api, ClassVisitor cv) {
        super(api, cv);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        if (name.equals("change1")) {
            return null;
        }
        MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
        if (name.equals("change2")) {
            mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
            mv.visitLdcInsn("i am new");
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V",false);
            return new AopMethodVisitor(this.api, mv);
        }
        return mv;
    }
}
```

#### ASM改写Java类

```java
public class App extends ClassLoader implements Opcodes {
    public static void main(String[] args) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        ClassReader cr=new ClassReader(SrcClass.class.getName());
        ClassWriter cw=new ClassWriter(ClassWriter.COMPUTE_MAXS);
        DemoVisitor myv=new DemoVisitor(Opcodes.ASM4,cw);
        cr.accept(myv, 0);

        byte[] code=cw.toByteArray();

        //自定义加载器
        App loader=new App();
        Class<?> appClass=loader.defineClass(null, code, 0,code.length);
        appClass.getMethods()[0].invoke(appClass.newInstance(), new Object[]{});
        Method[] methodArray = appClass.getMethods();
    }
```

最后输出结果:

```
 i am new
 i am aop
 i am change-two

```
同时查看methodArray中已经没有方法change1

![](/images/posts/java/ASM-method.jpeg)


text:
COD05 es una plataforma experimental para programar en tiempo real el comportamiento de un sistema de particulas a travez de captura de movimiento. Es un experimento que busca explorar la idea de una fusión entre Live Coding y Danza.

# requerimientos
Processing 2 (3 aun en prueba) (esto con link)
Driver de Kinect
 - Win : Microsoft Kinect SDK (link)
 - Linux : OpenNI v2 o algo (link)
 - Mac : creo que OpenNI tambien? (link)

# como instalar Kinect
## Win
seguir este tutorial -> (link a tutorial)
resumen(...)

## Linux
seguir este tutorial -> (link a tutorial)
resumen(...)

## Mac
seguir este tutorial -> (link a tutorial)
resumen(...)


text:
namespace BooCompiler.Tests.SupportingClasses
{
	public class NoParameterlessConstructor
	{
		public NoParameterlessConstructor(object param)
		{
		}
	}
}


text:
using BepuUtilities.Collections;
using BepuPhysics;
using BepuPhysics.Constraints;
using System.Numerics;
using BepuUtilities;

namespace DemoRenderer.Constraints
{
    struct BallSocketMotorLineExtractor : IConstraintLineExtractor<BallSocketMotorPrestepData>
    {
        public int LinesPerConstraint => 2;

        public unsafe void ExtractLines(ref BallSocketMotorPrestepData prestepBundle, int setIndex, int* bodyIndices,
            Bodies bodies, ref Vector3 tint, ref QuickList<LineInstance> lines)
        {
            //Could do bundles of constraints at a time, but eh.
            ref var poseA = ref bodies.Sets[setIndex].DynamicsState[bodyIndices[0]].Motion.Pose;
            ref var poseB = ref bodies.Sets[setIndex].DynamicsState[bodyIndices[1]].Motion.Pose;
            Vector3Wide.ReadFirst(prestepBundle.LocalOffsetB, out var localOffsetB);
            QuaternionEx.Transform(localOffsetB, poseB.Orientation, out var worldOffsetB);
            var anchor = poseB.Position + worldOffsetB;
            var color = new Vector3(0.2f, 0.2f, 1f) * tint;
            var packedColor = Helpers.PackColor(color);
            var backgroundColor = new Vector3(0f, 0f, 1f) * tint;
            lines.AllocateUnsafely() = new LineInstance(poseA.Position, anchor, packedColor, 0);
            lines.AllocateUnsafely() = new LineInstance(poseB.Position, anchor, packedColor, 0);
        }
    }
}


text:
require 'puppet/provider/package'
require 'set'
require 'uri'

Puppet::Type.type(:package).provide :pacman, :parent => Puppet::Provider::Package do
  desc "Support for the Package Manager Utility (pacman) used in Archlinux.

  This provider supports the `install_options` attribute, which allows command-line flags to be passed to pacman.
  These options should be specified as a string (e.g. '--flag'), a hash (e.g. {'--flag' => 'value'}),
  or an array where each element is either a string or a hash."

  commands :pacman => "/usr/bin/pacman"
  # Yaourt is a common AUR helper which, if installed, we can use to query the AUR
  commands :yaourt => "/usr/bin/yaourt" if Puppet::FileSystem.exist? '/usr/bin/yaourt'

  confine     :operatingsystem => :archlinux
  defaultfor  :operatingsystem => :archlinux
  has_feature :install_options
  has_feature :uninstall_options
  has_feature :upgradeable

  # If yaourt is installed, we can make use of it
  def yaourt?
    return Puppet::FileSystem.exist?('/usr/bin/yaourt')
  end

  # Install a package using 'pacman', or 'yaourt' if available.
  # Installs quietly, without confirmation or progressbar, updates package
  # list from servers defined in pacman.conf.
  def install
    if @resource[:source]
      install_from_file
    else
      install_from_repo
    end

    unless self.query
      raise Puppet::ExecutionFailure.new("Could not find package %s" % self.name)
    end
  end

  def install_from_repo
    if yaourt?
      cmd = %w{--noconfirm}
      cmd += install_options if @resource[:install_options]
      cmd << "-S" << @resource[:name]
      yaourt *cmd
    else
      cmd = %w{--noconfirm --noprogressbar}
      cmd += install_options if @resource[:install_options]
      cmd << "-Sy" << @resource[:name]
      pacman *cmd
    end
  end
  private :install_from_repo

  def install_from_file
    source = @resource[:source]
    begin
      source_uri = URI.parse source
    rescue => detail
      self.fail Puppet::Error, "Invalid source '#{source}': #{detail}", detail
    end

    source = case source_uri.scheme
    when nil then source
    when /https?/i then source
    when /ftp/i then source
    when /file/i then source_uri.path
    when /puppet/i
      fail "puppet:// URL is not supported by pacman"
    else
      fail "Source #{source} is not supported by pacman"
    end
    pacman "--noconfirm", "--noprogressbar", "-Sy"
    pacman "--noconfirm", "--noprogressbar", "-U", source
  end
  private :install_from_file

  def self.listcmd
    [command(:pacman), "-Q"]
  end

  # Pacman has a concept of package groups as well.
  # Package groups have no versions.
  def self.listgroupcmd
    [command(:pacman), "-Qg"]
  end

  # Get installed packages (pacman -Q)
  def self.installedpkgs
    packages = []
    begin
      execpipe(listcmd()) do |process|
        # pacman -Q output is 'packagename version-rel'
        regex = %r{^(\S+)\s(\S+)}
        fields = [:name, :ensure]
        hash = {}

        process.each_line { |line|
          if match = regex.match(line)
            fields.zip(match.captures) { |field,value|
              hash[field] = value
            }

            hash[:provider] = self.name

            packages << new(hash)

            hash = {}
          else
            warning("Failed to match line %s" % line)
          end
        }
      end
    rescue Puppet::ExecutionFailure
      return nil
    end
    packages
  end

  # Get installed groups (pacman -Qg)
  def self.installedgroups
    packages = []
    begin
      execpipe(listgroupcmd()) do |process|
        # pacman -Qg output is 'groupname packagename'
        # Groups need to be deduplicated
        groups = Set[]

        process.each_line { |line|
          groups.add(line.split[0])
        }

        groups.each { |line|
          hash = {
            :name   => line,
            :ensure => "1", # Groups don't have versions, so ensure => latest
                            # will still cause a reinstall.
            :provider => self.name
          }
          packages << new(hash)
        }
      end
    rescue Puppet::ExecutionFailure
      return nil
    end
    packages
  end

  # Fetch the list of packages currently installed on the system.
  def self.instances
    packages = self.installedpkgs
    groups   = self.installedgroups
    result   = nil

    if (!packages && !groups)
      nil
    elsif (packages && groups)
      packages.concat(groups)
    else
      packages
    end
  end

  # Because Archlinux is a rolling release based distro, installing a package
  # should always result in the newest release.
  def update
    # Install in pacman can be used for update, too
    self.install
  end

  # We rescue the main check from Pacman with a check on the AUR using yaourt, if installed
  def latest
    pacman "-Sy"
    pacman_check = true   # Query the main repos first
    begin
      if pacman_check
        output = pacman "-Sp", "--print-format", "%v", @resource[:name]
        return output.chomp
      else
        output = yaourt "-Qma", @resource[:name]
        output.split("\n").each do |line|
          return line.split[1].chomp if line =~ /^aur/
        end
      end
    rescue Puppet::ExecutionFailure
      if pacman_check and self.yaourt?
        pacman_check = false # now try the AUR
        retry
      else
        raise
      end
    end
  end

  # Querys the pacman master list for information about the package.
  def query
    begin
      output = pacman("-Qi", @resource[:name])

      if output =~ /Version.*:\s(.+)/
        return { :ensure => $1 }
      end
    rescue Puppet::ExecutionFailure
      return {
        :ensure => :purged,
        :status => 'missing',
        :name => @resource[:name],
        :error => 'ok',
      }
    end
    nil
  end

  # Removes a package from the system.
  def uninstall
    cmd = %w{--noconfirm --noprogressbar}
    cmd += uninstall_options if @resource[:uninstall_options]
    cmd << "-R" << @resource[:name]
    pacman *cmd
  end

  private

  def install_options
    join_options(@resource[:install_options])
  end

  def uninstall_options
    join_options(@resource[:uninstall_options])
  end
end


text:
/*********************************************************************
 *  The following code is part of the power modelling feature of VTR.
 *
 * For support:
 * http://code.google.com/p/vtr-verilog-to-routing/wiki/Power
 *
 * or email:
 * vtr.power.estimation@gmail.com
 *
 * If you are using power estimation for your researach please cite:
 *
 * Jeffrey Goeders and Steven Wilton.  VersaPower: Power Estimation
 * for Diverse FPGA Architectures.  In International Conference on
 * Field Programmable Technology, 2012.
 *
 ********************************************************************/

/**
 * This file provides functions relating to the cmos technology.  It
 * includes functions to read the transistor characteristics from the
 * xml file into data structures, and functions to search within
 * these data structures.
 */

#ifndef __POWER_CMOS_TECH_H__
#define __POWER_CMOS_TECH_H__

/************************* INCLUDES *********************************/
#include "power.h"

/************************* FUNCTION DECLARATIONS ********************/
void power_tech_init(char * cmos_tech_behavior_filepath);
bool power_find_transistor_info(t_transistor_size_inf ** lower,
		t_transistor_size_inf ** upper, e_tx_type type, float size);
void power_find_mux_volt_inf(t_power_mux_volt_pair ** lower,
		t_power_mux_volt_pair ** upper, t_power_mux_volt_inf * volt_inf,
		float v_in);
void power_find_nmos_leakage(t_power_nmos_leakage_inf * nmos_leakage_info,
		t_power_nmos_leakage_pair ** lower, t_power_nmos_leakage_pair ** upper,
		float v_ds);
void power_find_buffer_strength_inf(t_power_buffer_strength_inf ** lower,
		t_power_buffer_strength_inf ** upper,
		t_power_buffer_size_inf * size_inf, float stage_gain);
void power_find_buffer_sc_levr(t_power_buffer_sc_levr_inf ** lower,
		t_power_buffer_sc_levr_inf ** upper,
		t_power_buffer_strength_inf * buffer_sc, int input_mux_size);
#endif


text:
package vellum.data;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author evan.summers
 */
public class QueueMap<K, V> extends HashMap<K, V> {
    int capacity;
    Queue<K> keyQueue = new LinkedList();

    public QueueMap(int capacity) {
        this.capacity = capacity;
    }

    public V put(K key, V value) {
        while (size() >= capacity) {
            super.remove(keyQueue.remove());
        }
        keyQueue.add(key);
        return super.put(key, value);
    }

}


text:
<template name="search">
	<form class="navbar-form navbar-left" role="search">

				<input type="text" class="form-control" placeholder="Search">

					<button type="button" class="btn btn-default" title="Search" data-toggle="tooltip" data-placement="bottom">

					</button>

	</form>
</template>


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

namespace Seel3d.Human3d
{
    public enum Sexe
    {
        Man,
        Woman
    }
}


text:
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { ApiRequestStatus } from '../../../../../framework/client/rpc';
import { HomescreenStyle } from '../../../constants';
import { AppSidebar, BuildSettings } from '../../../interfaces';
import { cloneDeep } from '../../../util';

@Component({
  selector: 'rcc-app-sidebar-form',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: 'sidebar-form.component.html',
})
export class SidebarFormComponent {
  @Input() status: ApiRequestStatus;
  @Input() buildSettings: BuildSettings;
  @Input() homescreenStyles: HomescreenStyle[];
  @Output() save = new EventEmitter<AppSidebar>();
  FOOTER_ALIGNMENTS = [ 'normal', 'bottom' ];

  private _sidebar: AppSidebar;

  get sidebar() {
    return this._sidebar;
  }

  @Input() set sidebar(value: AppSidebar) {
    this._sidebar = cloneDeep(value);
  }

  is3x3() {
    return this.sidebar.style === '3x3';
  }

  submit() {
    this.save.emit(this.sidebar);
  }
}


text:
using System;
using Newtonsoft.Json;
using log4net;
using log4net.Config;
using System.Collections.Generic;

namespace Fleep.TypeClasses
{
    [JsonObject(MemberSerialization.OptOut)]
    public class FileInfoList : FleepTypeBase
    {
        public List<FileInfo> files { get; set; }
    }
}


text:
/**
 * To mock jest test
 */
module.exports = "test-file-stub";