text:
@import controllers.sugar.Requests.OreRequest
@import models.viewhelper.{ScopedProjectData, VersionData}
@import ore.OreConfig
@import ore.data.Platform
@import ore.markdown.MarkdownRenderer
@import ore.models.project.{ReviewState, Visibility}
@import ore.permission.Permission
@import util.StringFormatterUtils._
@import util.syntax._
@import views.html.helper.{CSRF, form}
@import views.html.utils.editor
@(v: VersionData, sp: ScopedProjectData)(implicit messages: Messages, request: OreRequest[_], flash: Flash, config: OreConfig, renderer: MarkdownRenderer, assetsFinder: AssetsFinder)

@projectRoutes = @{controllers.project.routes.Projects}
@versionRoutes = @{controllers.project.routes.Versions}
@reviewRoutes = @{controllers.routes.Reviews}
@appRoutes = @{controllers.routes.Application}

@projects.view(v.p, sp, "#versions", noButtons = true) {

@v.v.versionString

                @v.c.name

                    @v.p.project.ownerName

                released this version on @prettifyDate(v.v.createdAt)

                    @if(v.isRecommended) {

                    }

                    @if(v.v.reviewState.isChecked) {
                            @if(request.headerData.globalPerm(Permission.Reviewer)) {
                                @v.approvedBy.zip(v.v.approvedAt).map { t =>

                                        @Html(messages("version.approved.info", t._1, prettifyDate(t._2)))

                                }
                            }
                            @if(v.v.reviewState == ReviewState.PartiallyReviewed) {

                            } else {

                            }
                    }

@v.v.humanFileSize

                        @if(!v.isRecommended && sp.perms(Permission.EditVersion) && v.v.visibility != Visibility.SoftDelete) {
                            @form(action = versionRoutes.setRecommended(
                                v.p.project.ownerName, v.p.project.slug, v.v.versionString), Symbol("class") -> "form-inline") {
                                @CSRF.formField
                                <button type="submit" class="btn btn-info">
                                     Set recommended
                                </button>
                            }
                        }

                        @if(request.headerData.globalPerm(Permission.Reviewer)) {
                            @if(v.v.reviewState.isChecked) {
                                @messages("review.log")
                            } else {

                                     @messages("review.start")

                            }
                        }

                        @if(v.v.visibility == Visibility.SoftDelete) {

                                 @messages("general.delete")

                        } else {
                            @if(sp.perms(Permission.DeleteVersion)) {
                                @if(v.p.publicVersions == 1) {

                                         @messages("general.delete")

                                } else {
                                    <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal-delete">
                                         @messages("general.delete")
                                    </button>
                                }
                            }
                        }

                                 @messages("general.download")

                            <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                                Toggle Dropdown
                            </button>

@messages("general.download")

Copy URL

                        @if(request.hasUser && request.headerData.globalPerm(Permission.ViewLogs)) {

                                <button class="btn btn-alert dropdown-toggle" type="button" id="admin-version-actions" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                    Admin actions

                                </button>

User Action Logs

                                    @if(request.headerData.globalPerm(Permission.Reviewer)) {
                                        @if(v.v.visibility == Visibility.SoftDelete) {

Undo delete

                                        }
                                        @if(request.headerData.globalPerm(Permission.HardDeleteVersion) && !v.isRecommended && (v.p.publicVersions > 1 || v.v.visibility == Visibility.SoftDelete)) {

Hard delete

                                        }
                                    }

                        }

                @if(!v.v.reviewState.isChecked) {

                            @messages("project.download.warn")

                }

                @editor(
                    saveCall = versionRoutes.saveDescription(
                        v.p.project.ownerName, v.p.project.slug, v.v.versionString
                    ),
                    enabled = sp.perms(Permission.EditPage),
                    raw = v.v.description.getOrElse(""),
                    cooked = v.v.obj.render,
                    subject = "Version"
                )

        @if(v.v.dependencies.nonEmpty) {

Dependencies

                        @for(platform <- Platform.getPlatforms(v.dependencies.map(_._1.pluginId).toList)) {
                            @v.v.dependencies.find(_.pluginId == platform.dependencyId).map { dependency =>

                                        @{platform.name}

@dependency.version

                            }
                        }

                        @v.filteredDependencies.map { case (depend, project)=>

                            @if(project.isDefined) {

                                    @project.get.name

                            } else {

                                    @depend.pluginId

                            }

@depend.version

                        }

        } else {

@messages("version.dependency.no")

        }

    @if(sp.perms(Permission.DeleteVersion) && v.p.publicVersions != 1) {

                        <button type="button" class="close" data-dismiss="modal" aria-label="Cancel">
                            ×
                        </button>

@messages("version.delete.title")

                    @form(action = versionRoutes.softDelete(v.p.project.ownerName, v.p.project.slug, v.v.versionString)) {

                            @messages("version.delete.info")
                            <textarea name="comment" class="textarea-delete-comment form-control" rows="3"></textarea>

                                @CSRF.formField
                                <button type="button" class="btn btn-default" data-dismiss="modal">
                                @messages("channel.edit.close")
                                </button>
                                <input type="submit" name="delete" value="@messages("general.delete")" class="btn btn-danger">

                    }

    }

    @if(request.headerData.globalPerm(Permission.Reviewer)) {
        @if(v.v.visibility == Visibility.SoftDelete) {

                            <button type="button" class="close" data-dismiss="modal" aria-label="Cancel">
                                ×
                            </button>

@messages("general.restore")

                        @form(action = versionRoutes.restore(v.p.project.ownerName, v.p.project.slug, v.v.versionString)) {

                                <textarea name="comment" class="textarea-delete-comment form-control" rows="3"></textarea>

                                    @CSRF.formField
                                    <button type="button" class="btn btn-default" data-dismiss="modal">
                                    @messages("channel.edit.close")
                                    </button>
                                    <input type="submit" name="delete" value="@messages("general.restore")" class="btn btn-success">

                        }

        }
        @if(request.headerData.globalPerm(Permission.HardDeleteVersion)) {

                            <button type="button" class="close" data-dismiss="modal" aria-label="Cancel">
                                ×
                            </button>

@messages("general.harddelete")

                        @form(action = versionRoutes.delete(v.p.project.ownerName, v.p.project.slug, v.v.versionString)) {

                                <textarea name="comment" class="textarea-delete-comment form-control" rows="3"></textarea>

                                    @CSRF.formField
                                    <button type="button" class="btn btn-default" data-dismiss="modal">
                                    @messages("channel.edit.close")
                                    </button>
                                    <input type="submit" name="delete" value="@messages("general.harddelete")" class="btn btn-danger">

                        }

        }
    }
}


text:
"""
Implements the ID3 decision tree algorithm.

@author: drusk
"""

from pml.supervised.decision_trees.trees import Node, Tree
from pml.tools.info_theory import info_gain
from pml.utils.collection_utils import (get_key_with_highest_value,
                                        get_most_common)

def build_tree(dataset):
    """
    Builds the decision tree for a data set using the ID3 algorithm.

    Args:
      dataset: model.DataSet
        The data for which the decision tree will be built.

    Return:
      tree: Tree
        The decision tree that was built.
    """
    return Tree(_build_tree_recursively(dataset))

def _build_tree_recursively(dataset):
    """
    Private function used to build the decision tree in a recursive fashion.

    Args:
      dataset: model.DataSet
        The data at the current level of the tree.  Lower levels of the tree
        have filtered subsets of the original data set.

    Returns:
      current_root: Node
        The node which is the root of the level being processed.  For
        example, on the first/outermost call to this function the root
        node will be returned.  Subsequent calls will return the various
        child nodes.
    """
    label_set = set(dataset.get_labels())
    if len(label_set) == 1:
        # All remaining samples have the same label, no need to split further
        return Node(label_set.pop())

    if len(dataset.feature_list()) == 0:
        # No more features to split on
        return Node(get_most_common(dataset.get_labels()))

    # We can still split further
    split_feature = choose_feature_to_split(dataset)

    node = Node(split_feature)

    for value in dataset.get_feature_values(split_feature):
        subset = dataset.value_filter(
                            split_feature, value).drop_column(split_feature)
        node.add_child(value, _build_tree_recursively(subset))

    return node

def choose_feature_to_split(dataset):
    """
    Choose the root to be the feature which has the highest information
    gain.

    Args:
      dataset: model.DataSet
        The data set being used to build the decision tree.

    Returns:
      feature: string
        The feature which should be the root.
    """
    gains = {}
    for feature in dataset.feature_list():
        gains[feature] = info_gain(feature, dataset)

    return get_key_with_highest_value(gains)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace UEC\MediaPdfBundle\Entity;

use UEC\MediaPdfBundle\Model\MediaPdfImage as BaseMediaPdfImage;

class MediaPdfImage extends BaseMediaPdfImage
{

}


text:
namespace Framework.Crawler
{
    public enum EndTag
    {
        SelfEnd,
        EndTag,
        NoEnd
    }
    public enum BrowserType
    {
        Normal,
        Gzip,
        Ajax,
        NormalWithCookieSetup
    }
}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.zuolg.zsite</groupId>
    <artifactId>zsite-root</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.zuolg.zsite</groupId>
  <artifactId>zstie-domain</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>zstie-domain Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
		<!-- Spring boot 的批量依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

		<dependency>
			<!-- 用于查看系统状态的神器 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

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

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

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

		<!-- mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<!-- /Spring boot 的批量依赖 -->

		<!-- 和其他子模块的依赖关系 -->
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>zsite-common</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- /和其他子模块的依赖关系 -->

		<!-- webjar -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>bootstrap</artifactId>
			<version>3.3.7</version>
		</dependency>

		<!-- jquery -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.1.1</version>
		</dependency>

		<!-- /表单验证 -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>

		<!-- fastjson常用的包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.21</version>
		</dependency>

	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/banner</directory>
				<filtering>true</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
require "rails_helper"

describe Comment do
  it { is_expected.to belong_to(:repository) }
  it { is_expected.to belong_to(:author) }

  it "has a valid factory" do
    expect { Factory.build(:comment).to be_valid }
  end
end


text:
<?php
class AppBehavior extends CBehavior
{
    public $beforeCurrentModule = array();
    public $afterCurrentModule = array();

    public function events()
    {
        return array_merge(parent::events(),
                           array(
                           'onBeginRequest'=>'beginRequest',
                           )
                );
    }

    public function beginRequest($event)
    {
        UrlRulesHelper::importRequest($this->beforeCurrentModule,$this->afterCurrentModule);
    }
}


text:
#ifndef SkOffsetImageFilter_DEFINED
#define SkOffsetImageFilter_DEFINED

#include "SkImageFilter.h"
#include "SkPoint.h"

class SK_API SkOffsetImageFilter : public SkImageFilter {
    typedef SkImageFilter INHERITED;

public:
    static SkOffsetImageFilter* Create(SkScalar dx, SkScalar dy, SkImageFilter* input = NULL,
                                       const CropRect* cropRect = NULL) {
        if (!SkScalarIsFinite(dx) || !SkScalarIsFinite(dy)) {
            return NULL;
        }
        return new SkOffsetImageFilter(dx, dy, input, cropRect);
    }
    void computeFastBounds(const SkRect& src, SkRect* dst) const override;
    SK_TO_STRING_OVERRIDE()
    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkOffsetImageFilter)

protected:
    SkOffsetImageFilter(SkScalar dx, SkScalar dy, SkImageFilter* input, const CropRect* cropRect);
    void flatten(SkWriteBuffer&) const override;

    virtual bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
                               SkBitmap* result, SkIPoint* loc) const override;
    bool onFilterBounds(const SkIRect&, const SkMatrix&, SkIRect*) const override;

private:
    SkVector fOffset;
};

#endif


text:
package org.drools.core.spi;

import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;

import org.drools.core.WorkingMemory;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.rule.Declaration;
import org.kie.internal.security.KiePolicyHelper;

/**
 * Accumulator
 *
 * Created: 04/06/2006
 *
 * @version $Id$
 */
public interface Accumulator
    extends
    Invoker {

    /**
     * Creates and return a context object for each working memory instance
     *
     * @return
     */
    public Object createWorkingMemoryContext();

    /**
     * Creates the context object for an accumulator session.
     * The context is passed as a parameter to every subsequent accumulator
     * method call in the same session.
     *
     * @return
     */
    public Serializable createContext();

    /**
     * Executes the initialization block of code
     *
     * @param leftTuple tuple causing the rule fire
     * @param declarations previous declarations
     * @param workingMemory
     * @throws Exception
     */
    public void init(Object workingMemoryContext,
                     Object context,
                     Tuple leftTuple,
                     Declaration[] declarations,
                     WorkingMemory workingMemory) throws Exception;

    /**
     * Executes the accumulate (action) code for the given fact handle
     *
     * @param leftTuple
     * @param handle
     * @param declarations
     * @param innerDeclarations
     * @param workingMemory
     * @throws Exception
     */
    public void accumulate(Object workingMemoryContext,
                           Object context,
                           Tuple leftTuple,
                           InternalFactHandle handle,
                           Declaration[] declarations,
                           Declaration[] innerDeclarations,
                           WorkingMemory workingMemory) throws Exception;

    /**
     * Returns true if this accumulator supports operation reversal
     *
     * @return
     */
    public boolean supportsReverse();

    /**
     * Reverses the accumulate action for the given fact handle
     *
     * @param context
     * @param leftTuple
     * @param handle
     * @param declarations
     * @param innerDeclarations
     * @param workingMemory
     * @throws Exception
     */
    public void reverse(Object workingMemoryContext,
                        Object context,
                        Tuple leftTuple,
                        InternalFactHandle handle,
                        Declaration[] declarations,
                        Declaration[] innerDeclarations,
                        WorkingMemory workingMemory) throws Exception;

    /**
     * Gets the result of the accummulation
     *
     * @param leftTuple
     * @param declarations
     * @param workingMemory
     * @return
     * @throws Exception
     */
    public Object getResult(Object workingMemoryContext,
                            Object context,
                            Tuple leftTuple,
                            Declaration[] declarations,
                            WorkingMemory workingMemory) throws Exception;

    /**
     * This class is used as a wrapper delegate when a security
     * policy is in place.
     */
    public static class SafeAccumulator implements Accumulator, Serializable {
        private static final long serialVersionUID = -2845820209337318924L;
        private Accumulator delegate;

        public SafeAccumulator(Accumulator delegate) {
            super();
            this.delegate = delegate;
        }

        public Object createWorkingMemoryContext() {
            return AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return delegate.createWorkingMemoryContext();
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public Serializable createContext() {
            return AccessController.doPrivileged(new PrivilegedAction<Serializable>() {
                @Override
                public Serializable run() {
                    return delegate.createContext();
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public void init(final Object workingMemoryContext,
                final Object context,
                final Tuple leftTuple,
                final Declaration[] declarations,
                final WorkingMemory workingMemory) throws Exception {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    delegate.init(workingMemoryContext, context, leftTuple, declarations, workingMemory);
                    return null;
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public void accumulate(final Object workingMemoryContext,
                final Object context,
                final Tuple leftTuple,
                final InternalFactHandle handle,
                final Declaration[] declarations,
                final Declaration[] innerDeclarations,
                final WorkingMemory workingMemory) throws Exception {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    delegate.accumulate(workingMemoryContext, context, leftTuple, handle, declarations, innerDeclarations, workingMemory);
                    return null;
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public boolean supportsReverse() {
            // we have to secure even this call because it might run untrusted code
            return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    return delegate.supportsReverse();
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public void reverse(final Object workingMemoryContext,
                final Object context,
                final Tuple leftTuple,
                final InternalFactHandle handle,
                final Declaration[] declarations,
                final Declaration[] innerDeclarations,
                final WorkingMemory workingMemory) throws Exception {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    delegate.reverse(workingMemoryContext, context, leftTuple, handle, declarations, innerDeclarations, workingMemory);
                    return null;
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public Object getResult(final Object workingMemoryContext,
                final Object context,
                final Tuple leftTuple,
                final Declaration[] declarations,
                final WorkingMemory workingMemory) throws Exception {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    return delegate.getResult(workingMemoryContext, context, leftTuple, declarations, workingMemory);
                }
            }, KiePolicyHelper.getAccessContext());
        }

        public boolean wrapsCompiledInvoker() {
            return delegate instanceof CompiledInvoker;
        }
    }

    public static boolean isCompiledInvoker(final Accumulator accumulator) {
        return (accumulator instanceof CompiledInvoker)
                || (accumulator instanceof SafeAccumulator && ((SafeAccumulator) accumulator).wrapsCompiledInvoker());
    }

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
</menu>
<!-- From: file:/C:/Users/Administrator/workspace/Plugig/res/menu/menu_main.xml -->


text:
package ua.com.fielden.platform.sample.domain;

import org.junit.Ignore;

import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.annotation.CompanionObject;
import ua.com.fielden.platform.entity.annotation.DescTitle;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.MapEntityTo;

@KeyType(String.class)
@MapEntityTo
@DescTitle("Description")
@Ignore
@CompanionObject(ITgFuelType.class)
public class TgFuelType extends AbstractEntity<String> {
    private static final long serialVersionUID = 1L;

    protected TgFuelType() {
    }
}


text:
namespace acmacs
{

    class FontSlant
    {
     public:
        enum Value { Normal, Italic };

        FontSlant(Value aFontSlant = Normal) noexcept : mFontSlant{aFontSlant} {}
        FontSlant(const FontSlant&) noexcept = default;
        FontSlant(std::string_view aFontSlant) { from(aFontSlant); }
        FontSlant(const char* aFontSlant) { from(aFontSlant); }
        FontSlant& operator=(const FontSlant&) noexcept = default;
        FontSlant& operator=(std::string_view aFontSlant) { from(aFontSlant); return *this; }

        constexpr operator Value() const noexcept { return mFontSlant; }
        constexpr Value get() const noexcept { return mFontSlant; }

     private:
        Value mFontSlant;

        void from(std::string_view aFontSlant)
        {
            using namespace std::string_view_literals;
            if (aFontSlant == "normal"sv)
                mFontSlant = Normal;
            else if (aFontSlant == "italic"sv)
                mFontSlant = Italic;
            else
                std::runtime_error(acmacs::string::concat("Unrecognized slant: ", aFontSlant));
        }

    }; // class FontSlant

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

    class FontWeight
    {
     public:
        enum Value { Normal, Bold };

        FontWeight(Value aFontWeight = Normal) noexcept : mFontWeight{aFontWeight} {}
        FontWeight(const FontWeight&) noexcept = default;
        FontWeight(std::string_view aFontWeight) { from(aFontWeight); }
        FontWeight(const char* aFontWeight) { from(aFontWeight); }
        FontWeight& operator=(const FontWeight&) noexcept = default;
        FontWeight& operator=(std::string_view aFontWeight) { from(aFontWeight); return *this; }

        constexpr operator Value() const noexcept { return mFontWeight; }
        constexpr Value get() const noexcept { return mFontWeight; }

     private:
        Value mFontWeight;

        void from(std::string_view aFontWeight)
        {
            using namespace std::string_view_literals;
            if (aFontWeight == "normal"sv)
                mFontWeight = Normal;
            else if (aFontWeight == "bold"sv)
                mFontWeight = Bold;
            else
                std::runtime_error(fmt::format("Unrecognized font weight: \"{}\"", aFontWeight));
        }

    }; // class FontWeight

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

    class TextStyle
    {
     public:
        TextStyle() = default;
        TextStyle(std::string_view font_name) : font_family{std::string{font_name}} {}

        [[nodiscard]] bool operator==(const TextStyle& ts) const
            {
                return slant == ts.slant && weight == ts.weight && font_family == ts.font_family;
            }

        FontSlant slant;
        FontWeight weight;
        std::string font_family;

    }; // class TextStyle

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

    class LabelStyle
    {
     public:
        [[nodiscard]] bool operator==(const LabelStyle& ls) const
            {
                return shown == ls.shown && offset == ls.offset && size == ls.size && color == ls.color
                        && rotation == ls.rotation && float_equal(interline, ls.interline) && style == ls.style;
            }
        [[nodiscard]] bool operator!=(const LabelStyle& rhs) const { return !operator==(rhs); }

        bool shown{true};
        Offset offset{0, 1};
        Pixels size{10.0};
        color::Modifier color{BLACK};
        Rotation rotation{NoRotation};
        double interline{0.2};
        TextStyle style;

    }; // class LabelStyle

} // namespace acmacs

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

template <> struct fmt::formatter<acmacs::FontSlant> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
    template <typename FormatCtx> auto format(const acmacs::FontSlant& slant, FormatCtx& ctx)
    {
        switch (slant.get()) {
            case acmacs::FontSlant::Normal:
                return format_to(ctx.out(), "normal");
            case acmacs::FontSlant::Italic:
                return format_to(ctx.out(), "italic");
        }
        return format_to(ctx.out(), "normal");
    }
};

template <> struct fmt::formatter<acmacs::FontWeight> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
    template <typename FormatCtx> auto format(const acmacs::FontWeight& weight, FormatCtx& ctx)
    {
        switch (weight.get()) {
            case acmacs::FontWeight::Normal:
                return format_to(ctx.out(), "normal");
            case acmacs::FontWeight::Bold:
                return format_to(ctx.out(), "bold");
        }
        return format_to(ctx.out(), "normal");
    }
};

template <> struct fmt::formatter<acmacs::TextStyle> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
    template <typename FormatCtx> auto format(const acmacs::TextStyle& style, FormatCtx& ctx) {
        return format_to(ctx.out(), R"({{"slant": {}, "weight": {}, "family": {}}})", style.slant, style.weight, style.font_family);
    }
};

template <> struct fmt::formatter<acmacs::LabelStyle> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
    template <typename FormatCtx> auto format(const acmacs::LabelStyle& style, FormatCtx& ctx)
    {
        return format_to(ctx.out(), R"({{"shown": {}, "offset": {}, "size": {}, "color": {}, "rotation": {}, "interline": {:.2f}, "style": {}}})", style.shown, style.offset, style.size, style.color,
                         style.rotation, style.interline, style.style);
    }
};

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:


text:
FROM python:3.9.5-slim-buster

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV FLASK_APP=manage.py

# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt

# copy project
COPY manage.py /usr/src/app/
COPY fixtures/ /usr/src/app/fixtures/

CMD ["python", "manage.py", "run", "-h", "0.0.0.0"]


text:
package org.apache.usergrid.persistence;

import com.google.inject.Injector;
import org.apache.usergrid.AbstractCoreIT;
import org.apache.usergrid.cassandra.SpringResource;
import org.apache.usergrid.corepersistence.service.StatusService;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.UUID;

/**
 * test status service
 */
public class StatusServiceIT extends AbstractCoreIT {

    private static final Logger LOG = LoggerFactory.getLogger(StatusServiceIT.class);

    public StatusServiceIT() {
        super();
    }
    @Test
    public void testStatus(){
        Injector injector = SpringResource.getInstance().getBean(Injector.class);
        StatusService statusService = injector.getInstance(StatusService.class);
        UUID applicationID =  UUID.randomUUID();
        UUID jobid = UUID.randomUUID();
        //test no status yet
        StatusService.JobStatus status = statusService.getStatus(applicationID, jobid).toBlocking().lastOrDefault(null);
        Assert.assertNull(status);
        statusService.setStatus(applicationID,jobid, StatusService.Status.COMPLETE,null).subscribe();
        //test status no map
        status = statusService.getStatus(applicationID, jobid).toBlocking().lastOrDefault(null);
        Assert.assertNotNull(status);
        Assert.assertEquals(status.getJobStatusId(), jobid);
        Assert.assertEquals(status.getData(), new HashMap<String, Object>());
        Assert.assertEquals(status.getStatus(), StatusService.Status.COMPLETE);

        HashMap<String,Object> map = new HashMap<>();
        map.put("name","hello");
        map.put("count",0);

        statusService.setStatus(applicationID,jobid, StatusService.Status.INPROGRESS,map).subscribe();
        //test status  map
        status = statusService.getStatus(applicationID, jobid).toBlocking().lastOrDefault(null);
        Assert.assertNotNull(status);
        Assert.assertEquals(status.getJobStatusId(), jobid);
        Assert.assertEquals(status.getData(),map);
        Assert.assertEquals(status.getStatus(), StatusService.Status.INPROGRESS);

    }
}


text:
#ifndef GAME_HPP
#define GAME_HPP

#include <cmath>

#include <string>
#include <functional>
#include <fstream>
#include <memory>
#include <stack>

#include <SFML/Graphics/Shader.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/NonCopyable.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>

#include <Thor/Vectors.hpp>

#include <luawrapper/LuaContext.hpp>

#include "state.hpp"
#include "map.hpp"
#include "topbar.hpp"
#include "resourceHolder.hpp"
#include "resourceIdentifiers.hpp"
#include "utility.hpp"

class State;

class Game : private sf::NonCopyable
{
        friend class GameplayState;
        friend class MenuState;

    public:
        class GUI
        {
            public:
                static sfg::SFGUI& instance()
                {
                    static sfg::SFGUI instance;
                    return instance;
                }
        };

    public:
        static Game& instance()
        {
            static Game instance;
            return instance;
        }

    public:
        void run();

        void changeState(State& t_state);
        void pushState(State& t_state);
        void popState();

    private:
        Game();

    private:
        void processEvents();
        void update(const sf::Time& t_elapsedTime);
        void render();
        void updateStatistics(const sf::Time& t_elapsedTime);

    private:
        std::stack<std::reference_wrapper<State>> m_states;
        sf::RenderWindow m_window {};
        sf::Text m_statisticsText {};
        sf::Time m_statisticsUpdateTime {};
        std::size_t m_statisticsNumFrames {};
        static const sf::Time m_timePerFrame;
};

#endif // GAME_HPP


text:
package com.bbn.openmap.tools.beanbox;

import java.util.Vector;

/**
 * The {@link com.bbn.openmap.tools.beanbox.BeanBox}treats all bean
 * objects that implement this interface as container beans.
 */
public interface BeanContainer {

    /**
     * gets the contents of this container as a vector of bean
     * objects.
     */
    public Vector getContents();

    /**
     * sets the contents of this container as a vector of bean
     * objects.
     */
    public void setContents(Vector contents);

    /**
     * adds the specified bean object to this container.
     */
    public void add(Object bean);

    /**
     * removes the specified bean object from this container.
     */
    public void remove(Object bean);

    /**
     * removes all beans from this container.
     */
    public void removeAll();

    /**
     * checks if the specified bean lies in this container.
     */
    public boolean contains(Object bean);

    /**
     * gets the layout manager bean assocciated with this container.
     */
    public BeanLayoutManager getLayout();

    /**
     * sets the layout manager bean assocciated with this container.
     * The layout manager bean is responsible for laying out the
     * contents of this container.
     */
    public void setLayout(BeanLayoutManager layout);

    /**
     * gets the class name of the layout manager bean assocciated with
     * this container.
     */
    public String getLayoutClass();

    /**
     * sets the class name of the layout manager bean assocciated with
     * this container.
     */
    public void setLayoutClass(String lc);

    /**
     * calling this method is meant to generate a call to the layout
     * manager's layoutContainer method.
     */
    public void validate();
}


text:
title: Asynchronous HTTP programming
---

<!--
SPDX-FileCopyrightText: 2016 Mathieu Stefani
SPDX-FileCopyrightText: 2021 Andrea Pappacoda

SPDX-License-Identifier: Apache-2.0
-->

Interfaces provided by Pistaches are _asynchronous_ and _non-blocking_. Asynchronous programming allows for code to continue executing even if the result of a given call is not available yet. Calls that provide an asynchronous interface are referred to _asynchronous calls_.

An example of such a call is the `send()` function provided by the `ResponseWriter` interface. This function returns the number of bytes written to the socket file descriptor associated to the connection. However, instead of returning directly the value to the caller and thus blocking the caller, it wraps the value into a component called a `Promise`.

A `Promise` is the Pistache's implementation of the [Promises/A+](https://promisesaplus.com) standard available in many JavaScript implementations. Simply put, during an asynchronous call, a `Promise` separates the launch of an asynchronous operation from the retrieval of its result. While the asynchronous might still be running, a `Promise<T>` is directly returned to the caller to retrieve the final result when it becomes available. A so called continuation can be attach to a `Promise` to execute a callback when the result becomes available (when the `Promise` has been resolved or fulfilled).

```cpp
auto res = response.send(Http::Code::Ok, "Hello World");
res.then(
    [](ssize_t bytes) { std::cout << bytes << " bytes have been sent\n" },
    Async::NoExcept
);
```

The `then()` member is used to attach a callback to the `Promise`. The first argument is a callable that will be called when the `Promise` has been **succesfully** resolved. If, for some reason, an error occurs during the asynchronous operation, a `Promise` can be **rejected** and will then fail. In this case, the second callable will be called. `Async::NoExcept` is a special callback that will call [`std::terminate()`](https://en.cppreference.com/w/cpp/error/terminate) if the promise failed. This is the equivalent of the `noexcept` keyword.

Other generic callbacks can also be used in this case:

- `Async::IgnoreException` will simply ignore the exception and let the program continue
- `Async::Throw` will "rethrow" the exception up to an eventual promise call-chain. This has the same effect than the `throw` keyword, except that it is suitable for promises

Exceptions in promises callbacks are propagated through an `exception_ptr`. Promises can also be chained together to create a whole asynchronous pipeline:

```cpp
auto fetchOp = fetchDatabase();
fetchOp
    .then(
        [](const User& user) { return fetchUserInfo(user); },
        Async::Throw)
    .then(
        [](const UserInfo& info) { std::cout << "User name = " << info.name << '\n'; },
        [](exception_ptr ptr) { std::cerr << "An exception occured during user retrieval\n";}
);
```

Line 5 will propagate the exception if `fetchDatabase()` failed and rejected the promise.


text:
<title>
Inside Socialist Worker
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

June 13, 2003 | Issue 457

FRONT AND BACK PAGES

Robin Hood in reverse

Bush's class war

The Bush administration's budget proposals slash away at every social program that working people need--from Head Start to Medicare. Why? To pay for a massive tax cut giveaway to the rich.

Deadly attacks on Palestinians

Israel's rampage

With a series of deadly Israeli rocket attacks on Palestinian neighborhoods in Gaza, Israeli Prime Minister Ariel Sharon dramatically tore up the U.S.-backed "road map" to Middle East peace.

Interview with Palestinian author Naseer Aruri:

Breakdown of the "road map"

SPECIAL FEATURES

Why the Democrats don't deserve your support in 2004

Anybody but Bush?

Even though Election Day is more than 16 months away, many people who oppose the Bush agenda have already pinned their hopes on the 2004 presidential vote. But can we trust the Democrats to provide a real alternative?

The execution of Ethel and Julius Rosenberg

It is 50 years since the execution of the Rosenbergs--a cold-blooded murder committed by the U.S. government in the name of the Cold War fight against communism.

Interview with the Rosenbergs' son Robert Meeropol:

"What we need to do is speak out"

WHAT WE THINK

Iraqi resistance grows as U.S. launches military crackdown

America's iron heel

U.S. officials may try to dismiss the resistance as action by pro-Saddam elements, but the reality is that growing numbers of angry and impoverished Iraqis are prepared to resist the occupation–including by armed force.

NATIONAL NEWS

Supreme Court lawsuits mark the latest stage in...

The assault on affirmative action

If the U.S. Supreme Court rules against affirmative action policies at the University of Michigan, it will be a victory for racists--from George Bush on down.

Immigrant killed in workplace accident

Horror at a Texas factory

Daniel Cruz Romero was killed on the job at a meat processing factory north of Austin--the latest among a group of Mexican immigrants to meet death in Texas in ever more gruesome ways.

Mayor demands "sacrifice"

Taking aim at New York's poor

Mayor Michael Bloomberg is determined to balance the city's budget on the backs of poor and working New Yorkers--and poor kids will be the first targets.

Financial scandal at mortgage giant

The mortgage giant Freddie Mac is under criminal investigation by the Securities and Exchange Commission after its Enron-style accounting scams came to light.

INTERNATIONAL NEWS

New protests in Iran sign of political crisis

Student protests in Tehran and other cities are highlighting the rising social tensions in Iran, even as the U.S. steps up pressure on the country.

Strikes against pension cuts

Where is the fight headed in France?

Regional walkouts protesting the government's plan to "reform" the state-run pension system have broadened into a strike wave involving millions of public- and private-sector workers.

COLUMNS

READING BETWEEN THE LINES

Rolling back prices and workers rights

Mega-retailer Wal-Mart is the company that best represents today's free-market, low-benefit U.S. capitalism.

ON THE PICKET LINE

"The Congress is cheap"

Walkout over wage cuts at Chicago hotel

 "THE CONGRESS is cheap, cheap and mean!" That slogan rang out from the crowd of housekeepers, restaurant employees and bellmen as they walked off the job at the Congress Hotel in Chicago.

Reformers win key positions in Local 790, but…

SEIU accepts cuts in S.F.

Under threat of massive layoffs, unions representing San Francisco city and county workers have agreed to concessions totaling $80-$90 million. Adding insult to injury, the cuts are completely unnecessary.

Hoffa deal won't save jobs in carhaul

Teamster carhaul workers will vote on a tentative contract at the end of this month--a five-year deal with no hourly wage increase for in first two years of the deal, and only $1.30 over the remaining three.

Why did Charleston ILA cross a picket line?

East Coast dockworkers forced shipper Evergreen America Corp. to withdraw charges that the union was conducting an illegal strike. But questions remain as to why ILA Local 1422 in Charleston, S.C., crossed picket lines.

On the picket line

General Electric; Sacramento janitors; Seattle janitors; Los Angeles Unified School District; Washington, D.C., teachers; Chicago health care rally

SW READERS SPEAK OUT

YUM! treats chickens better than farmworkers

Modern-day slavery

YUM! Brands--which owns Taco Bell, KFC, Pizza Hut, Long John Silver's and A&W All American Food Restaurants--apparently thinks that chickens are more important than human beings.

Corporate vultures who prey on the sick

In response to increasing pressure from New Haven County residents, Yale New Haven Hospital has been forced to forgive some patients' debts and stop foreclosures.

Letters to the editor

We can't take four more years of Bush; Out of the closets and into the streets; Socialist Worker missed the point in the Matrix.

REVIEWS

Letters to a Young Activist from Todd Gitlin

Return to sender

Running throughout the condescending prose and sloppy fact-checking in Todd Gitlin's book lies the assertion that any challenge to the Democratic Party is either the product of youthful folly or crazed sectarianism.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
(function($) {
    // class $.jqplot.EnhancedLegendRenderer
    // Legend renderer which can specify the number of rows and/or columns in the legend.
    $.jqplot.EnhancedLegendRenderer = function(){
        $.jqplot.TableLegendRenderer.call(this);
    };

    $.jqplot.EnhancedLegendRenderer.prototype = new $.jqplot.TableLegendRenderer();
    $.jqplot.EnhancedLegendRenderer.prototype.constructor = $.jqplot.EnhancedLegendRenderer;

    // called with scope of legend.
    $.jqplot.EnhancedLegendRenderer.prototype.init = function(options) {
        // prop: numberRows
        // Maximum number of rows in the legend.  0 or null for unlimited.
        this.numberRows = null;
        // prop: numberColumns
        // Maximum number of columns in the legend.  0 or null for unlimited.
        this.numberColumns = null;
        // prop: seriesToggle
        // false to not enable series on/off toggling on the legend.
        // true or a fadein/fadeout speed (number of milliseconds or 'fast', 'normal', 'slow')
        // to enable show/hide of series on click of legend item.
        this.seriesToggle = 'normal';
        // prop: disableIEFading
        // true to toggle series with a show/hide method only and not allow fading in/out.
        // This is to overcome poor performance of fade in some versions of IE.
        this.disableIEFading = true;
        $.extend(true, this, options);

        if (this.seriesToggle) {
            $.jqplot.postDrawHooks.push(postDraw);
        }
    };

    // called with scope of legend
    $.jqplot.EnhancedLegendRenderer.prototype.draw = function() {
        var legend = this;
        if (this.show) {
            var series = this._series;
			var s;
            var ss = 'position:absolute;';
            ss += (this.background) ? 'background:'+this.background+';' : '';
            ss += (this.border) ? 'border:'+this.border+';' : '';
            ss += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
            ss += (this.fontFamily) ? 'font-family:'+this.fontFamily+';' : '';
            ss += (this.textColor) ? 'color:'+this.textColor+';' : '';
            ss += (this.marginTop != null) ? 'margin-top:'+this.marginTop+';' : '';
            ss += (this.marginBottom != null) ? 'margin-bottom:'+this.marginBottom+';' : '';
            ss += (this.marginLeft != null) ? 'margin-left:'+this.marginLeft+';' : '';
            ss += (this.marginRight != null) ? 'margin-right:'+this.marginRight+';' : '';
            this._elem = $('

');
            if (this.seriesToggle) {
                this._elem.css('z-index', '3');
            }

            var pad = false,
                reverse = false,
                nr, nc;
            if (this.numberRows) {
                nr = this.numberRows;
                if (!this.numberColumns){
                    nc = Math.ceil(series.length/nr);
                }
                else{
                    nc = this.numberColumns;
                }
            }
            else if (this.numberColumns) {
                nc = this.numberColumns;
                nr = Math.ceil(series.length/this.numberColumns);
            }
            else {
                nr = series.length;
                nc = 1;
            }

            var i, j, tr, td1, td2, lt, rs;
            var idx = 0;
            // check to see if we need to reverse
            for (i=series.length-1; i>=0; i--) {
                if (series[i]._stack || series[i].renderer.constructor == $.jqplot.BezierCurveRenderer){
                    reverse = true;
                }
            }

            for (i=0; i<nr; i++) {
                if (reverse){
                    tr = $('

').prependTo(this._elem);
                }
                else{
                    tr = $('

').appendTo(this._elem);
                }
                for (j=0; j<nc; j++) {
                    if (idx < series.length && series[idx].show && series[idx].showLabel){
                        s = series[idx];
                        lt = this.labels[idx] || s.label.toString();
                        if (lt) {
                            var color = s.color;
                            if (!reverse){
                                if (i>0){
                                    pad = true;
                                }
                                else{
                                    pad = false;
                                }
                            }
                            else{
                                if (i == nr -1){
                                    pad = false;
                                }
                                else{
                                    pad = true;
                                }
                            }
                            rs = (pad) ? this.rowSpacing : '0';

                            td1 = $(''+
                                '

'+
                                '
	');
                            td2 = $('	');
                            if (this.escapeHtml){
                                td2.text(lt);
                            }
                            else {
                                td2.html(lt);
                            }
                            if (reverse) {
                                if (this.showLabels) {td2.prependTo(tr);}
                                if (this.showSwatches) {td1.prependTo(tr);}
                            }
                            else {
                                if (this.showSwatches) {td1.appendTo(tr);}
                                if (this.showLabels) {td2.appendTo(tr);}
                            }

                            if (this.seriesToggle) {
                                var speed;
                                if (typeof(this.seriesToggle) == 'string' || typeof(this.seriesToggle) == 'number') {
                                    if (!$.browser.msie || !this.disableIEFading) {
                                        speed = this.seriesToggle;
                                    }
                                }
                                if (this.showSwatches) {
                                    td1.bind('click', {series:s, speed:speed}, s.toggleDisplay);
                                    td1.addClass('jqplot-seriesToggle');
                                }
                                if (this.showLabels)  {
                                    td2.bind('click', {series:s, speed:speed}, s.toggleDisplay);
                                    td2.addClass('jqplot-seriesToggle');
                                }
                            }

                            pad = true;
                        }
                    }
                    idx++;
                }
            }
        }
        return this._elem;
    };

    // called with scope of plot.
    var postDraw = function () {
        if (this.legend.renderer.constructor == $.jqplot.EnhancedLegendRenderer && this.legend.seriesToggle){
            var e = this.legend._elem.detach();
            this.eventCanvas._elem.after(e);
        }
    };
})(jQuery);


text:
<?php

/**
 * @file
 * Contains \Drupal\user\Tests\Migrate\MigrateUserStubTest.
 */

namespace Drupal\user\Tests\Migrate;

use Drupal\migrate_drupal\Tests\MigrateDrupalTestBase;
use Drupal\migrate_drupal\Tests\StubTestTrait;

/**
 * Test stub creation for user entities.
 *
 * @group user
 */
class MigrateUserStubTest extends MigrateDrupalTestBase {

  use StubTestTrait;

  /**
   * {@inheritdoc}
   */
  public static $modules = ['user'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installEntitySchema('user');
    $this->installSchema('system', ['sequences']);
  }

  /**
   * Tests creation of user stubs.
   */
  public function testStub() {
    $this->performStubTest('user');
  }

}


text:
package com.romanenco.cfrm;

import org.junit.Assert;
import org.junit.Test;

import com.romanenco.cfrm.grammar.builder.GrammarJBuilder;
import com.romanenco.cfrm.lexer.LexerError;
import com.romanenco.cfrm.lexer.LexerRule;
import com.romanenco.cfrm.lexer.RegLexer;
import com.romanenco.cfrm.llparser.LLParser;
import com.romanenco.cfrm.llparser.ParsingError;

public class LexerLLParserTest {

    private Grammar getGrammar() {
        final GrammarJBuilder builder = new GrammarJBuilder();

        builder.declareNonTerminals("E", "T", "E'", "T'", "F");
        builder.declareStartSymbol("E");
        builder.declareEpsilon("epsilon");

        builder.addTerminal("id", new LexerRule("\\d+"));
        builder.addTerminal("+", new LexerRule("\\+"));
        builder.addTerminal("*", new LexerRule("\\*"));
        builder.addTerminal("(", new LexerRule("\\("));
        builder.addTerminal(")", new LexerRule("\\)"));
        builder.addTerminal("WS", new LexerRule(" +", LexerRule.TYPE.IGNORE));

        builder.addProductions("E", "T E'");
        builder.addProductions("E'", "+ T E'", "epsilon");
        builder.addProductions("T", "F T'");
        builder.addProductions("T'", "* F T'", "epsilon");
        builder.addProductions("F", "( E )", "id");

        return builder.getGrammar();
    }

    private Lexer getLexer(Grammar grammar) {
        return new RegLexer(grammar);
    }

    private Parser getParser(Grammar grammar) {
        return new LLParser(grammar);
    }

    @Test
    public void goodTest() {
        final Grammar grammar = getGrammar();
        final Lexer lexer = getLexer(grammar);
        final Parser parser = getParser(grammar);

        final String input = "(45+12) * 45 + 45 + (5 + 5*6)";

        final ParsingTreeNode parsingTree = parser.parse(lexer.tokenize(input));
        Assert.assertTrue(ParsingTreeValidator.isValid(parsingTree));
    }

    @Test(expected = LexerError.class)
    public void badLexerTest() {
        final Grammar grammar = getGrammar();
        final Lexer lexer = getLexer(grammar);
        final Parser parser = getParser(grammar);

        final String input = "44*X+12";

        final ParsingTreeNode parsingTree = parser.parse(lexer.tokenize(input));
        Assert.assertTrue(ParsingTreeValidator.isValid(parsingTree));
    }

    @Test(expected = ParsingError.class)
    public void badParserTest() {
        final Grammar grammar = getGrammar();
        final Lexer lexer = getLexer(grammar);
        final Parser parser = getParser(grammar);

        final String input = "44 ++ 45";

        final ParsingTreeNode parsingTree = parser.parse(lexer.tokenize(input));
        Assert.assertTrue(ParsingTreeValidator.isValid(parsingTree));
    }

}


text:
package alluxio.cli.command.metadatacache;

import alluxio.AlluxioURI;
import alluxio.cli.command.AbstractFuseShellCommand;
import alluxio.client.file.FileSystem;
import alluxio.client.file.MetadataCachingFileSystem;
import alluxio.client.file.URIStatus;
import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.PropertyKey;
import alluxio.exception.runtime.InvalidArgumentRuntimeException;
import alluxio.exception.status.InvalidArgumentException;

/**
 * Metadata cache sub command.
 */
public abstract class AbstractMetadataCacheSubCommand extends AbstractFuseShellCommand {

  /**
   * @param fileSystem   the file system the command takes effect on
   * @param conf the Alluxio configuration
   * @param commandName  the parent command name
   */
  public AbstractMetadataCacheSubCommand(FileSystem fileSystem,
      AlluxioConfiguration conf, String commandName) {
    super(fileSystem, conf, commandName);
  }

  @Override
  public URIStatus run(AlluxioURI path, String[] argv) throws InvalidArgumentException {
    if (!mConf.getBoolean(PropertyKey.USER_METADATA_CACHE_ENABLED)) {
      throw new InvalidArgumentRuntimeException(String.format("%s command is "
              + "not supported when %s is false", getCommandName(),
          PropertyKey.USER_METADATA_CACHE_ENABLED.getName()));
    }
    return runSubCommand(path, argv, (MetadataCachingFileSystem) mFileSystem);
  }

  /**
   * Run the metadatacache subcommand.
   *
   * @return the result of running the command
   */
  protected abstract URIStatus runSubCommand(AlluxioURI path, String[] argv,
      MetadataCachingFileSystem fs);
}


text:
//
// Created by byter on 10/23/18.
//

#ifndef THREE_PP_TESTMODELREF_H
#define THREE_PP_TESTMODELREF_H

//#define IS_LOGGING_ACTIVE
#include <threepp/quick/objects/ModelRef.h>
#include <threepp/quick/scene/Dynamics.h>
#include <QStringListModel>

namespace three {
namespace quick {

class Dynamics;

/**
 * subclasses ModelRef to provide support functions for hinge editing based on the
 * physics integration with reactphysics3d
 */
class HingeEditorModelRef : public quick::ModelRef
{
Q_OBJECT
  Q_PROPERTY(QObject *dynamics READ dynamics WRITE setDynamics NOTIFY dynamicsChanged)

  std::vector<DynamicMesh::Ptr> _markers;

  Dynamics *_dynamics = nullptr;

public:
  HingeEditorModelRef(QObject *parent = nullptr)  : ModelRef(parent) {}

  QObject *dynamics() const {return _dynamics;}

  void setDynamics(QObject *physics);

  /**
   * set a marker on the model at the last picked position
   */
  Q_INVOKABLE void setMarker(three::quick::ObjectPicker *picker);

  /**
   * reset everything, removing all physics data
   */
  Q_INVOKABLE void resetAll();

  /**
   * remove all current hinge markers
   */
  Q_INVOKABLE void removeMarkers();

signals:
  void hingeNamesChanged();
  void dynamicsChanged();
};

}
}

#endif //THREE_PP_TESTMODELREF_H


text:
APPLICATION

using namespace Permute;

class QuadraticLOP : public Application {
private:
  static Core::ParameterInt paramRestart;
  int RESTART;
  Core::Timer timer;
public:
  QuadraticLOP () :
    Application ("q-lop")
  {}

  virtual void getParameters () {
    Application::getParameters ();
    RESTART = paramRestart (config);
  }

  int main (const std::vector <std::string> & args) {
    this -> getParameters ();

    std::cout << "Name Score Iterations Time" << std::endl;
    int index = 0;
    for (std::vector <std::string>::const_iterator it = args.begin (); it != args.end (); ++ it) {
      this -> LOLIB_FILE = * it;
      BeforeCostRef bcr (this -> lolib ());

      Permutation p;
      integerPermutation (p, bcr -> size ());

      ParseControllerRef pc = this -> parseController (p);
      ScorerRef gamma (new BeforeScorer (bcr, p));

      QuadraticNormalLOPChart chart (p, QUADRATIC_WIDTH, QUADRATIC_LEFT > 0);

      double best_score = Core::Type <double>::min;

      for (int i = 0; i < RESTART; ++ i) {
	timer.start ();

	p.randomize ();
	best_score = gamma -> score (p);
	int iterations = 0;
	do {
	  ++ iterations;
	  chart.permute (pc, gamma);
	  const ConstPathRef & bestPath = chart.getBestPath ();
	  p.changed (false);
	  if (bestPath -> getScore () > best_score) {
	    best_score = bestPath -> getScore ();
	    p.reorder (bestPath);
	  }
	} while (p.changed ());

	timer.stop ();

	std::cout << index ++ << ' '
		  << bcr -> name () << ' '
		  << best_score << ' '
		  << iterations << ' '
		  << timer.user () << std::endl;
      }
    }

    return EXIT_SUCCESS;
  }
} app;

Core::ParameterInt QuadraticLOP::paramRestart ("restart", "the number of restarts", 1, 1);


text:
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
        <meta name="keywords" content="" />
        <meta name="description" content="" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title> activiti和设计模式(8)  </title>
        <link rel="stylesheet" href="http://localhost:4000/css/default.css" type="text/css" />
        <link rel="stylesheet" href="http://localhost:4000/css/small.css" type="text/css" media="(max-width: 720px)"/>
        <link rel="stylesheet" href="http://localhost:4000/css/syntax.css" type="text/css" />
        <link rel="shortcut icon" href="http://localhost:4000/favicon.ico" type="image/x-icon" />

        首页
        分类
        周报
        计划
        关于

 activiti和设计模式(8)

BPMN中不仅规定了每一个图标代表的意义,例如:

而且还规定了每一个每一图形的行为标准,在Activiti中动作行为封装在了ActivityBehavior中,在ActivityBehavior中,不仅封装的有行为,线上的条件的判断。

首先是ActivityBehavior的构建,采用的是简单工厂的设计模式:

public interface ActivityBehaviorFactory {

  public abstract NoneStartEventActivityBehavior createNoneStartEventActivityBehavior(StartEvent startEvent);

  public abstract EventSubProcessStartEventActivityBehavior createEventSubProcessStartEventActivityBehavior(StartEvent startEvent, String activityId);

  public abstract TaskActivityBehavior createTaskActivityBehavior(Task task);

  public abstract ManualTaskActivityBehavior createManualTaskActivityBehavior(ManualTask manualTask);

  public abstract ReceiveTaskActivityBehavior createReceiveTaskActivityBehavior(ReceiveTask receiveTask);

  public abstract UserTaskActivityBehavior createUserTaskActivityBehavior(UserTask userTask, TaskDefinition taskDefinition);

  public abstract ClassDelegate createClassDelegateServiceTask(ServiceTask serviceTask);

  public abstract ServiceTaskDelegateExpressionActivityBehavior createServiceTaskDelegateExpressionActivityBehavior(ServiceTask serviceTask);

  public abstract ServiceTaskExpressionActivityBehavior createServiceTaskExpressionActivityBehavior(ServiceTask serviceTask);

  public abstract WebServiceActivityBehavior createWebServiceActivityBehavior(ServiceTask serviceTask);

  public abstract WebServiceActivityBehavior createWebServiceActivityBehavior(SendTask sendTask);

  public abstract MailActivityBehavior createMailActivityBehavior(ServiceTask serviceTask);

  public abstract MailActivityBehavior createMailActivityBehavior(SendTask sendTask);

  // We do not want a hard dependency on the Mule module, hence we return ActivityBehavior and instantiate
  // the delegate instance using a string instead of the Class itself.
  public abstract ActivityBehavior createMuleActivityBehavior(ServiceTask serviceTask, BpmnModel bpmnModel);

  public abstract ActivityBehavior createMuleActivityBehavior(SendTask sendTask, BpmnModel bpmnModel);

  public abstract ActivityBehavior createCamelActivityBehavior(ServiceTask serviceTask, BpmnModel bpmnModel);

  public abstract ActivityBehavior createCamelActivityBehavior(SendTask sendTask, BpmnModel bpmnModel);

  public abstract ShellActivityBehavior createShellActivityBehavior(ServiceTask serviceTask);

  public abstract ActivityBehavior createBusinessRuleTaskActivityBehavior(BusinessRuleTask businessRuleTask);

  public abstract ScriptTaskActivityBehavior createScriptTaskActivityBehavior(ScriptTask scriptTask);

  public abstract ExclusiveGatewayActivityBehavior createExclusiveGatewayActivityBehavior(ExclusiveGateway exclusiveGateway);

  public abstract ParallelGatewayActivityBehavior createParallelGatewayActivityBehavior(ParallelGateway parallelGateway);

  public abstract InclusiveGatewayActivityBehavior createInclusiveGatewayActivityBehavior(InclusiveGateway inclusiveGateway);

  public abstract EventBasedGatewayActivityBehavior createEventBasedGatewayActivityBehavior(EventGateway eventGateway);

  public abstract SequentialMultiInstanceBehavior createSequentialMultiInstanceBehavior(ActivityImpl activity, AbstractBpmnActivityBehavior innerActivityBehavior);

  public abstract ParallelMultiInstanceBehavior createParallelMultiInstanceBehavior(ActivityImpl activity, AbstractBpmnActivityBehavior innerActivityBehavior);

  public abstract SubProcessActivityBehavior createSubprocActivityBehavior(SubProcess subProcess);

  public abstract CallActivityBehavior createCallActivityBehavior(CallActivity callActivity);

  public abstract TransactionActivityBehavior createTransactionActivityBehavior(Transaction transaction);

  public abstract IntermediateCatchEventActivityBehavior createIntermediateCatchEventActivityBehavior(IntermediateCatchEvent intermediateCatchEvent);

  public abstract IntermediateThrowNoneEventActivityBehavior createIntermediateThrowNoneEventActivityBehavior(ThrowEvent throwEvent);

  public abstract IntermediateThrowSignalEventActivityBehavior createIntermediateThrowSignalEventActivityBehavior(ThrowEvent throwEvent, Signal signal, EventSubscriptionDeclaration eventSubscriptionDeclaration);

  public abstract IntermediateThrowCompensationEventActivityBehavior createIntermediateThrowCompensationEventActivityBehavior(ThrowEvent throwEvent, CompensateEventDefinition compensateEventDefinition);

 ...........

}

默认的实现是:

public class DefaultActivityBehaviorFactory extends AbstractBehaviorFactory implements ActivityBehaviorFactory {

  // Start event
  public final static String EXCEPTION_MAP_FIELD = "mapExceptions";

  public NoneStartEventActivityBehavior createNoneStartEventActivityBehavior(StartEvent startEvent) {
    return new NoneStartEventActivityBehavior();
  }

  public EventSubProcessStartEventActivityBehavior createEventSubProcessStartEventActivityBehavior(StartEvent startEvent, String activityId) {
    return new EventSubProcessStartEventActivityBehavior(activityId);
  }

  // Task

  public TaskActivityBehavior createTaskActivityBehavior(Task task) {
    return new TaskActivityBehavior();
  }
...........
}

我们在「activiti和设计模式(7)」 中定义的usertask是多实例的,所以对应的Behavior是:

Published on Aug 13, 2017 in categories

          activiti-desigen-pattern

                上一篇
                activiti和设计模式(7)

                下一篇
                复习算法和数据结构(1)

        <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">

Powered by andiHappy and Theme by AndiHappy


text:
package net.folab.fo.runtime._fo._lang._Integer._add;

import net.folab.fo.runtime.Evaluable;
import net.folab.fo.runtime._fo._lang.Integer;
import net.folab.fo.runtime._fo._lang._Integer.add;

public class _0 extends Evaluable<Integer> {

    private final add self;

    private final Evaluable<Integer> param;

    public _0(add fo_lang_int_add,
            Evaluable<Integer> param) {
        this.self = fo_lang_int_add;
        this.param = param;
    }

    @Override
    public Integer evaluate() {
        int a0 = self.getSelf().evaluate().getValue();
        int a1 = param.evaluate().getValue();
        Integer r = Integer.valueOf(a0 + a1);
        return r;
    }

}


text:
MochaUI.extend({
	/*

	Function: initializeTabs
		Add click event to each list item that fires the selected function.

	*/
	initializeTabs: function(el){
		$(el).getElements('li').each(function(listitem){
			listitem.addEvent('click', function(e){
				MochaUI.selected(this, el);
			});
		});
	},
	/*

	Function: selected
		Add "selected" class to current list item and remove it from sibling list items.

	Syntax:
		(start code)
			selected(el, parent);
		(end)

Arguments:
	el - the list item
	parent - the ul

	*/
	selected: function(el, parent){
		$(parent).getChildren().each(function(listitem){
			listitem.removeClass('selected');
		});
		el.addClass('selected');
	}
});


text:
package br.com.objectos.way.assertion;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author marcio.endo@objectos.com.br (Marcio Endo)
 */
public class SetAssertion<T> extends CollectionAssertion<SetAssertion<T>, Set<T>, T> {

  SetAssertion(Set<T> subject) {
    super(subject);
  }

  @Override
  protected SetAssertion<T> self() {
    return this;
  }

  @SuppressWarnings("unchecked")
  @Override
  Set<T> fromElements(T... elements) {
    List<T> list = Arrays.asList(elements);
    Set<T> subject = subject();
    if (subject instanceof LinkedHashSet) {
      return new LinkedHashSet<>(list);
    } else {
      return new HashSet<>(list);
    }
  }

}


text:
cask 'torguard' do
  version '3.96.1'
  sha256 'd1809b0240cea4291a318749791f0c8700f7c2a7270d1032397d535fb54c75cc'

  # torguard.biz was verified as official when first introduced to the cask
  url "https://updates.torguard.biz/Software/MacOSX/TorGuard-v#{version}.dmg"
  appcast 'https://updates.torguard.biz/Software/MacOSX/checksums.sha256'
  name 'TorGuard'
  homepage 'https://torguard.net/'

  pkg 'Install TorGuard.pkg'

  uninstall pkgutil: 'net.torguard.TorGuardDesktopQt',
            delete:  '/Applications/TorGuard.app'

  zap trash: [
               '~/Library/Preferences/net.torguard.TorGuard*.plist',
               '~/Library/Saved Application State/net.torguard.TorGuardDesktopQt.savedState',
             ]
end


text:
<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>halloween</title>
  <link rel="stylesheet" href="style.css">

Sorry,

you have participated in this activity today,

Please come back tomorrow and win ANOTHER Mystery Gift!

      The Sale YOU Need to See ►

Notes:

1. Every Gift is completely random;

2. Each registered member can gain ONE Mystery Gift every day;

3. Just enter your coupon code or FREE Z Points at the Checkout page for an instant discount!


text:
import json
import os
import subprocess
import time

import click
import yaml
import requests

__version__ = '0.0.1'

@click.command()
@click.argument('cmd', required=True, nargs=-1)
def cli(cmd):
    config_file_path = '/etc/maxload.yml'
    uuid = ''
    if os.path.exists(config_file_path):
        with open(config_file_path, 'r') as f:
            try:
                config = yaml.load(''.join(f.readlines()))
            except yaml.parser.ParserError:
                config = None

            if config:
                uuid = config.get('uuid', '')

    cmd = ' '.join(cmd)

    cron_info = dict()
    cron_info['cmd'] = cmd
    cron_info['start_time'] = time.time()
    cron_info['exit_status'] = subprocess.call(cmd, shell=True)
    cron_info['end_time'] = time.time()
    cron_info['process_time'] = cron_info['end_time'] - cron_info['start_time']

    if uuid:
        try:
            requests.post(
                'https://maxload.io/api/crons_logs',
                params={'uuid': uuid},
                data=json.dumps(cron_info),
                headers={
                    'Content-Type': 'Application/json',
                    'User-Agent': 'MaxCron %s' % __version__},
                timeout=3
            )
        except requests.exceptions.RequestException as e:
            pass

if __name__ == '__main__':
    cli()