text:
describe("util", function () {
    beforeEach(function () {
        setFixtures("<input type=\"hidden\" value=\"1287652847\" name=\"server_time\" id=\"server_timestamp\"/>\n" +
            "
\n" +
            "    clickable\n" +
            "    \n" +
            "    <input type=\"hidden\" value=\"1287651018131\"> \n" +
            "\n" +
            "

\n" +
            "    <input type=\"hidden\" id=\"shilpa_needs_to_work_more\"/>\n" +
            "    <button type=\"button\" id=\"btn\" name=\"button\">Push the button</button>\n" +
            "\n" +
            "    name_foo\n" +
            "    <input id=\"baz_input\" value=\"name_baz\"/>\n" +
            "\n" +
            "    <textarea id=\"id_bar\">id bar text</textarea>\n" +
            "    <textarea id=\"id_quux\">id quux text</textarea>\n" +
            "
Original content
\n" +
            "
");
    });
    var populatable;

    beforeEach(function () {
        populatable = $('populatable');
        populatable.update("");
    });

    afterEach(function () {
        populatable.update("");
    });

    it("test_executes_javascript_on_event", function () {
        Util.on_load(function () {
            populatable.update("foo bar");
        });
        window.load;
        assertEquals("foo bar", populatable.innerHTML);
    });

    it("test_executes_javascript_if_event_has_been_fired", function () {
        window.load;
        Util.on_load(function () {
            populatable.update("foo bar1");
        });
        assertEquals("foo bar1", populatable.innerHTML);
    });

    it("test_appends_child_with_given_text_to_the_given_id", function () {
        Util.refresh_child_text('populatable', "This text gets overridden", "success");
        Util.refresh_child_text('populatable', "second text", "success");
        assertEquals(1, populatable.getElementsBySelector("p").length);
        var p = populatable.down('p');
        assertEquals("second text", p.innerHTML);
        assertTrue("Should have class name", p.hasClassName("success"));
    });

    it("test_does_not_execute_handler_except_for_the_first_time_the_event_is_fired", function () {
        Util.on_load(function () {
            populatable.update("foo bar1");
        });
        window.load;
        Util.on_load(function () {
            populatable.update("foo bar2");
        });

        populatable.update("bar baz");
        window.load;
        assertEquals("bar baz", populatable.innerHTML);
    });

    it("test_set_value", function () {
        var call_back = Util.set_value('shilpa_needs_to_work_more', "foo");
        call_back();
        assertEquals("foo", $('shilpa_needs_to_work_more').value);
    });

    it("test_enable_disable", function () {
        Util.disable("btn");
        assertTrue($("btn").disabled);
        assertTrue($("btn").hasClassName("disabled"));

        Util.enable("btn");
        assertFalse($("btn").disabled);
        assertFalse($("btn").hasClassName("disabled"));
    });

    it("test_timeago_convertion", function () {
        assertEquals("", jQuery('#time_field').text());
        var elem = document.getElementById("time_field");
        Util.convert_to_timeago(elem);
        assertEquals("30 minutes ago", jQuery('#time_field').text());
    });

    it("test_escapeDotsFromId", function () {
        assertEquals("#2\\.1\\.1\\.2", Util.escapeDotsFromId("2.1.1.2"));
    });

    it("test_ajax_modal_success", function () {

        var ajax_options = null;
        var ajax_request = {};

        jQuery.ajax = function (options) {
            ajax_options = options;
            return ajax_request;
        };

        ajax_request.done = function (func) {
            func();
        };
        ajax_request.fail = function (func) {
        };
        ajax_request.responseText = 'response_body';

        var modal_box_options = null;
        var modal_box_content = null;
        Modalbox.show = function (data) {
            modal_box_content = data;
        };

        Util.ajax_modal("some_url", {title: "some_title"});

        assertEquals("some_url", ajax_options.url);
        assertContains('response_body', modal_box_content);
    });

    it("test_ajax_modal_failure", function () {

        var ajax_options = null;
        var ajax_request = {};

        jQuery.ajax = function (options) {
            ajax_options = options;
            return ajax_request;
        };

        ajax_request.done = function (func) {
        };
        ajax_request.fail = function (func) {
            func();
        };
        ajax_request.responseText = 'response_body';

        var modal_box_options = null;
        var modal_box_content = null;
        Modalbox.show = function (data, options) {
            modal_box_content = data;
            modal_box_options = options;
        };

        Util.ajax_modal("some_url", {title: "some_title"});

        assertEquals("some_url", ajax_options.url);
        assertContains('response_body', jQuery(modal_box_content)[0].innerHTML);
    });

    it("test_updates_dom_elements_on_callback", function () {
        var mapping = {name_foo: "id_bar", name_baz: "id_quux"};
        jQuery('#foo_link').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () {
            return this.innerHTML;
        }));
        jQuery('#baz_input').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () {
            return this.value;
        }));
        assertEquals("Original content", jQuery('#update_on_evt').text());
        fire_event($("foo_link"), 'click');
        assertEquals("id bar text", jQuery('#update_on_evt').text());
        fire_event($("baz_input"), 'click');
        assertEquals("id quux text", jQuery('#update_on_evt').text());
    });
});


text:
set -e

source ./../libbeat/scripts/wait_for.sh

# Main
waitFor ${APACHE_HOST} ${APACHE_PORT} Apache
waitFor ${CEPH_HOST} ${CEPH_PORT} Ceph
waitFor ${COUCHBASE_HOST} ${COUCHBASE_PORT} Couchbase
waitFor ${HAPROXY_HOST} ${HAPROXY_PORT} HAProxy
waitFor ${KAFKA_HOST} ${KAFKA_PORT} Kafka
waitFor ${MONGODB_HOST} ${MONGODB_PORT} MongoDB
waitFor ${MYSQL_HOST} ${MYSQL_PORT} MySQL
waitFor ${NGINX_HOST} ${NGINX_PORT} Nginx
waitFor ${PHPFPM_HOST} ${PHPFPM_PORT} PHP_FPM
waitFor ${POSTGRESQL_HOST} ${POSTGRESQL_PORT} Postgresql
waitFor ${PROMETHEUS_HOST} ${PROMETHEUS_PORT} Prometheus
waitFor ${REDIS_HOST} ${REDIS_PORT} Redis
waitFor ${ZOOKEEPER_HOST} ${ZOOKEEPER_PORT} Zookeeper
exec "$@"

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace MasterSmith.Classes {
	class Player : Creature {
		private List<Item> inventory = new List<Item>();

		public int inventoryWeight {
			get {
				int weight = 0;
				foreach (Item item in inventory) weight += item.weight;
				return weight;
			}
		}

		public Player(Vector2 position)	: base(position, Defaults.MAX_HP) {

		}

		public override void Update(GameTime gameTime) {
			base.Update(gameTime);

			KeyboardState state = Keyboard.GetState();
			if (onGround)
				velocity = Defaults.GetKeyboardInputDirection(state) * Defaults.PLAYER_SPEED;

			if (state.IsKeyDown(Keys.Space) && onGround) {
				velocity += new Vector2(0, -Defaults.JUMP_VELOCITY);
			}
		}

		public override void Move(Vector2 amount) {
			base.Move(amount);

			// Clamp player to screen
			Vector2 newPos = position;
			if (position.X < 0)
				newPos.X = 0;
			if (position.X >= Defaults.ScreenWidth - texture.Width)
				newPos.X = Defaults.ScreenWidth - texture.Width;

			position = newPos;
		}

		/// <summary>
		/// Add an item to the player's inventory if the player can carry it.
		/// </summary>
		/// <param name="item">Item to pickup.</param>
		/// <returns>True if picked up, false otherwise.</returns>
		public bool Pickup(Item item) {
			if (inventoryWeight + item.weight <= Defaults.MAX_CARRY_CAPACITY) {
				// pickup the item
				inventory.Add(item);
				return true;
			} else {
				// too heavy
				return false;
			}
		}
	}
}


text:
project=$1

dir=$(pwd)
wdir=$dir/dist/$project
basedir=$(dirname "$0")

if [ ! -d "$wdir" ];
then
	echo ERROR: project $project doesn\'t exists
	exit 1
fi

pkg_version=$(sh $basedir/package_info.sh $1 "version")
pkg_name=$(sh $basedir/package_info.sh $1 "name")

npm_version=$(npm show $pkg_name version)

echo "pkg name : $pkg_name"
echo "pkg version : $pkg_version"
echo "npm version : $npm_version"

if [ "$pkg_version" != "$npm_version" ];
then
	npm publish $wdir
	echo "$pkg_name@$pkg_version [updated]"
else
	echo "$pkg_name@$pkg_version [up_to_date]"
fi


text:
package esapi

import (
	"context"
	"net/http"
	"strings"
	"time"
)

func newIndicesDeleteIndexTemplateFunc(t Transport) IndicesDeleteIndexTemplate {
	return func(name string, o ...func(*IndicesDeleteIndexTemplateRequest)) (*Response, error) {
		var r = IndicesDeleteIndexTemplateRequest{Name: name}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// IndicesDeleteIndexTemplate deletes an index template.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html.
//
type IndicesDeleteIndexTemplate func(name string, o ...func(*IndicesDeleteIndexTemplateRequest)) (*Response, error)

// IndicesDeleteIndexTemplateRequest configures the Indices Delete Index Template API request.
//
type IndicesDeleteIndexTemplateRequest struct {
	Name string

	MasterTimeout time.Duration
	Timeout       time.Duration

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
//
func (r IndicesDeleteIndexTemplateRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "DELETE"

	path.Grow(1 + len("_index_template") + 1 + len(r.Name))
	path.WriteString("/")
	path.WriteString("_index_template")
	path.WriteString("/")
	path.WriteString(r.Name)

	params = make(map[string]string)

	if r.MasterTimeout != 0 {
		params["master_timeout"] = formatDuration(r.MasterTimeout)
	}

	if r.Timeout != 0 {
		params["timeout"] = formatDuration(r.Timeout)
	}

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), nil)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
//
func (f IndicesDeleteIndexTemplate) WithContext(v context.Context) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.ctx = v
	}
}

// WithMasterTimeout - specify timeout for connection to master.
//
func (f IndicesDeleteIndexTemplate) WithMasterTimeout(v time.Duration) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.MasterTimeout = v
	}
}

// WithTimeout - explicit operation timeout.
//
func (f IndicesDeleteIndexTemplate) WithTimeout(v time.Duration) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.Timeout = v
	}
}

// WithPretty makes the response body pretty-printed.
//
func (f IndicesDeleteIndexTemplate) WithPretty() func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
//
func (f IndicesDeleteIndexTemplate) WithHuman() func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f IndicesDeleteIndexTemplate) WithErrorTrace() func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
//
func (f IndicesDeleteIndexTemplate) WithFilterPath(v ...string) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
//
func (f IndicesDeleteIndexTemplate) WithHeader(h map[string]string) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f IndicesDeleteIndexTemplate) WithOpaqueID(s string) func(*IndicesDeleteIndexTemplateRequest) {
	return func(r *IndicesDeleteIndexTemplateRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
package endpoints
package play.client

import endpoints.algebra.{Decoder, Encoder, MuxRequest}
import endpoints.play.client.Endpoints.futureFromEither

import scala.concurrent.Future

trait MuxEndpoints extends algebra.Endpoints { self: Endpoints =>

  class MuxEndpoint[Req <: algebra.MuxRequest, Resp, Transport](
    request: Request[Transport],
    response: Response[Transport]
  ) {
    def apply(
      req: Req
    )(implicit
      encoder: Encoder[Req, Transport],
      decoder: Decoder[Transport, Resp]
    ): Future[req.Response] =
      request(encoder.encode(req)).flatMap { wsResponse =>
        futureFromEither(response(wsResponse).right.flatMap { t =>
          decoder.decode(t).asInstanceOf[Either[Throwable, req.Response]]
        })
      }
  }

  def muxEndpoint[Req <: MuxRequest, Resp, Transport](
    request: Request[Transport],
    response: Response[Transport]
  ): MuxEndpoint[Req, Resp, Transport] =
    new MuxEndpoint[Req, Resp, Transport](request, response)

}


text:
package org.n0pe.mojo.asadmin;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.ListFileUsers;

/**
 * @goal list-file-users
 */
public class ListFileUsersMojo
    extends AbstractAsadminMojo
{

    @Override
    protected AsAdminCmdList getAsCommandList()
        throws MojoExecutionException, MojoFailureException
    {
        getLog().info( "List file users" );
        AsAdminCmdList cmdList = new AsAdminCmdList();
        cmdList.add( new ListFileUsers() );
        return cmdList;
    }

}


text:
using UnityEngine;
using UnityEditor;

public class SplitterExample : EditorWindow
{

    [MenuItem("Window/Splitter Example")]
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        var window = GetWindow<SplitterExample>();
        window.titleContent = new GUIContent("Splitter Example Window");
        window.Show();
    }

    private float boxWidth = 300f;
    private float boxHeight = 50f;

    void OnGUI()
    {
        using (var horizontalScope = new EditorGUILayout.HorizontalScope())
        {
            GUILayout.Box(
                "Drag the right side of the box to change its width.\n Drag the bottom side of the box to change its height.",
                GUILayout.Width(boxWidth), GUILayout.Height(boxHeight));
            boxWidth = EditorGUILayoutExt.VerticalSplitter(2, boxWidth);
        }

        boxHeight = EditorGUILayoutExt.HorizontalSplitter(3, boxHeight);
    }

}


text:
package openmods.network.rpc;

@FunctionalInterface
public interface IRpcTargetProvider {
	public IRpcTarget createRpcTarget();
}


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccLoggingMetric_update(t *testing.T) {
	t.Parallel()

	suffix := randString(t, 10)
	filter := "resource.type=gae_app AND severity>=ERROR"
	updatedFilter := "resource.type=gae_app AND severity=ERROR"

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckLoggingMetricDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccLoggingMetric_update(suffix, filter),
			},
			{
				ResourceName:      "google_logging_metric.logging_metric",
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccLoggingMetric_update(suffix, updatedFilter),
			},
			{
				ResourceName:      "google_logging_metric.logging_metric",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccLoggingMetric_explicitBucket(t *testing.T) {
	t.Parallel()

	suffix := randString(t, 10)
	filter := "resource.type=gae_app AND severity>=ERROR"

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckLoggingMetricDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccLoggingMetric_explicitBucket(suffix, filter),
			},
			{
				ResourceName:      "google_logging_metric.logging_metric",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccLoggingMetric_descriptionUpdated(t *testing.T) {
	t.Parallel()

	suffix := randString(t, 10)

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckLoggingMetricDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccLoggingMetric_descriptionUpdated(suffix, "original"),
			},
			{
				ResourceName:      "google_logging_metric.logging_metric",
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccLoggingMetric_descriptionUpdated(suffix, "Updated"),
			},
			{
				ResourceName:      "google_logging_metric.logging_metric",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccLoggingMetric_update(suffix string, filter string) string {
	return fmt.Sprintf(`
resource "google_logging_metric" "logging_metric" {
  name   = "my-custom-metric-%s"
  filter = "%s"
  metric_descriptor {
    metric_kind  = "DELTA"
    value_type   = "INT64"
    display_name = "My metric"
  }
}
`, suffix, filter)
}

func testAccLoggingMetric_explicitBucket(suffix string, filter string) string {
	return fmt.Sprintf(`
resource "google_logging_metric" "logging_metric" {
  name   = "my-custom-metric-%s"
  filter = "%s"

  metric_descriptor {
    metric_kind = "DELTA"
    value_type  = "DISTRIBUTION"
  }

  value_extractor = "EXTRACT(jsonPayload.metrics.running_jobs)"

  bucket_options {
    explicit_buckets {
      bounds = [0, 1, 2, 3, 4.2]
    }
  }
}
`, suffix, filter)
}

func testAccLoggingMetric_descriptionUpdated(suffix, description string) string {
	return fmt.Sprintf(`
resource "google_logging_metric" "logging_metric" {
	name        = "my-custom-metric-%s"
	description = "Counter for  VM instances that have hostError's"
	filter      = "resource.type=gce_instance AND protoPayload.methodName=compute.instances.hostError"
	metric_descriptor {
	  metric_kind = "DELTA"
	  value_type  = "INT64"
	  labels {
		key         = "instance"
		value_type  = "STRING"
		description = "%s"
	  }
	  labels {
		key         = "zone"
		value_type  = "STRING"
		description = "Availability zone of instance"
	  }
	  display_name = "VM Host Errors"
	}
	label_extractors = {
	  "instance" = "REGEXP_EXTRACT(protoPayload.resourceName, \"projects/.+/zones/.+/instances/(.+)\")"
	  "zone"     = "EXTRACT(resource.labels.zone)"
	}
  }
`, suffix, description)
}


text:
@interface RCIsPresentTests : SenTestCase

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.mgnt.lifecycle.management.example</title>
<meta name="date" content="2022-10-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.mgnt.lifecycle.management.example

Interfaces

InfoFormatter

Classes

BaseInfoFormatter

InfoFormatterFactory


text:
Load external libs (not angular-based):

        <button class="btn btn-info" ng-click="loadBootstrap()" ng-disabled="bootstrapLoaded">Load Bootstrap</button>

Load a module by loading a state:

Go to "modal" state

        <button class="btn btn-info" ng-click="openModal()" ng-if="openModal">Open modal</button>

Autoload a complete module with dependencies and templates using the directive:

{{test}}


text:
package openmarker.trove.generics;

import java.lang.reflect.Constructor;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 *
 * @author Nick Hagan
 */
public class TypeVariableHandler
    extends AbstractGenericHandler<TypeVariable<?>> {

    private GenericType rawType;

    public TypeVariableHandler(GenericType rootType,
                               TypeVariable<?> genericType) {
        super(rootType, genericType);
    }

    @Override
    public GenericType getRawType() {
        if (this.rawType == null) {
            this.rawType = this.getRawType0();
        }

        return this.rawType;
    }

    @Override
    public int getDimensions() {
        return this.getRawType().getDimensions();
    }

    @Override
    public GenericType getComponentType() {
        return this.getRawType().getComponentType();
    }

    @Override
    public GenericType getRootComponentType() {
        return this.getRawType().getRootComponentType();
    }

    @Override
    public GenericType[] getTypeArguments() {
        return this.getRawType().getTypeArguments();
    }

    @SuppressWarnings("rawtypes")
    protected GenericType getRawType0() {
        TypeVariable<?> variable = this.getGenericType();

        // if no declaring root, try to resolve from type bounds
        // default to Object when type bounds does not exist
        GenericType rootType = this.getRootType();
        if (rootType == null) {
            Type[] bounds = variable.getBounds();
            if (bounds.length == 1) {
                return new GenericType(bounds[0]);
            }

            // no bounds found, so default to object
            return new GenericType(Object.class);
        }

        // otherwise, try to detect from the root object down to either the
        // method or class declaration encompassing the type variable
        String name = variable.getName();

        TypeParameter[] parameters = this.getTypeParameters(variable);
        for (int i = 0; i < parameters.length; i++) {
            TypeVariable<?> var = parameters[i].getParameter();

            // search for matching variable in the list of type params
            // from either the method, constructor or class declarations
            String variableName = parameters[i].getName();
            if (variableName.equals(name)) {
                GenericDeclaration declaration = var.getGenericDeclaration();

                // attempt to resolve the declared type argument of the
                // parameterized class by walking from the root to the
                // declared class
                GenericType result = null;
                if (declaration instanceof Class) {
                    result = resolveType
                    (
                        (Class) declaration,
                        this.getRootType(), parameters[i].getIndex()
                    );
                }

                // if unable to traverse the type, default to looking up
                // result from the bounds of the type
                if (result == null) {
                    Type[] bounds = var.getBounds();
                    if (bounds.length == 1) {
                        result =
                            new GenericType(this.getRootType(), bounds[0]);
                    }
                }

                // return if result found
                if (result != null) {
                    return result;
                }

                // otherwise, break and return object
                break;
            }
        }

        // unable to resolve, so default to object
        return new GenericType(Object.class);
    }

    protected GenericType resolveType(Class<?> typeClass,
                                      GenericType current, int index) {

        // use actual type if current not in tree
        if (!typeClass.isAssignableFrom(current.getType())) {
            return null;
        }

        // use current type if matches
        else if (typeClass.equals(current.getType())) {
            GenericType[] args = current.getTypeArguments();
            if (args != null && args.length > index) {
                return args[index];
            }

            return null;
        }

        // check if supertype matches
        GenericType supertype = current.getSupertype();
        if (supertype != null &&
            typeClass.isAssignableFrom(supertype.getType())) {

            // resolve type variable if supertype matches the type class
            if (supertype.getType().equals(typeClass)) {
                return resolveSubtype(supertype, index);
            }

            // otherwise recursively check the supertype on up the chain
            GenericType result =
                resolveType(typeClass, supertype, index);

            // if type found, return...otherwise, continue on to interfaces
            if (result != null) {
                return result;
            }
        }

        // check if any interface matches
        GenericType[] ifaces = current.getInterfaces();
        for (int j = 0; j < ifaces.length; j++) {
            GenericType iface = ifaces[j];

            // ignore if type class not in hiearchy of type clsas
            if (!typeClass.isAssignableFrom(iface.getType())) {
                continue;
            }

            // resolve type variable if match found
            if (iface.getType().equals(typeClass)) {
                return resolveSubtype(iface, index);
            }

            // otherwise recursively check the supertype on up the chain
            GenericType result = resolveType(typeClass, iface, index);

            // return if type found...otherwise, check remaining interfaces
            if (result != null) {
                return result;
            }
        }

        // none found so return null for no match
        return null;
    }

    protected GenericType resolveSubtype(GenericType type, int index) {
        GenericType result = null;
        Class<?> actualType = type.getType();
        Type genericType = type.getGenericType();

        // resolve against parameterized types
        if (genericType != null) {
            result = resolveSubtype(genericType, index);
        }

        // attempt to resolve against type variables
        if (result == null && actualType != null) {
            result = resolveSubtype(actualType, index);
        }

        // none found so return null for no match
        return result;
    }

    protected GenericType resolveSubtype(Type genericType, int index) {
        // check for available type arguments
        GenericType generic =
            new GenericType(this.getRootType(), genericType);

        GenericType[] arguments = generic.getTypeArguments();
        if (arguments != null && arguments.length > index) {
            return arguments[index].getRawType();
        }

        // none found so return null for no match
        return null;
    }

    protected GenericType resolveSubtype(Class<?> type, int index) {
        // attempt to resolve against type variables
        TypeVariable<?>[] variables = type.getTypeParameters();
        if (variables.length > index) {
            TypeVariable<?> variable = variables[index];
            Type[] bounds = variable.getBounds();
            if (bounds.length == 1) {
                return new GenericType(this.getRootType(), bounds[0]);
            }
        }

        // none found so return null for no match
        return null;
    }

    protected TypeParameter[] getTypeParameters(TypeVariable<?> variable) {
        Map<String, TypeParameter> parameters =
            new LinkedHashMap<String, TypeParameter>();

        GenericDeclaration declaration = variable.getGenericDeclaration();

        // handle method declarations
        // - pull variables from method, then declaring class
        // - method types override (or hide) class types, so ignore those
        if (declaration instanceof Method) {
            Method method = (Method) declaration;
            addTypeParameters(parameters, method);

            Class<?> declaringClass = method.getDeclaringClass();
            addTypeParameters(parameters, declaringClass);
        }

        // handle constructor declarations
        // - pull variables from constructor, then declaring class
        // - ctor types override (or hide) class types, so ignore those
        else if (declaration instanceof Constructor) {
            Constructor<?> ctor = (Constructor<?>) declaration;
            addTypeParameters(parameters, ctor);

            Class<?> declaringClass = ctor.getDeclaringClass();
            addTypeParameters(parameters, declaringClass);
        }

        // handle class declarations
        else if (declaration instanceof Class) {
            Class<?> declaringClass = (Class<?>) declaration;
            addTypeParameters(parameters, declaringClass);
        }

        // default to just pull from declaration
        else {
            addTypeParameters(parameters, declaration);
        }

        // convert to array form
        int size = parameters.size();
        return parameters.values().toArray(new TypeParameter[size]);
    }

    protected void addTypeParameters(Map<String, TypeParameter> parameters,
                                     GenericDeclaration declaration) {
        TypeVariable<?>[] types = declaration.getTypeParameters();
        for (int i = 0; i < types.length; i++) {
            TypeVariable<?> type = types[i];
            String name = type.getName();
            if (!parameters.containsKey(name)) {
                parameters.put(name, new TypeParameter(type, i));
            }
        }
    }

    protected static class TypeParameter {
        private final TypeVariable<?> parameter;
        private final int index;

        public TypeParameter(TypeVariable<?> parameter, int index) {
            this.parameter = parameter;
            this.index = index;
        }

        public String getName() {
            return this.parameter.getName();
        }

        public TypeVariable<?> getParameter() {
            return this.parameter;
        }

        public int getIndex() {
            return this.index;
        }
    }
}


text:
import kfp
import kfp.dsl as dsl
from kfp import components

from kubeflow.katib import ApiClient
from kubeflow.katib import V1beta1ExperimentSpec
from kubeflow.katib import V1beta1AlgorithmSpec
from kubeflow.katib import V1beta1ObjectiveSpec
from kubeflow.katib import V1beta1ParameterSpec
from kubeflow.katib import V1beta1FeasibleSpace
from kubeflow.katib import V1beta1TrialTemplate
from kubeflow.katib import V1beta1TrialParameterSpec

# You should define the Experiment name, namespace and number of training steps in the arguments.
def create_katib_experiment_task(experiment_name, experiment_namespace, training_steps):
    # Trial count specification.
    max_trial_count = 5
    max_failed_trial_count = 3
    parallel_trial_count = 2

    # Objective specification.
    objective = V1beta1ObjectiveSpec(
        type="minimize",
        goal=0.001,
        objective_metric_name="loss"
    )

    # Algorithm specification.
    algorithm = V1beta1AlgorithmSpec(
        algorithm_name="random",
    )

    # Experiment search space.
    # In this example we tune learning rate and batch size.
    parameters = [
        V1beta1ParameterSpec(
            name="learning_rate",
            parameter_type="double",
            feasible_space=V1beta1FeasibleSpace(
                min="0.01",
                max="0.05"
            ),
        ),
        V1beta1ParameterSpec(
            name="batch_size",
            parameter_type="int",
            feasible_space=V1beta1FeasibleSpace(
                min="80",
                max="100"
            ),
        )
    ]

    # Experiment Trial template.
    # TODO (andreyvelich): Use community image for the mnist example.
    trial_spec = {
        "apiVersion": "kubeflow.org/v1",
        "kind": "TFJob",
        "spec": {
            "tfReplicaSpecs": {
                "Chief": {
                    "replicas": 1,
                    "restartPolicy": "OnFailure",
                    "template": {
                        "metadata": {
                            "annotations": {
                                "sidecar.istio.io/inject": "false"
                            }
                        },
                        "spec": {
                            "containers": [
                                {
                                    "name": "tensorflow",
                                    "image": "docker.io/liuhougangxa/tf-estimator-mnist",
                                    "command": [
                                        "python",
                                        "/opt/model.py",
                                        "--tf-train-steps=" + str(training_steps),
                                        "--tf-learning-rate=${trialParameters.learningRate}",
                                        "--tf-batch-size=${trialParameters.batchSize}"
                                    ]
                                }
                            ]
                        }
                    }
                },
                "Worker": {
                    "replicas": 1,
                    "restartPolicy": "OnFailure",
                    "template": {
                        "metadata": {
                            "annotations": {
                                "sidecar.istio.io/inject": "false"
                            }
                        },
                        "spec": {
                            "containers": [
                                {
                                    "name": "tensorflow",
                                    "image": "docker.io/liuhougangxa/tf-estimator-mnist",
                                    "command": [
                                        "python",
                                        "/opt/model.py",
                                        "--tf-train-steps=" + str(training_steps),
                                        "--tf-learning-rate=${trialParameters.learningRate}",
                                        "--tf-batch-size=${trialParameters.batchSize}"
                                    ]
                                }
                            ]
                        }
                    }
                }
            }
        }
    }

    # Configure parameters for the Trial template.
    trial_template = V1beta1TrialTemplate(
        primary_container_name="tensorflow",
        primary_pod_labels={"training.kubeflow.org/job-role": "master"},
        trial_parameters=[
            V1beta1TrialParameterSpec(
                name="learningRate",
                description="Learning rate for the training model",
                reference="learning_rate"
            ),
            V1beta1TrialParameterSpec(
                name="batchSize",
                description="Batch size for the model",
                reference="batch_size"
            ),
        ],
        trial_spec=trial_spec
    )

    # Create an Experiment from the above parameters.
    experiment_spec = V1beta1ExperimentSpec(
        max_trial_count=max_trial_count,
        max_failed_trial_count=max_failed_trial_count,
        parallel_trial_count=parallel_trial_count,
        objective=objective,
        algorithm=algorithm,
        parameters=parameters,
        trial_template=trial_template
    )

    # Create the KFP task for the Katib Experiment.
    # Experiment Spec should be serialized to a valid Kubernetes object.
    katib_experiment_launcher_op = components.load_component_from_url(
        "https://raw.githubusercontent.com/kubeflow/pipelines/master/components/kubeflow/katib-launcher/component.yaml")
    op = katib_experiment_launcher_op(
        experiment_name=experiment_name,
        experiment_namespace=experiment_namespace,
        experiment_spec=ApiClient().sanitize_for_serialization(experiment_spec),
        experiment_timeout_minutes=60,
        delete_finished_experiment=False)

    return op

# This function converts Katib Experiment HP results to args.
def convert_katib_results(katib_results) -> str:
    import json
    import pprint
    katib_results_json = json.loads(katib_results)
    print("Katib results:")
    pprint.pprint(katib_results_json)
    best_hps = []
    for pa in katib_results_json["currentOptimalTrial"]["parameterAssignments"]:
        if pa["name"] == "learning_rate":
            best_hps.append("--tf-learning-rate=" + pa["value"])
        elif pa["name"] == "batch_size":
            best_hps.append("--tf-batch-size=" + pa["value"])
    print("Best Hyperparameters: {}".format(best_hps))
    return " ".join(best_hps)

# You should define the TFJob name, namespace, number of training steps, output of Katib and model volume tasks in the arguments.
def create_tfjob_task(tfjob_name, tfjob_namespace, training_steps, katib_op, model_volume_op):
    import json
    # Get parameters from the Katib Experiment.
    # Parameters are in the format "--tf-learning-rate=0.01 --tf-batch-size=100"
    convert_katib_results_op = components.func_to_container_op(convert_katib_results)
    best_hp_op = convert_katib_results_op(katib_op.output)
    best_hps = str(best_hp_op.output)

    # Create the TFJob Chief and Worker specification with the best Hyperparameters.
    # TODO (andreyvelich): Use community image for the mnist example.
    tfjob_chief_spec = {
        "replicas": 1,
        "restartPolicy": "OnFailure",
        "template": {
            "metadata": {
                "annotations": {
                    "sidecar.istio.io/inject": "false"
                }
            },
            "spec": {
                "containers": [
                    {
                        "name": "tensorflow",
                        "image": "docker.io/liuhougangxa/tf-estimator-mnist",
                        "command": [
                            "sh",
                            "-c"
                        ],
                        "args": [
                            "python /opt/model.py --tf-export-dir=/mnt/export --tf-train-steps={} {}".format(training_steps, best_hps)
                        ],
                        "volumeMounts": [
                            {
                                "mountPath": "/mnt/export",
                                "name": "model-volume"
                            }
                        ]
                    }
                ],
                "volumes": [
                    {
                        "name": "model-volume",
                        "persistentVolumeClaim": {
                            "claimName": str(model_volume_op.outputs["name"])
                        }
                    }
                ]
            }
        }
    }

    tfjob_worker_spec = {
        "replicas": 1,
        "restartPolicy": "OnFailure",
        "template": {
            "metadata": {
                "annotations": {
                    "sidecar.istio.io/inject": "false"
                }
            },
            "spec": {
                "containers": [
                    {
                        "name": "tensorflow",
                        "image": "docker.io/liuhougangxa/tf-estimator-mnist",
                        "command": [
                            "sh",
                            "-c",
                        ],
                        "args": [
                          "python /opt/model.py --tf-export-dir=/mnt/export --tf-train-steps={} {}".format(training_steps, best_hps)
                        ],
                    }
                ],
            }
        }
    }

    # Create the KFP task for the TFJob.
    tfjob_launcher_op = components.load_component_from_url(
        "https://raw.githubusercontent.com/kubeflow/pipelines/master/components/kubeflow/launcher/component.yaml")
    op = tfjob_launcher_op(
        name=tfjob_name,
        namespace=tfjob_namespace,
        chief_spec=json.dumps(tfjob_chief_spec),
        worker_spec=json.dumps(tfjob_worker_spec),
        tfjob_timeout_minutes=60,
        delete_finished_tfjob=False)
    return op

# You should define the model name, namespace, output of the TFJob and model volume tasks in the arguments.
def create_kserve_task(model_name, model_namespace, tfjob_op, model_volume_op):

    inference_service = '''
apiVersion: "serving.kserve.io/v1beta1"
kind: "InferenceService"
metadata:
  name: {}
  namespace: {}
  annotations:
    "sidecar.istio.io/inject": "false"
spec:
  predictor:
    tensorflow:
      storageUri: "pvc://{}/"
'''.format(model_name, model_namespace, str(model_volume_op.outputs["name"]))

    kserve_launcher_op = components.load_component_from_url(
        'https://raw.githubusercontent.com/kubeflow/pipelines/master/components/kserve/component.yaml')
    kserve_launcher_op(action="create", inferenceservice_yaml=inference_service).after(tfjob_op)

name="mnist-e2e"
namespace="kubeflow-user-example-com"
training_steps="200"

@dsl.pipeline(
    name="end-to-end-pipeline",
    description="An end to end mnist example including hyperparameter tuning, train and inference"
)
def mnist_pipeline(name=name, namespace=namespace, training_steps=training_steps):
    # Run the hyperparameter tuning with Katib.
    katib_op = create_katib_experiment_task(name, namespace, training_steps)

    # Create volume to train and serve the model.
    model_volume_op = dsl.VolumeOp(
        name="model-volume",
        resource_name="model-volume",
        size="1Gi",
        modes=dsl.VOLUME_MODE_RWM
    )

    # Run the distributive training with TFJob.
    tfjob_op = create_tfjob_task(name, namespace, training_steps, katib_op, model_volume_op)

    # Create the KServe inference.
    create_kserve_task(name, namespace, tfjob_op, model_volume_op)

if __name__ == '__main__':
    from kfp_tekton.compiler import TektonCompiler
    TektonCompiler().compile(mnist_pipeline, __file__.replace('.py', '.yaml'))


text:
'''Mini Excel'''

__author__ = "Miki Tebeka <miki@mikitebeka.com>"

import wx
from wx.grid import (
    Grid, PyGridTableBase, GridTableMessage, GRIDTABLE_REQUEST_VIEW_GET_VALUES,
    EVT_GRID_CELL_LEFT_CLICK
)

from math import * # Get math functions in namespace
import re

# Make sure cell is not quoted yet
cell_re = re.compile("((?<!--\")[A-Z]\d+)")
range_re = re.compile("([A-Z]\d+):([A-Z]\d+)")
NUM_ROWS, NUM_COLS = 20, 10 # Arbitrary grid size
CELLS = {} # (row, col) --> cell

def get_cell_value(row, col):
    cell = CELLS.get((row, col), None)
    if cell:
        return cell.calculate()
    else:
        return None

def name2location(cell_name):
    col, row = cell_name[0], cell_name[1:]
    col = ord(col) - ord("A")
    row = int(row)

    return row, col

def cell(cell_name):
    row, col = name2location(cell_name)
    return get_cell_value(row, col)

def cell_range(start, end):
    start_row, start_col = name2location(start)
    end_row, end_col = name2location(end)

    if start_row == end_row:
        indexes = [(start_row, col) for col in range(start_col, end_col + 1)]
    elif start_col == end_col:
        indexes = [(row, end_col) for row in range(start_row, end_row + 1)]
    else:
        raise ValueError

    return [get_cell_value(row, col) for row, col in indexes]

class TableCell:
    def __init__(self, value):
        self.value = value

    def calculate(self):
        try:
            return float(self.value)
        except ValueError:
            return self.value

class FunctionTableCell(TableCell):
    def __init__(self, value):
        TableCell.__init__(self, value)

        # Convert expression to valid Python expression
        # Replace `A4:A10` with `cell_range("A4", "A10")`
        self.py_expr = range_re.sub("cell_range(\"\\1\", \"\\2\")", value[1:])
        # Replace `A4` with `cell("A4")`
        self.py_expr = cell_re.sub("cell(\"\\1\")", self.py_expr)

    def calculate(self):
        return eval(self.py_expr)

class Table(PyGridTableBase):
    def __init__(self):
        PyGridTableBase.__init__(self)

    def GetNumberCols(self):
        return NUM_COLS

    def GetNumberRows(self):
        return NUM_ROWS

    def GetColLabelValue(self, col):
        return chr(ord("A") + col)

    def GetRowLabelValue(self, row):
        return "%d" % row

    def GetValue(self, row, col):
        try:
            value = get_cell_value(row, col)
            if value is None:
                return ""
            return str(value)
        except Exception:
            return "#ERR"

    def SetValue(self, row, col, value):
        if value.startswith("="):
            cell = FunctionTableCell(value)
        else:
            cell = TableCell(value)

        CELLS[(row, col)] = cell

        # Notify change
        msg = GridTableMessage(None, GRIDTABLE_REQUEST_VIEW_GET_VALUES)
        self.GetView().ProcessTableMessage(msg)

class MiniExcel(wx.Dialog):
    def __init__(self):
        wx.Dialog.__init__(self, None, -1, "Mini Excel")
        sizer = wx.BoxSizer(wx.VERTICAL)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(wx.StaticText(self, -1, "Value:"), 0,
                   wx.ALIGN_CENTER_VERTICAL)
        self.cell_value = wx.TextCtrl(self, -1)
        hsizer.Add(self.cell_value, 1, wx.EXPAND)
        b = wx.Button(self, -1, "&Set")
        self.Bind(wx.EVT_BUTTON, self.OnSetCell, b)
        hsizer.Add(b)
        sizer.Add(hsizer, 0, wx.EXPAND)

        grid = Grid(self)
        grid.SetTable(Table())
        grid.ForceRefresh()
        self.grid = grid

        self.Bind(EVT_GRID_CELL_LEFT_CLICK, self.OnCellClick, grid)
        self.current_cell = (0, 0)

        sizer.Add(grid, 1, wx.EXPAND)
        self.SetSizer(sizer)
        sizer.Fit(self)
        grid.SetFocus()

        self.CenterOnScreen()

    def OnSetCell(self, evt):
        value = self.cell_value.GetValue().strip()
        table = self.grid.GetTable()

        table.SetValue(self.current_cell[0], self.current_cell[1], value)

    def OnCellClick(self, evt):
        row = evt.GetRow()
        col = evt.GetCol()

        self.current_cell = (row, col)

        cell = CELLS.get((row, col), None)
        if cell:
            self.cell_value.SetValue(str(cell.value))
        else:
            self.cell_value.SetValue("")
            evt.Skip() # Let the grid process the event as well

if __name__ == "__main__":
    app = wx.PySimpleApp()
    dlg = MiniExcel()
    dlg.ShowModal()


text:
.form-control .select2-choice {
	border: 0;
	border-radius: 2px;
}

.form-control .select2-choice .select2-arrow {
	border-radius: 0 2px 2px 0;
}

.form-control.select2-container {
	height: auto !important;
	padding: 0px;
}

.form-control.select2-container.select2-dropdown-open {
	border-color: #5897FB;
	border-radius: 3px 3px 0 0;
}

.form-control .select2-container.select2-dropdown-open .select2-choices
	{
	border-radius: 3px 3px 0 0;
}

.form-control.select2-container .select2-choices {
	border: 0 !important;
	border-radius: 3px;
}

.control-group.warning .select2-container .select2-choice,
	.control-group.warning .select2-container .select2-choices,
	.control-group.warning .select2-container-active .select2-choice,
	.control-group.warning .select2-container-active .select2-choices,
	.control-group.warning .select2-dropdown-open.select2-drop-above .select2-choice,
	.control-group.warning .select2-dropdown-open.select2-drop-above .select2-choices,
	.control-group.warning .select2-container-multi.select2-container-active .select2-choices
	{
	border: 1px solid #C09853 !important;
}

.control-group.warning .select2-container .select2-choice div {
	border-left: 1px solid #C09853 !important;
	background: #FCF8E3 !important;
}

.control-group.error .select2-container .select2-choice, .control-group.error .select2-container .select2-choices,
	.control-group.error .select2-container-active .select2-choice,
	.control-group.error .select2-container-active .select2-choices,
	.control-group.error .select2-dropdown-open.select2-drop-above .select2-choice,
	.control-group.error .select2-dropdown-open.select2-drop-above .select2-choices,
	.control-group.error .select2-container-multi.select2-container-active .select2-choices
	{
	border: 1px solid #B94A48 !important;
}

.control-group.error .select2-container .select2-choice div {
	border-left: 1px solid #B94A48 !important;
	background: #F2DEDE !important;
}

.control-group.info .select2-container .select2-choice, .control-group.info .select2-container .select2-choices,
	.control-group.info .select2-container-active .select2-choice,
	.control-group.info .select2-container-active .select2-choices,
	.control-group.info .select2-dropdown-open.select2-drop-above .select2-choice,
	.control-group.info .select2-dropdown-open.select2-drop-above .select2-choices,
	.control-group.info .select2-container-multi.select2-container-active .select2-choices
	{
	border: 1px solid #3A87AD !important;
}

.control-group.info .select2-container .select2-choice div {
	border-left: 1px solid #3A87AD !important;
	background: #D9EDF7 !important;
}

.control-group.success .select2-container .select2-choice,
	.control-group.success .select2-container .select2-choices,
	.control-group.success .select2-container-active .select2-choice,
	.control-group.success .select2-container-active .select2-choices,
	.control-group.success .select2-dropdown-open.select2-drop-above .select2-choice,
	.control-group.success .select2-dropdown-open.select2-drop-above .select2-choices,
	.control-group.success .select2-container-multi.select2-container-active .select2-choices
	{
	border: 1px solid #468847 !important;
}

.control-group.success .select2-container .select2-choice div {
	border-left: 1px solid #468847 !important;
	background: #DFF0D8 !important;
}


text:
APP_NAME="rails-demo"
APP_USER="rails"
APP_SCRIPT_NAME="unicorn"

# Path to the Mina deploy directory
MINA_DEPLOY_DIR=/home/$APP_USER/$APP_NAME

# Path to the Rails app
APP_PATH=$MINA_DEPLOY_DIR/current

# Unicorn configuration file
UNICORN_CONF=$MINA_DEPLOY_DIR/shared/config/unicorn.conf.rb

# Path to Unicorn PID file (as specified in unicorn configuration file)
PIDFILE=$MINA_DEPLOY_DIR/shared/unicorn.pid

# User to run unicorn as
UNICORN_USER=$APP_USER

# determine the rvm wrapper script for unicorn that sets up the ruby environment
# for the app according to its .ruby-version
# See: https://github.com/wayneeseguin/rvm/issues/3365
RVM=/home/$APP_USER/.rvm/bin/rvm
DAEMON="$RVM in $APP_PATH do bundle exec unicorn"

DAEMON_ARGS="-D -c $UNICORN_CONF -E production"

# Do NOT "set -e": https://serverfault.com/questions/143445/what-does-set-e-do-and-why-might-it-be-considered-dangerous

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=$APP_NAME
NAME=$APP_SCRIPT_NAME
SCRIPTNAME=/etc/init.d/$APP_SCRIPT_NAME

# -----------------------------------------------------------------
# This is copied from /etc/init.d/skeleton
# changes:
# - added "--chuid $UNICORN_USER", removed "--name $NAME"
# - enabled reload
# - added -p $PIDFILE to status

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --chuid $UNICORN_USER --test > /dev/null \
		|| return 1
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --chuid $UNICORN_USER -- \
		$DAEMON_ARGS \
		|| return 2
	# Add code here, if necessary, that waits for the process to be ready
	# to handle requests from services started subsequently which depend
	# on this one.  As a last resort, sleep for some time.
}

#
# Function that stops the daemon/service
#
do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE
	RETVAL="$?"
	[ "$RETVAL" = 2 ] && return 2
	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
	[ "$?" = 2 ] && return 2
	# Many daemons don't delete their pidfiles when they exit.
	rm -f $PIDFILE
	return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
	start-stop-daemon --stop --signal HUP --quiet --pidfile $PIDFILE
	return 0
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  status)
	status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $?
	;;
  reload)
	log_daemon_msg "Reloading $DESC" "$NAME"
	do_reload
	log_end_msg $?
	;;
  restart|force-reload)
	#
	# If the "reload" option is implemented then remove the
	# 'force-reload' alias
	#
	log_daemon_msg "Restarting $DESC" "$NAME"
	do_stop
	case "$?" in
	  0|1)
		do_start
		case "$?" in
			0) log_end_msg 0 ;;
			1) log_end_msg 1 ;; # Old process is still running
			*) log_end_msg 1 ;; # Failed to start
		esac
		;;
	  *)
		# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
	exit 3
	;;
esac

:


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shanegenschaw.cervezacountdown"
    android:versionCode="4"
    android:versionName="4.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.shanegenschaw.cervezacountdown.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { DenseMatrixDependencies } from './dependenciesDenseMatrixClass.generated';
import { matrixDependencies } from './dependenciesMatrix.generated';
import { typedDependencies } from './dependenciesTyped.generated';
import { createXor } from '../../factoriesAny.js';
export var xorDependencies = {
  DenseMatrixDependencies: DenseMatrixDependencies,
  matrixDependencies: matrixDependencies,
  typedDependencies: typedDependencies,
  createXor: createXor
};


text:
var __MAX_LAYOUT_COLUMN_ = 2;

var __JOB_DISPLAY_SIDE_OFFSET = 0.05;
var __JOB_DISPLAY_CENTER_OFFSET = 0.1;
var __JOB_DISPLAY_INTERROW_OFFSET = 0.05;

var __CAT_DISPLAY_SIDE_OFFSET = 0.05;
var __CAT_DISPLAY_CENTER_OFFSET = 0.1;
var __CAT_DISPLAY_INTERROW_OFFSET = 0.15;

var __JOB_PANEL_HEIGHT = 50;
var __CAT_PANEL_HEIGHT = 50;

var appDimensionObject = {

  //Application Dimensions
  appWidth : 0,
  appHeight : 0,

  jobPanelWidth : 0,
  jobPanelHeight : __JOB_PANEL_HEIGHT,

  catPanelWidth : 0,
  catPanelHeight : __CAT_PANEL_HEIGHT,

}

var appLayoutObject = {

  joblistXOffset : 0,
  joblistYOffset : 0,

  joblistInterXOffset : 0,
  joblistInterYOffset : 0,

  catXOffset : 0,
  catYOffset : 0,

  catInterXOffset : 0,
  catInterYOffset : 0,

}

var LayoutManager = {}

LayoutManager.calcAppDimensions = function calcAppDimensions(){

  appDimensionObject.appWidth  = window.innerWidth;
  appDimensionObject.appHeight = window.innerHeight;

  appDimensionObject.catPanelWidth = (appDimensionObject.appWidth * 0.6) * 0.4;

  appDimensionObject.jobPanelWidth = appDimensionObject.appWidth * 0.4;

  appLayoutObject.joblistXOffset = appDimensionObject.appWidth * __JOB_DISPLAY_SIDE_OFFSET;
  appLayoutObject.joblistInterXOffset = appDimensionObject.appWidth * __JOB_DISPLAY_CENTER_OFFSET;

  appLayoutObject.joblistYOffset = appDimensionObject.appWidth * __JOB_DISPLAY_SIDE_OFFSET;
  appLayoutObject.joblistInterYOffset = appDimensionObject.appHeight * __JOB_DISPLAY_INTERROW_OFFSET;

  appLayoutObject.catXOffset = (appDimensionObject.appWidth * 0.6) * __CAT_DISPLAY_SIDE_OFFSET;
  appLayoutObject.catInterXOffset = (appDimensionObject.appWidth * 0.6) * __CAT_DISPLAY_CENTER_OFFSET;

  appLayoutObject.catYOffset = (appDimensionObject.appWidth * 0.6) * __CAT_DISPLAY_SIDE_OFFSET;
  appLayoutObject.catInterYOffset = (appDimensionObject.appHeight * 0.6) * __CAT_DISPLAY_INTERROW_OFFSET;

}

LayoutManager.getAppDimensionWidth = function getAppDimensionWidth(){

  return appDimensionObject.appWidth;

}

LayoutManager.getAppDimensionHeight = function getAppDimensionHeight(){

  return appDimensionObject.appHeight;

}

LayoutManager.getAppJobDisplaySideOffset = function getAppJobDisplaySideOffset(){
  return __JOB_DISPLAY_SIDE_OFFSET;
}

LayoutManager.getAppJobDisplayCenterOffset = function getAppJobDisplayCenterOffset(){
  return __JOB_DISPLAY_CENTER_OFFSET;
}

LayoutManager.getAppJobDisplayWidth = function getAppJobDisplayWidth(){
  return appDimensionObject.jobPanelWidth;
}

LayoutManager.getAppJobDisplayHeight = function getAppJobDisplayHeight(){
  return appDimensionObject.jobPanelHeight;
}

LayoutManager.getAppCatDisplayWidth = function getAppCatDisplayWidth(){
  return appDimensionObject.catPanelWidth;
}

LayoutManager.getAppCatDisplayHeight = function getAppCatDisplayHeight(){
  return appDimensionObject.catPanelHeight;
}

LayoutManager.getAppJobDisplayPanelHeight = function getAppJobDisplayPanelHeight(numOfJobs){

  var numOfRows =  Math.ceil(numOfJobs / __MAX_LAYOUT_COLUMN_);

  var YSpan =  appLayoutObject.joblistInterYOffset + appDimensionObject.jobPanelHeight;

  return (YSpan * numOfRows) + (appLayoutObject.joblistYOffset * 2);

}

LayoutManager.getJobPanelPosition = function getJobPanelPosition(pSeq){

  var rowPos =  Math.ceil(pSeq / __MAX_LAYOUT_COLUMN_);

  var colPos = pSeq % __MAX_LAYOUT_COLUMN_ ? pSeq % __MAX_LAYOUT_COLUMN_ : __MAX_LAYOUT_COLUMN_;

  var XPos =  appLayoutObject.joblistXOffset + ((colPos - 1) * appLayoutObject.joblistInterXOffset) + ((colPos - 1) * appDimensionObject.jobPanelWidth);

  var YPos =  appLayoutObject.joblistYOffset + ((rowPos - 1) * appLayoutObject.joblistInterYOffset) + ((rowPos - 1) * appDimensionObject.jobPanelHeight);

  return [XPos , YPos , 50];

}

LayoutManager.getCatPanelPosition = function getCatPanelPosition(pSeq){

  var rowPos =  Math.ceil(pSeq / __MAX_LAYOUT_COLUMN_);

  var colPos = pSeq % __MAX_LAYOUT_COLUMN_ ? pSeq % __MAX_LAYOUT_COLUMN_ : __MAX_LAYOUT_COLUMN_;

  var XPos =  appLayoutObject.catXOffset + ((colPos - 1) * appLayoutObject.catInterXOffset) + ((colPos - 1) * appDimensionObject.catPanelWidth);

  var YPos =  appLayoutObject.catYOffset + ((rowPos - 1) * appLayoutObject.catInterYOffset) + ((rowPos - 1) * appDimensionObject.catPanelHeight);

  return [XPos , YPos , 50];

}

module.exports = LayoutManager;


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>
    <color name="window_background">#FFF5F5F5</color>
    <color name="check_background" >#D755E5</color>
</resources>


text:
class PagesController < ApplicationController
  include HighVoltage::StaticPage

  # before_filter :authenticate
  # layout :layout_for_page

  private

  def layout_for_page
    case params[:id]
    when 'home'
      'home'
    else
      'application'
    end
  end
end


text:
<?php

namespace App\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        //print_r(\Util\UserSession::getCurrentSessionID());
        $this->layout('layout/layout_client');
        return new ViewModel();
    }
}


text:
.class final Landroid/hardware/camera2/impl/CameraMetadataNative$1;
.super Ljava/lang/Object;
.source "CameraMetadataNative.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/camera2/impl/CameraMetadataNative;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/hardware/camera2/impl/CameraMetadataNative;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 68
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/hardware/camera2/impl/CameraMetadataNative;
    .locals 1
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    .line 71
    new-instance v0, Landroid/hardware/camera2/impl/CameraMetadataNative;

    invoke-direct {v0}, Landroid/hardware/camera2/impl/CameraMetadataNative;-><init>()V

    .line 72
    .local v0, "metadata":Landroid/hardware/camera2/impl/CameraMetadataNative;
    invoke-virtual {v0, p1}, Landroid/hardware/camera2/impl/CameraMetadataNative;->readFromParcel(Landroid/os/Parcel;)V

    .line 73
    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # Landroid/os/Parcel;

    .prologue
    .line 68
    invoke-virtual {p0, p1}, Landroid/hardware/camera2/impl/CameraMetadataNative$1;->createFromParcel(Landroid/os/Parcel;)Landroid/hardware/camera2/impl/CameraMetadataNative;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/hardware/camera2/impl/CameraMetadataNative;
    .locals 1
    .param p1, "size"    # I

    .prologue
    .line 78
    new-array v0, p1, [Landroid/hardware/camera2/impl/CameraMetadataNative;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # I

    .prologue
    .line 68
    invoke-virtual {p0, p1}, Landroid/hardware/camera2/impl/CameraMetadataNative$1;->newArray(I)[Landroid/hardware/camera2/impl/CameraMetadataNative;

    move-result-object v0

    return-object v0
.end method


text:
var Dicer = require('..');
var assert = require('assert'),
    fs = require('fs'),
    path = require('path'),
    inspect = require('util').inspect;

var FIXTURES_ROOT = __dirname + '/fixtures/';

var t = 0,
    group = path.basename(__filename, '.js') + '/';

var tests = [
  { source: 'many',
    opts: { boundary: '----WebKitFormBoundaryWLHCs9qmcJJoyjKR' },
    chsize: 16,
    nparts: 7,
    what: 'Extra trailer data pushed after finished'
  },
];

function next() {
  if (t === tests.length)
    return;
  var v = tests[t],
      fixtureBase = FIXTURES_ROOT + v.source,
      fd,
      n = 0,
      buffer = Buffer.allocUnsafe(v.chsize),
      state = { parts: [] };

  fd = fs.openSync(fixtureBase + '/original', 'r');

  var dicer = new Dicer(v.opts),
      error,
      partErrors = 0,
      finishes = 0;

  dicer.on('part', function(p) {
    var part = {
      body: undefined,
      bodylen: 0,
      error: undefined,
      header: undefined
    };

    p.on('header', function(h) {
      part.header = h;
    }).on('data', function(data) {
      // make a copy because we are using readSync which re-uses a buffer ...
      var copy = Buffer.allocUnsafe(data.length);
      data.copy(copy);
      data = copy;
      if (!part.body)
        part.body = [ data ];
      else
        part.body.push(data);
      part.bodylen += data.length;
    }).on('error', function(err) {
      part.error = err;
      ++partErrors;
    }).on('end', function() {
      if (part.body)
        part.body = Buffer.concat(part.body, part.bodylen);
      state.parts.push(part);
    });
  }).on('error', function(err) {
    error = err;
  }).on('finish', function() {
    assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));

    if (v.dicerError)
      assert(error !== undefined, makeMsg(v.what, 'Expected error'));
    else
      assert(error === undefined, makeMsg(v.what, 'Unexpected error'));

    if (v.events && v.events.indexOf('part') > -1) {
      assert.equal(state.parts.length,
                   v.nparts,
                   makeMsg(v.what,
                           'Part count mismatch:\nActual: '
                           + state.parts.length
                           + '\nExpected: '
                           + v.nparts));

      if (!v.npartErrors)
        v.npartErrors = 0;
      assert.equal(partErrors,
                   v.npartErrors,
                   makeMsg(v.what,
                           'Part errors mismatch:\nActual: '
                           + partErrors
                           + '\nExpected: '
                           + v.npartErrors));

      for (var i = 0, header, body; i < v.nparts; ++i) {
        if (fs.existsSync(fixtureBase + '/part' + (i+1))) {
          body = fs.readFileSync(fixtureBase + '/part' + (i+1));
          if (body.length === 0)
            body = undefined;
        } else
          body = undefined;
        assert.deepEqual(state.parts[i].body,
                         body,
                         makeMsg(v.what,
                                 'Part #' + (i+1) + ' body mismatch'));
        if (fs.existsSync(fixtureBase + '/part' + (i+1) + '.header')) {
          header = fs.readFileSync(fixtureBase
                                   + '/part' + (i+1) + '.header', 'binary');
          header = JSON.parse(header);
        } else
          header = undefined;
        assert.deepEqual(state.parts[i].header,
                         header,
                         makeMsg(v.what,
                                 'Part #' + (i+1)
                                 + ' parsed header mismatch:\nActual: '
                                 + inspect(state.parts[i].header)
                                 + '\nExpected: '
                                 + inspect(header)));
      }
    }
    ++t;
    next();
  });

  while (true) {
    n = fs.readSync(fd, buffer, 0, buffer.length, null);
    if (n === 0) {
      setTimeout(function() {
        dicer.write('\r\n\r\n\r\n');
        dicer.end();
      }, 50);
      break;
    }
    dicer.write(n === buffer.length ? buffer : buffer.slice(0, n));
  }
  fs.closeSync(fd);
}
next();

function makeMsg(what, msg) {
  return '[' + group + what + ']: ' + msg;
}

process.on('exit', function() {
  assert(t === tests.length,
         makeMsg('_exit', 'Only ran ' + t + '/' + tests.length + ' tests'));
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Alectoria forissii var. penduloides Gyeln.

### Remarks
null


text:
package org.geojson;

public class LineString extends MultiPoint {

	public LineString() {
	}

	public LineString(LngLatAlt... points) {
		super(points);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.andrl</groupId>
    <artifactId>example-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>default</id>
            <activation>
                <property>
                    <name>!spring.profiles.active</name>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <optional>true</optional>
                </dependency>
            </dependencies>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <jvmArguments>-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments>
                            <fork>true</fork>
                        </configuration>
                    </plugin>
                </plugins>
            </build>

        </profile>
    </profiles>

</project>


text:
@interface LYSLineChart : UIView
@property (nonatomic,assign)UIEdgeInsets edgeInsets;        // 内容边距
@property (nonatomic,assign)UIEdgeInsets canvasEdgeInsets;  // 画布边距
@property (nonatomic,strong)LYAxisStyle *xStyle;            // x轴样式
@property (nonatomic,strong)LYAxisStyle *yStyle;            // y轴样式

@property (nonatomic,assign)NSInteger row;                  // 图表有多少行
@property (nonatomic,assign)NSInteger column;               // 图表有多少列

@property (nonatomic,assign)CGFloat rowSpace;               // 竖直方向每一行间距
@property (nonatomic,assign)CGFloat columnSpace;            // 水平方向每一列间距

@property (nonatomic,assign)BOOL isShowGriddingGuide;       // 是否显示网格线
@property (nonatomic,strong)LYGuideStyle *griddingStyle;    // 网格样式

@property (nonatomic,assign)BOOL isShowHorizontalGuide;     // 是否显示水平辅助线
@property (nonatomic,strong)LYGuideStyle *horizontalStyle;  // 水平线样式

@property (nonatomic,assign)BOOL isShowVerticalGuide;       // 是否显示竖直辅助线
@property (nonatomic,strong)LYGuideStyle *verticalStyle;    // 竖直线样式

@property (nonatomic,strong)NSArray *columnData;            // x轴下标
@property (nonatomic,strong)NSArray *valueData;             // 展示数据
@property (nonatomic,assign)NSInteger precisionScale;       // 计算精度,10,100,1000,默认是1
@property (nonatomic,assign)NSInteger yAxisPrecisionScale;  // y轴下标计算精度,0,1,2,3,4,5,默认是2

@property (nonatomic,strong)LYAxisDataStyle *xAxisDataStyle;   // x轴下标样式
@property (nonatomic,strong)LYAxisDataStyle *yAxisDataStyle;   // y轴下标样式

@property (nonatomic,assign)BOOL isPercent;                    // 是否是百分比
@property (nonatomic,assign)BOOL isHundredPercent;             // 是否最大值100%

@property (nonatomic,strong)LYAxisDataStyle *yValueDataStyle;  // 显示数据样式

@property (nonatomic,assign)BOOL isShowBenchmarkLine;          // 是否显示阈值线
@property (nonatomic,strong)LYBenchmarkLineStyle *benchmarkLineStyle; // 阈值线样式

@property (nonatomic,strong)UIColor *lineChartFillColor;       // 折线图填充颜色
@property (nonatomic,strong)UIColor *lineChartColor;           // 折线颜色
@property (nonatomic,assign)CGFloat lineChartWidth;            // 折线宽度
@property (nonatomic,assign)CGFloat lineChartDotRadius;        // 折线圆点
@property (nonatomic,strong)UIColor *lineChartDotColor;        // 折线圆点颜色

@property (nonatomic,assign)BOOL isCurve;                      // 曲线
@property (nonatomic,assign)BOOL isGradient;                   // 填充渐变

// 绘制图表
- (void)reloadData;
@end


text:
```typescript
function reducer(state, action) {
  switch (action.type) {
    case 'LOAD_VILLAGERS':
      return {
        ...state,
        villagers: action.payload,
      };
    case 'SELECT_SORT':
      return {
        ...state,
        selectedSortOption: action.payload,
      };
    default:
      return state;
  }
}
```


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="Shaka Player Demo">
    <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="theme-color" content="#ffffff">

    <base target="_blank">

    <title>Shaka Player Demo</title>

    <link rel="manifest" href="app_manifest.json">
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="demo.css">
    <link rel="stylesheet" href="common/controls.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Condensed">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Shaka Player

          uncompiled |
          compiled (debug) |
          compiled (release)

This is a demo of Google's Shaka Player, a JavaScript library for
           adaptive video streaming.

Choose an asset and tap Load.
           (On Android, you may also need to press the play button on the
            video.)

          Documentation |
          Repo |
          NPM |
          CDNJS

          Asset:
          <select id="assetList" class="flex-grow"></select>

            Custom manifest:
            <input id="manifestInput" type="text" class="flex-grow">

            Custom license server:
            <input id="licenseServerInput" type="text" class="flex-grow">

            Custom license certificate URL:
            <input id="certificateInput" type="text" class="flex-grow">

          <button id="loadButton">Load</button>
          <button id="unloadButton">Unload</button>

x

        <video id="video" autoplay></video>

          <button id="giantPlayButton" class="material-icons">play_arrow</button>

          <svg class="spinnerSvg" viewBox="25 25 50 50">
            <circle class="spinnerPath" cx="50" cy="50" r="20"
                    fill="none" stroke-width="2" stroke-miterlimit="10" />
          </svg>

          <button id="playPauseButton" class="material-icons">play_arrow</button>
          seek
          <input id="seekBar" type="range" step="any" min="0" max="1" value="0">
          <button id="rewindButton" class="material-icons">fast_rewind</button>

0:00

          <button id="fastForwardButton" class="material-icons">fast_forward</button>
          <button id="muteButton" class="material-icons">volume_up</button>
          volume
          <input id="volumeBar" type="range" step="any" min="0" max="1" value="0">
          <button id="castButton" class="material-icons">cast</button>
          <button id="captionButton" class="material-icons">closed_caption</button>
          <button id="fullscreenButton" class="material-icons">fullscreen</button>

        Logs

        Configuration

          Preferred audio language:
          <input id="preferredAudioLanguage" class="flex-grow" type="text">

          Preferred text language:
          <input id="preferredTextLanguage" class="flex-grow" type="text">

          Preferred audio channel count:
          <input id="preferredAudioChannelCount" type="number">

          Show native browser controls:
          <input id="showNative" type="checkbox">

          Show trick play controls:
          <input id="showTrickPlay" type="checkbox">

          Enable adaptation:
          <input id="enableAdaptation" type="checkbox" checked>

          Auto-load on page refresh:
          <input id="enableLoadOnRefresh" type="checkbox">

          Log to the screen:
          <input id="logToScreen" type="checkbox">

          Maximum small gap size:
          <input id="smallGapLimit" class="flex-grow" type="text">

          Jump large gaps:
          <input id="jumpLargeGaps" type="checkbox">

          Log Level:
          <select id="logLevelList" class="flex-grow">
            <option value="info">Info</option>
            <option value="debug">Debug</option>
            <option value="v">Verbose</option>
            <option value="vv">Very Verbose</option>
          </select>

          Video Robustness:
          <input id="drmSettingsVideoRobustness" type="text" class="flex-grow" list="robustnessSuggestions">

          Audio Robustness:
          <input id="drmSettingsAudioRobustness" type="text" class="flex-grow" list="robustnessSuggestions">

	<datalist id="robustnessSuggestions"></datalist>

        Info

          Audio languages:
          <select id="audioLanguages" class="flex-grow"></select>

          Video+audio track combinations:
          <select id="variantTracks" class="flex-grow"></select>

          Text languages:
          <select id="textLanguages" class="flex-grow"></select>

          Text tracks:
          <select id="textTracks" class="flex-grow"></select>

          Active resolution:

          Buffered:

        Offline

          <button id="storeDeleteButton">Store</button>

          Progress:
          0%

          Name:
          <input id="offlineName" class="flex-grow" type="text">


text:
module Improb.Transition where

import Improb.AST

import System.Random

type MarkovMap = [(MusicPattern, [MusicPattern])]
type MarkovState = (MusicPattern, StdGen)

begin :: StdGen -> [MusicPattern] -> MarkovState
begin g beginStates =
    let (index, newGen) = randomR (0, length beginStates - 1) g
        startPattern = beginStates !! index
    in
        (startPattern, newGen)

transition :: MarkovMap -> MarkovState -> Either MarkovState MusicPattern
transition store (state, gen) =
    let options = possibleTransitions store state
    in  case options of
            [] -> Right state
            _  ->
                let (index, newGen) = randomR (0, length options - 1) gen
                    nextSegment = options !! index
                in  Left (rightAlign (Continuation state nextSegment), newGen)
    where
        rightAlign :: MusicPattern -> MusicPattern
        rightAlign (Continuation (Continuation mpll mplr) mpr) =
            (Continuation (rightAlign mpll) (Continuation (rightAlign mplr) mpr))
        rightAlign (Lookup str) = lookupError
        rightAlign mp = mp

possibleTransitions :: MarkovMap -> MusicPattern -> [MusicPattern]
possibleTransitions store (Continuation mpl mpr) =
    (case lookup (Continuation mpl mpr) store of
        Just c -> c
        Nothing -> []) ++ (possibleTransitions store mpr)
possibleTransitions store (Single ml) =
    maybe [] id $ lookup (Single ml) store
possibleTransitions store (Lookup str) = lookupError

willTerminate :: MarkovMap -> Bool
willTerminate store =
    let ends :: [(MusicPattern, MusicPattern)] -- [(pattern match, transition)]
        ends = foldr (++) [] $ map (\(x,ys) -> map ((,) x ) ys) store
        startHasEnd (start, transition) = (start, possibleTransitions store transition)
        endPoints = filter (\(st, trans) -> (length trans) == 0 ) $ map startHasEnd ends
    in
        length endPoints > 0

lookupError = error "There should be no lookups at this point"

walkTilDone :: StdGen -> MarkovMap -> [MusicPattern] -> MusicPattern
walkTilDone g store beginStates =
    if (willTerminate store)
    then
        let (state, gen) = begin g beginStates
        in
            keepWalking (state, gen)
    else error "Music cannot loop forever! Add an end node!"
    where
        keepWalking :: MarkovState -> MusicPattern
        keepWalking markovState =
            case transition store markovState of
                Right finalState -> finalState
                Left markovState -> keepWalking markovState


text:
module WykopTop (
      indexTop
    , dateTop
    , hitsTop
    , module WykopTypes
    ) where

import WykopTypes
import WykopUtils

import Data.Map (Map)

indexTop :: Keys -> Int -> IO (Maybe (Map String [Link]))
indexTop k year = get k [] [] $ "top/index/" ++ show year

dateTop :: Keys -> Int -> Int -> IO (Maybe [Link])
dateTop k year month = get k [] [] res
    where
        res = "top/date/" ++ show year ++ "/" ++ show month

hitsTop :: Keys -> IO (Maybe [Link])
hitsTop k = get k [] [] "top/hits"


text:
<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
    xsi:schemaLocation="http://www.ehcache.org/v3 ../../../../xml/src/main/resources/ehcache-core.xsd
                        http://www.ehcache.org/v3/jsr107 ../../main/resources/ehcache-107ext.xsd">

  <service>
    <jsr107:defaults default-template="tinyCache">
      <jsr107:cache name="foos" template="stringCache"/>
    </jsr107:defaults>
  </service>

  <cache-template name="stringCache">
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <heap unit="entries">2000</heap>
  </cache-template>

  <cache-template name="tinyCache">
    <heap unit="entries">20</heap>
  </cache-template>

</config>


text:
<configuration scan="true" scanPeriod=" 5 seconds">
    <jmxConfigurator />
    <property name="LOG_HOME" value="${log.path}" />
    <property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{56} - %msg%n" />
    <property name="PATTERN_SIMPLE" value="%d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%n" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${PATTERN}</pattern>
        </encoder>
    </appender>

    <appender name="ROOT" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
            <Key>destination</Key>
            <DefaultValue>dts</DefaultValue>
        </discriminator>
        <sift>
            <appender name="FILE-dts" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <File>${LOG_HOME}/dts/dts.log</File>
                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                    <fileNamePattern>${LOG_HOME}/dts/%d{yyyy-MM-dd}/dts-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
                    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                        <maxFileSize>32MB</maxFileSize>
                    </timeBasedFileNamingAndTriggeringPolicy>
                    <maxHistory>10</maxHistory>
                </rollingPolicy>
                <encoder>
                    <pattern>${PATTERN}</pattern>
                </encoder>
            </appender>
        </sift>
    </appender>

    <appender name="HEARTBEAT" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
            <Key>destination</Key>
            <DefaultValue>heartbeat</DefaultValue>
        </discriminator>
        <sift>
            <appender name="FILE-HEARTBEAT" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <File>${LOG_HOME}/heartbeat/heartbeat.log</File>
                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                    <fileNamePattern>${LOG_HOME}/heartbeat/%d{yyyy-MM-dd}/heartbeat-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
                    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                        <maxFileSize>32MB</maxFileSize>
                    </timeBasedFileNamingAndTriggeringPolicy>
                    <maxHistory>10</maxHistory>
                </rollingPolicy>
                <encoder>
                    <pattern>${PATTERN_SIMPLE}</pattern>
                </encoder>
            </appender>
        </sift>
    </appender>

    <appender name="ERROR" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
            <Key>logType</Key>
            <DefaultValue>error</DefaultValue>
        </discriminator>
        <sift>
            <appender name="ERROR-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <File>${LOG_HOME}/error/error.log</File>
                <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                    <fileNamePattern>${LOG_HOME}/error/%d{yyyy-MM-dd}/error-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
                    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                        <maxFileSize>32MB</maxFileSize>
                    </timeBasedFileNamingAndTriggeringPolicy>
                    <maxHistory>10</maxHistory>
                </rollingPolicy>
                <encoder>
                    <pattern>${PATTERN}</pattern>
                </encoder>
            </appender>
        </sift>
    </appender>

    <logger name="com.alibaba" additivity="false">
        <level value="INFO" />
        <appender-ref ref="ROOT" />
    </logger>

    <logger name="com.youzan.dts" additivity="false">
        <level value="${log.level}" />
        <appender-ref ref="ROOT" />
    </logger>
    <logger name="HEARTBEAT" additivity="false">
        <level value="INFO" />
        <appender-ref ref="HEARTBEAT" />
    </logger>

    <logger name="ERROR" additivity="false">
        <level value="ERROR" />
        <appender-ref ref="ERROR" />
    </logger>

    <root level="${log.level}">
        <appender-ref ref="${log.appender}" />
    </root>
</configuration>