text:
package org.rakam.client.builder.document;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.base.CaseFormat;
import com.google.common.base.Throwables;
import com.google.common.collect.*;
import com.google.common.io.Resources;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.github.robwin.markup.builder.markdown.MarkdownBuilder;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.config.CodegenConfigurator;
import io.swagger.models.*;
import io.swagger.models.parameters.AbstractSerializableParameter;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import org.apache.commons.lang3.StringUtils;
import org.rakam.client.utils.ParameterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.rakam.client.utils.PropertyUtils.getType;

public class SlateDocumentGenerator
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SlateDocumentGenerator.class);
    private static final List supportedLanguages = ImmutableList.builder()
            .add("java")
            .add("python")
            .add("php")
            .build();
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String TERMS_OF_SERVICE = "Terms of service: ";
    private static final String URI_SCHEME = "URI scheme";
    private static final String HOST = "Host: ";
    private static final String BASE_PATH = "BasePath: ";
    private static final String SCHEMES = "Schemes: ";
    private final MarkdownBuilder markdownBuilder;
    private final List<CodegenConfigurator> configurators;
    private Swagger swagger;
    private Set<String> definitions;

    private Map<OperationIdentifier, Map<String, String>> templates;

    public SlateDocumentGenerator(ImmutableList<CodegenConfigurator> configurators)
    {
        this.configurators = configurators;
        markdownBuilder = new MarkdownBuilder();
        definitions = new HashSet<>();
    }

    public MarkdownBuilder build()
            throws IOException
    {
        markdownBuilder.textLine("---");
        markdownBuilder.textLine("title: API Reference");
        markdownBuilder.textLine("language_tabs:");
        markdownBuilder.textLine("  - shell");
        configurators.stream().map(c -> c.getLang()).forEach(lang -> markdownBuilder.textLine("  - " + lang));

        markdownBuilder.textLine("toc_footers:");
        markdownBuilder.textLine(" - Sign Up for a Developer Key");

        markdownBuilder.textLine("includes:").textLine("    - errors");
        markdownBuilder.textLine("search: true");
        markdownBuilder.textLine("---");

        this.templates = generateExampleUsages();
        buildSlateDocument();
        new DefinitionsDocument(this.swagger, markdownBuilder).process(definitions);
        return markdownBuilder;
    }

    private void buildSlateDocument()
    {
        Info info = swagger.getInfo();

        markdownBuilder.documentTitle("Introduction");

        markdownBuilder.listing("We have language bindings in " +
                configurators.stream().map(c -> c.getLang()).collect(Collectors.joining(", "))
                + "! You can view code examples in the dark area to the right, and you can switch the programming language of the examples with the tabs in the top right.");

        if (info.getDescription() != null) {
            markdownBuilder.textLine(info.getDescription());
            markdownBuilder.newLine();
        }

        if (StringUtils.isNotBlank(info.getVersion())) {
            markdownBuilder.sectionTitleLevel2("Version");
            markdownBuilder.textLine("Version: " + info.getVersion());
            markdownBuilder.newLine();
        }

        Contact contact = info.getContact();
        if (contact != null) {
            markdownBuilder.sectionTitleLevel1("Contact Information");
            if (StringUtils.isNotBlank(contact.getName())) {
                markdownBuilder.textLine("Contact: " + contact.getName());
            }
            if (StringUtils.isNotBlank(contact.getEmail())) {
                markdownBuilder.textLine("Email: " + contact.getEmail());
            }
            markdownBuilder.newLine();
        }

        License license = info.getLicense();
        if (license != null && (StringUtils.isNotBlank(license.getName()) || StringUtils.isNotBlank(license.getUrl()))) {
            markdownBuilder.sectionTitleLevel2("License");
            if (StringUtils.isNotBlank(license.getName())) {
                markdownBuilder.textLine("License: " + license.getName()).newLine();
            }
            if (StringUtils.isNotBlank(license.getUrl())) {
                markdownBuilder.textLine("License url: " + license.getUrl());
            }
            markdownBuilder.newLine();
        }

        if (StringUtils.isNotBlank(info.getTermsOfService())) {
            markdownBuilder.textLine(TERMS_OF_SERVICE + info.getTermsOfService());
            markdownBuilder.newLine();
        }

        if (StringUtils.isNotBlank(swagger.getHost()) || StringUtils.isNotBlank(swagger.getBasePath())) {
            markdownBuilder.sectionTitleLevel2(URI_SCHEME);
            if (StringUtils.isNotBlank(swagger.getHost())) {
                markdownBuilder.textLine(HOST + swagger.getHost());
            }
            if (StringUtils.isNotBlank(swagger.getBasePath())) {
                markdownBuilder.textLine(BASE_PATH + swagger.getBasePath());
            }
            if (swagger.getSchemes() != null && !swagger.getSchemes().isEmpty()) {
                List<String> schemes = swagger.getSchemes().stream().map(Scheme::toString).collect(Collectors.toList());
                markdownBuilder.textLine(SCHEMES + StringUtils.join(schemes, ", "));
            }
            markdownBuilder.newLine();
        }

        if (!swagger.getTags().isEmpty()) {
            for (Tag tag : swagger.getTags()) {
                String name = tag.getName();
                String description = tag.getDescription();
                markdownBuilder.documentTitle(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name.replaceAll("-", " "))).newLine().textLine(description).newLine();
                processOperation(name);
            }
            markdownBuilder.newLine();
        }
    }

    private void processOperation(String path, String method, Operation operation)
    {
        try {
            markdownBuilder.sectionTitleLevel1(operation.getSummary());

            StringBuilder builder = new StringBuilder();
            builder.append("curl ").append('"').append(swagger.getHost() == null ? "" : swagger.getHost()).append(path).append('"');
            if (operation.getSecurity() != null) {
                for (Map<String, List<String>> map : operation.getSecurity()) {
                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        builder.append(" -H \"" + entry.getKey() + ": my" + entry.getKey() + '"');
                    }
                }
            }

            builder.append(" -X "+method);
            if(operation.getParameters().stream().anyMatch(p -> p instanceof FormParameter || p instanceof BodyParameter)) {
                builder.append(" -d @- << EOF \n" + toExampleJsonParameters(operation) + "\nEOF");
            }

            markdownBuilder.source(builder.toString(), "shell");

            for (Map.Entry<String, String> entry : templates.get(new OperationIdentifier(path, method)).entrySet()) {
                markdownBuilder.source(entry.getValue(), entry.getKey());
            }

            // TODO: response object also have example property
            Response response = operation.getResponses().get("200");
            if (response != null) {
                markdownBuilder.textLine("> The above command returns JSON structured like this:").newLine();

                Object example = response.getSchema().getExample();
                if (example != null) {
                    markdownBuilder.source(example.toString(), "json");
                }
                else {
                    String value = getValue(response.getSchema());
                    String prettyJson = mapper.writerWithDefaultPrettyPrinter()
                            .writeValueAsString(mapper.readValue(value, Object.class));

                    getValue(response.getSchema());

                    markdownBuilder.source(prettyJson, "json");
                }
            }

            markdownBuilder.sectionTitleLevel2("HTTP Request").textLine("`" + method + " " + path + "`");

            renderParameters(operation.getParameters(), markdownBuilder);

            markdownBuilder.sectionTitleLevel2("Responses for status codes");
            List<String> responses = new ArrayList<>();

            String headerRow = operation.getResponses()
                    .keySet().stream()
                    .collect(Collectors.joining("|"));
            responses.add(headerRow);

            String responseRow = operation.getResponses().values().stream()
                    .filter(e -> e.getSchema() != null) // some responses can be null
                    .map(e -> getType(e.getSchema(), definitions))
                    .collect(Collectors.joining("|"));
            responses.add(responseRow);

            markdownBuilder.tableWithHeaderRow(responses);

            String description = trimNullableText(operation.getDescription());
            if (!description.isEmpty()) {
                markdownBuilder.paragraph(description);
            }
        }
        catch (Exception e) {
            LOGGER.error(format("An error occurred while processing operation. %s %s. Skipping..",
                    method.toUpperCase(Locale.ENGLISH), path), e);
        }
    }

    private void renderParameters(List<Parameter> _parameters, MarkdownBuilder markdownBuilder) {
        Multimap<ParameterIn, String> parameterGroups = ArrayListMultimap.create();

        if (_parameters == null || _parameters.isEmpty()) {
            return;
        }

        _parameters.forEach(p -> {
            ParameterIn parameterIn;
            try {
                parameterIn = ParameterIn.valueOf(p.getIn().toUpperCase(Locale.ENGLISH));
            } catch (IllegalArgumentException e) {
                throw new UnsupportedOperationException(format("Parameter type '%s' not supported yet.",
                        p.getIn()));
            }

            parameterGroups.putAll(parameterIn, renderParameter(parameterIn, p));
        });

        parameterGroups.keySet().forEach(key -> {
            List<String> group = new ArrayList<>();
            group.add("Parameter|Required|Type|Description");
            group.addAll(parameterGroups.get(key));

            markdownBuilder.sectionTitleLevel2(key.getQuery() + " Parameters");
            markdownBuilder.tableWithHeaderRow(group);
        });
    }

    private List<String> renderParameter(ParameterIn parameterIn, Parameter p) {
        if (parameterIn.equals(ParameterIn.BODY)) {
            Model schema = ((BodyParameter) p).getSchema();
            if (schema instanceof RefModel) {
                schema = swagger.getDefinitions().get(((RefModel) schema).getSimpleRef());
            }

            Map<String, Property> properties;
            if (schema instanceof ArrayModel) {
                Property items = ((ArrayModel) schema).getItems();
                properties = ImmutableMap.of("array", items);
            } else {
                properties = schema.getProperties();
            }
            return properties.entrySet().stream()
                    .map(entry -> entry.getKey() + "|" +
                            entry.getValue().getRequired() + "|" +
                            getType(entry.getValue(), definitions) + "|" +
                            trimNullableText(entry.getValue().getDescription()))
                    .collect(Collectors.toList());
        } else {
            return newArrayList(p.getName() + "|" +
                    p.getRequired() + "|" +
                    ParameterUtils.getType(p, definitions) + "|" +
                    trimNullableText(p.getDescription()));
        }
    }

    private String toExampleJsonParameters(Map<String, Property> properties)
    {
        return "{" + properties.entrySet()
                .stream().map(e -> "\"" + e.getKey() + "\" : " + getValue(e.getValue()) + "\n")
                .collect(Collectors.joining(", ")) + "}";
    }

    private String toExampleJsonParameters(Operation operation)
    {
        if (operation.getParameters().size() == 1 && operation.getParameters().get(0).getIn().equals("body")) {
            Model model = ((BodyParameter) operation.getParameters().get(0)).getSchema();

            Map<String, Property> properties;
            if (model.getReference() != null) {
                String prefix = "#/definitions/";
                if (model.getReference().startsWith(prefix)) {
                    Model model1 = swagger.getDefinitions().get(model.getReference().substring(prefix.length()));
                    if (model1 instanceof ArrayModel) {
                        return prettyJson("[" + getValue(((ArrayModel) model1).getItems()) + "]");
                    }
                    properties = model1.getProperties();
                }
                else {
                    throw new IllegalStateException();
                }
            }
            else {
                properties = model.getProperties();
            }
            return prettyJson(toExampleJsonParameters(properties));
        }

        String jsonString = "{" + operation.getParameters().stream()
                .filter(e -> e instanceof FormParameter).map(e -> "\"" + e.getName() + "\" : " + getValue((AbstractSerializableParameter) e))
                .collect(Collectors.joining(", ")) + "}";

        return prettyJson(jsonString);
    }

    private static String prettyJson(String json)
    {
        try {
            return mapper.enable(SerializationFeature.INDENT_OUTPUT)
                    .writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readValue(json, Object.class));
        }
        catch (IOException e) {
            throw new IllegalStateException("Example generator couldn't generate a valid JSON");
        }
    }

    private String getValue(Property value) {
        return getValue(value, null);
    }

    private String getValue(Property value, Property parent)
    {
        if (value.getExample() != null && value.getExample() != null) {
            return value.getExample().toString();
        }
        if (value instanceof StringProperty) {
            List<String> anEnum = ((StringProperty) value).getEnum();
            if (anEnum != null && !anEnum.isEmpty()) {
                try {
                    return mapper.writeValueAsString(anEnum.get(0));
                }
                catch (JsonProcessingException e) {
                    throw Throwables.propagate(e);
                }
            }
            return "\"str\"";
        }
        else if (value instanceof IntegerProperty || value instanceof LongProperty) {
            return "1";
        }
        else if (value instanceof DoubleProperty) {
            return "1.0";
        }
        else if (value instanceof DateProperty) {
            return "\"2015-01-20\"";
        }
        else if (value instanceof BooleanProperty) {
            return "true";
        }
        else if (value instanceof MapProperty) {
            return "{\"prop\": {}}";
        }
        else if (value instanceof RefProperty) {
            Model model = swagger.getDefinitions().get(((RefProperty) value).getSimpleRef());
            return "{" + model.getProperties()
                    .entrySet()
                    .stream()
                    .map(e -> "\"" + e.getKey() + "\" : " + getValue(e.getValue(), parent) + "")
                    .collect(Collectors.joining(", ")) + "}";
        }
        else if (value instanceof ArrayProperty) {
            if (parent != null && parent.equals(value)) {
                return "[]";
            } else {
                return "[\n\t" + getValue(((ArrayProperty) value).getItems(), value) + "\n]";
            }
        }
        else if (value instanceof ObjectProperty) {
            return "\"object\"";
        }
        else if (value instanceof DateTimeProperty) {
            return "\"2016-03-03T10:15:30.00Z\"";
        }
        else if (value instanceof UUIDProperty) {
            return "\"4f884c73-7d2d-4c70-9e16-9685bda4263a\"";
        }
        else {
            throw new IllegalStateException("Value " + value + " is not supported.");
        }
    }

    private String getValue(AbstractSerializableParameter value)
    {
        switch (value.getType()) {
            case "date":
                return "\"2015-01-20\"";
            case "string":
                return "\"str\"";
            case "integer":
            case "long":
                return "0";
            case "double":
                return "0.0";
            case "boolean":
                return "false";
            case "map":
                return "{\"prop\": value}";
            case "array":
                return "[\n\t" + getValue(value.getItems()) + "\n]";
            default:
                return "";
        }
    }

    private String trimNullableText(String text)
    {
        if (text == null || text.equals("null")) {
            return "";
        }
        return text.trim();
    }

    private enum ParameterIn
    {
        PATH("Path"), BODY("Body"), HEADER("Header"), FORMDATA("Form"), QUERY("Query");

        private final String query;

        ParameterIn(String query)
        {
            this.query = query;
        }

        public String getQuery()
        {
            return query;
        }
    }

    private Map<OperationIdentifier, Map<String, String>> generateExampleUsages()
            throws IOException
    {
        Map<OperationIdentifier, Map<String, String>> templates = Maps.newHashMap();

        Map<String, Map.Entry<CodegenConfig, DefaultGenerator>> languages = new HashMap<>();

        for (CodegenConfigurator configurator : configurators) {
            ClientOptInput clientOptInput = configurator.toClientOptInput();
            clientOptInput.getConfig().processOpts();

            DefaultGenerator defaultGenerator = new DefaultGenerator();
            defaultGenerator.opts(clientOptInput);

            if (!supportedLanguages.contains(configurator.getLang())) {
                throw new IllegalArgumentException(format("Language %s is not supported at the moment.", configurator.getLang()));
            }

            languages.put(configurator.getLang(), new AbstractMap.SimpleImmutableEntry<>(clientOptInput.getConfig(), defaultGenerator));

            if (swagger == null) {
                swagger = clientOptInput.getSwagger();
            }
        }

        for (Map.Entry<String, Map.Entry<CodegenConfig, DefaultGenerator>> entry : languages.entrySet()) {
            String language = entry.getKey();
            Map.Entry<CodegenConfig, DefaultGenerator> value = entry.getValue();

            Map<String, List<CodegenOperation>> operations = value.getValue().processPaths(swagger.getPaths());
            for (String parentTag : operations.keySet()) {
                List<CodegenOperation> ops = operations.get(parentTag);
                for (CodegenOperation op : ops) {
                    Map<String, Object> operation = value.getValue().processOperations(value.getKey(), parentTag, ImmutableList.of(op));

                    operation.put("modelPackage", value.getKey().modelPackage());
                    operation.put("classname", value.getKey().toApiName(parentTag));
                    operation.put("hostname", swagger.getHost());

                    for (String templateName : value.getKey().apiTemplateFiles().keySet()) {
                        String filename = value.getKey().apiFilename(templateName, parentTag);
                        if (!value.getKey().shouldOverwrite(filename) && new File(filename).exists()) {
                            continue;
                        }

                        String template;
                        URL resource = this.getClass().getClassLoader().getResource("templates/" + language + "_api_example.mustache");

                        template = Resources.toString(resource, StandardCharsets.UTF_8);

                        Template tmpl = Mustache.compiler()
                                .withLoader(name -> value.getValue().getTemplateReader(value.getKey().templateDir() + File.separator + name + ".mustache"))
                                .defaultValue("")
                                .compile(template);

                        templates.computeIfAbsent(new OperationIdentifier(op.path, op.httpMethod), key -> Maps.newHashMap()).put(language, tmpl.execute(operation));
                    }
                }
            }
        }

        return templates;
    }

    public static class OperationIdentifier
    {
        public final String path;
        public final String httpMethod;

        public OperationIdentifier(String path, String httpMethod)
        {
            this.path = path;
            this.httpMethod = httpMethod;
        }

        @Override
        public boolean equals(Object o)
        {
            if (this == o) {
                return true;
            }
            if (!(o instanceof OperationIdentifier)) {
                return false;
            }

            OperationIdentifier that = (OperationIdentifier) o;

            if (!path.equals(that.path)) {
                return false;
            }
            return httpMethod.equals(that.httpMethod);
        }

        @Override
        public int hashCode()
        {
            int result = path.hashCode();
            result = 31 * result + httpMethod.hashCode();
            return result;
        }

        @Override
        public String toString()
        {
            return "OperationIdentifier{" +
                    "path='" + path + '\'' +
                    ", httpMethod='" + httpMethod + '\'' +
                    '}';
        }
    }

    private void processOperation(String tag)
    {

        for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {

            Path value = entry.getValue();
            if (value.getGet() != null && value.getGet().getTags().contains(tag)) {
                processOperation(entry.getKey(), "GET", value.getGet());
            }
            if (value.getPut() != null && value.getPut().getTags().contains(tag)) {
                processOperation(entry.getKey(), "PUT", value.getPut());
            }
            if (value.getPost() != null && value.getPost().getTags().contains(tag)) {
                processOperation(entry.getKey(), "POST", value.getPost());
            }
            if (value.getDelete() != null && value.getDelete().getTags().contains(tag)) {
                processOperation(entry.getKey(), "DELETE", value.getDelete());
            }
            if (value.getPatch() != null && value.getPatch().getTags().contains(tag)) {
                processOperation(entry.getKey(), "PATH", value.getPatch());
            }
            if (value.getOptions() != null && value.getOptions().getTags().contains(tag)) {
                processOperation(entry.getKey(), "OPTIONS", value.getOptions());
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Repert. Spec. Nov. Regni Veg. 29: 155

#### Original name
Parmelia pulvinaris f. pulvinaris

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core')

/**
 * Directive to handle activity completion. It can be adapted to handle course completion once it's implemented.
 *
 * @module mm.core
 * @ngdoc directive
 * @name mmCompletion
 * @description
 * This directive will show a checkbox to show completion status and to allow manually changing the completion if it's allowed.
 * Attributes:
 *
 * @param {Object} completion    Completion status of the activity. Required properties:
 *                                   - cmid: Module ID.
 *                                   - state: Current completion state: 0 incomplete, 1 complete, 2 complete pass, 3 complete fail.
 *                                   - tracking: 0 means none, 1 manual, 2 automatic.
 * @param {String} after-change  Name of a scope function to call when completion changes.
 * @param {String} module-name   Name of the module this completion refers to.
 */
.directive('mmCompletion', function($mmSite, $mmUtil, $mmText, $translate, $q, $mmUser) {

    // Set image and description to show as completion icon.
    function showStatus(scope) {
        var langKey,
            moduleName = scope.moduleName || '',
            image = false;

        if (scope.completion.tracking === 1 && scope.completion.state === 0) {
            image = 'completion-manual-n';
            langKey = 'mm.core.completion-alt-manual-n';
        } else if(scope.completion.tracking === 1 && scope.completion.state === 1) {
            image = 'completion-manual-y';
            langKey = 'mm.core.completion-alt-manual-y';
        } else if(scope.completion.tracking === 2 && scope.completion.state === 0) {
            image = 'completion-auto-n';
            langKey = 'mm.core.completion-alt-auto-n';
        } else if(scope.completion.tracking === 2 && scope.completion.state === 1) {
            image = 'completion-auto-y';
            langKey = 'mm.core.completion-alt-auto-y';
        } else if(scope.completion.tracking === 2 && scope.completion.state === 2) {
            image = 'completion-auto-pass';
            langKey = 'mm.core.completion-alt-auto-pass';
        } else if(scope.completion.tracking === 2 && scope.completion.state === 3) {
            image = 'completion-auto-fail';
            langKey = 'mm.core.completion-alt-auto-fail';
        }

        if (image) {
            if (scope.completion.overrideby > 0) {
                image += '-override';
            }
            scope.completionImage = 'img/completion/' + image + '.svg';
        }

        if (moduleName) {
            $mmText.formatText(moduleName, true, true, 50).then(function(modNameFormatted) {
                var promise;

                if (scope.completion.overrideby > 0) {
                    langKey += '-override';

                    promise = $mmUser.getProfile(scope.completion.overrideby, scope.completion.courseId, true).then(function(profile) {
                        return {
                            overrideuser: profile.fullname,
                            modname: modNameFormatted
                        };
                    });
                } else {
                    promise = $q.when(modNameFormatted);
                }
                return promise.then(function(translateParams) {
                    $translate(langKey, {$a: translateParams}).then(function(translated) {
                        scope.completionDescription = translated;
                    });
                });
            });
        }
    }

    return {
        restrict: 'E',
        priority: 100,
        scope: {
            completion: '=',
            afterChange: '=',
            moduleName: '=?'
        },
        templateUrl: 'core/templates/completion.html',
        link: function(scope) {
            if (scope.completion) {
                showStatus(scope);
            }

            scope.completionClicked = function (e) {
                if (scope.completion) {
                    if (typeof scope.completion.cmid == 'undefined' || scope.completion.tracking !== 1) {
                        return;
                    }

                    e.preventDefault();
                    e.stopPropagation();

                    var modal = $mmUtil.showModalLoading(),
                        params = {
                            cmid: scope.completion.cmid,
                            completed: scope.completion.state === 1 ? 0 : 1
                        };

                    $mmSite.write('core_completion_update_activity_completion_status_manually', params).then(function(response) {
                        if (!response.status) {
                            return $q.reject();
                        }

                        if (angular.isFunction(scope.afterChange)) {
                            scope.afterChange();
                        }
                    }).catch(function(error) {
                        $mmUtil.showErrorModalDefault(error, 'mm.core.errorchangecompletion', true);
                    }).finally(function() {
                        modal.dismiss();
                    });

                    return false;
                }
            };
        }
    };
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.galets.OneWay">
	<uses-sdk />
	<application android:label="OneWay" android:icon="@drawable/icon"></application>
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>


text:
namespace Microsoft.Azure.Management.Batch.Models
{
    using Azure;
    using Management;
    using Batch;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Defines headers for Create operation.
    /// </summary>
    public partial class BatchAccountCreateHeaders
    {
        /// <summary>
        /// Initializes a new instance of the BatchAccountCreateHeaders class.
        /// </summary>
        public BatchAccountCreateHeaders() { }

        /// <summary>
        /// Initializes a new instance of the BatchAccountCreateHeaders class.
        /// </summary>
        /// <param name="location">The URL of the resource used to check the
        /// status of the asynchronous operation.</param>
        /// <param name="retryAfter">Suggested delay to check the status of the
        /// asynchronous operation. The value is an integer that specifies the
        /// delay in seconds.</param>
        public BatchAccountCreateHeaders(string location = default(string), int? retryAfter = default(int?))
        {
            Location = location;
            RetryAfter = retryAfter;
        }

        /// <summary>
        /// Gets or sets the URL of the resource used to check the status of
        /// the asynchronous operation.
        /// </summary>
        [JsonProperty(PropertyName = "Location")]
        public string Location { get; set; }

        /// <summary>
        /// Gets or sets suggested delay to check the status of the
        /// asynchronous operation. The value is an integer that specifies the
        /// delay in seconds.
        /// </summary>
        [JsonProperty(PropertyName = "Retry-After")]
        public int? RetryAfter { get; set; }

    }
}


text:
    <!DOCTYPE html>

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <meta http-equiv="Content-Style-Type" content="text/css"/>
            <meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>Resources</title>

            <link href="../../unipoole/skin/sakai/tool_base.css" type="text/css" rel="stylesheet" media="all"/>
            <link href="../../unipoole/skin/neo-unisa-fixed/tool.css" type="text/css" rel="stylesheet" media="all"/>
            <link href="../../unipoole/skin/datatables/jquery.dataTables.css" type="text/css" rel="stylesheet" media="all"/>
            <link href="../../unipoole/skin/treetable/jquery.treetable.css" rel="stylesheet" type="text/css"  media="all"/>
            <link href="../../unipoole/skin/treetable/jquery.treetable.theme.resources.css" rel="stylesheet" type="text/css"  media="all"/>
            <link href="../../unipoole/skin/jqueryUI/jquery-ui.css" type="text/css" rel="stylesheet" media="all" />
            <link href="skin/resources.css" type="text/css" rel="stylesheet" media="all" />


text:
reactour
========

A simple tour library built for React.js


text:
package ru.qatools.properties.internal;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 04.06.15
 */
@SuppressWarnings("unused")
public class PropertyInfo {

    private String key;

    private String stringValue;

    private Object value;

    public PropertyInfo() {
    }

    public PropertyInfo(Object value) {
        this.value = value;
    }

    public PropertyInfo(String key, String stringValue, Object value) {
        this.key = key;
        this.stringValue = stringValue;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getStringValue() {
        return stringValue;
    }

    public void setStringValue(String stringValue) {
        this.stringValue = stringValue;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}


text:
module AttrEncryptedAuthenticator
  VERSION = "0.9.2"
end


text:
Package.describe({
  name: 'maximum:transformto',
  version: '1.0.0',
  summary: 'Provides a `transformTo` function on collections, to transform items to a class',
  git: 'https://github.com/maximummeteor/transformto/',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use([
    'maximum:multi-transform@1.0.0',
    'coffeescript',
    'mongo'
  ]);

  api.addFiles('transformto.coffee');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('coffeescript');
  api.use('maximum:transformto');
  api.addFiles('transformto-tests.coffee');
});


text:
package bt.protocol.handler;

import bt.net.buffer.ByteBufferView;
import bt.protocol.DecodingContext;
import bt.protocol.EncodingContext;
import bt.protocol.Piece;

import java.nio.ByteBuffer;

import static bt.protocol.Protocols.readInt;

public final class PieceHandler extends UniqueMessageHandler<Piece> {

    public PieceHandler() {
        super(Piece.class);
    }

    @Override
    public int doDecode(DecodingContext context, ByteBufferView buffer) {
        return decodePiece(context, buffer, buffer.remaining());
    }

    @Override
    public boolean doEncode(EncodingContext context, Piece message, ByteBuffer buffer) {
        return writePiece(message, buffer);
    }

    // piece: <len=0009+X><id=7><index><begin><block>
    private static boolean writePiece(Piece message, ByteBuffer buffer) {
        int pieceIndex = message.getPieceIndex();
        int offset = message.getOffset();
        int length = message.getLength();
        if (buffer.remaining() < Integer.BYTES * 2 + length) {
            return false;
        }

        buffer.putInt(pieceIndex);
        buffer.putInt(offset);

        return message.writeBlockTo(buffer);
    }

    private static int decodePiece(DecodingContext context, ByteBufferView buffer, int length) {

        int consumed = 0;

        if (buffer.remaining() >= length) {

            int pieceIndex = readInt(buffer);
            int blockOffset = readInt(buffer);
            int blockLength = length - Integer.BYTES * 2;
            buffer.position(buffer.position() + blockLength);

            context.setMessage(new Piece(pieceIndex, blockOffset, blockLength));
            consumed = length;
        }

        return consumed;
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>goog.editor.plugins.LoremIpsum Tests</title>


text:
class TFrmLogin : public TForm
{
__published:	// IDE-managed Components
	TGroupBox *GroupBox1;
	TLabel *Label1;
	TLabel *Label3;
	TEdit *Login;
	TButton *btOK;
	TButton *btCancelar;
	TEdit *Senha;
	void __fastcall btOKClick(TObject *Sender);
	void __fastcall btCancelarClick(TObject *Sender);
	void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
private:	// User declarations
	bool __fastcall UserValido();
	bool __fastcall SenhaValida();
	void __fastcall CarregaInfoUser();
   bool __fastcall CadastraUserAdm();
public:		// User declarations
	__fastcall TFrmLogin(TComponent* Owner);
	__fastcall ~TFrmLogin(void);
};
//---------------------------------------------------------------------------
#endif


text:
using Foundation;
using UIKit;

namespace ProgrammaticLayout.Example
{
    [Register("AppDelegate")]
    public class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations

        public override UIWindow Window
        {
            get;
            set;
        }

        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            Window = new UIWindow();
            Window.RootViewController = new UINavigationController(new ViewController());
            Window.MakeKeyAndVisible();
            return true;
        }

    }
}


text:
class User < Wrapper::Base

  attr_accessor :id, :name, :lastname, :gender,
                :age, :url, :address, :created_at, :updated_at

  def to_json
    {user: {
        id: self.id,
        name: self.name,
        lastname: self.lastname,
        age: self.age,
        address: self.address,
        gender: self.gender
    }}.to_json
  end
end


text:
"""Stacked fixed noise dCOnvAE test"""

import sys;
sys.path.append("..");

import numpy as np;
import matplotlib.pyplot as plt;
import cPickle as pickle;

import theano;
import theano.tensor as T;

import telaugesa.datasets as ds;
from telaugesa.fflayers import ReLULayer;
from telaugesa.fflayers import SoftmaxLayer;
from telaugesa.convnet import ReLUConvLayer;
from telaugesa.convnet import SigmoidConvLayer;
from telaugesa.convnet import IdentityConvLayer;
from telaugesa.model import ConvAutoEncoder;
from telaugesa.convnet import MaxPooling;
from telaugesa.convnet import Flattener;
from telaugesa.model import FeedForward;
from telaugesa.optimize import gd_updates;
from telaugesa.cost import mean_square_cost;
from telaugesa.cost import categorical_cross_entropy_cost;
from telaugesa.cost import L2_regularization;

n_epochs=50;
batch_size=100;
nkerns=100;

Xtr, Ytr, Xte, Yte=ds.load_CIFAR10("../data/CIFAR10");

Xtr=np.mean(Xtr, 3);
Xte=np.mean(Xte, 3);
Xtrain=Xtr.reshape(Xtr.shape[0], Xtr.shape[1]*Xtr.shape[2])/255.0;
Xtest=Xte.reshape(Xte.shape[0], Xte.shape[1]*Xte.shape[2])/255.0;

train_set_x, train_set_y=ds.shared_dataset((Xtrain, Ytr));
test_set_x, test_set_y=ds.shared_dataset((Xtest, Yte));

n_train_batches=train_set_x.get_value(borrow=True).shape[0]/batch_size;
n_test_batches=test_set_x.get_value(borrow=True).shape[0]/batch_size;

print "[MESSAGE] The data is loaded"

################################## FIRST LAYER #######################################

X=T.matrix("data");
y=T.ivector("label");
idx=T.lscalar();

images=X.reshape((batch_size, 1, 32, 32))
layer_0_en=ReLUConvLayer(filter_size=(7,7),
                         num_filters=64,
                         num_channels=1,
                         fm_size=(32,32),
                         batch_size=batch_size,
                         border_mode="same");

layer_0_de=IdentityConvLayer(filter_size=(7,7),
                             num_filters=1,
                             num_channels=64,
                             fm_size=(32,32),
                             batch_size=batch_size,
                             border_mode="same");

model=ConvAutoEncoder(layers=[layer_0_en, layer_0_de]);

out=model.fprop(images, corruption_level=0.5);
cost=mean_square_cost(out[-1], images)#+L2_regularization(model.params, 0.005);

updates=gd_updates(cost=cost, params=model.params, method="sgd", learning_rate=0.01, momentum=0.9);

train=theano.function(inputs=[idx],
                      outputs=[cost],
                      updates=updates,
                      givens={X: train_set_x[idx * batch_size: (idx + 1) * batch_size]});

print "[MESSAGE] The Layer 0 model is built"

epoch = 0;
while (epoch < n_epochs):
    epoch = epoch + 1;
    c = []
    for batch_index in xrange(n_train_batches):
        train_cost=train(batch_index)
        c.append(train_cost);

    print 'Training epoch %d, cost ' % epoch, np.mean(c);

print "[MESSAGE] The Lyer 0 model is trained"

################################## SECOND LAYER #######################################

## append a max-pooling layer

model_trans=FeedForward(layers=[layer_0_en, MaxPooling(pool_size=(2,2))]);
out_trans=model_trans.fprop(images);

## construct new dConvAE

layer_1_en=ReLUConvLayer(filter_size=(4,4),
                         num_filters=32,
                         num_channels=64,
                         fm_size=(16,16),
                         batch_size=batch_size,
                         border_mode="same");

layer_1_de=IdentityConvLayer(filter_size=(4,4),
                             num_filters=64,
                             num_channels=32,
                             fm_size=(16,16),
                             batch_size=batch_size,
                             border_mode="same");

model_1=ConvAutoEncoder(layers=[layer_1_en, layer_1_de]);

out_1=model_1.fprop(out_trans[-1], corruption_level=0.5);
cost_1=mean_square_cost(out_1[-1], out_trans[-1])#+L2_regularization(model_1.params, 0.005);

updates=gd_updates(cost=cost_1, params=model_1.params, method="sgd", learning_rate=0.01, momentum=0.9);

train_1=theano.function(inputs=[idx],
                        outputs=[cost_1],
                        updates=updates,
                        givens={X: train_set_x[idx * batch_size: (idx + 1) * batch_size]});

print "[MESSAGE] The Layer 1 model is built"

epoch = 0;
while (epoch < n_epochs):
    epoch = epoch + 1;
    c = []
    for batch_index in xrange(n_train_batches):
        train_cost=train_1(batch_index)
        c.append(train_cost);

    print 'Training epoch %d, cost ' % epoch, np.mean(c);

print "[MESSAGE] The Lyer 1 model is trained"

################################## BUILD SUPERVISED MODEL #######################################

pool_0=MaxPooling(pool_size=(2,2));
pool_1=MaxPooling(pool_size=(2,2));
flattener=Flattener();
layer_2=ReLULayer(in_dim=32*64,
                  out_dim=800);
layer_3=SoftmaxLayer(in_dim=800,
                     out_dim=10);
model_sup=FeedForward(layers=[layer_0_en, pool_0, layer_1_en, pool_1, flattener, layer_2, layer_3]);

out_sup=model_sup.fprop(images);
cost_sup=categorical_cross_entropy_cost(out_sup[-1], y);
updates=gd_updates(cost=cost_sup, params=model_sup.params, method="sgd", learning_rate=0.01, momentum=0.9);

train_sup=theano.function(inputs=[idx],
                          outputs=cost_sup,
                          updates=updates,
                          givens={X: train_set_x[idx * batch_size: (idx + 1) * batch_size],
                                  y: train_set_y[idx * batch_size: (idx + 1) * batch_size]});

test_sup=theano.function(inputs=[idx],
                         outputs=model_sup.layers[-1].error(out_sup[-1], y),
                         givens={X: test_set_x[idx * batch_size: (idx + 1) * batch_size],
                                 y: test_set_y[idx * batch_size: (idx + 1) * batch_size]});

print "[MESSAGE] The supervised model is built"

n_epochs=100;
test_record=np.zeros((n_epochs, 1));
epoch = 0;
while (epoch < n_epochs):
    epoch+=1;
    for minibatch_index in xrange(n_train_batches):
        mlp_minibatch_avg_cost = train_sup(minibatch_index);

        iteration = (epoch - 1) * n_train_batches + minibatch_index;

        if (iteration + 1) % n_train_batches == 0:
            print 'MLP MODEL';
            test_losses = [test_sup(i) for i in xrange(n_test_batches)];
            test_record[epoch-1] = np.mean(test_losses);

            print(('     epoch %i, minibatch %i/%i, test error %f %%') %
                  (epoch, minibatch_index + 1, n_train_batches, test_record[epoch-1] * 100.));

filters=model.layers[0].filters.get_value(borrow=True);

pickle.dump(test_record, open("../data/stacked_0_3_dconvae.pkl", "w"));

for i in xrange(64):
    image_adr="../data/stacked_0_3_dconvae/stacked_0_3_dconvae_filter_%d.eps" % (i);
    plt.imshow(filters[i, 0, :, :], cmap = plt.get_cmap('gray'), interpolation='nearest');
    plt.axis('off');
    plt.savefig(image_adr , bbox_inches='tight', pad_inches=0);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="pref_sync_frequency">
        <item>@string/preference_entry_sync_frequency_zero</item>
        <item>@string/preference_entry_sync_frequency_1m</item>
        <item>@string/preference_entry_sync_frequency_3h</item>
        <item>@string/preference_entry_sync_frequency_6h</item>
        <item>@string/preference_entry_sync_frequency_24h</item>
    </string-array>
    <string-array name="pref_sync_frequency_values">
        <item>@string/preference_entry_value_sync_frequency_zero</item>
        <item>@string/preference_entry_value_sync_frequency_1m</item>
        <item>@string/preference_entry_value_sync_frequency_3h</item>
        <item>@string/preference_entry_value_sync_frequency_6h</item>
        <item>@string/preference_entry_value_sync_frequency_24h</item>
    </string-array>
</resources>


text:
/**
 * Source Security Group
 *
 * \ingroup ElasticLoadBalancing
 */

@interface ElasticLoadBalancingSourceSecurityGroup:NSObject

{
    NSString *ownerAlias;
    NSString *groupName;
}

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Owner of the source security group. Use this value for the
 * --source-group-user parameter of the
 * ec2-authorize command in the Amazon EC2 command line
 * tool.
 */
@property (nonatomic, retain) NSString *ownerAlias;

/**
 * Name of the source security group. Use this value for the
 * --source-group parameter of the
 * ec2-authorize command in the Amazon EC2 command line
 * tool.
 */
@property (nonatomic, retain) NSString *groupName;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
package org.apache.storm.kafka;

import java.nio.ByteBuffer;
import java.util.List;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;

public class StringMessageAndMetadataScheme extends StringScheme implements MessageMetadataScheme {
    public static final String STRING_SCHEME_PARTITION_KEY = "partition";
    public static final String STRING_SCHEME_OFFSET = "offset";
    private static final long serialVersionUID = -5441841920447947374L;

    @Override
    public List<Object> deserializeMessageWithMetadata(ByteBuffer message, Partition partition, long offset) {
        String stringMessage = StringScheme.deserializeString(message);
        return new Values(stringMessage, partition.partition, offset);
    }

    @Override
    public Fields getOutputFields() {
        return new Fields(STRING_SCHEME_KEY, STRING_SCHEME_PARTITION_KEY, STRING_SCHEME_OFFSET);
    }

}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.Azure.WebJobs.Host.Converters;
using Newtonsoft.Json;
using Azure.Messaging.ServiceBus;

namespace Microsoft.Azure.WebJobs.ServiceBus.Bindings
{
    internal class UserTypeToBrokeredMessageConverter<TInput> : IConverter<TInput, ServiceBusMessage>
    {
        public ServiceBusMessage Convert(TInput input)
        {
            string text = JsonConvert.SerializeObject(input, Constants.JsonSerializerSettings);
            byte[] bytes = StrictEncodings.Utf8.GetBytes(text);

            return new ServiceBusMessage(bytes)
            {
                ContentType = ContentTypes.ApplicationJson
            };
        }
    }
}


text:
wordpress
=========

example for my wordpress project


text:
package org.spongepowered.common.mixin.core.network;

import static org.spongepowered.common.util.SpongeCommonTranslationHelper.t;

import com.flowpowered.math.vector.Vector3d;
import net.minecraft.command.server.CommandBlockLogic;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityMinecartCommandBlock;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBucket;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.network.play.client.C12PacketUpdateSign;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import net.minecraft.network.play.client.C19PacketResourcePackStatus;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityCommandBlock;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.WorldServer;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.data.value.mutable.ListValue;
import org.spongepowered.api.entity.Transform;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.block.tileentity.ChangeSignEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.entity.DisplaceEntityEvent;
import org.spongepowered.api.event.entity.living.player.ResourcePackStatusEvent.ResourcePackStatus;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.network.PlayerConnection;
import org.spongepowered.api.resourcepack.ResourcePack;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.sink.MessageSink;
import org.spongepowered.api.text.sink.MessageSinks;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.Sponge;
import org.spongepowered.common.event.SpongeImplEventFactory;
import org.spongepowered.common.interfaces.IMixinNetworkManager;
import org.spongepowered.common.interfaces.IMixinPacketResourcePackSend;
import org.spongepowered.common.interfaces.network.IMixinC08PacketPlayerBlockPlacement;
import org.spongepowered.common.text.SpongeTexts;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

@Mixin(NetHandlerPlayServer.class)
public abstract class MixinNetHandlerPlayServer implements PlayerConnection {

    @Shadow private static Logger logger;
    @Shadow public NetworkManager netManager;
    @Shadow public EntityPlayerMP playerEntity;
    @Shadow private MinecraftServer serverController;

    @Shadow public abstract void sendPacket(final Packet packetIn);

    private boolean justTeleported = false;
    private Location<World> lastMoveLocation = null;

    private final Map<String, ResourcePack> sentResourcePacks = new HashMap<String, ResourcePack>();

    private Long lastPacket;
    // Store the last block right-clicked
    private Item lastItem;

    @Override
    public Player getPlayer() {
        return (Player) this.playerEntity;
    }

    @Override
    public InetSocketAddress getAddress() {
        return ((IMixinNetworkManager) this.netManager).getAddress();
    }

    @Override
    public InetSocketAddress getVirtualHost() {
        return ((IMixinNetworkManager) this.netManager).getVirtualHost();
    }

    @Override
    public int getPing() {
        return this.playerEntity.ping;
    }

    /**
     * @Author Zidane
     *
     * Invoke before {@code System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4);} (line 1156 in source) to call SignChangeEvent.
     * @param packetIn Injected packet param
     * @param ci Info to provide mixin on how to handle the callback
     * @param worldserver Injected world param
     * @param blockpos Injected blockpos param
     * @param tileentity Injected tilentity param
     * @param tileentitysign Injected tileentitysign param
     */
    @Inject(method = "processUpdateSign", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/play/client/C12PacketUpdateSign;getLines()[Lnet/minecraft/util/IChatComponent;"), cancellable = true, locals = LocalCapture.CAPTURE_FAILSOFT)
    public void callSignChangeEvent(C12PacketUpdateSign packetIn, CallbackInfo ci, WorldServer worldserver, BlockPos blockpos, TileEntity tileentity, TileEntitySign tileentitysign) {
        ci.cancel();
        final Optional<SignData> existingSignData = ((Sign) tileentitysign).get(SignData.class);
        if (!existingSignData.isPresent()) {
            // TODO Unsure if this is the best to do here...
            throw new RuntimeException("Critical error! Sign data not present on sign!");
        }
        final SignData changedSignData = existingSignData.get().copy();
        final ListValue<Text> lines = changedSignData.lines();
        for (int i = 0; i < packetIn.getLines().length; i++) {
            lines.set(i, SpongeTexts.toText(packetIn.getLines()[i]));
        }
        changedSignData.set(lines);
        // I pass changedSignData in here twice to emulate the fact that even-though the current sign data doesn't have the lines from the packet
        // applied, this is what it "is" right now. If the data shown in the world is desired, it can be fetched from Sign.getData
        final ChangeSignEvent event =
                SpongeEventFactory.createChangeSignEvent(Sponge.getGame(), Cause.of(this.playerEntity), changedSignData.asImmutable(),
                        changedSignData, (Sign) tileentitysign);
        if (!Sponge.getGame().getEventManager().post(event)) {
            ((Sign) tileentitysign).offer(event.getText());
        } else {
            // If cancelled, I set the data back that was fetched from the sign. This means that if its a new sign, the sign will be empty else
            // it will be the text of the sign that was showing in the world
            ((Sign) tileentitysign).offer(existingSignData.get());
        }
        tileentitysign.markDirty();
        worldserver.markBlockForUpdate(blockpos);
    }

    /**
     * @author zml
     *
     * Purpose: replace the logic used for command blocks to make functional
     *
     * @param ci callback
     * @param packetIn method param
     */
    @Inject(method = "processVanilla250Packet", at = @At(value = "INVOKE", shift = At.Shift.AFTER,
            target = "net/minecraft/network/PacketThreadUtil.checkThreadAndEnqueue(Lnet/minecraft/network/Packet;"
                    + "Lnet/minecraft/network/INetHandler;Lnet/minecraft/util/IThreadListener;)V"), cancellable = true)
    public void processCommandBlock(C17PacketCustomPayload packetIn, CallbackInfo ci) {
        if ("MC|AdvCdm".equals(packetIn.getChannelName())) {
            PacketBuffer packetbuffer;
            try {
                if (!this.serverController.isCommandBlockEnabled()) {
                    this.playerEntity.addChatMessage(new ChatComponentTranslation("advMode.notEnabled", new Object[0]));
                    // Sponge: Check permissions for command block usage TODO: Maybe throw an event instead?
                    // } else if (this.playerEntity.canCommandSenderUseCommand(2, "") && this.playerEntity.capabilities.isCreativeMode) {
                } else {
                    packetbuffer = packetIn.getBufferData();

                    try {
                        byte b0 = packetbuffer.readByte();
                        CommandBlockLogic commandblocklogic = null;

                        String permissionCheck = null; // Sponge
                        if (b0 == 0) {
                            TileEntity tileentity = this.playerEntity.worldObj
                                    .getTileEntity(new BlockPos(packetbuffer.readInt(), packetbuffer.readInt(), packetbuffer.readInt()));

                            if (tileentity instanceof TileEntityCommandBlock) {
                                commandblocklogic = ((TileEntityCommandBlock) tileentity).getCommandBlockLogic();
                                permissionCheck = "minecraft.commandblock.edit.block." + commandblocklogic.getCommandSenderName(); // Sponge
                            }
                        } else if (b0 == 1) {
                            Entity entity = this.playerEntity.worldObj.getEntityByID(packetbuffer.readInt());

                            if (entity instanceof EntityMinecartCommandBlock) {
                                commandblocklogic = ((EntityMinecartCommandBlock) entity).getCommandBlockLogic();
                                permissionCheck = "minecraft.commandblock.edit.minecart." + commandblocklogic.getCommandSenderName(); // Sponge
                            }
                            // Sponge begin
                        } else {
                            throw new IllegalArgumentException("Unknown command block type!");
                        }
                        Player spongePlayer = ((Player) this.playerEntity);
                        if (permissionCheck == null || !spongePlayer.hasPermission(permissionCheck)) {
                            spongePlayer.sendMessage(t("You do not have permission to edit this command block!").builder()
                                    .color(TextColors.RED).build());
                            return;
                            // Sponge end
                        }

                        String s1 = packetbuffer.readStringFromBuffer(packetbuffer.readableBytes());
                        boolean flag = packetbuffer.readBoolean();

                        if (commandblocklogic != null) {
                            commandblocklogic.setCommand(s1);
                            commandblocklogic.setTrackOutput(flag);

                            if (!flag) {
                                commandblocklogic.setLastOutput((IChatComponent) null);
                            }

                            commandblocklogic.func_145756_e();
                            this.playerEntity.addChatMessage(new ChatComponentTranslation("advMode.setCommand.success", new Object[] {s1}));
                        }
                    } catch (Exception exception1) {
                        logger.error("Couldn\'t set command block", exception1);
                    } finally {
                        packetbuffer.release();
                    }
                /*} else { // Sponge: Give more accurate no permission message
                    this.playerEntity.addChatMessage(new ChatComponentTranslation("advMode.notAllowed", new Object[0]));*/
                }
            } finally {
                ci.cancel();
            }
        }
    }

    @Redirect(method = "processChatMessage", at = @At(value = "INVOKE", target = "org.apache.commons.lang3.StringUtils.normalizeSpace"
            + "(Ljava/lang/String;)Ljava/lang/String;", remap = false))
    public String dontNormalizeStringBecauseSomeMojangDevSucks(String input) {
        return input;
    }

    @Inject(method = "setPlayerLocation(DDDFFLjava/util/Set;)V", at = @At(value = "RETURN"))
    public void setPlayerLocation(double x, double y, double z, float yaw, float pitch, Set<?> relativeSet, CallbackInfo ci) {
        this.justTeleported = true;
    }

    @Inject(method = "processPlayer", at = @At(value = "FIELD", target = "net.minecraft.network.NetHandlerPlayServer.hasMoved:Z", ordinal = 2), cancellable = true)
    public void proccesPlayerMoved(C03PacketPlayer packetIn, CallbackInfo ci){
        if (packetIn.isMoving() || packetIn.getRotating() && !this.playerEntity.isDead) {
            Player player = (Player) this.playerEntity;
            Vector3d fromrot = player.getRotation();

            // If Sponge used the player's current location, the delta might never be triggered which could be exploited
            Location<World> from = player.getLocation();
            if (this.lastMoveLocation != null) {
                from = this.lastMoveLocation;
            }

            Vector3d torot = new Vector3d(packetIn.getPitch(), packetIn.getYaw(), 0);
            Location<World> to = new Location<World>(player.getWorld(), packetIn.getPositionX(), packetIn.getPositionY(), packetIn.getPositionZ());

            // Minecraft sends a 0, 0, 0 position when rotation only update occurs, this needs to be recognized and corrected
            boolean rotationOnly = !packetIn.isMoving() && packetIn.getRotating();
            if (rotationOnly) {
                // Correct the to location so it's not misrepresented to plugins, only when player rotates without moving
                // In this case it's only a rotation update, which isn't related to the to location
                from = player.getLocation();
                to = from;
            }

            // Minecraft does the same with rotation when it's only a positional update
            boolean positionOnly = packetIn.isMoving() && !packetIn.getRotating();
            if (positionOnly) {
                // Correct the new rotation to match the old rotation
                torot = fromrot;
            }

            double deltaSquared = to.getPosition().distanceSquared(from.getPosition());
            double deltaAngleSquared = fromrot.distanceSquared(torot);

            // These magic numbers are sad but help prevent excessive lag from this event.
            // eventually it would be nice to not have them
            if (deltaSquared > ((1f / 16) * (1f / 16)) || deltaAngleSquared > (.15f * .15f)) {
                Transform<World> fromTransform = player.getTransform().setLocation(from).setRotation(fromrot);
                Transform<World> toTransform = player.getTransform().setLocation(to).setRotation(torot);
                DisplaceEntityEvent.Move.TargetPlayer event =
                        SpongeEventFactory.createDisplaceEntityEventMoveTargetPlayer(Sponge.getGame(), fromTransform, toTransform, player);
                Sponge.getGame().getEventManager().post(event);
                if (event.isCancelled()) {
                    player.setTransform(fromTransform);
                    this.lastMoveLocation = from;
                    ci.cancel();
                } else if (!event.getToTransform().equals(toTransform)) {
                    player.setTransform(event.getToTransform());
                    this.lastMoveLocation = event.getToTransform().getLocation();
                    ci.cancel();
                } else if (!from.equals(player.getLocation()) && this.justTeleported) {
                    this.lastMoveLocation = player.getLocation();
                    // Prevent teleports during the move event from causing odd behaviors
                    this.justTeleported = false;
                    ci.cancel();
                } else {
                    this.lastMoveLocation = event.getToTransform().getLocation();
                }
            }
        }
    }

    private ChatComponentTranslation tmpQuitMessage;

    /**
     * @author Simon816
     *
     * Store the quit message and ServerConfigurationManager instance for use in
     * {@link #onDisconnectPlayer}.
     */
    @Redirect(method = "onDisconnect", at = @At(value = "INVOKE",
            target = "Lnet/minecraft/server/management/ServerConfigurationManager;sendChatMsg(Lnet/minecraft/util/IChatComponent;)V"))
    public void onSendChatMsgCall(ServerConfigurationManager thisCtx, IChatComponent chatcomponenttranslation) {
        this.tmpQuitMessage = (ChatComponentTranslation) chatcomponenttranslation;
    }

    /**
     * @author Simon816
     *
     * Fire the PlayerQuitEvent before playerLoggedOut is called in order for
     * event handlers to change the quit message captured from
     * {@link #onSendChatMsgCall}.
     */
    @Inject(method = "onDisconnect", at = @At(value = "INVOKE",
            target = "Lnet/minecraft/server/management/ServerConfigurationManager;playerLoggedOut(Lnet/minecraft/entity/player/EntityPlayerMP;)V"))
    public void onDisconnectPlayer(IChatComponent reason, CallbackInfo ci) {
        Text message = SpongeTexts.toText(this.tmpQuitMessage);
        Text newMessage = Texts.of(message);
        Player player = (Player) this.playerEntity;
        Set<CommandSource> sources = new HashSet<CommandSource>();
        sources.add(player);
        MessageSink originalSink = MessageSinks.to(sources);
        ClientConnectionEvent.Disconnect event =
                SpongeImplEventFactory.createClientConnectionEventDisconnect(Sponge.getGame(), Cause.of(player), message, newMessage,
                        originalSink, player.getMessageSink(), player);
        this.tmpQuitMessage = null;
        Sponge.getGame().getEventManager().post(event);
        event.getSink().sendMessage(event.getMessage());
    }

    @Inject(method = "handleResourcePackStatus", at = @At("HEAD"))
    public void onResourcePackStatus(C19PacketResourcePackStatus packet, CallbackInfo ci) {
        String hash = packet.hash;
        ResourcePackStatus status;
        ResourcePack pack = this.sentResourcePacks.get(hash);
        switch (packet.status) {
            case ACCEPTED:
                status = ResourcePackStatus.ACCEPTED;
                break;
            case DECLINED:
                status = ResourcePackStatus.DECLINED;
                break;
            case SUCCESSFULLY_LOADED:
                status = ResourcePackStatus.SUCCESSFULLY_LOADED;
                break;
            case FAILED_DOWNLOAD:
                status = ResourcePackStatus.FAILED;
                break;
            default:
                throw new AssertionError();
        }
        if (status.wasSuccessful().isPresent()) {
            this.sentResourcePacks.remove(hash);
        }
        Sponge.getGame().getEventManager()
                .post(SpongeEventFactory.createResourcePackStatusEvent(Sponge.getGame(), pack, (Player)this.playerEntity, status));
    }

    @Inject(method = "sendPacket", at = @At("HEAD"))
    public void onResourcePackSend(Packet packet, CallbackInfo ci) {
        if (packet instanceof IMixinPacketResourcePackSend) {
            IMixinPacketResourcePackSend p = (IMixinPacketResourcePackSend) packet;
            this.sentResourcePacks.put(p.setFakeHash(), p.getResourcePack());
        }
    }

    @Inject(method = "processPlayerBlockPlacement", at = @At("HEAD"), cancellable = true)
    public void injectBlockPlacement(C08PacketPlayerBlockPlacement packetIn, CallbackInfo ci) {
        // This is a horrible hack needed because the client sends 2 packets on 'right mouse click'
        // aimed at a block. We shouldn't need to get the second packet if the data is handled
        // but we cannot know what the client will do, so we might still get it
        //
        // If the time between packets is small enough, and the 'signature' similar, we discard the
        // second one. This sadly has to remain until Mojang makes their packets saner. :(
        //  -- Grum
        if (packetIn.getPlacedBlockDirection() == 255) {
            if (packetIn.getStack() != null && packetIn.getStack().getItem() == this.lastItem && this.lastPacket != null && ((IMixinC08PacketPlayerBlockPlacement)packetIn).getTimeStamp() - this.lastPacket < 100) {
                this.lastPacket = null;
                ci.cancel();
            }
        } else {
            this.lastItem = null;
            if (packetIn.getStack() != null) {
                // ignore placement of liquids
                if (!(packetIn.getStack().getItem() instanceof ItemBucket)) {
                    this.lastItem = packetIn.getStack().getItem() ;
                    this.lastPacket = ((IMixinC08PacketPlayerBlockPlacement)packetIn).getTimeStamp();
                }
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zutubi.android.example"
    android:versionCode="4" android:versionName="1.2.3">
        <application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ExampleApplication">
        <activity android:name=".ExampleActivity" 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:
package com.lowagie.text.pdf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * This class captures an AcroForm on input. Basically, it extends Dictionary
 * by indexing the fields of an AcroForm
 * @author Mark Thompson
 */

class PRAcroForm extends PdfDictionary {

    /**
     * This class holds the information for a single field
     */
    private static class FieldInformation {
        private final String name;
        private final PdfDictionary info;
        private final PRIndirectReference ref;

        private FieldInformation(final String name, final PdfDictionary info, final PRIndirectReference ref) {
            this.name = name; this.info = info; this.ref = ref;
        }
        public String getName() { return this.name; }
        public PdfDictionary getInfo() { return this.info; }
        public PRIndirectReference getRef() { return this.ref; }
    };
    private final ArrayList fields;
    private final ArrayList stack;
    private final HashMap fieldByName;
    private final PdfReader reader;

    /**
     * Constructor
     * @param reader reader of the input file
     */
    PRAcroForm(final PdfReader reader) {
        this.reader = reader;
        this.fields = new ArrayList();
        this.fieldByName = new LinkedHashMap();
        this.stack = new ArrayList();
    }
    /**
     * Number of fields found
     * @return size
     */
    @Override
	public int size() {
        return this.fields.size();
    }

    public ArrayList getFields() {
        return this.fields;
    }

    /**
     * Read, and comprehend the acroform
     * @param root the document root
     */
    void readAcroForm(final PdfDictionary root) {
        if (root == null) {
			return;
		}
        this.hashMap = root.hashMap;
        pushAttrib(root);
        final PdfArray fieldlist = (PdfArray)PdfReader.getPdfObjectRelease(root.get(PdfName.FIELDS));
        iterateFields(fieldlist, null, null);
    }

    /**
     * After reading, we index all of the fields. Recursive.
     * @param fieldlist An array of fields
     * @param fieldDict the last field dictionary we encountered (recursively)
     * @param title the pathname of the field, up to this point or null
     */
    private void iterateFields(final PdfArray fieldlist, final PRIndirectReference fieldDict, final String title) {
        for (final Iterator it = fieldlist.listIterator(); it.hasNext();) {
            final PRIndirectReference ref = (PRIndirectReference)it.next();
            final PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObjectRelease(ref);

            // if we are not a field dictionary, pass our parent's values
            PRIndirectReference myFieldDict = fieldDict;
            String myTitle = title;
            final PdfString tField = (PdfString)dict.get(PdfName.T);
            final boolean isFieldDict = tField != null;

            if (isFieldDict) {
                myFieldDict = ref;
                if (title == null) {
					myTitle = tField.toString();
				} else {
					myTitle = title + '.' + tField.toString();
				}
            }

            final PdfArray kids = (PdfArray)dict.get(PdfName.KIDS);
            if (kids != null) {
                pushAttrib(dict);
                iterateFields(kids, myFieldDict, myTitle);
                this.stack.remove(this.stack.size() - 1);   // pop
            }
            else {          // leaf node
                if (myFieldDict != null) {
                    PdfDictionary mergedDict = (PdfDictionary)this.stack.get(this.stack.size() - 1);
                    if (isFieldDict) {
						mergedDict = mergeAttrib(mergedDict, dict);
					}

                    mergedDict.put(PdfName.T, new PdfString(myTitle));
                    final FieldInformation fi = new FieldInformation(myTitle, mergedDict, myFieldDict);
                    this.fields.add(fi);
                    this.fieldByName.put(myTitle, fi);
                }
            }
        }
    }
    /**
     * merge field attributes from two dictionaries
     * @param parent one dictionary
     * @param child the other dictionary
     * @return a merged dictionary
     */
    private PdfDictionary mergeAttrib(final PdfDictionary parent, final PdfDictionary child) {
        final PdfDictionary targ = new PdfDictionary();
        if (parent != null) {
			targ.putAll(parent);
		}

        for (final Object element : child.getKeys()) {
            final PdfName key = (PdfName) element;
            if (key.equals(PdfName.DR) || key.equals(PdfName.DA) ||
            key.equals(PdfName.Q)  || key.equals(PdfName.FF) ||
            key.equals(PdfName.DV) || key.equals(PdfName.V)
            || key.equals(PdfName.FT)
            || key.equals(PdfName.F)) {
                targ.put(key,child.get(key));
            }
        }
        return targ;
    }
    /**
     * stack a level of dictionary. Merge in a dictionary from this level
     */
    private void pushAttrib(final PdfDictionary dict) {
        PdfDictionary dic = null;
        if (!this.stack.isEmpty()) {
            dic = (PdfDictionary)this.stack.get(this.stack.size() - 1);
        }
        dic = mergeAttrib(dic, dict);
        this.stack.add(dic);
    }
}


text:
namespace AngleSharp.Css.Declarations
{
    using AngleSharp.Css.Dom;
    using System;
    using static ValueConverters;

    static class StrokeWidthDeclaration
    {
        public static String Name = PropertyNames.StrokeWidth;

        public static IValueConverter Converter = Or(
            LengthOrPercentConverter,
            NumberConverter);

        public static ICssValue InitialValue = InitialValues.StrokeWidthDecl;

        public static PropertyFlags Flags = PropertyFlags.Unitless | PropertyFlags.Animatable;
    }
}


text:
package com.beantimer.controller.validator;

import com.beantimer.model.ProcessedMetric;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 *
 */
public class OrderByValidatorTest {

    @Test
    public void checkIfClazzContainsColumn_classContainsFieldName_true() throws Exception {
        assertEquals(true, OrderByValidator.checkIfClazzContainsColumn(ProcessedMetric.class, "beanName"));
    }

    @Test
    public void checkIfClazzContainsColumn_classDoesNotContainFieldName_false() throws Exception {
        assertEquals(false, OrderByValidator.checkIfClazzContainsColumn(ProcessedMetric.class, "beanNameX"));
    }

    @Test
    public void checkIfClazzContainsColumn_validValues_true() throws Exception {
        assertEquals(true, OrderByValidator.validateDirection("asc"));
        assertEquals(true, OrderByValidator.validateDirection("ASC"));
        assertEquals(true, OrderByValidator.validateDirection("desc"));
        assertEquals(true, OrderByValidator.validateDirection("DESC"));
    }

    @Test
    public void checkIfClazzContainsColumn_invalidValues_false() throws Exception {
        assertEquals(false, OrderByValidator.validateDirection("DESCx"));
    }

}


text:
class Post < ActiveRecord::Base

  has_many :comments
  has_many :commenters, through: :comments, source: :user
  belongs_to :submitter, class_name: "User", foreign_key: :user_id

  def age
    ((Time.now - created_at) / 3600).round
  end

  def comment_count
    comments.count
  end

end


text:
package mockit;

import java.lang.annotation.*;

/**
 * Used inside a mock class to indicate a mock method whose implementation will temporarily replace
 * the implementation of a matching "real" method.
 *

 * The mock method must have the same name and the same parameters as the matching real method, except for an optional
 * first parameter of type {@link Invocation}; if this extra parameter is present, the remaining ones must match the
 * parameters in the real method.
 * The mock method must also have the same return type as the matching real method.
 *

 * Method modifiers (including public, final, and even static), however,
 * don't have to be the same.
 * Checked exceptions in the throws clause (if any) can also differ between the two matching methods.
 * A mock method can also target a constructor, in which case the previous considerations still apply,
 * except for the name of the mock method which must be "$init".
 *

 * A mock method can specify constraints on the number of invocations it should receive while in effect
 * (ie, from the time a real method/constructor is mocked to the time it is restored to its original definition).
 *

 * The special mock methods {@code void $init(...)} and {@code void $clinit()}
 * correspond to constructors and to {@code static} class initializers, respectively.
 * (Notice that it makes no difference if the real class contains more than one static initialization block, because the
 * compiler merges the sequence of static blocks into a single internal "<clinit>" static method in the class file.)
 * Mock methods named {@code $init} will apply to the corresponding constructor in the real class, by matching the
 * declared parameters; just like regular mock methods, they can also have a first parameter of type {@link Invocation}.
 *

 * In the Tutorial
 *
 * @see #invocations invocations
 * @see #minInvocations minInvocations
 * @see #maxInvocations maxInvocations
 * @see #reentrant reentrant
 * @see MockClass
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mock
{
   /**
    * Number of expected invocations of the mock method.
    * If 0 (zero), no invocations will be expected.
    * A negative value (the default) means there is no expectation on the number of invocations;
    * that is, the mock can be called any number of times or not at all during any test which uses it.
    *

    * A non-negative value is equivalent to setting {@link #minInvocations minInvocations} and
    * {@link #maxInvocations maxInvocations} to that same value.
    */
   int invocations() default -1;

   /**
    * Minimum number of expected invocations of the mock method, starting from 0 (zero, which is the default).
    *
    * @see #invocations invocations
    * @see #maxInvocations maxInvocations
    */
   int minInvocations() default 0;

   /**
    * Maximum number of expected invocations of the mock method, if positive.
    * If zero the mock is not expected to be called at all.
    * A negative value (the default) means there is no expectation on the maximum number of invocations.
    *
    * @see #invocations invocations
    * @see #minInvocations minInvocations
    */
   int maxInvocations() default -1;

   /**
    * Indicates whether or not the mock method implementation is allowed to call the corresponding real method on the
    * {@code it} field before it returns from an execution.
    * (The {@code it} field is an instance field defined in the mock class with name "it" and of the same type as the
    * mocked class, which will be set to the real class instance for each indirect call to a mock method.)
    * By default, such reentrant calls are not allowed because they lead to infinite recursion, with the mock method
    * calling itself indirectly through the mocked method.
    *

    * When allowed to make such calls, the mock method effectively behaves as advice to the corresponding real
    * method.
    *

    * As an alternative, consider adding a first parameter of type {@link Invocation} to the mock method, making it
    * automatically reentrant.
    */
   boolean reentrant() default false;
}