text:
<?php

require_once 'Swift/CharacterReader/Utf8Reader.php';

class Swift_CharacterReader_Utf8ReaderTest
  extends UnitTestCase
{

  private $_reader;

  public function setUp()
  {
    $this->_reader = new Swift_CharacterReader_Utf8Reader();
  }

  public function testLeading7BitOctetCausesReturnZero()
  {
    for ($ordinal = 0x00; $ordinal <= 0x7F; ++$ordinal)
    {
      $this->assertIdentical(
        0, $this->_reader->validateByteSequence(array($ordinal), 1)
        );
    }
  }

  public function testLeadingByteOf2OctetCharCausesReturn1()
  {
    for ($octet = 0xC0; $octet <= 0xDF; ++$octet)
    {
      $this->assertIdentical(
        1, $this->_reader->validateByteSequence(array($octet), 1)
        );
    }
  }

  public function testLeadingByteOf3OctetCharCausesReturn2()
  {
    for ($octet = 0xE0; $octet <= 0xEF; ++$octet)
    {
      $this->assertIdentical(
        2, $this->_reader->validateByteSequence(array($octet), 1)
        );
    }
  }

  public function testLeadingByteOf4OctetCharCausesReturn3()
  {
    for ($octet = 0xF0; $octet <= 0xF7; ++$octet)
    {
      $this->assertIdentical(
        3, $this->_reader->validateByteSequence(array($octet), 1)
        );
    }
  }

  public function testLeadingByteOf5OctetCharCausesReturn4()
  {
    for ($octet = 0xF8; $octet <= 0xFB; ++$octet)
    {
      $this->assertIdentical(
        4, $this->_reader->validateByteSequence(array($octet),1)
        );
    }
  }

  public function testLeadingByteOf6OctetCharCausesReturn5()
  {
    for ($octet = 0xFC; $octet <= 0xFD; ++$octet)
    {
      $this->assertIdentical(
        5, $this->_reader->validateByteSequence(array($octet),1)
        );
    }
  }

}


text:
<?php
include 'tm.php';
include 'Utils/MetaProcessor.php';
include 'Algorithms/Base.php';

/* Surely, this piece of code is not a complete quine in PHP Turing Machine Code Generator.
   I guess that I got my grade by simply explaining how this thing works, thus lost the interest
   (because, well, it really works, which is amusing). But now that I shed a manly tear, I want
   to finish this quine meta-programm as a hat-tip to the school days. */

$seek = B::SeekForChar(-1, 1, '!', 'HALT');
$move = B::Move(1, 11, $seek);

//

$start = "TM::q0('$move');\n";
file_put_contents('Quine.tm.php', MP::$b."$start?>");
?>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>bb.component Demo</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
	 crossorigin="anonymous">

Building Blocks. Component. Demo

Repository

Documentation

Custom form element

		<form>
			<my-field-element class="form-control" label="My field" type="text"></my-field-element>
		</form>

Adding features

		<form>
			<my-field-clear-element class="form-control" label="My field with clear" type="text" value="some value"></my-field-clear-element>
		</form>

Extending native elements

		<form>

				<button type="button" is="my-custom-button" class="btn btn-primary">Toggle loading</button>

		</form>

Handle attributes

		<form class="well">
			<my-mixed-element class="form-control" label="With validation and clear" type="text" id="element">

			</my-mixed-element>

			<button id="change" class="btn btn-default">Set some value</button>

				Existing field can use validation too
				<input type="text" class="form-control">

		</form>


text:
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');

class Tickets_Admin_Page_Init extends EE_Admin_Page_Init  {

	/**
	 * 		constructor
	 * 		@Constructor
	 * 		@access public
	 * 		@return void
	 */
	public function __construct() {

		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );

		define( 'TICKETS_PG_SLUG', 'tickets' );
		define( 'TICKETS_LABEL', __('Default Tickets', 'event_espresso'));
		define( 'TICKETS_ADMIN', EE_CORE_CAF_ADMIN . 'new' . DS . TICKETS_PG_SLUG . DS );
		define( 'TICKETS_ADMIN_URL', admin_url( 'admin.php?page=' . TICKETS_PG_SLUG ));
		define( 'TICKETS_ASSETS_PATH', TICKETS_ADMIN . 'assets' . DS );
		define( 'TICKETS_ASSETS_URL', EE_CORE_CAF_ADMIN_URL . 'new' . DS . TICKETS_PG_SLUG .'/assets/' );
		define( 'TICKETS_TEMPLATE_PATH', TICKETS_ADMIN . 'templates' . DS );
		define( 'TICKETS_TEMPLATE_URL', EE_CORE_CAF_ADMIN_URL . 'new' . DS . TICKETS_PG_SLUG . DS . 'templates/' );

		parent::__construct();
		$this->_folder_path = EE_CORE_CAF_ADMIN . 'new' . DS . $this->_folder_name . DS;

	}

	protected function _set_init_properties() {
		$this->label = TICKETS_LABEL;
	}

	protected function _set_menu_map() {
		$this->_menu_map = new EE_Admin_Page_Sub_Menu( array(
			'menu_group' => 'management',
			'menu_order' => 15,
			'show_on_menu' => EE_Admin_Page_Menu_Map::BLOG_ADMIN_ONLY,
			'parent_slug' => 'espresso_events',
			'menu_slug' => TICKETS_PG_SLUG,
			'menu_label' => TICKETS_LABEL,
			'capability' => 'ee_read_default_tickets',
			'admin_init_page' => $this
			));
	}
}
// end of file:	caffeinated/admin/new/tickets/Tickets_Admin_Page_Init.core.php


text:
//TODO: WE NEED TO CONVERT ALL OF THESE METHODS TO PROXY TO OUR APPLICATION SINCE MANY CUSTOM APPS USE THIS!

Umbraco.Sys.registerNamespace("Umbraco.Application");

(function($) {
    Umbraco.Application.ClientManager = function() {

        /**
         * @ngdoc function
         * @name getRootScope
         * @methodOf UmbClientMgr
         * @function
         *
         * @description
         * Returns the root angular scope
         */
        function getRootScope() {
            return angular.element(document.getElementById("umbracoMainPageBody")).scope();
        }

        /**
         * @ngdoc function
         * @name getRootInjector
         * @methodOf UmbClientMgr
         * @function
         *
         * @description
         * Returns the root angular injector
         */
        function getRootInjector() {
            return angular.element(document.getElementById("umbracoMainPageBody")).injector();
        }

        return {
            _isDirty: false,
            _isDebug: false,
            _mainTree: null,
            _appActions: null,
            _historyMgr: null,
            _rootPath: "/umbraco", //this is the default
            _modal: new Array(), //track all modal window objects (they get stacked)

            historyManager: function () {

                throw "Not implemented!";

                //if (!this._historyMgr) {
                //    this._historyMgr = new Umbraco.Controls.HistoryManager();
                //}
                //return this._historyMgr;
            },

            setUmbracoPath: function(strPath) {
                /// <summary>
                /// sets the Umbraco root path folder
                /// </summary>
                this._debug("setUmbracoPath: " + strPath);
                this._rootPath = strPath;
            },

            mainWindow: function() {
                return top;
            },
            mainTree: function() {

                throw "Not implemented!";

                //if (this._mainTree == null) {
                //    if (this.mainWindow().jQuery == null
                //        || this.mainWindow().jQuery(".umbTree").length == 0
                //        || this.mainWindow().jQuery(".umbTree").UmbracoTreeAPI() == null) {
                //        //creates a false tree with all the public tree params set to a false method.
                //        var tmpTree = {};
                //        var treeProps = ["init", "setRecycleBinNodeId", "clearTreeCache", "toggleEditMode", "refreshTree", "rebuildTree", "saveTreeState", "syncTree", "childNodeCreated", "moveNode", "copyNode", "findNode", "selectNode", "reloadActionNode", "getActionNode", "setActiveTreeType", "getNodeDef"];
                //        for (var p in treeProps) {
                //            tmpTree[treeProps[p]] = function() { return false; };
                //        }
                //        this._mainTree = tmpTree;
                //    }
                //    else {
                //        this._mainTree = this.mainWindow().jQuery(".umbTree").UmbracoTreeAPI();
                //    }
                //}
                //return this._mainTree;
            },
            appActions: function() {

                throw "Not implemented!";

                ////if the main window has no actions, we'll create some
                //if (this._appActions == null) {
                //    if (typeof this.mainWindow().appActions == 'undefined') {
                //        this._appActions = new Umbraco.Application.Actions();
                //    }
                //    else this._appActions = this.mainWindow().appActions;
                //}
                //return this._appActions;
            },
            uiKeys: function() {

                throw "Not implemented!";

                ////TODO: If there is no main window, we need to go retrieve the appActions from the server!
                //return this.mainWindow().uiKeys;
            },
            contentFrameAndSection: function(app, rightFrameUrl) {

                throw "Not implemented!";

                ////this.appActions().shiftApp(app, this.uiKeys()['sections_' + app]);
                //var self = this;
                //self.mainWindow().UmbClientMgr.historyManager().addHistory(app, true);
                //window.setTimeout(function() {
                //    self.mainWindow().UmbClientMgr.contentFrame(rightFrameUrl);
                //}, 200);
            },

            /**
             * @ngdoc function
             * @name contentFrame
             * @methodOf UmbClientMgr
             * @function
             *
             * @description
             * This will tell our angular app to create and load in an iframe at the specified location
             * @param strLocation {String} The URL to load the iframe in
             */
            contentFrame: function (strLocation) {

                if (!strLocation || strLocation == "") {
                    //SD: NOTE: We used to return the content iframe object but now I'm not sure we should do that ?!

                    if (typeof top.right != "undefined") {
                        return top.right;
                    }
                    else {
                        return top; //return the current window if the content frame doesn't exist in the current context
                    }
                    //return;
                }

                this._debug("contentFrame: " + strLocation);

                //get our angular navigation service
                var injector = getRootInjector();
                var navService = injector.get("navigationService");

                //if the path doesn't start with "/" or with the root path then
                //prepend the root path
                if (!strLocation.startsWith("/")) {
                    strLocation = this._rootPath + "/" + strLocation;
                }
                else if (strLocation.length >= this._rootPath.length
                    && strLocation.substr(0, this._rootPath.length) != this._rootPath) {
                    strLocation = this._rootPath + "/" + strLocation;
                }

                navService.loadLegacyIFrame(strLocation);

            },
            openModalWindow: function(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback) {
                //need to create the modal on the top window if the top window has a client manager, if not, create it on the current window

                //get our angular navigation service
                var injector = getRootInjector();
                var dialogService = injector.get("dialogService");

                var dialog = dialogService.open({
                    template: url,
                    width: width,
                    height: height,
                    iframe: true,
                    show: true,
                    callback: function (result) {
                        dialog.hide();
                    }
                });

               // var m = new Umbraco.Controls.ModalWindow();
               // this._modal.push(m);
               // m.open(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback);

                //throw "Not implemented!";

                ////if this is the top window, or if the top window doesn't have a client manager, create the modal in this manager
                //if (window == this.mainWindow() || !this.mainWindow().UmbClientMgr) {
                //    var m = new Umbraco.Controls.ModalWindow();
                //    this._modal.push(m);
                //    m.open(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback);
                //}
                //else {
                //    //if the main window has a client manager, then call the main window's open modal method whilst keeping the context of it's manager.
                //    if (this.mainWindow().UmbClientMgr) {
                //        this.mainWindow().UmbClientMgr.openModalWindow.apply(this.mainWindow().UmbClientMgr,
                //            [url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback]);
                //    }
                //    else {
                //        return; //exit recurse.
                //    }
                //}
            },
            closeModalWindow: function(rVal) {

                getRootScope().$emit("closeDialogs");

                //if (this._modal != null && this._modal.length > 0) {
                //    this._modal.pop().close(rVal);
                //}
                //else {
                //    //this will recursively try to close a modal window until the parent window has a modal object or the window is the top and has the modal object
                //    var mgr = null;
                //    if (window.parent == null || window.parent == window) {
                //        //we are at the root window, check if we can close the modal window from here
                //        if (window.UmbClientMgr != null && window.UmbClientMgr._modal != null && window.UmbClientMgr._modal.length > 0) {
                //            mgr = window.UmbClientMgr;
                //        }
                //        else {
                //            return; //exit recursion.
                //        }
                //    }
                //    else if (typeof window.parent.UmbClientMgr != "undefined") {
                //        mgr = window.parent.UmbClientMgr;
                //    }
                //    mgr.closeModalWindow.call(mgr, rVal);
                //}
            },
            _debug: function(strMsg) {
                if (this._isDebug) {
                    Sys.Debug.trace("UmbClientMgr: " + strMsg);
                }
            },
            get_isDirty: function() {
                return this._isDirty;
            },
            set_isDirty: function(value) {
                this._isDirty = value;
            }
        };
    };
})(jQuery);

//define alias for use throughout application
var UmbClientMgr = new Umbraco.Application.ClientManager();


text:
package net.lipecki.watson.account;

import net.lipecki.watson.combiner.AggregateCombinerHandler;
import net.lipecki.watson.event.Event;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AccountAddedEventHandler implements AggregateCombinerHandler<Account, AccountAdded> {

    @Override
    public Class<AccountAdded> getPayloadClass() {
        return AccountAdded.class;
    }

    @Override
    public void accept(final Map<String, Account> collection, final Event event, final AccountAdded payload) {
        if (Boolean.TRUE.equals(payload.getUseDefault())) {
            collection.values()
                    .stream()
                    .filter(acc ->  Boolean.TRUE.equals(acc.getUseDefault()))
                    .forEach(acc -> acc.setUseDefault(false));
        }
        collection.put(
                event.getStreamId(),
                Account.builder()
                        .uuid(event.getStreamId())
                        .name(payload.getName())
                        .useDefault(payload.getUseDefault())
                        .build()
        );
    }

}


text:
(function () {
    'use strict';
angular.module('boadingBudgetApp').controller('HomeTabCtrl',HomeTabCtrl);
HomeTabCtrl.$inject = ['$scope','$state','PurchaseService'];

function HomeTabCtrl($scope,$state,PurchaseService) {
    $scope.formData = {};
    $scope.loading = false;
    $scope.formData.categoryId = "1";

    $scope.createPurchaseItem = function () {

        if ($scope.formData.text != undefined) {
            $scope.loading = true;

            PurchaseService.create($scope.formData)

                // if successful creation, call our get function to get all the new todos
                .success(function (data) {
                    $scope.loading = false;
                    $state.go("tabs.list");

                }).error(function (err) {
                    $scope.loading = false;
                    console.log('error in saving data' + err)
                });
        }
    };

}
})();


text:
package normal;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import pojo.original.ActivationFunction;
import normal.expcalc.FunctionInterpreter;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Tomasz
 */

public class ValueCalculator
{
    private FunctionInterpreter f_interpreter;

    public ValueCalculator()
    {
        f_interpreter = new FunctionInterpreter();
    }

    public double calculateValue(List<ActivationFunction> activation_functions, double input)
    {
        double output = Double.NaN;
        for(ActivationFunction af: activation_functions)
        {
            if(checkIfDomainRuleApply(af.getDomain_rule(), input))
            {
                output = calculateFunctionValue(af.getFunction(), input);
                break;
            }
        }
        return output;
    }

    /**
     * Check if any of rules apply
     * @author Tomasz Kowal
    */
    private boolean checkIfDomainRuleApply(String domain_rules, double x_value)
    {
        Set<String> comparators = new HashSet<String>();

        comparators.add(">");
        comparators.add(">=");
        comparators.add("<");
        comparators.add("<=");
        comparators.add("=");

        String[] domain_rules_arr = domain_rules.split(",");

        //check conjunction
        for(String domain_rule: domain_rules_arr)
        {
            for(String c: comparators)
            {
                String[] rightAndLeft = domain_rule.split(c);
                if(rightAndLeft != null && rightAndLeft.length == 2)
                {
                    String right = rightAndLeft[1];
                    String left = rightAndLeft[0];
                    if(isRuleTrue(left, right, c, x_value))
                        return true;
                }
            }
        }

        return false;
    }

    private boolean isRuleTrue(String left, String right, String comparator, double x)
    {
        double leftValue = calculateFunctionValue(left, x);
        double rightValue = calculateFunctionValue(right, x);

        switch(comparator)
        {
            case ">":
                return leftValue > rightValue;
            case ">=":
                return leftValue >= rightValue;
            case "<=":
                return leftValue <= rightValue;
            case "<":
                return leftValue <= rightValue;
            case "=":
                return leftValue == rightValue;
            default:
                return false;
        }
    }

    private double calculateFunctionValue(String funcion_raw, double argument)
    {
        return f_interpreter.calculateValueInfix(funcion_raw.replaceAll("x", String.valueOf(argument)), new double[]{argument});
    }
}


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

namespace SimpleFramework.Xml.Stream {

   /// <summary>
   /// The <c>Stack</c> object is used to provide a lightweight
   /// stack implementation. To ensure top performance this stack is not
   /// synchronized and keeps track of elements using an array list.
   /// A null from either a <c>pop</c> or <c>top</c> means
   /// that the stack is empty. This allows the stack to be peeked at
   /// even if it has not been populated with anything yet.
   /// </summary>
   class Stack<T> : List<T> {

      /// <summary>
      /// Constructor for the <c>Stack</c> object. This is used
      /// to create a stack that can be used to keep track of values
      /// in a first in last out manner. Typically this is used to
      /// determine if an XML element is in or out of context.
      /// </summary>
      /// <param name="size">
      /// This is the initial size of the stack to use.
      /// </param>
      public Stack(int size) : base(size) {
      }

      /// <summary>
      /// This is used to remove the element from the top of this
      /// stack. If the stack is empty then this will return null, as
      /// such it is not advisable to push null elements on the stack.
      /// </summary>
      /// <returns>
      /// This returns the node element the top of the stack.
      /// </returns>
      public T Pop() {
         int size = Count;

         if(Count <= 0) {
            return default(T);
         }
         T value = this[size - 1];
         RemoveAt(size - 1);
         return value;
      }

      /// <summary>
      /// This is used to peek at the element from the top of this
      /// stack. If the stack is empty then this will return null, as
      /// such it is not advisable to push null elements on the stack.
      /// </summary>
      /// <returns>
      /// This returns the node element the top of the stack.
      /// </returns>
      public T Top() {
         int size = Count;

         if(size <= 0) {
            return default(T);
         }
         return this[size - 1];
      }

      /// <summary>
      /// This is used to acquire the node from the bottom of the stack.
      /// If the stack is empty then this will return null, as such it
      /// is not advisable to push null elements on the stack.
      /// </summary>
      /// <returns>
      /// This returns the element from the bottom of the stack.
      /// </returns>
      public T Bottom() {
         int size = Count;

         if(size <= 0) {
            return default(T);
         }
         return this[0];
      }

      /// <summary>
      /// This method is used to add an element to the top of the stack.
      /// Although it is possible to add a null element to the stack it
      /// is not advisable, as null is returned when the stack is empty.
      /// </summary>
      /// <param name="value">
      /// This is the element to add to the stack.
      /// </param>
      /// <returns>
      /// This returns the actual node that has just been added.
      /// </returns>
      public T Push(T value) {
         Add(value);
         return value;
      }
   }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { CheckboxPageComponent } from './checkbox-page.component';

const routes: Routes = [
  {
    path: '',
    component: CheckboxPageComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CheckboxPageRoutingModule {}


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

import {BaseDChartComponent} from './base-d-chart.component';

// chartType === 'bar-vertical'
@Component({
  templateUrl: './d-chart-bar-vertical.component.html',
})
export class DChartBarVerticalComponent implements BaseDChartComponent {
  @Input() data: any;
}


text:
using UnityEngine;
using System.Collections;

public class TestController : MonoBehaviour {

	// Update is called once per frame
	void Update () {
		if(Input.GetKey (KeyCode.PageUp)){
			Debug.Log ("PageUp");
		}
		if(Input.GetKey (KeyCode.PageDown)){
			Debug.Log ("PageDown");
		}
	}
}


text:
package org.kiji.common.flags.parser;

import org.kiji.common.flags.FlagSpec;

public class StringParser extends SimpleValueParser<String> {
  /** {@inheritDoc} */
  @Override
  public Class<? extends String> getParsedClass() {
    return String.class;
  }

  /** {@inheritDoc} */
  @Override
  public String parse(FlagSpec flag, String string) {
    return string;
  }
}


text:
package ca.uhn.fhir.example;

import org.hl7.fhir.dstu3.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.dstu3.model.ContactPoint.ContactPointUse;
import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender;
import org.hl7.fhir.dstu3.model.Patient;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;

public class Example04_EncodeResource {
	public static void main(String[] theArgs) {

		// Create a Patient
		Patient pat = new Patient();
		pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");
		pat.addIdentifier().setSystem("http://acme.org/MRNs").setValue("7000135");
		pat.addTelecom().setUse(ContactPointUse.HOME).setSystem(ContactPointSystem.PHONE).setValue("1 (416) 340-4800");
		pat.setGender(AdministrativeGender.MALE);

		// Create a context
		FhirContext ctx = FhirContext.forDstu3();

		// Create a JSON parser
		IParser parser = ctx.newJsonParser();
		parser.setPrettyPrint(true);

		String encode = parser.encodeResourceToString(pat);
		System.out.println(encode);

	}
}


text:
#include "config.h"
#include "MediaQuery.h"

#include <wtf/text/StringBuilder.h>
#include <wtf/text/TextStream.h>

namespace WebCore {

// http://dev.w3.org/csswg/cssom/#serialize-a-media-query
String MediaQuery::serialize() const
{
    if (m_ignored) {
        // If query is invalid, serialized text should turn into "not all".
        return ASCIILiteral("not all");
    }

    bool shouldOmitMediaType = false;
    StringBuilder result;
    switch (m_restrictor) {
    case MediaQuery::Only:
        result.appendLiteral("only ");
        break;
    case MediaQuery::Not:
        result.appendLiteral("not ");
        break;
    case MediaQuery::None:
        shouldOmitMediaType = !m_expressions.isEmpty() && m_mediaType == "all";
        break;
    }
    bool needsAnd = false;
    if (!shouldOmitMediaType) {
        result.append(m_mediaType);
        needsAnd = true;
    }
    for (auto& expression : m_expressions) {
        if (needsAnd)
            result.appendLiteral(" and ");
        result.append(expression.serialize());
        needsAnd = true;
    }
    return result.toString();
}

MediaQuery::MediaQuery(Restrictor restrictor, const String& mediaType, Vector<MediaQueryExpression>&& expressions)
    : m_restrictor(restrictor)
    , m_mediaType(mediaType.convertToASCIILowercase())
    , m_expressions(WTFMove(expressions))
{
    std::sort(m_expressions.begin(), m_expressions.end(), [](auto& a, auto& b) {
        return codePointCompare(a.serialize(), b.serialize()) < 0;
    });

    // Remove all duplicated expressions.
    String key;
    for (int i = m_expressions.size() - 1; i >= 0; --i) {

        // If any expression is invalid the media query must be ignored.
        if (!m_ignored)
            m_ignored = !m_expressions[i].isValid();

        if (m_expressions[i].serialize() == key)
            m_expressions.remove(i);
        else
            key = m_expressions[i].serialize();
    }
}

// http://dev.w3.org/csswg/cssom/#compare-media-queries
bool MediaQuery::operator==(const MediaQuery& other) const
{
    return cssText() == other.cssText();
}

// http://dev.w3.org/csswg/cssom/#serialize-a-list-of-media-queries
const String& MediaQuery::cssText() const
{
    if (m_serializationCache.isNull())
        m_serializationCache = serialize();
    return m_serializationCache;
}

TextStream& operator<<(TextStream& ts, const MediaQuery& query)
{
    ts << query.cssText();
    return ts;
}

} //namespace


text:
import React, { Component } from 'react';
import {render} from 'react-dom';
import ContractsAppContainer from './ContractsAppContainer';

render(<ContractsAppContainer />, document.getElementById('root'));


text:
The Leap Motion is a user-interface device that tracks the user's hand motions, and translates them into events that can control robots and physical computing hardware.

For more info about the Leap Motion platform click [Leap Motion](https://www.leapmotion.com/)

## How to Install

First install the [Leap Motion Software](https://www.leapmotion.com/setup)

Now you can install the package with:

```
go get -d -u gobot.io/x/gobot/... && go install gobot.io/x/gobot/platforms/leap
```

## How to Use

```go
package main

import (
	"fmt"

	"gobot.io/x/gobot"
	"gobot.io/x/gobot/platforms/leap"
)

func main() {
	leapMotionAdaptor := leap.NewAdaptor("127.0.0.1:6437")
	l := leap.NewDriver(leapMotionAdaptor)

	work := func() {
		gobot.On(l.Event("message"), func(data interface{}) {
			fmt.Println(data.(leap.Frame))
		})
	}

	robot := gobot.NewRobot("leapBot",
		[]gobot.Connection{leapMotionAdaptor},
		[]gobot.Device{l},
		work,
	)

	robot.Start()
}
```

## How To Connect

### OSX

This driver works out of the box with the vanilla installation of the Leap Motion Software that you get in their [Setup Guide](https://www.leapmotion.com/setup).

The main steps are:

*   Run Leap Motion.app to open a websocket connection in port 6437.
*   Connect your Computer and Leap Motion Controller.
*   Connect to the device via Gobot.

### Ubuntu

The Linux download of the Leap Motion software can be obtained from [Leap Motion Dev Center](https://developer.leapmotion.com/downloads) (requires free signup)

The main steps are:

*   Run the leapd daemon, to open a websocket connection in port 6437.
*   Connect your computer and the Leap Motion controller
*   Connect to the device via Gobot


text:
package com.training;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@MapperScan("com.training.dao")
@EnableDiscoveryClient
public class MsAuthorityServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(MsAuthorityServiceApplication.class, args);
	}
}


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

namespace Cosmos.Shell.Console.Commands
{
    public class BreakCommand : CommandBase
    {
        public override string Name
        {
            get { return "break"; }
        }

        public override string Summary
        {
            get { return "If a debugger is attached, causes a break."; }
        }

        public override void Execute(string param)
        {
            System.Diagnostics.Debugger.Break();
        }

        public override void Help()
        {
            System.Console.WriteLine(Name);
            System.Console.Write(" "); System.Console.WriteLine(Summary);
        }
    }
}


text:
function checkSingleElementState(browser, selector, className, isPresent) {
  if (isPresent) {
    browser.expect.element(selector).to.have.attribute('class').which.contains(className);
  } else {
    browser.expect.element(selector).to.have.attribute('class').which.not.contains(className);
  }
}

function checkElementsClass(browser, selectors = [], classes = [], states = []) {
  selectors.forEach((selector, index) => {
    checkSingleElementState(browser, selector, classes[index], states[index]);
  });
}

module.exports = {
  '@disable': true,
  checkElementsClass,
};


text:
require 'test_helper'

class RecommendsControllerTest < ActionController::TestCase
  setup do
    @recommend = recommends(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:recommends)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create recommend" do
    assert_difference('Recommend.count') do
      post :create, recommend: { clothing_id: @recommend.clothing_id, day: @recommend.day, user_id: @recommend.user_id }
    end

    assert_redirected_to recommend_path(assigns(:recommend))
  end

  test "should show recommend" do
    get :show, id: @recommend
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @recommend
    assert_response :success
  end

  test "should update recommend" do
    patch :update, id: @recommend, recommend: { clothing_id: @recommend.clothing_id, day: @recommend.day, user_id: @recommend.user_id }
    assert_redirected_to recommend_path(assigns(:recommend))
  end

  test "should destroy recommend" do
    assert_difference('Recommend.count', -1) do
      delete :destroy, id: @recommend
    end

    assert_redirected_to recommends_path
  end
end


text:
/*
@title Beautify CSS
@input
{
  "content-type" : "text/css",
  "example" : "menu{color:red} navigation{background-color:#333}"
}
@output
{
  "content-type" : "text/css"
}
@pragma editor replace
*/

var css = require('css');

module.exports = function(req, res, next) {
  var ast = css.parse(req.body);
  var output = css.stringify(ast);

  res.send(output);
};


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
    <meta http-equiv='x-ua-compatible' content='ie=edge'>
    <title>test</title>


text:
using System;

namespace Nelibur.ObjectMapper.CodeGenerators.Emitters
{
    internal interface IEmitterType : IEmitter
    {
        Type ObjectType { get; }
    }
}


text:
Automatically loads PHP files from a given path based on a modular separator.

---

## INTRODUCTION

aLoad ('a' abbr. for **auto**) is a flexible auto file loader primarily based on a modular separator.

## SETUP INFORMATION

This script requires no additional frameworks or libraries.

Use your CLI and enter the following to clone:

git clone https://github.com/thielicious/aLoad.git

## USAGE

aLoad::register(array module || aLoad::ALL, [string folderpath]);

Simply register modules and define the foldername if your PHP classes reside in a different directory.
- **modules** are separated file contents. Usually classes are named "**class**" e.g. email.class.php and additional code that is included are called "**inc**" e.g. utilities.inc.php. Feel free to name them however you want.
- If you don't want to use modules, you may use the constant "**aLoad::ALL**" as the first parameter to register all PHP scripts which have no modules.
- Leave the parameter for the foldername blank if your scripts are in your root directory.
- Feel free to remove or change the namespace.

## EXAMPLE

require_once "scripts/aLoad.class.php";
aLoad::register(["class", "inc"], "scripts/");

This example above will register all PHP files containing the module name "class" and "inc" in the folder "scripts".

require_once "aLoad.class.php";
aLoad::register(aLoad::ALL);

This above will register all PHP files without modules in your root directory.

###### If you encounter any bugs, feel free to open up an [issue](https://github.com/thielicious/aLoad/issues), thank you.

---
[thielicious.github.io](http://thielicious.github.io)


text:
package com.example.bajie.poff.adapter;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bajie.poff.R;
import com.example.bajie.poff.bean.SensorData;

import java.util.List;

/**
 * Created by bajie on 2017/6/24.
 */

public class DataAdapter extends RecyclerView.Adapter< DataAdapter.ViewHolder> {
    private Context mContext;
    private List<SensorData> mDataList;

    public DataAdapter(List<SensorData> dataList){
        mDataList = dataList;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        CardView cardView;
        TextView texCollectTime;
        TextView tevData;

        public ViewHolder(View view){
            super(view);
            cardView = (CardView) view;
            texCollectTime = (TextView) view.findViewById(R.id.list_item_data_collectTime);
            tevData = (TextView)view.findViewById(R.id.list_item_data);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(mContext == null){
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_data_item,parent,false);
        ViewHolder holder=new ViewHolder(view);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "请点击右上角!", Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    public void onBindViewHolder(ViewHolder holder, int position) {
            SensorData sensorData = mDataList.get(position);
            if(sensorData.getDeviceId() == 1){
                holder.tevData.setText("温度:"+sensorData.getData());
            }else{
                holder.tevData.setText("气体:"+sensorData.getData());
            }
            holder.texCollectTime.setText("采集时间:"+sensorData.getCollectTime());
        }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2009 Jose Aparicio

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_recovery_rate_model_hpp
#define quantlib_recovery_rate_model_hpp

#include <ql/settings.hpp>
#include <ql/handle.hpp>
#include <ql/experimental/credit/defaultprobabilitykey.hpp>
#include <ql/experimental/credit/recoveryratequote.hpp>

namespace QuantLib {

    /*! Models of the recovery rate provide future values of a recovery
        rate in the event of a default.
    */
    class RecoveryRateModel : public virtual Observable {
      public:
        /*! returns the expected recovery rate at a future time conditional
            on some default event type and seniority.
        */
        virtual Real recoveryValue(const Date& defaultDate,
            const DefaultProbKey& defaultKey = DefaultProbKey()) const {
            // no check on dates...
            return recoveryValueImpl(defaultDate, defaultKey);
        }
        /*! Returns true if the model will return recovery rates for
            the requested seniority.
        */
        virtual bool appliesToSeniority(Seniority) const = 0;
        virtual ~RecoveryRateModel() {}
      protected:
        /*! Returns Null<Real> if unable to produce a recovery for
            the requested seniority.
        */
        virtual Real recoveryValueImpl(const Date&,
                                       const DefaultProbKey& defaultKey
                                       ) const = 0;
    };

    /*! Simple Recovery Rate model returning the constant value of the quote
        independently of the date and the seniority.
    */
    class ConstantRecoveryModel : public RecoveryRateModel,
                                  public Observer {
      public:
        ConstantRecoveryModel(const Handle<RecoveryRateQuote>& quote);
        ConstantRecoveryModel(Real recovery,
                              Seniority sen = NoSeniority);
        void update() { notifyObservers();}
        bool appliesToSeniority(Seniority) const {return true;}
      protected:
        /*! Notice the quote's value is returned without a
            check on a match of the seniorties of the
            quote and the request.
        */
        Real recoveryValueImpl(const Date&,
                               const DefaultProbKey&) const {
            // no match on requested seniority, all pass
            return quote_->value();
        }
      private:
        Handle<RecoveryRateQuote> quote_;
    };

}

#endif


text:
<?php

namespace Elastica\Test\Node;

use Elastica\Node;
use Elastica\Node\Info as NodeInfo;
use Elastica\Test\Base as BaseTest;

class InfoTest extends BaseTest
{
    public function testGet()
    {
        $client = $this->_getClient();
        $names = $client->getCluster()->getNodeNames();
        $name = reset($names);

        $node = new Node($name, $client);
        $info = new NodeInfo($node);

        $this->assertNull($info->get('os', 'mem', 'total'));

        // Load os infos
        $info = new NodeInfo($node, array('os'));

        $this->assertTrue(!is_null($info->get('os', 'mem', 'total_in_bytes')));
        $this->assertInternalType('array', $info->get('os', 'mem'));
        $this->assertNull($info->get('test', 'notest', 'notexist'));
    }

    public function testHasPlugin()
    {
        $client = $this->_getClient();
        $nodes = $client->getCluster()->getNodes();
        $node = $nodes[0];
        $info = $node->getInfo();

        $pluginName = 'mapper-attachments';

        $this->assertTrue($info->hasPlugin($pluginName));
        $this->assertFalse($info->hasPlugin('foo'));
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.easyrec.model.web;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.List;

/**
 *
 * @author Stephan
 */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ClusterNode {

    String data;
    NodeAttributes attr;
    String description;
    String rel;
    List<ClusterNode> children;

    public ClusterNode() {
    }

    public ClusterNode(String data, NodeAttributes attr, String description) {
        this.data = data;
        this.attr = attr;
        this.description = description;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public NodeAttributes getAttr() {
        return attr;
    }

    public void setAttr(NodeAttributes attr) {
        this.attr = attr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<ClusterNode> getChildren() {
        return children;
    }

    public void setChildren(List<ClusterNode> children) {
        this.children = children;
    }

    public String getRel() {
        return rel;
    }

    public void setRel(String rel) {
        this.rel = rel;
    }

}


text:
package com.intellij.pom.xml.impl;

import com.intellij.lang.ASTNode;
import com.intellij.pom.PomModel;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.tree.TreeAspect;
import com.intellij.pom.tree.events.ChangeInfo;
import com.intellij.pom.tree.events.TreeChange;
import com.intellij.pom.tree.events.TreeChangeEvent;
import com.intellij.pom.tree.events.impl.ChangeInfoImpl;
import com.intellij.pom.tree.events.impl.TreeChangeImpl;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.impl.events.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.TokenType;
import com.intellij.psi.XmlElementVisitor;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.*;
import com.intellij.util.CharTable;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;

import javax.annotation.Nonnull;
import java.util.Collections;

@Singleton
public class XmlAspectImpl implements XmlAspect
{
	private final PomModel myModel;
	private final TreeAspect myTreeAspect;

	@Inject
	public XmlAspectImpl(PomModel model, TreeAspect aspect)
	{
		myModel = model;
		myTreeAspect = aspect;
		myModel.registerAspect(XmlAspect.class, this, Collections.singleton(myTreeAspect));
	}

	@Override
	public void update(PomModelEvent event)
	{
		if(!event.getChangedAspects().contains(myTreeAspect))
		{
			return;
		}
		final TreeChangeEvent changeSet = (TreeChangeEvent) event.getChangeSet(myTreeAspect);
		if(changeSet == null)
		{
			return;
		}
		final ASTNode rootElement = changeSet.getRootElement();
		final PsiFile file = (PsiFile) rootElement.getPsi();
		if(!(file instanceof XmlFile))
		{
			return;
		}
		final XmlAspectChangeSetImpl xmlChangeSet = event.registerChangeSetIfAbsent(this, new XmlAspectChangeSetImpl(myModel));
		xmlChangeSet.addChangedFile((XmlFile) file);

		final ASTNode[] changedElements = changeSet.getChangedElements();
		final CharTable table = ((FileElement) changeSet.getRootElement()).getCharTable();
		for(ASTNode changedElement : changedElements)
		{
			TreeChangeImpl changesByElement = (TreeChangeImpl) changeSet.getChangesByElement(changedElement);
			PsiElement psiElement;
			while((psiElement = changedElement.getPsi()) == null)
			{
				changesByElement = createChildrenChangedInfo(changedElement);
				changedElement = changesByElement.getChangedParent();
			}
			final TreeChange finalChangedElement = changesByElement;
			psiElement.accept(new XmlElementVisitor()
			{
				TreeChange myChange = finalChangedElement;

				@Override
				public void visitElement(PsiElement element)
				{
					myChange = createChildrenChangedInfo(element.getNode());
					element.getParent().accept(this);
				}

				@Override
				public void visitXmlAttribute(XmlAttribute attribute)
				{
					final ASTNode[] affectedChildren = myChange.getAffectedChildren();
					String oldName = null;
					String oldValue = null;
					for(final ASTNode treeElement : affectedChildren)
					{
						final ChangeInfo changeByChild = myChange.getChangeByChild(treeElement);
						final int changeType = changeByChild.getChangeType();
						if(treeElement.getElementType() == XmlTokenType.XML_NAME)
						{
							if(changeType == ChangeInfo.REMOVED)
							{
								oldName = treeElement.getText();
							}
							else if(changeType == ChangeInfo.REPLACE)
							{
								oldName = getReplacedNode(changeByChild).getText();
							}
						}
						if(treeElement.getElementType() == XmlElementType.XML_ATTRIBUTE_VALUE)
						{
							if(changeType == ChangeInfo.REMOVED)
							{
								oldValue = treeElement.getText();
							}
							else if(changeType == ChangeInfo.REPLACE)
							{
								oldValue = getReplacedNode(changeByChild).getText();
							}
						}
					}
					if(oldName != null && !oldName.equals(attribute.getName()))
					{
						xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), oldName, null));
						xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), attribute.getName(), attribute.getValue()));
					}
					else if(oldValue != null)
					{
						xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), attribute.getName(), attribute.getValue()));
					}
					else
					{
						xmlChangeSet.add(new XmlElementChangedImpl(attribute));
					}
				}

				private TreeElement getReplacedNode(ChangeInfo info)
				{
					return ((ChangeInfoImpl) info).getOldChild();
				}

				@Override
				public void visitXmlTag(XmlTag tag)
				{
					ASTNode[] affectedChildren = myChange.getAffectedChildren();

					for(final ASTNode treeElement : affectedChildren)
					{
						if(!(treeElement.getPsi() instanceof XmlTagChild))
						{
							visitElement(tag);
							return;
						}
					}

					for(final ASTNode treeElement : affectedChildren)
					{
						final ChangeInfo changeByChild = myChange.getChangeByChild(treeElement);
						final int changeType = changeByChild.getChangeType();
						final IElementType type = treeElement.getElementType();
						if(type == TokenType.WHITE_SPACE)
						{
							continue;
						}

						final PsiElement element = treeElement.getPsi();

						switch(changeType)
						{
							case ChangeInfo.ADD:
								xmlChangeSet.add(new XmlTagChildAddImpl(tag, (XmlTagChild) element));
								break;
							case ChangeInfo.REMOVED:
								treeElement.putUserData(CharTable.CHAR_TABLE_KEY, table);
								xmlChangeSet.add(new XmlTagChildRemovedImpl(tag, (XmlTagChild) element));
								break;
							case ChangeInfo.CONTENTS_CHANGED:
								xmlChangeSet.add(new XmlTagChildChangedImpl(tag, (XmlTagChild) element));
								break;
							case ChangeInfo.REPLACE:
								final PsiElement psi = getReplacedNode(changeByChild).getPsi();
								if(psi instanceof XmlTagChild)
								{
									final XmlTagChild replaced = (XmlTagChild) psi;
									replaced.putUserData(CharTable.CHAR_TABLE_KEY, table);
									xmlChangeSet.add(new XmlTagChildRemovedImpl(tag, replaced));
									xmlChangeSet.add(new XmlTagChildAddImpl(tag, (XmlTagChild) element));
								}
								break;
						}
					}
				}

				@Override
				public void visitXmlDocument(XmlDocument document)
				{
					xmlChangeSet.clear();
					xmlChangeSet.add(new XmlDocumentChangedImpl(document));
				}

				@Override
				public void visitFile(PsiFile file)
				{
					final XmlDocument document = ((XmlFile) file).getDocument();

					if(document != null)
					{
						xmlChangeSet.clear();
						xmlChangeSet.add(new XmlDocumentChangedImpl(document));
					}
				}
			});
		}
	}

	@Nonnull
	private static TreeChangeImpl createChildrenChangedInfo(ASTNode changedElement)
	{
		ASTNode parent = changedElement.getTreeParent();
		TreeChangeImpl changesByElement = new TreeChangeImpl((CompositeElement) parent);
		changesByElement.markChildChanged((TreeElement) changedElement, 0); // nobody cares about lengths here
		return changesByElement;
	}
}


text:
Shape analysis outputs numeric properties for an input object (contour or grouped contours), works best on grouped contours.

**plantcv.analyze_object**(*img, obj, mask, label="default"*)

**returns** analysis_image

- **Parameters:**
    - img - RGB or grayscale image data for plotting.
    - obj - Single or grouped contour object.
    - mask - Binary image to use as mask for moments analysis.
    - label - Optional label parameter, modifies the variable name of observations recorded. (default `label="default"`)
- **Context:**
    - Used to output shape characteristics of an image, including height, object area, convex hull, convex hull area,
    perimeter, extent x, extent y, longest axis, centroid x coordinate, centroid y coordinate, in bounds QC (if object
    touches edge of image, image is flagged).
- **Example use:**
    - [Use In VIS Tutorial](tutorials/vis_tutorial.md)
    - [Use In NIR Tutorial](tutorials/nir_tutorial.md)
    - [Use In PSII Tutorial](tutorials/psII_tutorial.md)
- **Output data stored:** Data ('area', 'convex_hull_area', 'solidity', 'perimeter', 'width', 'height', 'longest_path', 'center_of_mass,
    'convex_hull_vertices', 'object_in_frame', 'ellipse_center', 'ellipse_major_axis', 'ellipse_minor_axis', 'ellipse_angle', 'ellipse_eccentricity')
    automatically gets stored to the [`Outputs` class](outputs.md) when this function is ran.
    These data can always get accessed during a workflow (example below). For more detail about data output see [Summary of Output Observations](output_measurements.md#summary-of-output-observations)

**Original image**

![Screenshot](img/documentation_images/analyze_shape/original_image.jpg)

```python

from plantcv import plantcv as pcv

# Set global debug behavior to None (default), "print" (to file),
# or "plot" (Jupyter Notebooks or X11)

pcv.params.debug = "print"

# Characterize object shapes

shape_image = pcv.analyze_object(img=img, obj=objects, mask=mask, label="default")

# Save returned images with more specific naming
pcv.print_image(shape_image, '/home/malia/setaria_shape_img.png')

# Access data stored out from analyze_object
plant_solidity = pcv.outputs.observations['default']['solidity']['value']

```

**Image with identified objects**

![Screenshot](img/documentation_images/analyze_shape/objects_on_image.jpg)

**Image with shape characteristics**

![Screenshot](img/documentation_images/analyze_shape/shapes_on_image.jpg)

**Source Code:** [Here](https://github.com/danforthcenter/plantcv/blob/main/plantcv/plantcv/analyze_object.py)


text:
package org.jamesframework.core.search.algo.vns;

import java.util.List;
import org.jamesframework.core.exceptions.JamesRuntimeException;
import org.jamesframework.core.problems.Problem;
import org.jamesframework.core.problems.sol.Solution;
import org.jamesframework.core.search.MultiNeighbourhoodSearch;
import org.jamesframework.core.search.neigh.Move;
import org.jamesframework.core.search.neigh.Neighbourhood;

/**
 *

 * Reduced variable neighbourhood search (RVNS) algorithm. In every search step, a random neighbour of the current
 * solution is sampled using the k-th neighbourhood (initially, k = 0). If this neighbour is a improvement, it is
 * accepted as the new current solution. Else, k is increased by 1 so that the next neighbourhood will be used in
 * the next step. Whenever an improvement is found, or whenever all neighbourhoods have been used, k is reset to 0.
 * Note that, by default, RVNS never terminates internally, as neighbourhoods are applied cyclically. This behaviour
 * can be changed so that the search stops when all neighbourhoods have been successively applied without yielding
 * any improvement. However, in most cases, this is not desired as random moves are produced so that a few cycles
 * through all neighbourhoods might be required to find an improvement.
 *

 *

 * The reduced variable neighbourhood search can be useful for larger problems, for which variable neighbourhood
 * descent is too costly because it generates and evaluates all neighbours in every step.
 *

 *
 * @param <SolutionType> solution type of the problems that may be solved using this search,
 *                       required to extend {@link Solution}
 * @author Herman De Beukelaer
 */
public class ReducedVariableNeighbourhoodSearch<SolutionType extends Solution>
        extends MultiNeighbourhoodSearch<SolutionType> {

    // index of currently used neighbourhood
    private int k;

    // cycle neighbourhoods or stop when all neighbourhoods have been used? default: cycle
    private boolean cycleNeighbourhoods;

    /**
     * Creates a new reduced variable neighbourhood search, specifying the problem to solve and the neighbourhoods
     * used to modify the current solution. Neither arguments can be null and the list of neighbourhoods
     * can not be empty and can not contain any null elements. The search name defaults to
     * "ReducedVariableNeighbourhoodSearch".
     *
     * @param problem problem to solve
     * @param neighs list of neighbourhoods used to create neighbouring solutions
     * @throws NullPointerException if problem or neighs are null, or if
     *                              neighs contains a null element
     * @throws IllegalArgumentException if neighs is empty
     */
    public ReducedVariableNeighbourhoodSearch(Problem<SolutionType> problem,
                                              List<? extends Neighbourhood<? super SolutionType>> neighs){
        this(null, problem, neighs);
    }

    /**
     * Creates a new reduced variable neighbourhood search, specifying the problem to solve, the neighbourhoods used
     * to modify the current solution, and a custom search name. The problem and list of neighbourhoods can not be
     * null, and the list of neighbourhoods can not be empty and can not contain any null
     * elements. The search name can be null in which case the default name
     * "ReducedVariableNeighbourhoodSearch" is assigned.
     *
     * @param problem problem to solve
     * @param neighs list of neighbourhoods used to create neighbouring solutions
     * @param name custom search name
     * @throws NullPointerException if problem or neighs are null, or if
     *                              neighs contains a null element
     * @throws IllegalArgumentException if neighs is empty
     */
    public ReducedVariableNeighbourhoodSearch(String name, Problem<SolutionType> problem,
                                              List<? extends Neighbourhood<? super SolutionType>> neighs){
        this(name, problem, neighs, true);
    }

    /**
     * Creates a new reduced variable neighbourhood search, specifying the problem to solve, the neighbourhoods used
     * to modify the current solution, and a custom search name; also, it is indicated whether neighbourhoods should
     * be applied cyclically or not (by default, they are). The problem and list of neighbourhoods can not be
     * null, and the list of neighbourhoods can not be empty and can not contain any null
     * elements. The search name can be null in which case the default name
     * "ReducedVariableNeighbourhoodSearch" is assigned.
     *
     * @param problem problem to solve
     * @param neighs list of neighbourhoods used to create neighbouring solutions
     * @param cycleNeighbourhoods indicates whether neighbourhoods are applied cyclically; if not, the search
     *                            will terminate internally when all neighbourhoods have been successively applied
     *                            without yielding any improvement
     * @param name custom search name
     * @throws NullPointerException if problem or neighs are null, or if
     *                              neighs contains a null element
     * @throws IllegalArgumentException if neighs is empty
     */
    public ReducedVariableNeighbourhoodSearch(String name, Problem<SolutionType> problem,
                                              List<? extends Neighbourhood<? super SolutionType>> neighs,
                                              boolean cycleNeighbourhoods){
        super(name != null ? name : "ReducedVariableNeighbourhoodSearch", problem, neighs);
        // cycle or not?
        this.cycleNeighbourhoods = cycleNeighbourhoods;
        // start with 0th neighbourhood
        k = 0;
    }

    /**
     * Indicates whether neighbourhoods should be applied cyclically or not, when all neighbourhoods have been
     * successively applied without finding any improvements.
     *
     * @param cycleNeighbourhoods indicates whether neighbourhoods are cyclically applied
     */
    public void setCycleNeighbourhoods(boolean cycleNeighbourhoods){
        this.cycleNeighbourhoods = cycleNeighbourhoods;
    }

    /**
     * Samples a random neighbour of the current solution, using the k-th neighbourhood, and accepts it as the new
     * current solution if it is an improvement. If no improvement is found, k is increased. Upon each improvement,
     * k is reset to 0. If cycling is enabled (which is the default setting), k is also reset to 0 when all
     * neighbourhoods have been used so that the first neighbourhood will again be applied in the next step.
     * If cycling is disabled, the search stops if no improvement was found using the last available neighbourhood.
     *

     * If the k-th neighbourhood is unable to generate any move, k is also increased to try the next neighbourhood
     * (if any) in the next step.
     *
     * @throws JamesRuntimeException if depending on malfunctioning components (problem, neighbourhood, ...)
     */
    @Override
    protected void searchStep() {
        // use k-th neighbourhood to get a random valid move
        Move<? super SolutionType> move = getNeighbourhoods().get(k).getRandomMove(getCurrentSolution(), getRandom());
        // check: got move ?
        if(move != null){
            // check: improvement ?
            if(isImprovement(move)){
                // improvement: accept move and reset k
                accept(move);
                k = 0;
            } else {
                reject(move);
                // no improvement: switch to next neighbourhood, if any
                nextNeighbourhood();
            }
        } else {
            // k-th neighbourhood did not produce any random move: switch to next neighbourhood, if any
            nextNeighbourhood();
        }
    }

    /**
     * Switches to the next neighbourhood in the list, if any,
     * going back to the start if cycling is enabled and all
     * neighbourhoods have been used.
     */
    private void nextNeighbourhood(){
        if(cycleNeighbourhoods || k < getNeighbourhoods().size()-1){
            // try again with next neighbourhood in next step
            k = (k+1) % getNeighbourhoods().size();
        } else {
            // no next neighbourhood... stop
            stop();
        }
    }

}


text:
<layout name="layout" />

  			加班调休表 /
  			加班调休

加班

						        <volist name='arr' id='st' empty="没有数据">

<{$st.riqi}>:<{$st.remark}>:<{$st.hourlong}>小时

						        </volist>

						<volist name='syses' id='st' empty="没有数据">

<{$st.sysno}>:<{$st.name}>
						      <a href="__URL__/insert/branch/<{$st.id}>" class="btn btn-danger pull-right"> 关联

						</volist>

	        <button type="button" class="close" data-dismiss="modal">×Close</button>

加班

	      	<form action="__URL__/insert" method="post" class="form-horizontal" role="form" >
	      	<input type="hidden" name="userid" value="<{$_SESSION.id}>" />
	      	<input type="hidden" name="type" value="0" />
	      	<input type="hidden" name="state" value="0" />
	      	<input type="hidden" name="table" value="tp_overtime" />

					日期:

<input type="date" class="form-control" name="riqi" value="<{$riqi}>" placeholder="日期">

					开始:

<input type="time" class="form-control" name="begin" value="<{$begin}>" placeholder="开始">

					结束:

<input type="time" class="form-control" name="end" value="<{$end}>" placeholder="结束">

					时长:

<input type="text" class="form-control" name="hourlong" value="" placeholder="时长">

					备注:

<input type="text" class="form-control" name="remark" value="" placeholder="原因">

		     <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		     <button type="submit" class="btn btn-primary">提交</button></form>


text:
using System;
using System.Linq;
using System.Reflection;

namespace CsDebugScript.Engine
{
    internal class UserTypeMetadata
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UserTypeMetadata"/> class.
        /// </summary>
        /// <param name="moduleName">Name of the module.</param>
        /// <param name="typeName">Name of the type.</param>
        /// <param name="type">The type.</param>
        public UserTypeMetadata(string moduleName, string typeName, Type type)
        {
            ModuleName = moduleName;
            TypeName = typeName;
            Type = type;
        }

        /// <summary>
        /// Gets the name of the module.
        /// </summary>
        public string ModuleName { get; private set; }

        /// <summary>
        /// Gets the name of the user code type.
        /// </summary>
        public string TypeName { get; private set; }

        /// <summary>
        /// Gets the user type.
        /// </summary>
        public Type Type { get; private set; }

        /// <summary>
        /// Reads metadata from the type.
        /// </summary>
        /// <param name="type">The type.</param>
        public static UserTypeMetadata[] ReadFromType(Type type)
        {
            UserTypeAttribute[] attributes = type.GetCustomAttributes<UserTypeAttribute>(false).ToArray();
            bool derivedFromUserType = IsDerivedFrom(type, typeof(UserType));

            /* #fixme temp workaround for genertic types
            if (type.IsGenericType)
            {
                foreach(Type genericArgument in type.GetGenericArguments())
                {
                    UserTypeAttribute genericAttribute = genericArgument.GetCustomAttribute<UserTypeAttribute>();
                    if (genericAttribute != null)
                    {
                        string moduleName = genericAttribute.ModuleName;
                        // #fixme temp workaround
                        string typeName = type.Name + "<>";

                        return new UserTypeMetadata(moduleName, typeName, type);
                    }
                }
            }
            */

            if (attributes.Length > 0 && !derivedFromUserType)
            {
                throw new Exception(string.Format("Type {0} has defined UserTypeAttribute, but it does not inherit UserType", type.FullName));
            }
            else if (derivedFromUserType)
            {
                UserTypeMetadata[] metadata = new UserTypeMetadata[attributes.Length];

                for (int i = 0; i < metadata.Length; i++)
                {
                    UserTypeAttribute attribute = attributes[i];
                    string moduleName = attribute != null ? attribute.ModuleName : null;
                    string typeName = attribute != null ? attribute.TypeName : !type.IsGenericType ? type.Name : type.Name.Substring(0, type.Name.IndexOf('`')) + "<>"; // TODO: Form better name for generics type

                    metadata[i] = new UserTypeMetadata(moduleName, typeName, type);
                }

                return metadata;
            }

            return new UserTypeMetadata[0];
        }

        /// <summary>
        /// Converts metadata to description using the current process.
        /// </summary>
        public UserTypeDescription ConvertToDescription()
        {
            return new UserTypeDescription(ModuleName, TypeName, Type);
        }

        /// <summary>
        /// Converts metadata to description.
        /// </summary>
        /// <param name="process">The process.</param>
        public UserTypeDescription ConvertToDescription(Process process)
        {
            return new UserTypeDescription(process, ModuleName, TypeName, Type);
        }

        /// <summary>
        /// Determines whether type is derived from the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="derivedType">Type of the derived.</param>
        private static bool IsDerivedFrom(Type type, Type derivedType)
        {
            while (type != null)
            {
                if (type == derivedType)
                    return true;

                type = type.BaseType;
            }

            return false;
        }
    }

    internal static class UserTypeMetadataExtensions
    {
        /// <summary>
        /// Finds metadata that comes from the specified module or first if not found.
        /// </summary>
        /// <param name="metadatas">The metadatas.</param>
        /// <param name="module">The module.</param>
        public static UserTypeMetadata FromModuleOrFirst(this UserTypeMetadata[] metadatas, CsDebugScript.Module module)
        {
            foreach (var metadata in metadatas)
                if (metadata.ModuleName == module.Name)
                    return metadata;
            return metadatas.First();
        }
    }
}


text:
import sys,os,time

prog = os.path.split(sys.argv[0])[-1]
myversion = 'Oct 10 2009'

galhtmlprefix = """<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
<title></title>
<link rel="stylesheet" href="/static/style/base.css" type="text/css" />

"""

def timenow():
    """return current time as a string
    """
    return time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time()))

def rgConv(inpedfilepath,outhtmlname,outfilepath):
  """convert linkage ped/map to fbat"""
  recode={'A':'1','C':'2','G':'3','T':'4','N':'0','0':'0','1':'1','2':'2','3':'3','4':'4'}
  basename = os.path.split(inpedfilepath)[-1] # get basename
  inmap = '%s.map' % inpedfilepath
  inped = '%s.ped' % inpedfilepath
  outf = '%s.ped' % basename # note the fbat exe insists that this is the extension for the ped data
  outfpath = os.path.join(outfilepath,outf) # where to write the fbat format file to
  try:
    mf = file(inmap,'r')
  except:
    sys.stderr.write('%s cannot open inmap file %s - do you have permission?\n' % (prog,inmap))
    sys.exit(1)
  try:
    rsl = [x.split()[1] for x in mf]
  except:
      sys.stderr.write('## cannot parse %s' % inmap)
      sys.exit(1)
  try:
      os.makedirs(outfilepath)
  except:
      pass # already exists
  head = ' '.join(rsl) # list of rs numbers
  # TODO add anno to rs but fbat will prolly barf?
  pedf = file(inped,'r')
  o = file(outfpath,'w',2**20)
  o.write(head)
  o.write('\n')
  for i,row in enumerate(pedf):
    if i == 0:
       lrow = row.split()
       try:
          x = [int(x) for x in lrow[10:50]] # look for non numeric codes
       except:
          dorecode = 1
    if dorecode:
        lrow = row.strip().split()
        p = lrow[:6]
        g = lrow[6:]
        gc = [recode.get(x,'0') for x in g]
        lrow = p+gc
        row = '%s\n' % ' '.join(lrow)
    o.write(row)
  o.close()

def main():
    """call fbater
    need to work with rgenetics composite datatypes
    so in and out are html files with data in extrafiles path
    <command interpreter="python">rg_convert_lped_fped.py '$input1/$input1.metadata.base_name'
    '$output1' '$output1.extra_files_path'
    </command>
    """
    nparm = 3
    if len(sys.argv) < nparm:
        sys.stderr.write('## %s called with %s - needs %d parameters \n' % (prog,sys.argv,nparm))
        sys.exit(1)
    inpedfilepath = sys.argv[1]
    outhtmlname = sys.argv[2]
    outfilepath = sys.argv[3]
    try:
        os.makedirs(outfilepath)
    except:
        pass
    rgConv(inpedfilepath,outhtmlname,outfilepath)
    f = file(outhtmlname,'w')
    f.write(galhtmlprefix % prog)
    flist = os.listdir(outfilepath)
    print '## Rgenetics: http://rgenetics.org Galaxy Tools %s %s' % (prog,timenow()) # becomes info
    f.write('
## Rgenetics: http://rgenetics.org Galaxy Tools %s %s\n
' % (prog,timenow()))
    for i, data in enumerate( flist ):
        f.write('
%s
\n' % (os.path.split(data)[-1],os.path.split(data)[-1]))
    f.write("
")
    f.close()

if __name__ == "__main__":
   main()


text:
package com.example.ottosimple;

public class MyButtonEvent {

}


text:
=begin

  Copyright (C) 2015 Rackspace

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
=end

require 'date'

class Fluent::RackspaceCloudFeedsOutput < Fluent::Output
  include Fluent::PluginLoggerMixin

  Fluent::Plugin.register_output('rackspace_cloud_feeds', self)

  config_param :identity_endpoint, :string, :default => nil
  config_param :identity_username, :string, :default => nil
  config_param :identity_password, :string, :default => nil

  config_param :feeds_endpoint, :string, :default => nil

  def configure(conf)
    super
    $log.debug("   Identity endpoint: #{@identity_endpoint}")
    $log.debug("   Identity username: #{@identity_username}")
    $log.debug("Cloud Feeds endpoint: #{@feeds_endpoint}")
  end

  def start
    super
    require 'net/http/persistent'

    @feeds_uri = URI @feeds_endpoint
    @feeds_http = Net::HTTP::Persistent.new 'fluent-feeds-output'

  end

  def shutdown
    super
  end

  ##
  # either get a token back from identity, or poop the pants
  # noinspection RubyStringKeysInHashInspection
  def authenticate_user
    uri = URI @identity_endpoint
    http = Net::HTTP.new(uri.host, uri.port)
    if uri.scheme == 'https'
      http.use_ssl = true
    end
    req = Net::HTTP::Post.new(uri.path)
    content = {
        'auth' => {
            'passwordCredentials' => {
                'username' => @identity_username,
                'password' => @identity_password
            }
        }
    }
    req.body = content.to_json
    req['content-type'] = 'application/json'
    req['accept'] = 'application/json'
    res = http.request(req)

    case res
      when Net::HTTPSuccess
        # Get the token
        JSON.parse(res.body)['access']['token']['id']
      else
        raise "Unable to authenticate with identity at #{@identity_endpoint} as #{@identity_username}"
    end
  end

  ##
  # putting content into an atom entry document
  def atomic_wrapper(content, time)
    # date format
    now = DateTime.strptime(time.to_s, '%s').strftime("%FT%T.%LZ")

    <<EOF
<?xml version="1.0" encoding="UTF-8" ?>
<entry xmlns="http://www.w3.org/2005/Atom">
    <id>#{SecureRandom.uuid.to_s}</id>
    <title type="text">User Access Event</title>
    <author><name>Repose</name></author>
    <updated>#{now}</updated>
    <content type="application/xml">#{content}</content>
</entry>
EOF
  end

  def emit(tag, es, chain)
    es.each { |time, record|
      http = Net::HTTP.new(@feeds_uri.host, @feeds_uri.port)
      if @feeds_uri.scheme == 'https'
        http.use_ssl = true
      end

      # take the data, put it in to an abdera envelope
      post = Net::HTTP::Post.new @feeds_uri.path

      post.body = atomic_wrapper(record['message'], time)
      unless @auth_token
        #get new auth token
        @auth_token = authenticate_user
      end
      post['x-auth-token'] = @auth_token
      post['content-type'] = 'application/atom+xml'

      begin
        response = http.request(post)

        if response.code !~ /2\d\d/
          @auth_token = nil
          raise "NOT AUTHORIZED TO POST TO FEED ENDPOINT #{@feeds_endpoint}"
        end
        $log.debug "FEEDS RESPONSE CODE #{response.code}"
        $log.error "FEEDS RESPONSE BODY: #{response.body}" if response.code !~ /2\d\d/
      end
    }

    chain.next
  end

end


text:
@interface LBLHomeTitleButton : UIButton

@end


text:
'use strict';

var Shape = require('./shape.js');

class ShapeWithVertex extends Shape {
    constructor() {
        super();
        this.shapeType = 2;
        this.numberOfVertices = 0;
    }

    static getModelDescriptor(apatite) {
        var modelDescriptor = apatite.newModelDescriptor(ShapeWithVertex, apatite.getTable('SHAPE'));
        modelDescriptor.inheritFrom(apatite.getModelDescriptor(Shape), apatite.newTypeFilterQuery().attr('shapeType').eq(2));

        var column = apatite.getTable('SHAPE').addNewColumn('NOOFVERTICES', apatite.dialect.newIntegerType(2));
        modelDescriptor.newSimpleMapping('numberOfVertices', column);

        return modelDescriptor;
    }
}

module.exports = ShapeWithVertex;


text:
byname
======
[![Build Status](https://travis-ci.org/kode4food/byname.svg)](https://travis-ci.org/kode4food/byname)

A simple library, it lets you take a function, introspect (parse) its arguments, and invoke it with an options object instead of positional arguments.

## Directly Invoking a Function
So as a basic example, here is how you would invoke a function directly using `byname.invoke(targetFunction, options)`:

```javascript
var byname = require('byname');

function someFunction(name, value) {
  console.log("name = " + name);
  console.log("value = " + value);
}

byname.invoke(someFunction, {
  name: "This is the name",
  value: "This is the value"
});
```

## Wrapping a Function
You can also wrap the function using `byname.wrap(targetFunction)`. This will generate a wrapper function that can be used to invoke the target function repeatedly without having to perform introspection.

```javascript
var byname = require('byname');

function someFunction(name, value) {
  console.log("name = " + name);
  console.log("value = " + value);
}

var wrapped = byname.wrap(someFunction);
wrapped({
  name: "This is the name",
  value: "This is the value"
});
```

## Trailing Arguments
If you provide explicit arguments to the wrapped function, they will serve as the trailing arguments of the target function.  This is especially useful for providing a callback outside of the options object:

```javascript
var byname = require('byname');

function someFunction(name, value, callback) {
  var result = "name = " + name + " / value = " + value;
  callback(null, result);
}

var wrapped = byname.wrap(someFunction);
wrapped({
  name: "This is the name",
  value: "This is the value"
}, handler);

function handler(err, result) {
  console.log(result);
}
```

## Explicitly Naming Arguments
If you don't like the argument names you've chosen for your target function, or if it has been bound and the argument names lost, you can explicitly set the names used.  It's even good for mapping some arbitrary object to a function's arguments:

```javascript
var byname = require('byname');

function someFunction(name, value) {
  console.log("name = " + name);
  console.log("value = " + value);
}

var wrapped = byname.wrap(someFunction, "n", "v");
wrapped({
  n: "This is the name",
  v: "This is the value"
});
```

## Default Argument Values
Perhaps you need default values?  The wrapped function exposes a couple of utility functions, one of which is `withDefaults(defaults)`.  It returns an augmented version of the wrapper that provides defaults for any arguments not specific upon invocation:

```javascript
var byname = require('byname');

function someFunction(name, value) {
  console.log("name = " + name);
  console.log("value = " + value);
}

var defaulted = byname.wrap(someFunction).withDefaults({
  value: "This is the value"
});

defaulted({
  name: "This is the name"
});
```

`withDefaults(defaults)` will accept either an object or a function that returns an object.  If provided a function to generate defaults, that function will be invoked every time the wrapped function is called.

## Retrieving Argument Names
The other is `getArgumentNames()` which can be used to return the names of the wrapped function's introspected arguments:

```javascript
var byname = require('byname');

function someFunction(name, value) {
}

var wrapped = byname.wrap(someFunction);

console.log(wrapped.getArgumentNames());
```

## Options is Optional
If you do not include an object as your first argument, any arguments specified will continue to be treated as trailing arguments, and an empty options object will be assumed:

```javascript
var byname = require('byname');

function someFunction(name, value, callback) {
  var result = "name = " + name + " / value = " + value;
  callback(null, result);
}

var wrapped = byname.wrap(someFunction);
// invoke someFunction with name and value undefined
wrapped(handler);

function handler(err, result) {
  console.log(result);
}
```

This behavior also applies to interfaces created using `withDefaults(defaults)`.

## License (MIT License)
Copyright (c) 2015 Thomas S. Bradford

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.


text:
description: This template creates a Network Security Group
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: security-group-create
languages:
- json
---
# Create a Network Security Group

![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.network/security-group-create/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.network%2Fsecurity-group-create%2Fazuredeploy.json)
[![Deploy To Azure US Gov](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazuregov.svg?sanitize=true)](https://portal.azure.us/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.network%2Fsecurity-group-create%2Fazuredeploy.json)
[![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.network%2Fsecurity-group-create%2Fazuredeploy.json)

This template creates a subnet, a Network Security Group and attaches it to the subnet in the VNET. For more information on how to configure the Network Security Group, go here: https://docs.microsoft.com/azure/templates/microsoft.network/2018-11-01/networksecuritygroups

`Tags: Microsoft.Network/networkSecurityGroups, Microsoft.Network/virtualNetworks`


text:
package org.locationtech.geowave.adapter.vector.plugin;

import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.process.ProcessException;
import org.geotools.process.factory.DescribeParameter;
import org.geotools.process.factory.DescribeProcess;
import org.geotools.process.factory.DescribeResult;
import org.geotools.util.factory.Hints;
import org.opengis.coverage.grid.GridGeometry;

/**
 * This class can be used as a GeoTools Render Transform ('geowave:Subsample') within an SLD on any
 * layer that uses the GeoWave Data Store. An example SLD is provided
 * (example-slds/SubsamplePoints.sld). The pixel-size allows you to skip more than a single pixel.
 * For example, a pixel size of 3 would skip an estimated 3x3 pixel cell in GeoWave's row IDs. Note
 * that rows are only skipped when a feature successfully passes filters.
 */
@DescribeProcess(
    title = "SubsampleAtScreenResolution",
    description = "This process will enable GeoWave to subsample WMS requests based on pixel resolution to not oversample data.  This will efficiently render overlapping point geometry that would otherwise be hidden but it assumes an opaque style and does not take transparency into account.  It will use the centroid for other geometry types than point which can produce visual artifacts - distributed rendering is an alternative approach to efficiently render lines and polygons")
public class SubsampleProcess {
  public static final Hints.Key SUBSAMPLE_ENABLED = new Hints.Key(Boolean.class);
  public static final Hints.Key PIXEL_SIZE = new Hints.Key(Double.class);
  public static final Hints.Key OUTPUT_BBOX = new Hints.Key(ReferencedEnvelope.class);
  public static final Hints.Key OUTPUT_WIDTH = new Hints.Key(Integer.class);
  public static final Hints.Key OUTPUT_HEIGHT = new Hints.Key(Integer.class);

  @DescribeResult(
      name = "result",
      description = "This is just a pass-through, the key is to provide enough information within invertQuery to perform a map to screen transform")
  public SimpleFeatureCollection execute(
      @DescribeParameter(
          name = "data",
          description = "Feature collection containing the data") final SimpleFeatureCollection features,
      @DescribeParameter(
          name = "outputBBOX",
          description = "Georeferenced bounding box of the output") final ReferencedEnvelope argOutputEnv,
      @DescribeParameter(
          name = "outputWidth",
          description = "Width of the output raster") final Integer argOutputWidth,
      @DescribeParameter(
          name = "outputHeight",
          description = "Height of the output raster") final Integer argOutputHeight,
      @DescribeParameter(
          name = "pixelSize",
          description = "The pixel size to base subsampling on") final Double pixelSize)
      throws ProcessException {
    // vector-to-vector render transform that is just a pass through - the
    // key is to add map to screen transform within invertQuery
    return features;
  }

  public Query invertQuery(
      @DescribeParameter(
          name = "outputBBOX",
          description = "Georeferenced bounding box of the output") final ReferencedEnvelope argOutputEnv,
      @DescribeParameter(
          name = "outputWidth",
          description = "Width of the output raster") final Integer argOutputWidth,
      @DescribeParameter(
          name = "outputHeight",
          description = "Height of the output raster") final Integer argOutputHeight,
      @DescribeParameter(
          name = "pixelSize",
          description = "The pixel size to base subsampling on") final Double pixelSize,
      final Query targetQuery,
      final GridGeometry targetGridGeometry) throws ProcessException {

    // add to the query hints
    targetQuery.getHints().put(SUBSAMPLE_ENABLED, true);
    targetQuery.getHints().put(OUTPUT_WIDTH, argOutputWidth);
    targetQuery.getHints().put(OUTPUT_HEIGHT, argOutputHeight);
    targetQuery.getHints().put(OUTPUT_BBOX, argOutputEnv);
    if (pixelSize != null) {
      targetQuery.getHints().put(PIXEL_SIZE, pixelSize);
    }
    return targetQuery;
  }
}


text:
from OnePy.sys_module.components.order_checker import PendingOrderChecker
from OnePy.sys_module.components.order_generator import OrderGenerator
from setting_for_test import TICKER, global_setting

def test_pending_order_checker():
    go = global_setting()
    strategy = go.env.strategies['DemoStrategy']
    go.market_maker.update_market()
    order_generator = OrderGenerator()
    pending_order_checker = PendingOrderChecker()

    go.env.execute_on_close_or_next_open = 'open'

    CLOSE = go.env.feeds[TICKER].current_ohlc['close'] = 11
    HIGH = go.env.feeds[TICKER].current_ohlc['high'] = 20
    LOW = go.env.feeds[TICKER].current_ohlc['low'] = 5
    NEXT_OPEN = go.env.feeds[TICKER].next_ohlc['open'] = 10

    # 挂单带pending
    go.env.initialize_env()
    strategy.buy(100, TICKER, price=12, takeprofit_pct=0.01)

    order_generator.run()  # 提交订单到挂单
    assert len(go.env.orders_pending) == 1

    pending_order_checker.run()  # 触发mkt挂单生成信号
    assert len(go.env.orders_pending) == 0
    assert len(go.env.signals_trigger_cur) == 1
    assert len(go.env.orders_child_of_mkt_dict) == 0

    order_generator.run()  # mkt挂单信号生成为order
    assert len(go.env.orders_mkt_absolute_cur) == 1
    assert len(go.env.signals_trigger_cur) == 0
    assert len(go.env.orders_child_of_mkt_dict) == 1  # 伴随takeprofit挂单

    pending_order_checker.run()  # takeprofit触发生成信号
    assert len(go.env.signals_trigger_cur) == 1

    order_generator.run()  # takeprofit 信号生成为order
    assert len(go.env.orders_mkt_absolute_cur) == 2
    assert len(go.env.signals_trigger_cur) == 0
    assert go.env.orders_mkt_absolute_cur[0].execute_price == 12
    assert go.env.orders_mkt_absolute_cur[1].execute_price == round(
        12*1.01, 3)

    # 市价单带pending
    go.env.initialize_env()
    strategy.buy(100, TICKER, takeprofit_pct=0.01)

    order_generator.run()  # 生成市价单
    assert len(go.env.signals_trigger_cur) == 0
    assert go.env.orders_child_of_mkt_dict != {}
    assert len(go.env.orders_mkt_normal_cur) == 1

    pending_order_checker.run()  # 生成挂单触发信号
    assert go.env.orders_child_of_mkt_dict == {}
    assert len(go.env.signals_trigger_cur) == 1

    order_generator.run()  # 挂单信号成交并转化为order
    assert len(go.env.orders_mkt_absolute_cur) == 1
    assert go.env.orders_mkt_absolute_cur[-1].execute_price == round(
        NEXT_OPEN*1.01, 3)
    assert len(go.env.signals_trigger_cur) == 0
    assert len(go.env.orders_mkt_absolute_cur) == 1


text:
using GrandTheftMultiplayer.Shared;

namespace Enums
{
  public enum VehicleHashHelicopters
  {
    Annihilator = VehicleHash.Annihilator,
    Buzzard = VehicleHash.Buzzard,
    Buzzard2 = VehicleHash.Buzzard2,
    Cargobob = VehicleHash.Cargobob,
    Cargobob2 = VehicleHash.Cargobob2,
    Cargobob3 = VehicleHash.Cargobob3,
    Cargobob4 = VehicleHash.Cargobob4,
    Frogger = VehicleHash.Frogger,
    Frogger2 = VehicleHash.Frogger2,
    Maverick = VehicleHash.Maverick,
    Savage = VehicleHash.Savage,
    Skylift = VehicleHash.Skylift,
    Supervolito = VehicleHash.Supervolito,
    Supervolito2 = VehicleHash.Supervolito2,
    Swift = VehicleHash.Swift,
    Swift2 = VehicleHash.Swift2,
    Valkyrie = VehicleHash.Valkyrie,
    Valkyrie2 = VehicleHash.Valkyrie2,
    Volatus = VehicleHash.Volatus
  }
}


text: require('./scripts/gulp')


text:
import {
  Card,
  Carousel,
  CarouselItem,
  Message,
  MessageValue,
  removeSSML,
  SpeechMessage,
  TextMessage,
  toSSML,
} from '@jovotech/output';
import AplCardJson from './apl/Card.json';
import AplCarouselJson from './apl/Carousel.json';
import { ALEXA_STRING_MAX_LENGTH } from './constants';
import {
  AplRenderDocumentDirective,
  Card as AlexaCard,
  CardType,
  OutputSpeech,
  OutputSpeechType,
} from './models';

export function validateAlexaString(value: unknown): string | undefined | null | void {
  if (typeof value !== 'string') {
    return '$property must be a string';
  }
  if (!value) {
    return '$property should not be empty';
  }
  if (value.length > ALEXA_STRING_MAX_LENGTH) {
    return `$property can not exceed ${ALEXA_STRING_MAX_LENGTH} characters`;
  }
  return;
}

export function convertMessageToOutputSpeech(message: MessageValue): OutputSpeech {
  if (typeof message === 'string') {
    return {
      type: OutputSpeechType.Ssml,
      ssml: toSSML(message),
    };
  }
  if (message.speech) {
    return {
      type: OutputSpeechType.Ssml,
      ssml: toSSML(message.speech),
    };
  }
  return {
    type: OutputSpeechType.Plain,
    text: removeSSML((message as TextMessage).text),
  };
}

export function augmentModelPrototypes(): void {
  Card.prototype.toAlexaCard = function (): AlexaCard<CardType.Standard> {
    const card: AlexaCard<CardType.Standard> = {
      type: CardType.Standard,
      title: this.title,
      text: this.content,
    };
    if (this.imageUrl) {
      card.image = {
        // TODO: determine whether large should always be set
        largeImageUrl: this.imageUrl,
      };
    }
    return card;
  };

  Card.prototype.toApl = function (): AplRenderDocumentDirective {
    AplCardJson.datasources.data.title = this.title;

    if (this.subtitle) {
      AplCardJson.datasources.data.subtitle = this.subtitle;
    }

    if (this.content) {
      AplCardJson.datasources.data.content = this.content;
    }

    if (this.imageUrl) {
      AplCardJson.datasources.data.imageUrl = this.imageUrl;
    }

    if (this.header) {
      AplCardJson.datasources.data.header = this.header;
    }

    if (this.backgroundImageUrl) {
      AplCardJson.datasources.data.backgroundImageUrl = this.backgroundImageUrl;
    }

    return {
      type: 'Alexa.Presentation.APL.RenderDocument',
      token: 'token',
      ...AplCardJson,
    };
  };

  Carousel.prototype.toApl = function (): AplRenderDocumentDirective {
    if (this.title) {
      AplCarouselJson.datasources.data.title = this.title;
    }

    if (this.header) {
      AplCarouselJson.datasources.data.header = this.header;
    }

    if (this.backgroundImageUrl) {
      AplCarouselJson.datasources.data.backgroundImageUrl = this.backgroundImageUrl;
    }

    (AplCarouselJson.datasources.data.items as CarouselItem[]) = this.items.map((item) => ({
      ...item,
      selection: item.selection
        ? {
            type: 'Selection',
            ...item.selection,
          }
        : undefined,
    }));

    return {
      type: 'Alexa.Presentation.APL.RenderDocument',
      token: 'token',
      ...AplCarouselJson,
    };
  };

  Message.prototype.toAlexaOutputSpeech = function () {
    return convertMessageToOutputSpeech(this as TextMessage | SpeechMessage);
  };
}


text:
priorWD=$PWD
appPath=$1
ipaPath=$2
dir=$(dirname "$appPath")
basename=$(basename "$appPath" ".app")
ipadir=$(dirname "$ipaPath")
ipabasename=$(basename "$ipaPath" ".ipa")

cd $dir

payloadDir="$dir/Payload"
if [ ! -d "$payloadDir" ];then
	mkdir "$payloadDir"
fi
rm -rf "$payloadDir/*"
cp -rf "$appPath" "$payloadDir"
zip -qry "$dir/$basename.ipa" "Payload"
mv "$dir/$basename.ipa" "$ipaPath"
mv "$dir/"$basename".app.dsym" "$ipadir/"$ipabasename".app.dsym"
#恢复环境
cd "$priorWD"


text:
var execSync = require("../index.js");

// direct
var output = execSync("ls -la");
console.log(output);

// with callback
// execSync("ls -la", {}, console.log)
// execSync("ls -la", {}, function(output){
//     console.log(output)
// });