text:
package org.openapitools.api;

import javax.ws.rs.*;
import javax.ws.rs.core.Response;

import io.swagger.annotations.*;

import java.io.InputStream;
import java.util.Map;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;

@Path("/createItem")
@Api(description = "the createItem API")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2022-06-04T08:09:11.684443Z[Etc/UTC]")
public class CreateItemApi {

    @POST
    @Consumes({ "application/json" })
    @Produces({ "*/*" })
    @ApiOperation(value = "", notes = "Create a new job using job configuration, or copied from an existing job", response = Void.class, authorizations = {

        @Authorization(value = "jenkins_auth")
         }, tags={ "remoteAccess" })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully created a new job", response = Void.class),
        @ApiResponse(code = 400, message = "An error has occurred - error message is embedded inside the HTML response", response = String.class),
        @ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password", response = Void.class),
        @ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password", response = Void.class)
    })
    public Response postCreateItem(@QueryParam("name") @NotNull  @ApiParam("Name of the new job")  String name,@QueryParam("from")  @ApiParam("Existing job to copy from")  String from,@QueryParam("mode")  @ApiParam("Set to 'copy' for copying an existing job")  String mode,@HeaderParam("Jenkins-Crumb")   @ApiParam("CSRF protection token") String jenkinsCrumb,@HeaderParam("Content-Type")   @ApiParam("Content type header application/xml") String contentType,@Valid String body) {
        return Response.ok().entity("magic!").build();
    }
}


text:
import {Directive, Input} from '@angular/core';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {CdkAccordion} from '@angular/cdk/accordion';

/** MatAccordion's display modes. */
export type MatAccordionDisplayMode = 'default' | 'flat';

/**
 * Directive for a Material Design Accordion.
 */
@Directive({
  selector: 'mat-accordion',
  exportAs: 'matAccordion',
  host: {
    class: 'mat-accordion'
  }
})
export class MatAccordion extends CdkAccordion {
  /** Whether the expansion indicator should be hidden. */
  @Input()
  get hideToggle(): boolean { return this._hideToggle; }
  set hideToggle(show: boolean) { this._hideToggle = coerceBooleanProperty(show); }
  private _hideToggle: boolean = false;

  /**
   * The display mode used for all expansion panels in the accordion. Currently two display
   * modes exist:
   *  default - a gutter-like spacing is placed around any expanded panel, placing the expanded
   *     panel at a different elevation from the reset of the accordion.
   *  flat - no spacing is placed around expanded panels, showing all panels at the same
   *     elevation.
   */
  @Input() displayMode: MatAccordionDisplayMode = 'default';
}

redpajama_set_name: RedPajamaGithub


text:
#include "absl/numeric/bits.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/tpu/tpu_defs.h"

namespace tensorflow {
namespace {

using ::tensorflow::errors::InvalidArgument;

// Computes the Kth order statistic of a data set. The current
// implementation uses a binary search requiring exactly 32 passes
// over the input data. The running time is linear with respect to
// input size. The median-of-medians algorithm is probably faster, but
// is difficult to implement efficiently in XLA. The implementation
// imposes a total ordering on floats. The ordering is consistent with
// the usual partial order.  Positive NaNs are greater than positive
// infinity. Negative NaNs are less than negative infinity. NaNs with
// distinct payloads are treated as distinct. Subnormal numbers are
// preserved (not flushed to zero). Positive infinity is greater than
// all numbers. Negative infinity is less than all numbers. Positive
// is greater than negative zero. There are less than k values greater
// than the kth order statistic. There are at least k values greater
// than or equal to the Kth order statistic. The semantics are not the
// same as TopKUnique.
xla::XlaOp CreateKthOrderStatisticComputation(xla::XlaBuilder* builder,
                                              const TensorShape& input_shape,
                                              const xla::XlaOp input,
                                              const xla::XlaOp k) {
  const int64_t height = input_shape.dim_size(0);
  const int64_t width = input_shape.dim_size(1);

  xla::XlaOp input_sm32 = xla::BitcastConvertType(input, xla::S32);
  xla::XlaOp zero_r0 = xla::ConstantR0<int32>(builder, 0);
  xla::XlaOp zero_r1 = xla::Broadcast(zero_r0, {height});
  xla::XlaOp zero_r2 = xla::Broadcast(zero_r0, {height, width});

  xla::XlaOp max_r0 = xla::ConstantR0<int32>(builder, 0x7FFFFFFF);
  xla::XlaOp max_r1 = xla::Broadcast(max_r0, {height});

  // Start at positive zero, so that pivot is always less than top.
  xla::XlaOp negative_zero_r0 = xla::ConstantR0<int32>(builder, 0x80000000);
  xla::XlaOp negative_zero_r1 = xla::Broadcast(negative_zero_r0, {height});
  xla::XlaOp top_r1 = zero_r1;

  for (uint32 mask = 1U << 31; mask; mask >>= 1) {
    xla::XlaOp broadcast_mask_r1 =
        xla::Broadcast(xla::ConstantR0<int32>(builder, mask), {height});

    // The first iteration of the loop determines if the kth element
    // is positive or negative. If the kth element is negative, we
    // start the search from +QNAN (0x7FFFFFF). If k is negative, we
    // start from -0 (0x8000000). The pivot is less than the top and
    // is always half way between the top and the implicit bottom in
    // IEEE754 space.
    xla::XlaOp pivot_r1 = xla::Xor(top_r1, broadcast_mask_r1);
    xla::XlaOp pivot_r2 = xla::Add(pivot_r1, zero_r2, {0});
    xla::XlaOp both_negative_r2 =
        xla::Lt(xla::And(input_sm32, pivot_r2), zero_r0);
    xla::XlaOp left_r2 = xla::Select(both_negative_r2, pivot_r2, input_sm32);
    xla::XlaOp right_r2 = xla::Select(both_negative_r2, input_sm32, pivot_r2);
    xla::XlaOp pred_r2 = xla::Gt(left_r2, right_r2);
    xla::XlaOp conv_r2 = xla::ConvertElementType(pred_r2, xla::S32);

    xla::XlaComputation add = CreateScalarAddComputation(xla::S32, builder);
    xla::XlaOp sum_r1 = xla::Reduce(conv_r2, zero_r0, add, {1});

    xla::XlaOp pivot_too_low_r1 = xla::Le(k, sum_r1, {});

    if (mask == (1U << 31)) {
      top_r1 = xla::Select(pivot_too_low_r1, max_r1, negative_zero_r1);
    } else {
      top_r1 = xla::Select(pivot_too_low_r1, top_r1, pivot_r1);
    }
  }
  return xla::BitcastConvertType(top_r1, xla::F32);
}

class KthOrderStatistic : public XlaOpKernel {
 public:
  explicit KthOrderStatistic(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("k", &k_));
    OP_REQUIRES(ctx, k_ >= 0, errors::InvalidArgument("Need k >= 0, got ", k_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    xla::XlaBuilder* builder = ctx->builder();
    xla::XlaOp input = ctx->Input(0);
    const TensorShape& input_shape = ctx->InputShape(0);
    OP_REQUIRES(
        ctx, input_shape.dims() == 2,
        InvalidArgument("input must be rank-2: ", input_shape.DebugString()));

    xla::XlaOp k = xla::ConstantR0<int32>(builder, k_);
    xla::XlaOp kth_order_statistics =
        CreateKthOrderStatisticComputation(builder, input_shape, input, k);
    ctx->SetOutput(0, kth_order_statistics);
  }

 private:
  int32 k_;
};

REGISTER_XLA_OP(Name("KthOrderStatistic"), KthOrderStatistic);

// Returns the TopK unique values in the array in sorted order and the
// indices of those elements. The running time is proportional to the
// product of K and the input size. Sorting the whole array is more
// efficient for sufficiently large values of K. The median-of-medians
// algorithm is probably faster, but difficult to implement
// efficiently in XLA. If there are fewer than K unique values, the
// results are padded with negative infinity. NaNs are never
// returned. Subnormal numbers are flushed to zero.
//
// If an element appears at multiple indices, the highest index is
// returned. If a TopK element never appears in the input due to
// padding values, the indices are padded with negative one. If a
// padding value appears in the input and padding is needed, the
// highest index of the padding value will be returned.
//
// The semantics are not the same as KthOrderStatistic.
//
// If masked_with_iota is true, the index is already encoded in the lower bits
// of the mantissa, which will be extracted as the index in the output.
// Otherwise, every iteration will use the following algorithm to get the index:
//   index = max([i if data[i] == max else -1 for i in size])
//
// TODO(b/74994968): Replace TopKUnique with an LLO implementation of
// TopK with reasonable semantics.
std::pair<xla::XlaOp, xla::XlaOp> CreateTopKUnique(
    xla::XlaBuilder* builder, const xla::XlaOp input,
    const TensorShape& input_shape, int64_t k, bool masked_with_iota) {
  const int64_t height = input_shape.dim_size(0);
  const int64_t width = input_shape.dim_size(1);

  xla::XlaOp iota_r1 = xla::Iota(builder, xla::S32, width);
  xla::XlaOp iota_r2 = xla::Broadcast(iota_r1, {height});

  xla::XlaOp negative_one_r0 = xla::ConstantR0<int>(builder, -1);
  xla::XlaOp negative_one_r2 = xla::Broadcast(negative_one_r0, {height, width});

  xla::XlaOp negative_infinity_r0 = xla::ConstantR0<float>(builder, -INFINITY);
  xla::XlaOp negative_infinity_r2 =
      xla::Broadcast(negative_infinity_r0, {height, width});

  xla::XlaOp scratch_pad_r2 = input;
  std::vector<xla::XlaOp> topk_r1s;
  std::vector<xla::XlaOp> topk_indices;
  for (int i = 0; i < k; ++i) {
    xla::XlaOp kth_order_statistic_r1 =
        xla::Reduce(scratch_pad_r2, negative_infinity_r0,
                    CreateScalarMaxComputation(xla::F32, builder), {1});
    topk_r1s.push_back(kth_order_statistic_r1);

    xla::XlaOp ge_r2 = xla::Ge(input, kth_order_statistic_r1, {0});
    scratch_pad_r2 = xla::Select(ge_r2, negative_infinity_r2, input);

    if (!masked_with_iota) {
      xla::XlaOp eq_r2 = xla::Eq(input, kth_order_statistic_r1, {0});
      xla::XlaOp indices_r2 = xla::Select(eq_r2, iota_r2, negative_one_r2);
      xla::XlaOp topk_index_r1 =
          xla::Reduce(indices_r2, negative_one_r0,
                      CreateScalarMaxComputation(xla::S32, builder), {1});
      topk_indices.push_back(topk_index_r1);
    }
  }
  xla::XlaOp topk_r1_concat = xla::ConcatInDim(builder, topk_r1s, 0);
  xla::XlaOp topk_r2 =
      xla::Transpose(xla::Reshape(topk_r1_concat, {k, height}), {1, 0});

  xla::XlaOp topk_indices_r2;
  if (masked_with_iota) {
    int32_t next_power_of_two = absl::bit_ceil<uint64_t>(width);
    int32_t count_mask = next_power_of_two - 1;
    xla::XlaOp mask_r0 = xla::ConstantR0(builder, count_mask);
    xla::XlaOp mask_r2 = xla::Broadcast(mask_r0, {height, k});
    xla::XlaOp topk_r2_s32 = xla::BitcastConvertType(topk_r2, xla::S32);
    topk_indices_r2 = xla::And(topk_r2_s32, mask_r2);
  } else {
    xla::XlaOp topk_indices_concat = xla::ConcatInDim(builder, topk_indices, 0);
    topk_indices_r2 =
        xla::Transpose(xla::Reshape(topk_indices_concat, {k, height}), {1, 0});
  }
  return std::make_pair(topk_r2, topk_indices_r2);
}

class TopKUnique : public XlaOpKernel {
 public:
  explicit TopKUnique(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("k", &k_));
    OP_REQUIRES(ctx, k_ >= 0, errors::InvalidArgument("Need k >= 0, got ", k_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    xla::XlaBuilder* builder = ctx->builder();
    xla::XlaOp input = ctx->Input(0);
    const TensorShape& input_shape = ctx->InputShape(0);
    OP_REQUIRES(
        ctx, input_shape.dims() == 2,
        InvalidArgument("input must be rank-2: ", input_shape.DebugString()));

    auto topk = CreateTopKUnique(builder, input, input_shape, k_, false);
    ctx->SetOutput(0, topk.first);
    ctx->SetOutput(1, topk.second);
  }

 private:
  int k_;
};
REGISTER_XLA_OP(Name("TopKUnique"), TopKUnique);

// Make all elements in the non-Batch dimension unique and close to
// their initial value on a relative scale, but potential far from
// their initial value in an absolute scale.
//
// This operation is meant to be combined with TopKUnique to avoid
// suppressing identical elements. For most TopK users, the indices of
// the TopK elements are important but the relative order of the TopK
// elements and their exact values is not so important. Ideally, the
// the indices of the TopK elements of the output of MakeUnique are
// the same as the indices of the TopK elements of the inputs.
//
// Its an open question whether it is better to accept the risk of two
// elements in the input to TopK have exactly the same value or the
// risk that MakeUnique will alter the indices of the TopK
// elements. Model owners are encouraged to experiment!
//
// Never returns a sub-normal number. Never returns zero. The sign of
// each input element is always identical to the sign of the
// corresponding output element. Behavior for infinite elements is
// undefined. Behavior for subnormal elements is undefined.
//
// Algorithm:
// 1. Replace zeros with the smallest representable normal floating
// point number with the same sign.
// 2. Mask away enough low order bits that every value can be distinct.
// 3. Replace the low order bits with iota.
//
// TODO(b/74994968): Replace MakeUnique with an LLO implementation of
// TopK with reasonable semantics.
xla::XlaOp CreateMakeUnique(xla::XlaBuilder* builder, const xla::XlaOp input,
                            const TensorShape& input_shape) {
  const int64_t height = input_shape.dim_size(0);
  const int64_t width = input_shape.dim_size(1);

  xla::XlaOp zero_r0 = xla::ConstantR0(builder, 0U);
  xla::XlaOp zero_r2 = xla::Broadcast(zero_r0, {height, width});

  // count_mask is used to mask away the low order bits to ensure
  // that every element is distinct.
  uint32_t next_power_of_two = absl::bit_ceil<uint64_t>(width);
  uint32 count_mask = ~(next_power_of_two - 1);
  xla::XlaOp count_mask_r0 = xla::ConstantR0(builder, count_mask);
  xla::XlaOp count_mask_r2 = xla::Broadcast(count_mask_r0, {height, width});

  // smallest_normal is the bit representation of the smallest
  // positive normal floating point number. The sign is zero,
  // exponent is one, and the fraction is zero.
  uint32 smallest_normal = 1U << 23;
  xla::XlaOp smallest_normal_r0 = xla::ConstantR0(builder, smallest_normal);
  xla::XlaOp smallest_normal_r2 =
      xla::Broadcast(smallest_normal_r0, {height, width});

  // Used to mask away the sign bit when computing the absolute
  // value.
  uint32 low_bit_mask = ~(1U << 31);
  xla::XlaOp low_bit_mask_r0 = xla::ConstantR0(builder, low_bit_mask);
  xla::XlaOp low_bit_mask_r2 = xla::Broadcast(low_bit_mask_r0, {height, width});

  xla::XlaOp iota_r1 = xla::Iota(builder, xla::U32, width);
  xla::XlaOp iota_r2 = xla::Broadcast(iota_r1, {height});

  // Compare the absolute value with positive zero to handle
  // negative zero.
  //
  // Pseudocode: input_no_zeros = abs(input) == 0 ? FLT_MIN : input
  xla::XlaOp input_u32_r2 = xla::BitcastConvertType(input, xla::U32);
  xla::XlaOp abs_r2 = xla::And(input_u32_r2, low_bit_mask_r2);
  xla::XlaOp if_zero_r2 = xla::Eq(abs_r2, zero_r2);
  xla::XlaOp smallest_normal_preserving_sign_r2 =
      xla::Or(input_u32_r2, smallest_normal_r2);
  xla::XlaOp input_no_zeros_r2 =
      xla::Select(if_zero_r2, smallest_normal_preserving_sign_r2, input_u32_r2);

  // Discard the low-order bits and replace with iota.
  xla::XlaOp and_r2 = xla::And(input_no_zeros_r2, count_mask_r2);
  xla::XlaOp or_r2 = xla::Or(and_r2, iota_r2);
  return xla::BitcastConvertType(or_r2, xla::F32);
}

class MakeUnique : public XlaOpKernel {
 public:
  explicit MakeUnique(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}

  void Compile(XlaOpKernelContext* ctx) override {
    xla::XlaBuilder* builder = ctx->builder();
    xla::XlaOp input = ctx->Input(0);
    const TensorShape& input_shape = ctx->InputShape(0);
    OP_REQUIRES(
        ctx, input_shape.dims() == 2,
        InvalidArgument("input must be rank-2: ", input_shape.DebugString()));

    ctx->SetOutput(0, CreateMakeUnique(builder, input, input_shape));
  }
};
REGISTER_XLA_OP(Name("MakeUnique"), MakeUnique);

// Returns the TopK approximate values in the array in sorted order and the
// indices of those elements. The running time is proportional to the
// product of K and the input size.
//
// The algorithm first updates the lower bits of each element with iota,
// which is used to derive the index. The iota also serves the purpose to
// make each element unique so that each iteration, we are guaranteed to
// get one and only one unique top-1 element.
class TopKWithUnique : public XlaOpKernel {
 public:
  explicit TopKWithUnique(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("k", &k_));
    OP_REQUIRES(ctx, k_ >= 0, errors::InvalidArgument("Need k >= 0, got ", k_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    xla::XlaBuilder* builder = ctx->builder();
    xla::XlaOp input = ctx->Input(0);
    const TensorShape& input_shape = ctx->InputShape(0);
    OP_REQUIRES(
        ctx, input_shape.dims() == 2,
        InvalidArgument("input must be rank-2: ", input_shape.DebugString()));

    xla::XlaOp unique = CreateMakeUnique(builder, input, input_shape);
    auto topk = CreateTopKUnique(builder, unique, input_shape, k_, true);
    ctx->SetOutput(0, topk.first);
    ctx->SetOutput(1, topk.second);
  }

 private:
  int k_;
};
REGISTER_XLA_OP(Name("TopKWithUnique"), TopKWithUnique);
}  // namespace
}  // namespace tensorflow


text:
package org.gearvrf.controls;

import android.view.MotionEvent;

import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.gearvrf.GVRCameraRig;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.animation.GVRAnimation;
import org.gearvrf.animation.GVROnFinish;
import org.gearvrf.animation.GVRRelativeMotionAnimation;
import org.gearvrf.animation.GVRRotationByAxisAnimation;
import org.gearvrf.animation.GVRRotationByAxisWithPivotAnimation;
import org.gearvrf.animation.GVRScaleAnimation;
import org.gearvrf.controls.anim.ScaleWorm;
import org.gearvrf.controls.input.GamepadInput;
import org.gearvrf.controls.input.TouchPadInput;
import org.gearvrf.controls.model.Apple;
import org.gearvrf.controls.util.ColorControls;
import org.gearvrf.controls.util.ColorControls.Color;
import org.gearvrf.controls.util.Constants;
import org.gearvrf.controls.util.MathUtils;
import org.gearvrf.controls.util.RenderingOrder;
import org.gearvrf.controls.util.Util;
import org.gearvrf.controls.util.VRSamplesTouchPadGesturesDetector.SwipeDirection;

public class Worm extends GVRSceneObject {

    private static final float SHADOW_END_OFFSET = 0.801f;
    private static final float SHADOW_MIDDLE_OFFSET = 0.8f;
    private static final float SHADOW_HEAD_OFFSET = 0.9f;
    // private static final float MINIMUM_DISTANCE_FACTOR = 0.5f;
    // Chain Data
    private final float CHAIN_DISTANCE_HEAD_MIDDLE = 0.575f;
    private final float CHAIN_DISTANCE_MIDDLE_END = 0.475f;

    private final float CHAIN_SPEED_HEAD_MIDDLE = 0.055f;
    private final float CHAIN_SPEED_MIDDLE_END = 0.065f;
    private final float WORM_INITIAL_Z = -3;
    private final float WORM_INITIAL_Y = -0.9f;

    private float DISTANCE_TO_EAT_APPLE = 0.50f;
    private WormBasePart head, middle, end;

    public GVRSceneObject wormParent;
    private boolean isRotatingWorm = false;

    private GVRAnimation wormParentAnimation;

    private MovementDirection wormDirection = MovementDirection.Up;

    private Color color;

    private float[] scaleWorm = new float[] {
            0.4f, 0.4f, 0.4f
    };
    private WormShadow shadowHead;
    private WormShadow shadowMiddle;
    private WormShadow shadowEnd;

    public enum MovementDirection {
        Up, Right, Down, Left
    }

    public Worm(GVRContext gvrContext) {
        super(gvrContext);

        ColorControls gvrColor = new ColorControls(gvrContext.getContext());
        Color color = gvrColor.parseColor(R.color.color10);

        this.color = color;

        createWormParts(color);
    }

    public GVRSceneObject getWormParentation() {
        return wormParent;
    }

    public void resetColor(Color color) {
        head.resetColor(color);
        middle.resetColor(color);
        end.resetColor(color);
    }

    private void createWormParts(Color color) {

        wormParent = new GVRSceneObject(getGVRContext());
        addChildObject(wormParent);

        head = new WormBasePart(getGVRContext(), R.raw.sphere_head, R.drawable.worm_head_texture, color);
        middle = new WormBasePart(getGVRContext(), R.raw.sphere_body, R.drawable.worm_head_texture, color);
        end = new WormBasePart(getGVRContext(), R.raw.sphere_tail, R.drawable.worm_head_texture, color);

        wormParent.getTransform().setPosition(0, WORM_INITIAL_Y, WORM_INITIAL_Z);
        head.getTransform().setPosition(0, 0, 0);

        wormParent.addChildObject(head);

        addChildObject(middle);
        addChildObject(end);
    }

    public void enableShadow() {

        float factor = 3f;
        shadowHead = new WormShadow(getGVRContext(), 0.27f * factor, 0.27f * factor, RenderingOrder.WORM_SHADOW_HEADER);
        shadowMiddle = new WormShadow(getGVRContext(), 0.2f * factor, 0.2f * factor, RenderingOrder.WORM_SHADOW_MIDDLE);
        shadowEnd = new WormShadow(getGVRContext(), 0.18f * factor, 0.18f * factor, RenderingOrder.WORM_SHADOW_END);

        head.addChildObject(shadowHead);
        middle.addChildObject(shadowMiddle);
        end.addChildObject(shadowEnd);

        startShadowsPosition();
    }

    private void startShadowsPosition() {

        shadowHead.getTransform().setPositionY(shadowHead.getParent().getParent().getTransform().getPositionY() + SHADOW_HEAD_OFFSET);
        shadowMiddle.getTransform().setPositionY(shadowMiddle.getParent().getTransform().getPositionY() + SHADOW_MIDDLE_OFFSET);
        shadowEnd.getTransform().setPositionY(shadowEnd.getParent().getTransform().getPositionY() + SHADOW_END_OFFSET);
    }

    public void changeColor(Color color) {

        this.color = color;

        float[] colorArray = new float[3];
        colorArray[0] = color.getRed();
        colorArray[1] = color.getGreen();
        colorArray[2] = color.getBlue();

        head.animChangeColor(color);
        middle.animChangeColor(color);
        end.animChangeColor(color);
    }

    public Color getColor() {
        return color;
    }

    public float[] getScaleFactor() {

        this.scaleWorm[0] = getHead().getTransform().getScaleX();
        this.scaleWorm[1] = getMiddle().getTransform().getScaleX();
        this.scaleWorm[2] = getEnd().getTransform().getScaleX();

        return scaleWorm;
    }

    public void chainMove(GVRContext gvrContext) {

        if (!ScaleWorm.animPlaying) {

            if (MathUtils.distance(wormParent, middle) > CHAIN_DISTANCE_HEAD_MIDDLE
                    * middle.getTransform().getScaleX()) {

                float chainSpeed = CHAIN_SPEED_HEAD_MIDDLE
                        * (float) Util.distance(wormParent.getTransform(), getGVRContext()
                                .getMainScene().getMainCameraRig().getTransform());

                middle.getTransform().setRotationByAxis(
                        MathUtils.getYRotationAngle(middle, wormParent), 0, 1, 0);
                end.getTransform().setRotationByAxis(MathUtils.getYRotationAngle(end, middle), 0, 1, 0);

                float newX = middle.getTransform().getPositionX()
                        + (wormParent.getTransform().getPositionX() -
                        middle.getTransform().getPositionX()) * chainSpeed;

                float newY = middle.getTransform().getPositionY()
                        + (wormParent.getTransform().getPositionY() -
                        middle.getTransform().getPositionY()) * chainSpeed;

                float newZ = middle.getTransform().getPositionZ()
                        + (wormParent.getTransform().getPositionZ() -
                        middle.getTransform().getPositionZ()) * chainSpeed;

                middle.getTransform().setPosition(newX, newY, newZ);
            }

            if (MathUtils.distance(middle, end) > CHAIN_DISTANCE_MIDDLE_END
                    * end.getTransform().getScaleX()) {

                float chainSpeed = CHAIN_SPEED_MIDDLE_END
                        * (float) Util.distance(wormParent.getTransform(), getGVRContext()
                                .getMainScene().getMainCameraRig().getTransform());

                middle.getTransform().setRotationByAxis(
                        MathUtils.getYRotationAngle(middle, wormParent), 0, 1, 0);
                end.getTransform().setRotationByAxis(MathUtils.getYRotationAngle(end, middle), 0, 1, 0);

                float newX = end.getTransform().getPositionX() + (middle.getTransform().getPositionX() -
                        end.getTransform().getPositionX()) * chainSpeed;

                float newY = end.getTransform().getPositionY() + (middle.getTransform().getPositionY() -
                        end.getTransform().getPositionY()) * chainSpeed;

                float newZ = end.getTransform().getPositionZ() + (middle.getTransform().getPositionZ() -
                        end.getTransform().getPositionZ()) * chainSpeed;

                end.getTransform().setPosition(newX, newY, newZ);
            }
        }
    }

    public void rotateWorm(MovementDirection movementDirection) {
        if (!isRotatingWorm) {
            isRotatingWorm = true;
            float angle = getRotatingAngle(movementDirection);
            new GVRRotationByAxisAnimation(head, .1f, angle, 0, 1, 0).start(
                    getGVRContext().getAnimationEngine()).setOnFinish(
                    new GVROnFinish() {

                        @Override
                        public void finished(GVRAnimation arg0) {
                            isRotatingWorm = false;
                        }
                    });
        }
    }

    private int getRotatingAngle(MovementDirection movementDirection) {
        int movementDiference = movementDirection.ordinal() - wormDirection.ordinal();
        wormDirection = movementDirection;
        if (movementDiference == 1 || movementDiference == -3) {
            return -90;
        } else if (movementDiference == 2 || movementDiference == -2) {
            return 180;
        } else if (movementDiference == 3 || movementDiference == -1) {
            return 90;
        } else {
            return 0;
        }
    }

    public void moveAlongCameraVector(float duration, float movement) {
        if (wormParentAnimation != null) {
            getGVRContext().getAnimationEngine().stop(wormParentAnimation);
        }

        GVRCameraRig cameraObject = getGVRContext().getMainScene().getMainCameraRig();

        float distance = (float) Util.distance(wormParent.getTransform(),
                cameraObject.getTransform())
                + movement;
        float[] newPosition = Util.calculatePointBetweenTwoObjects(cameraObject.getTransform(),
                wormParent.getTransform(), distance);

        if (movement < 0
                && MathUtils.distance(cameraObject.getTransform(), newPosition) < Constants.MIN_WORM_MOVE_DISTANCE)
            return;
        if (movement > 0
                && MathUtils.distance(cameraObject.getTransform(),
                        wormParent.getTransform()) > Constants.MAX_WORM_MOVE_DISTANCE)
            return;

        wormParentAnimation = new GVRRelativeMotionAnimation(wormParent.getTransform(),
                duration, newPosition[0] - wormParent.getTransform().getPositionX(),
                0,
                newPosition[2] - wormParent.getTransform().getPositionZ())
                .start(getGVRContext().getAnimationEngine());
    }

    public void rotateAroundCamera(float duration, float degree) {
        if (wormParentAnimation != null) {
            getGVRContext().getAnimationEngine().stop(wormParentAnimation);
        }

        wormParentAnimation = new GVRRotationByAxisWithPivotAnimation(
                wormParent.getTransform(), duration, degree, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f)
                .start(getGVRContext().getAnimationEngine());

    }

    public void interactWithDPad() {

        if (!ScaleWorm.animPlaying) {

            if (GamepadInput.getCenteredAxis(MotionEvent.AXIS_HAT_X) >= 1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_X) >= 1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_RX) >= 1) {

                rotateAroundCamera(.1f, -5f);
                rotateWorm(MovementDirection.Right);
            }
            if (GamepadInput.getCenteredAxis(MotionEvent.AXIS_HAT_X) <= -1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_X) <= -1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_RX) <= -1) {

                rotateAroundCamera(.1f, 5f);
                rotateWorm(MovementDirection.Left);
            }
            if (GamepadInput.getCenteredAxis(MotionEvent.AXIS_HAT_Y) >= 1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_Y) >= 1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_RY) >= 1) {

                moveAlongCameraVector(.1f, -.225f);
                rotateWorm(MovementDirection.Down);
            }
            if (GamepadInput.getCenteredAxis(MotionEvent.AXIS_HAT_Y) <= -1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_Y) <= -1
                    || GamepadInput.getCenteredAxis(MotionEvent.AXIS_RY) <= -1) {

                moveAlongCameraVector(.1f, .225f);
                rotateWorm(MovementDirection.Up);
            }
        }
    }

    public void checkWormEatingApple(GVRContext gvrContext) {

        Vector3D wormPosition = new Vector3D(wormParent.getTransform().getPositionX(), head
                .getParent()
                .getTransform().getPositionY(), wormParent.getTransform().getPositionZ());

        for (Apple a : Apple.appleList) {
            Vector3D applePosition = new Vector3D(a.getTransform().getPositionX(), a.getTransform()
                    .getPositionY(), a.getTransform().getPositionZ());

            if (Vector3D.distance(applePosition, wormPosition) < DISTANCE_TO_EAT_APPLE) {

                a.resetPosition(gvrContext);
            }
        }
    }

    public void animateWormByTouchPad() {

        if (!ScaleWorm.animPlaying) {

            SwipeDirection swipeDirection = TouchPadInput.getCurrent().swipeDirection;

            float duration = 0.6f;
            float movement = 0.75f;
            float degree = 22.5f;

            if (swipeDirection.name() == SwipeDirection.Up.name()) {
                moveAlongCameraVector(duration, movement);
                rotateWorm(MovementDirection.Up);

            } else if (swipeDirection.name() == SwipeDirection.Down.name()) {
                moveAlongCameraVector(duration, -movement);
                rotateWorm(MovementDirection.Down);

            } else if (swipeDirection.name() == SwipeDirection.Forward.name()) {
                rotateAroundCamera(duration, -degree);
                rotateWorm(MovementDirection.Right);

            } else if (swipeDirection.name() == SwipeDirection.Backward.name()) {
                rotateAroundCamera(duration, degree);
                rotateWorm(MovementDirection.Left);
            }
        }
    }

    public GVRSceneObject getHead() {
        return head;
    }

    public GVRSceneObject getMiddle() {
        return middle;
    }

    public GVRSceneObject getEnd() {
        return end;
    }

    public void moveWorm(float scaleFactor) {
        moveWormPart(getHead(), scaleFactor);
        moveWormPart(getEnd(), scaleFactor);
    }

    public void resetScaleWorm(float[] scaleFactor) {

        getHead().getTransform().setScale(scaleFactor[0], scaleFactor[0], scaleFactor[0]);
        getMiddle().getTransform().setScale(scaleFactor[1], scaleFactor[1], scaleFactor[1]);
        getEnd().getTransform().setScale(scaleFactor[2], scaleFactor[2], scaleFactor[2]);
    }

    public void scaleWorm(float scaleFactor) {

        scaleWormPart(getHead(), scaleFactor);
        scaleWormPart(getMiddle(), scaleFactor);
        scaleWormPart(getEnd(), scaleFactor);
    }

    private void moveWormPart(GVRSceneObject part, float scaleFactor) {

        float currentScale = part.getTransform().getScaleX();
        float ratio = (currentScale + scaleFactor) / currentScale;
        float currentPartPositionX = part.getTransform().getPositionX();
        float newPartPositionX = ratio * currentPartPositionX;

        new GVRRelativeMotionAnimation(part, 0.1f,
                newPartPositionX
                        - currentPartPositionX, 0, 0).start(getGVRContext()
                .getAnimationEngine());
    }

    private void scaleWormPart(GVRSceneObject part, float scaleFactor) {

        new GVRScaleAnimation(part, 0.1f, part.getTransform().getScaleX()
                + scaleFactor)
                .setOnFinish(new GVROnFinish() {

                    @Override
                    public void finished(GVRAnimation arg0) {
                        ScaleWorm.animPlaying = false;
                    }

                }).start(getGVRContext().getAnimationEngine());
    }
}


text:
package com.sun.source.tree;

import java.util.List;

/**
 * A tree node for a 'switch' statement.
 *
 * For example:
 *

 *   switch ( expression ) {
 *     cases
 *   }
 *

 *
 * @jls section 14.11
 *
 * @author Peter von der Ahé
 * @author Jonathan Gibbons
 * @since 1.6
 */
@jdk.Exported
public interface SwitchTree extends StatementTree {
    ExpressionTree getExpression();
    List<? extends CaseTree> getCases();
}


text:
import json

import pkg_resources
from tornado import testing

from tests import utils

class TestRenderersHandler(utils.HandlerTestCase):

    @testing.gen_test
    def test_get_status(self):
        resp = yield self.http_client.fetch(self.get_url('/renderers'))

        renderers = {}
        for ep in pkg_resources.iter_entry_points(group='mfr.renderers'):
            renderers.update({ep.name: ep.load().__name__})

        data = json.loads(resp.body.decode('utf-8'))
        assert resp.code == 200
        assert data['renderers'] == renderers


text:
typedef int (*_compar_fn_t)(const void * r1, const void * r2, size_t rsize);
typedef void (*_bisect_fn_t)(void * r, const void * r1, const void * r2, size_t rsize);

struct crstruct {
    void * base;
    size_t nmemb;
    size_t size;
    size_t rsize;
    void * arg;
    void (*radix)(const void * ptr, void * radix, void * arg);
    _compar_fn_t compar;
    _bisect_fn_t bisect;
};

void _setup_radix_sort(
        struct crstruct *d,
        void * base,
        size_t nmemb,
        size_t size,
        void (*radix)(const void * ptr, void * radix, void * arg),
        size_t rsize,
        void * arg);
#endif


text:
using System;

namespace DD.CloudControl.Client.Models.Server
{
	/// <summary>
	/// 	The query configuration for listing servers.
	/// </summary>
	public class ServerQuery
	{
		/// <summary>
		/// 	Only return servers in the specified network domain.
		/// </summary>
		public Guid? NetworkDomainId { get; set; }

		/// <summary>
		/// 	Create a <see cref="ServerQuery"/> that returns all servers.
		/// </summary>
		/// <returns>
		/// 	The configured <see cref="ServerQuery"/>.
		/// </returns>
		public static ServerQuery All() => new ServerQuery();

		/// <summary>
		/// 	Create a <see cref="ServerQuery"/> that returns all servers in the specified network domain.
		/// </summary>
		/// <param name="networkDomainId">
		/// 	The network domain Id.
		/// </param>
		/// <returns>
		/// 	The configured <see cref="ServerQuery"/>.
		/// </returns>
		public static ServerQuery ByNetworkDomain(Guid networkDomainId) => new ServerQuery { NetworkDomainId = networkDomainId };
	}
}


text:
<?php

/**
 * Generates site-wide global page nav.
 **/
?>

<header role="banner" class="-basic<?php if (isset($sponsors)): print ' -sponsored'; endif; ?>">

<?php print $title; ?>

    <?php if (isset($subtitle)): ?>

<?php if (isset($subtitle)): print $subtitle; endif; ?>

    <?php endif; ?>

    <?php if (isset($sponsors)): ?>

<?php print t('Powered by'); ?>

      <?php foreach ($sponsors as $key => $sponsor) :?>
        <?php if (isset($sponsor['display'])): print $sponsor['display']; endif; ?>
      <?php endforeach; ?>

    <?php endif; ?>


text:
layout: page
title: Pride Networks Award Ceremony
date: 2016-05-24
author: Stephanie Kerr
tags: weekly links, java
status: published
summary: Aliquam convallis ultricies quam, ac dignissim risus.
banner: images/banner/office-01.jpg
booking:
  startDate: 02/15/2019
  endDate: 02/16/2019
  ctyhocn: ATLDMHX
  groupCode: PNAC
published: true
---
Morbi vitae mi porta, pellentesque est in, ullamcorper sapien. Etiam dapibus et dolor ullamcorper sagittis. Maecenas sagittis a sapien vel congue. Phasellus viverra dui sed nunc congue commodo. Pellentesque eu arcu ut enim viverra pellentesque. Integer placerat turpis justo, imperdiet tempus lorem varius sed. Phasellus tempus, lorem et placerat accumsan, diam ex dignissim dui, et dignissim neque nulla vitae ligula. Etiam finibus, velit eget sagittis scelerisque, lorem felis gravida lectus, aliquam dictum nunc metus eget libero. Quisque molestie tincidunt sapien sed interdum. Sed nec diam ut risus convallis aliquet non at erat. Donec viverra ultricies quam eget varius.

1 Suspendisse dignissim lacus quis orci feugiat consequat
1 Etiam et ligula vitae mauris pellentesque ultrices id nec nisi.

Aliquam congue ante nulla, sed consequat sem cursus sed. Praesent scelerisque dui tincidunt tristique sodales. Sed id vehicula elit. Proin venenatis accumsan laoreet. Sed sodales, augue et imperdiet viverra, justo lacus tristique dui, ac rutrum diam purus at dui. Suspendisse vel velit et dui mollis facilisis. Duis euismod ex ut ultricies pulvinar. Nullam consectetur tempor sollicitudin. Interdum et malesuada fames ac ante ipsum primis in faucibus.


text:
"""Functions for deleting nodes and edges in networks."""

from ...filters.edge_filters import filter_edges
from ...filters.edge_predicates import is_associative_relation, not_causal_relation
from ...filters.node_filters import filter_nodes
from ...filters.node_predicates import (
    is_biological_process,
    is_isolated_list_abundance,
    is_pathology,
)
from ...pipeline import in_place_transformation

__all__ = [
    "remove_filtered_edges",
    "remove_filtered_nodes",
    "remove_associations",
    "remove_pathologies",
    "remove_biological_processes",
    "remove_isolated_list_abundances",
    "remove_non_causal_edges",
]

@in_place_transformation
def remove_filtered_edges(graph, edge_predicates=None):
    """Remove edges passing the given edge predicates.

    :param pybel.BELGraph graph: A BEL graph
    :param edge_predicates: A predicate or list of predicates
    :type edge_predicates: None or ((pybel.BELGraph, tuple, tuple, int) -> bool) or iter[(pybel.BELGraph, tuple, tuple, int) -> bool]]
    :return:
    """
    edges = list(filter_edges(graph, edge_predicates=edge_predicates))
    graph.remove_edges_from(edges)

@in_place_transformation
def remove_filtered_nodes(graph, node_predicates=None):
    """Remove nodes passing the given node predicates.

    :param pybel.BELGraph graph: A BEL graph
    :type node_predicates: None or ((pybel.BELGraph, tuple) -> bool) or iter[(pybel.BELGraph, tuple) -> bool)]
    """
    nodes = list(filter_nodes(graph, node_predicates=node_predicates))
    graph.remove_nodes_from(nodes)

@in_place_transformation
def remove_associations(graph):
    """Remove all associative relationships from the graph.

    :param pybel.BELGraph graph: A BEL graph
    """
    remove_filtered_edges(graph, is_associative_relation)

@in_place_transformation
def remove_pathologies(graph):
    """Remove pathology nodes from the graph.

    :param pybel.BELGraph graph: A BEL graph
    """
    remove_filtered_nodes(graph, node_predicates=is_pathology)

@in_place_transformation
def remove_biological_processes(graph):
    """Remove biological process nodes from the graph.

    :param pybel.BELGraph graph: A BEL graph
    """
    remove_filtered_nodes(graph, node_predicates=is_biological_process)

@in_place_transformation
def remove_isolated_list_abundances(graph):
    """Remove isolated list abundances from the graph.

    :param pybel.BELGraph graph: A BEL graph
    """
    remove_filtered_nodes(graph, is_isolated_list_abundance)

@in_place_transformation
def remove_non_causal_edges(graph):
    """Remove non-causal edges from the graph."""
    remove_filtered_edges(graph, not_causal_relation)


text:
package nl.maastrichtuniversity.networklibrary.cyneo4j.internal.cypher.querytemplate.xml;

public abstract class Mapping {
    abstract void accept(MappingVisitor visitor);
}


text:
<?php

// Création d'une fonction php
function show(){
    //echo("coucou");
    echo "coucou" . PHP_EOL;
}

show();


text:
require 'anima'
require 'parslet'
require 'thor'

require 'timetrack/cli'
require 'timetrack/day'
require 'timetrack/event'
require 'timetrack/time_formatter'
require 'timetrack/parser'
require 'timetrack/reader'
require 'timetrack/transform'
require 'timetrack/version'
require 'timetrack/writer'

# :nodoc:
#
# @api private
module Timetrack
end


text:
using System;

namespace Shared
{
    public class HelloWorldClass
    {
#if WINDOWS_APP
        private string _platform = "Windows Store";
#elif WINDOWS_PHONE_APP
        private string _platform = "Windows Phone";
#else
        private string _platform = "...";
#endif

        public string SayHi()
	    {
            return "Hello from " + _platform;
	    }
    }
}


text:
#import "ChineseSkillNew-Structs.h"
#import <XXUnknownSuperclass.h> // Unknown library

@class NSArray;

@interface AFSecurityPolicy : XXUnknownSuperclass {
	BOOL _validatesCertificateChain;
	BOOL _allowInvalidCertificates;
	BOOL _validatesDomainName;
	unsigned _SSLPinningMode;
	NSArray* _pinnedCertificates;
	NSArray* _pinnedPublicKeys;
}
@property(assign, nonatomic) unsigned SSLPinningMode;
@property(assign, nonatomic) BOOL allowInvalidCertificates;
@property(retain, nonatomic) NSArray* pinnedCertificates;
@property(retain, nonatomic) NSArray* pinnedPublicKeys;
@property(assign, nonatomic) BOOL validatesCertificateChain;
@property(assign, nonatomic) BOOL validatesDomainName;
+ (id)defaultPinnedCertificates;
+ (id)defaultPolicy;
+ (id)keyPathsForValuesAffectingPinnedPublicKeys;
+ (id)policyWithPinningMode:(unsigned)pinningMode;
- (id)init;
- (void).cxx_destruct;
- (BOOL)evaluateServerTrust:(SecTrust*)trust;
- (BOOL)evaluateServerTrust:(SecTrust*)trust forDomain:(id)domain;
@end


text:
package com.coolweather.app.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coolweather.R;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;

/**
 * Created by WangZ on 2015/5/14.
 */
public class WeatherActivity extends Activity {
    private LinearLayout weatherInfoLayout;

    /*
        用于显示城市名称
     */
    private TextView cityNameText;
    /*
        用于显示发布时间
     */
    private TextView publishText;
    /*
        用于显示天气描述信息
     */
    private TextView weatherDespText;
    /*
        用于显示气温1和气温2
     */
    private TextView temp1Text;
    private TextView temp2Text;

    /*
        用于显示当前日期
     */
    private TextView currentDateText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);
        //初始化各种控件
        weatherInfoLayout = (LinearLayout)findViewById(R.id.weather_info_layout);
        cityNameText = (TextView)findViewById(R.id.city_name);
        publishText = (TextView)findViewById(R.id.publish_text);
        weatherDespText = (TextView)findViewById(R.id.weather_desp);
        temp1Text = (TextView)findViewById(R.id.temp1);
        temp2Text = (TextView)findViewById(R.id.temp2);
        currentDateText = (TextView)findViewById(R.id.current_date);
        String countyCode = getIntent().getStringExtra("county_code");
        if(!TextUtils.isEmpty(countyCode)){
            //有县级代号时就去查询天气
            publishText.setText("同步中...");
            weatherInfoLayout.setVisibility(View.INVISIBLE);
            cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherCode(countyCode);
        }else{
            //没有县级代号时就直接显示本地天气
            showWeather();
        }
    }

    /*
        查询县级代号所对应的天气代号
     */
    private void queryWeatherCode(String countyCode){
        String address = address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml";
        queryFromServer(address,"countyCode");
    }

    /*
        查询天气代号所对应的天气
     */
    private void queryWeatherInfo(String weatherCode){
        String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
        queryFromServer(address,"weatherCode");
    }

    /*
        根据传入的地址和类型向服务器查询天气代号或者天气信息
     */
    private void queryFromServer(final String address, final String type){
        HttpUtil.sendHttpRequest(address,new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                if("countyCode".equals(type)){
                    if(!TextUtils.isEmpty(response)){
                        //从服务器返回的数据中解析出天气代号
                        String[] array = response.split("\\|");
                        if(array != null && array.length == 2){
                            String weatherCode = array[1];
                            queryWeatherInfo(weatherCode);
                        }
                    }
                }else if("weatherCode".equals(type)){
                    //处理服务器返回的天气信息
                    Utility.handleWeatherResponse(WeatherActivity.this,response);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeather();
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        publishText.setText("同步失败");
                    }
                });
            }
        });
    }

    /*
        从SharedPreferences中读取存储的天气信息,并显示在界面上
     */
    private void showWeather(){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(sp.getString("city_name", ""));
        temp1Text.setText(sp.getString("temp1", ""));
        temp2Text.setText(sp.getString("temp2", ""));
        weatherDespText.setText(sp.getString("weather_desp", ""));
        publishText.setText(sp.getString("publish_time", ""));
        currentDateText.setText(sp.getString("current_date", ""));
        weatherInfoLayout.setVisibility(View.VISIBLE);
        cityNameText.setVisibility(View.VISIBLE);
    }
}


text:
RSpec.describe Hyrax::Admin::StatsController, type: :controller do
  let(:user) { create(:user) }

  context "a non admin" do
    describe "#show" do
      it 'is unauthorized' do
        get :show
        expect(response).to be_redirect
      end
    end
  end

  context "as an admin" do
    before do
      allow(controller).to receive(:authorize!).and_return(true)
    end

    describe "#show" do
      let(:expected_params) do
        ActionController::Parameters.new
      end

      it 'allows an authorized user to view the page' do
        get :show

        expect(response).to be_successful
        expect(assigns[:presenter]).to be_kind_of Hyrax::AdminStatsPresenter
        expect(assigns[:presenter])
          .to have_attributes(limit: 5, stats_filters: {})
      end

      context 'with a custom presenter' do
        let(:presenter_class) { Class.new(Hyrax::AdminStatsPresenter) }

        before { described_class.admin_stats_presenter = presenter_class }

        it 'allows an authorized user to view the page' do
          get :show

          expect(assigns[:presenter]).to be_kind_of presenter_class
          expect(assigns[:presenter])
            .to have_attributes(limit: 5, stats_filters: {})
        end
      end

      context 'with custom stats services' do
        let(:by_depositor_class) { Class.new(Hyrax::Statistics::Works::ByDepositor) }
        let(:service_config)     { { by_depositor: by_depositor_class } }

        before { described_class.admin_stats_services = service_config }

        it 'allows an authorized user to view the page' do
          get :show

          expect(assigns[:presenter])
            .to have_attributes(by_depositor: by_depositor_class)
        end
      end
    end
  end
end


text:
#include "drivers/fs/fs.h"
#include "lib.h"

/*
 # Open a file
 @ filename : full file name and path
 @ flag     : operation flags
 @ RETURN   : -1 means failed, other number is the file descriptor index in the caller's process
 */
FILE open(const char *filename, FILE_OP_FLAG flag) {
	struct proc_msg msg;
	struct ipc_msg_payload_fs *ptr_payload;
	uint32 dev_num;

	struct ipc_msg_payload_fs_open_file open_file_payload;

	/* Initialize */
	ptr_payload = (struct ipc_msg_payload_fs *)&msg.payload;
	dev_num = FS_DEV_NUM_GEN(
		((uint32)FS_SYSROOT_MBR_IDX),
		((uint32)FS_SYSROOT_LOGICAL_IDX)
		);

	/* Open FS device */
	msg.type = FS_MSG_OPEN;
	ptr_payload->dev_num = dev_num;
	comm_msg(DRV_PID_FS, &msg);

	/* Send OPEN_FILE message to FS driver */
    msg.type = FS_MSG_IOCTL;
	ptr_payload->dev_num = dev_num;
	ptr_payload->ioctl_msg = FS_IMSG_OPEN_FILE;

	open_file_payload.path = filename;
	open_file_payload.mode = flag;
	ptr_payload->buf_address = &open_file_payload;
	comm_msg(DRV_PID_FS, &msg);

	/* File descriptor index is returned by payload[0] */
	return (FILE)msg.payload[0];
}

/*
 # Write bytes to a file
 @ fd   : file descriptor index
 @ buf  : source buffer
 @ size : count of bytes
 @ RETURN : actual write bytes
 */
uint32 write(FILE fd, const void *buf, uint32 size) {
	return 0;
}

/*
 # Read bytes from a file
 @ fd   : file descriptor index
 @ buf  : destination buffer
 @ size : count of bytes
 @ RETURN : actual read bytes
 */
uint32 read(FILE fd, void *buf, uint32 size) {
	return 0;
}

/*
 # Close a file
 @ fd     : file descriptor index
 */
rtc close(FILE fd) {
	struct proc_msg msg;
	struct ipc_msg_payload_fs *ptr_payload;
	uint32 dev_num;

	/* Initialize */
	ptr_payload = (struct ipc_msg_payload_fs *)&msg.payload;
	dev_num = FS_DEV_NUM_GEN(
		((uint32)FS_SYSROOT_MBR_IDX),
		((uint32)FS_SYSROOT_LOGICAL_IDX)
		);

	/* Send CLOSE_FILE message to FS driver */

	/* Close FS device */
	msg.type = FS_MSG_CLOSE;
	ptr_payload->dev_num = dev_num;
	comm_msg(DRV_PID_FS, &msg);

	return OK;
}

/*
 # Make file system
 @ mbr_index     : MBR partition index
 @ logical_index : Logical partition index
 */
rtc mkfs(uint8 mbr_index, uint8 logical_index) {
    struct proc_msg msg;
	struct ipc_msg_payload_fs *ptr_payload;
	uint32 dev_num;

	/* Initialize */
	ptr_payload = (struct ipc_msg_payload_fs *)&msg.payload;
	dev_num = FS_DEV_NUM_GEN(((uint32)mbr_index), ((uint32)logical_index));

	/* Open FS device */
	msg.type = FS_MSG_OPEN;
	ptr_payload->dev_num = dev_num;
	comm_msg(DRV_PID_FS, &msg);

	/* Send MKFS message to FS driver */
    msg.type = FS_MSG_IOCTL;
	ptr_payload->dev_num = dev_num;
	ptr_payload->ioctl_msg = FS_IMSG_MKFS;
	comm_msg(DRV_PID_FS, &msg);

	/* Close FS device */
	msg.type = FS_MSG_CLOSE;
	ptr_payload->dev_num = dev_num;
	comm_msg(DRV_PID_FS, &msg);

    return OK;
}


text:
Simple VAT service

An excuse to play with Go.


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>phpDocumentor » \Moneybird\HttpClient\UnknownHttpStatusException</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

phpDocumentor

                                    API Documentation

Namespaces

 Moneybird

 global

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                622

 Markers

todo
                1

 Deprecated elements
                0

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Methods

__construct()

__construct()

__toString()

__toString()

getCode()

getCode()

getFile()

getFile()

getLine()

getLine()

getMessage()

getMessage()

getPrevious()

getPrevious()

getTrace()

getTrace()

getTraceAsString()

getTraceAsString()

\

Moneybird

\
HttpClient

\UnknownHttpStatusException

Exception for unknown http status

 Methods

__construct()

__construct()

Inherited

inherited_from
Exception::__construct()

inherited_from
\Moneybird\Exception::__construct()

inherited_from
\Moneybird\HttpClient\Exception::__construct()

__toString()

__toString()

Inherited

inherited_from
Exception::__toString()

inherited_from
\Moneybird\Exception::__toString()

inherited_from
\Moneybird\HttpClient\Exception::__toString()

getCode()

getCode()

Inherited

inherited_from
Exception::getCode()

inherited_from
\Moneybird\Exception::getCode()

inherited_from
\Moneybird\HttpClient\Exception::getCode()

getFile()

getFile()

Inherited

inherited_from
Exception::getFile()

inherited_from
\Moneybird\Exception::getFile()

inherited_from
\Moneybird\HttpClient\Exception::getFile()

getLine()

getLine()

Inherited

inherited_from
Exception::getLine()

inherited_from
\Moneybird\Exception::getLine()

inherited_from
\Moneybird\HttpClient\Exception::getLine()

getMessage()

getMessage()

Inherited

inherited_from
Exception::getMessage()

inherited_from
\Moneybird\Exception::getMessage()

inherited_from
\Moneybird\HttpClient\Exception::getMessage()

getPrevious()

getPrevious()

Inherited

inherited_from
Exception::getPrevious()

inherited_from
\Moneybird\Exception::getPrevious()

inherited_from
\Moneybird\HttpClient\Exception::getPrevious()

getTrace()

getTrace()

Inherited

inherited_from
Exception::getTrace()

inherited_from
\Moneybird\Exception::getTrace()

inherited_from
\Moneybird\HttpClient\Exception::getTrace()

getTraceAsString()

getTraceAsString()

Inherited

inherited_from
Exception::getTraceAsString()

inherited_from
\Moneybird\Exception::getTraceAsString()

inherited_from
\Moneybird\HttpClient\Exception::getTraceAsString()

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.0.0a8 and

            generated on 2013-07-12T22:19:09+02:00.


text:
package com.github.tkurz.media.ontology.impl;

import com.github.tkurz.media.ontology.type.Coordinate;
import com.github.tkurz.media.ontology.type.SpatialEntity;
import com.github.tkurz.media.ontology.utils.Utils;

import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;

/**
 * ...
 * <p/>
 * Author: Thomas Kurz (tkurz@apache.org)
 */
public class Circle extends Ellipse2D.Double implements SpatialEntity {

    public Circle(Point point, int radius) {
        super(point.getX()-radius,point.getY()-radius,2*radius,2*radius);
    }

    public Circle(int x, int y, int radius) {
        super(x-radius,y-radius,2*radius,2*radius);
    }

    @Override
    public Coordinate getCenter() {
        return new Point(getCenterX(),getCenterY());
    }

    @Override
    public Rectangle getBoundingBox() {
        return new Rectangle(getBounds2D());
    }

    @Override
    public Area getArea() {
        return new Area(this);
    }

    @Override
    public String stringValue() {
        return "xcr="+ Utils.prettyPrint(getCenterX())+","+Utils.prettyPrint(getCenterY())+","+Utils.prettyPrint(width/2);
    }

    @Override
    public String stringValue(Format format) {
        return stringValue(); //TODO should support more types
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GroupControl.WinForm
{
    public partial class SearchWithNumberForm : BaseForm
    {

        public  delegate void IdentificationEquipmentWithNumber(string number);

        public event IdentificationEquipmentWithNumber _identificationEquipmentWithNumber;

        public SearchWithNumberForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var text = this.textBox1.Text;

            if (string.IsNullOrEmpty(text))
            {
                MessageBox.Show("请输入设备编号!");

                return;
            }

            _identificationEquipmentWithNumber(text);
        }
    }
}


text:
Our best products!

Try our amazing products

            {% for post in site.posts %}

                                {{ post.title }}

                                {{ post.category }}

            {% endfor %}


text:
import time
import json
import asyncio
import tornado.web
import tornado.ioloop
import tornado.websocket

class SocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        print("WebSocket opened")

    async def sleep_send(self, message, second=0.5):
        await asyncio.sleep(second)
        msg_dict = json.loads(message)
        msg_dict["res_time"] = int(time.time() * 1000)
        self.write_message(json.dumps(msg_dict))

    async def on_message(self, message):
        print(f"client: {message}")
        await self.sleep_send(message, second=1)

    async def ping(self, data):
        pass

    async def on_ping(self, data):
        pass

    def on_close(self):
        print("WebSocket closed")

def main(port):
    application = tornado.web.Application([
        (r"/websocket", SocketHandler),
    ])
    application.listen(port)
    print("ws_server is running.")
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main(18889)


text:
package luyao.everything.enity;

import java.util.List;

/**
 * Created by Lu
 * on 2016/11/22 18:26.
 */

public class LotteryResult {

    /**
     * awardDateTime : 2016-11-21 20:30
     * lotteryDetails : [{"awardNumber":2,"awardPrice":10000000,"awards":"一等奖"},{"awardNumber":0,"awardPrice":0,"awards":"一等奖","type":"追加"},{"awardNumber":63,"awardPrice":119261,"awards":"二等奖"},{"awardNumber":14,"awardPrice":71556,"awards":"二等奖","type":"追加"},{"awardNumber":766,"awardPrice":3582,"awards":"三等奖"},{"awardNumber":264,"awardPrice":2149,"awards":"三等奖","type":"追加"},{"awardNumber":34941,"awardPrice":200,"awards":"四等奖"},{"awardNumber":10590,"awardPrice":100,"awards":"四等奖","type":"追加"},{"awardNumber":604177,"awardPrice":10,"awards":"五等奖"},{"awardNumber":203195,"awardPrice":5,"awards":"五等奖","type":"追加"},{"awardNumber":5256234,"awardPrice":5,"awards":"六等奖"}]
     * lotteryNumber : ["07","20","23","29","34","02","10"]
     * name : 大乐透
     * period : 16137
     * pool : 3.8072204459E9
     * sales : 181006344
     */

    private String awardDateTime;
    private String name;
    private String period;
    private double pool;
    private int sales;
    private List<LotteryDetailsBean> lotteryDetails;
    private List<String> lotteryNumber;
    private String number;

    public String getNumber() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : lotteryNumber) {
            stringBuffer.append(s+"  ");
        }
        return stringBuffer.toString();
    }

    public String getAwardDateTime() {
        return awardDateTime;
    }

    public void setAwardDateTime(String awardDateTime) {
        this.awardDateTime = awardDateTime;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPeriod() {
        return period;
    }

    public void setPeriod(String period) {
        this.period = period;
    }

    public double getPool() {
        return pool;
    }

    public void setPool(double pool) {
        this.pool = pool;
    }

    public int getSales() {
        return sales;
    }

    public void setSales(int sales) {
        this.sales = sales;
    }

    public List<LotteryDetailsBean> getLotteryDetails() {
        return lotteryDetails;
    }

    public void setLotteryDetails(List<LotteryDetailsBean> lotteryDetails) {
        this.lotteryDetails = lotteryDetails;
    }

    public List<String> getLotteryNumber() {
        return lotteryNumber;
    }

    public void setLotteryNumber(List<String> lotteryNumber) {
        this.lotteryNumber = lotteryNumber;
    }

    public static class LotteryDetailsBean {
        /**
         * awardNumber : 2
         * awardPrice : 10000000
         * awards : 一等奖
         * type : 追加
         */

        private int awardNumber;
        private int awardPrice;
        private String awards;
        private String type;

        public int getAwardNumber() {
            return awardNumber;
        }

        public void setAwardNumber(int awardNumber) {
            this.awardNumber = awardNumber;
        }

        public int getAwardPrice() {
            return awardPrice;
        }

        public void setAwardPrice(int awardPrice) {
            this.awardPrice = awardPrice;
        }

        public String getAwards() {
            return awards;
        }

        public void setAwards(String awards) {
            this.awards = awards;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }

}


text:
package org.geogit.geotools.cli.porcelain;

import java.io.IOException;

import org.geogit.cli.CLICommand;
import org.geogit.cli.CommandFailedException;
import org.geogit.cli.GeogitCLI;
import org.geogit.geotools.plumbing.GeoToolsOpException;
import org.geogit.geotools.plumbing.ImportOp;
import org.geotools.data.DataStore;
import org.opengis.util.ProgressListener;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

/**
 * Imports one or more tables from a PostGIS database.
 *
 * PostGIS CLI proxy for {@link ImportOp}
 *
 * @see ImportOp
 */
@Parameters(commandNames = "import", commandDescription = "Import PostGIS database")
public class PGImport extends AbstractPGCommand implements CLICommand {

    /**
     * If this is set, only this table will be imported.
     */
    @Parameter(names = { "--table", "-t" }, description = "Table to import.")
    public String table = "";

    /**
     * If this is set, all tables will be imported.
     */
    @Parameter(names = "--all", description = "Import all tables.")
    public boolean all = false;

    /**
     * do not overwrite or delete features
     */
    @Parameter(names = { "--add" }, description = "Do not replace or delete features in the destitnation path")
    boolean add;

    /**
     * Set the path default feature type to the the feature type of imported features, and modify
     * existing features to match it
     */
    @Parameter(names = { "--alter" }, description = "Set the path default feature type to the the feature type of imported features, and modify existing features to match it")
    boolean alter;

    /**
     * Destination path to add features to. Only allowed when importing a single table
     */
    @Parameter(names = { "-d", "--dest" }, description = "Path to import to")
    String destTable;

    /**
     * Executes the import command using the provided options.
     */
    @Override
    protected void runInternal(GeogitCLI cli) throws IOException {

        DataStore dataStore = getDataStore();
        try {
            cli.getConsole().println("Importing from database " + commonArgs.database);

            ProgressListener progressListener = cli.getProgressListener();
            cli.getGeogit().command(ImportOp.class).setAll(all).setTable(table).setAlter(alter)
                    .setDestinationPath(destTable).setOverwrite(!add).setDataStore(dataStore)
                    .setProgressListener(progressListener).call();

            cli.getConsole().println("Import successful.");

        } catch (GeoToolsOpException e) {
            switch (e.statusCode) {
            case TABLE_NOT_DEFINED:
                throw new CommandFailedException(
                        "No tables specified for import. Specify --all or --table <table>.", e);
            case ALL_AND_TABLE_DEFINED:
                throw new CommandFailedException(
                        "Specify --all or --table <table>, both cannot be set.", e);
            case NO_FEATURES_FOUND:
                throw new CommandFailedException("No features were found in the database.", e);
            case TABLE_NOT_FOUND:
                throw new CommandFailedException("Could not find the specified table.", e);
            case UNABLE_TO_GET_NAMES:
                throw new CommandFailedException("Unable to get feature types from the database.",
                        e);
            case UNABLE_TO_GET_FEATURES:
                throw new CommandFailedException("Unable to get features from the database.", e);
            case UNABLE_TO_INSERT:
                throw new CommandFailedException(
                        "Unable to insert features into the working tree.", e);
            case ALTER_AND_ALL_DEFINED:
                throw new CommandFailedException(
                        "Alter cannot be used with --all option and more than one table.", e);
            default:
                throw new CommandFailedException("Import failed with exception: "
                        + e.statusCode.name(), e);
            }
        } finally {
            dataStore.dispose();
            cli.getConsole().flush();
        }
    }
}


text:
<?php
/**
 * PHP version ~5.5
 *
 * @category Model
 * @package  Fluency\Silex\Security\Model
 * @author   Rafael Ernesto Espinosa Santiesteban <ralphlnx@gmail.com>
 * @license  MIT <http://www.opensource.org/licenses/mit-license.php>
 * @link     http://fluency.inc.com
 */

namespace Fluency\Silex\Security\Model;

use Fluency\Silex\Framework\Model\DbalModel;

/**
 * Class UserModel
 *
 * @category Model
 * @package  Fluency\Silex\Security\Model
 * @author   Rafael Ernesto Espinosa Santiesteban <ralphlnx@gmail.com>
 * @license  MIT <http://www.opensource.org/licenses/mit-license.php>
 * @link     http://fluency.inc.com
 */
class UserModel extends DbalModel
{

}


text:
<?php

namespace Maba\Bundle\OAuthCommerceAccountsBundle\Login;

use Doctrine\ORM\EntityManager;
use Maba\Bundle\OAuthCommerceAccountsBundle\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

class FailureHandler implements AuthenticationFailureHandlerInterface
{
    /**
     * @var EncoderFactoryInterface
     */
    protected $encoderFactory;

    /**
     * @var EntityManager
     */
    protected $entityManager;

    /**
     * @var AuthenticationFailureHandlerInterface
     */
    protected $defaultFailureHandler;

    /**
     * @var HttpKernelInterface
     */
    protected $httpKernel;

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(
        ContainerInterface $container,
        AuthenticationFailureHandlerInterface $defaultFailureHandler,
        EncoderFactoryInterface $encoderFactory,
        EntityManager $entityManager,
        HttpKernelInterface $httpKernel
    ) {
        $this->container = $container;
        $this->defaultFailureHandler = $defaultFailureHandler;
        $this->encoderFactory = $encoderFactory;
        $this->entityManager = $entityManager;
        $this->httpKernel = $httpKernel;
    }

    /**
     * This is called when an interactive authentication attempt fails. This is
     * called by authentication listeners inheriting from
     * AbstractAuthenticationListener.
     *
     * @param Request                 $request
     * @param AuthenticationException $exception
     *
     * @throws \RuntimeException
     * @return Response The response to return, never null
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $token = $exception->getToken();
        if ($token instanceof UsernamePasswordToken) {
            $existingUser = $this->entityManager->getRepository(User::CLASS_NAME)
                ->findOneBy(array('username' => $token->getUser()));
            if (!$existingUser) {
                $user = new User();
                $user
                    ->setUsername($token->getUser())
                    ->setPassword(
                        $this->encoderFactory->getEncoder($user)
                            ->encodePassword($token->getCredentials(), $user->getSalt())
                    )
                ;

                $this->entityManager->persist($user);
                $this->entityManager->flush();

                return $this->httpKernel->handle(
                    $this->getCurrentRequest()->duplicate(),
                    HttpKernelInterface::MASTER_REQUEST
                );
            }
        }

        return $this->defaultFailureHandler->onAuthenticationFailure($request, $exception);
    }

    /**
     * @return Request
     */
    protected function getCurrentRequest()
    {
        return $this->container->get('request');
    }

}


text:
const ArgumentType = require('./base');

class IntegerArgumentType extends ArgumentType {
	constructor(client) {
		super(client, 'integer');
	}

	validate(value, msg, arg) {
		const int = Number.parseInt(value);
		return !Number.isNaN(int) &&
			(arg.min === null || typeof arg.min === 'undefined' || int >= arg.min) &&
			(arg.max === null || typeof arg.max === 'undefined' || int <= arg.max);
	}

	parse(value) {
		return Number.parseInt(value);
	}
}

module.exports = IntegerArgumentType;


text:
#include <common.h>
#include <micrel.h>
#include <nand.h>
#include <netdev.h>
#include <phy.h>
#include <rtc.h>
#include <asm/io.h>
#include <asm/mach-types.h>
#include <asm/arch/hardware.h>
#include <asm/arch/spr_defs.h>
#include <asm/arch/spr_misc.h>
#include <linux/mtd/fsmc_nand.h>
#include "fpga.h"

static struct nand_chip nand_chip[CONFIG_SYS_MAX_NAND_DEVICE];

int board_init(void)
{
	/*
	 * X600 is equipped with an M41T82 RTC. This RTC has the
	 * HT bit (Halt Update), which needs to be cleared upon
	 * power-up. Otherwise the RTC is halted.
	 */
	rtc_reset();

	return spear_board_init(MACH_TYPE_SPEAR600);
}

int board_late_init(void)
{
	/*
	 * Monitor and env protection on by default
	 */
	flash_protect(FLAG_PROTECT_SET,
		      CONFIG_SYS_FLASH_BASE, CONFIG_SYS_FLASH_BASE +
		      CONFIG_SYS_SPL_LEN + CONFIG_SYS_MONITOR_LEN +
		      2 * CONFIG_ENV_SECT_SIZE - 1,
		      &flash_info[0]);

	/* Init FPGA subsystem */
	x600_init_fpga();

	return 0;
}

/*
 * board_nand_init - Board specific NAND initialization
 * @nand:	mtd private chip structure
 *
 * Called by nand_init_chip to initialize the board specific functions
 */

void board_nand_init(void)
{
	struct misc_regs *const misc_regs_p =
		(struct misc_regs *)CONFIG_SPEAR_MISCBASE;
	struct nand_chip *nand = &nand_chip[0];

	if (!(readl(&misc_regs_p->auto_cfg_reg) & MISC_NANDDIS))
		fsmc_nand_init(nand);
}

int board_phy_config(struct phy_device *phydev)
{
	unsigned short id1, id2;

	/* check whether KSZ9031 or AR8035 has to be configured */
	id1 = phy_read(phydev, MDIO_DEVAD_NONE, 2);
	id2 = phy_read(phydev, MDIO_DEVAD_NONE, 3);

	if ((id1 == 0x22) && ((id2 & 0xFFF0) == 0x1620)) {
		/* PHY configuration for Micrel KSZ9031 */
		printf("PHY KSZ9031 detected - ");

		phy_write(phydev, MDIO_DEVAD_NONE, MII_CTRL1000, 0x1c00);

		/* control data pad skew - devaddr = 0x02, register = 0x04 */
		ksz9031_phy_extended_write(phydev, 0x02,
					   MII_KSZ9031_EXT_RGMII_CTRL_SIG_SKEW,
					   MII_KSZ9031_MOD_DATA_NO_POST_INC,
					   0x0000);
		/* rx data pad skew - devaddr = 0x02, register = 0x05 */
		ksz9031_phy_extended_write(phydev, 0x02,
					   MII_KSZ9031_EXT_RGMII_RX_DATA_SKEW,
					   MII_KSZ9031_MOD_DATA_NO_POST_INC,
					   0x0000);
		/* tx data pad skew - devaddr = 0x02, register = 0x05 */
		ksz9031_phy_extended_write(phydev, 0x02,
					   MII_KSZ9031_EXT_RGMII_TX_DATA_SKEW,
					   MII_KSZ9031_MOD_DATA_NO_POST_INC,
					   0x0000);
		/* gtx and rx clock pad skew - devaddr = 0x02, reg = 0x08 */
		ksz9031_phy_extended_write(phydev, 0x02,
					   MII_KSZ9031_EXT_RGMII_CLOCK_SKEW,
					   MII_KSZ9031_MOD_DATA_NO_POST_INC,
					   0x03FF);
	} else {
		/* PHY configuration for Vitesse VSC8641 */
		printf("PHY VSC8641 detected - ");

		/* Extended PHY control 1, select GMII */
		phy_write(phydev, MDIO_DEVAD_NONE, 23, 0x0020);

		/* Software reset necessary after GMII mode selction */
		phy_reset(phydev);

		/* Enable extended page register access */
		phy_write(phydev, MDIO_DEVAD_NONE, 31, 0x0001);

		/* 17e: Enhanced LED behavior, needs to be written twice */
		phy_write(phydev, MDIO_DEVAD_NONE, 17, 0x09ff);
		phy_write(phydev, MDIO_DEVAD_NONE, 17, 0x09ff);

		/* 16e: Enhanced LED method select */
		phy_write(phydev, MDIO_DEVAD_NONE, 16, 0xe0ea);

		/* Disable extended page register access */
		phy_write(phydev, MDIO_DEVAD_NONE, 31, 0x0000);

		/* Enable clock output pin */
		phy_write(phydev, MDIO_DEVAD_NONE, 18, 0x0049);
	}

	if (phydev->drv->config)
		phydev->drv->config(phydev);

	return 0;
}

int board_eth_init(bd_t *bis)
{
	int ret = 0;

	if (designware_initialize(CONFIG_SPEAR_ETHBASE,
				  PHY_INTERFACE_MODE_GMII) >= 0)
		ret++;

	return ret;
}


text:
import { Component, OnInit, OnDestroy, HostListener } from '@angular/core';
import { ProjectComponent } from '../project.component';
import { AppStateService } from '../app-state.service';
import { FiniteAutomaton } from './finite-automaton';
import { Subscription } from 'rxjs/Subscription';
import { ToolEvent } from '../toolbar.component';
import { AlphabetSymbol } from '../automaton';
import { Router } from '@angular/router';
import { Metadata } from '../project';

declare var alertify;

@Component({
  templateUrl: './finite.component.html'
})
export class FiniteComponent extends ProjectComponent implements OnInit, OnDestroy {
  project: FiniteAutomaton;

  @HostListener('document:keydown', ['$event']) onKeyDown($event: KeyboardEvent) {
    let keyCode = $event.code;

    if ($event.ctrlKey) {
      $event.preventDefault();
      $event.stopPropagation();
      switch (keyCode) {
        case "KeyO":
          this.openFile(this.parseAutomatonObject);
          break;
        case "KeyN":
          this.createNewFSM();
          break;
        case "KeyS":
          this.saveProject(this.saveFilterFunction);
          break;
        default:
          super.onKeyDown($event);
      }
    }
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.appStateService.hasActiveProject) {
      this.project = this.appStateService.project as FiniteAutomaton;
      if (this.project.type != "finite-automaton") { // This should never happen
        this.router.navigateByUrl("/home", { replaceUrl: true });
      }
    } else {
      this.createNewFSM();
    }
  }

  onToolClicked($event: ToolEvent) {
    switch ($event.target) {
      case "new":
        this.createNewFSM();
        break;
      case "open":
        this.openFile(this.parseAutomatonObject);
        break;
      case "save":
        this.saveProject(this.saveFilterFunction);
        break;
      default:
        super.onToolClicked($event);
    }
  }

  createNewFSM() {
    this.newProject(new FiniteAutomaton(true), "New Finite State Automaton", "/finite/options");
  }

  parseAutomatonObject(rawAutomaton: FiniteAutomaton): FiniteAutomaton {
    let automaton = new FiniteAutomaton(rawAutomaton.isDeterministic);
    automaton.metadata = rawAutomaton.metadata;

    rawAutomaton.alphabet.symbols.forEach((symbol) => {
      automaton.alphabet.addSymbol(new AlphabetSymbol(symbol.symbol));
    })

    rawAutomaton.states.forEach((rawState) => {
      let newState = automaton.createState(rawState.layoutPosition);
      newState.id = rawState.id;
      newState.name = rawState.name;
      newState.type = rawState.type;
    });

    rawAutomaton.states.forEach((rawState, i) => {
      rawState.transitions.forEach((rawTransition, j) => {
        let destinationState = automaton.states.find((state) => {
          return state.id == (rawTransition.destination as any);
        });

        let newTransition = automaton.states[i].addTransition(destinationState);

        newTransition.shouldDuplicateLayout = rawTransition.shouldDuplicateLayout;

        rawTransition.conditions.forEach((condition) => {
          newTransition.addCondition(new AlphabetSymbol(condition.symbol));
        });
      });
    });

    automaton.stateAutoIncrement = rawAutomaton.stateAutoIncrement;

    return automaton;
  }

  saveFilterFunction(key, value) {
    if (key == 'origin' || key == 'destination') {
      return value.id;
    } else if (["selectedState", "selectedTransition", "activeElement"].includes(key)) {
      return undefined;
    } else {
      return value;
    }
  }
}


text:
  -- this file exists for testing statement tokenization of *.sql files

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `product` /*!40100 DEFAULT CHARACTER SET latin1 */;
/* hello */   USE product

CREATE #fun interruption
TABLE `users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `na``me` varchar(30) NOT NULL DEFAULT 'it\'s complicated "escapes''',--	end of line comment with tab
  `credits` decimal(9,2) DEFAULT '10.00', -- end of line; " comment with ideographic space
  `last_modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, # another end-of-line comment;
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
          CREATE TABLE `posts with spaces` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) unsigned NOT NULL,
  `body` varchar(50) DEFAULT '/* lol\'',
  `created_at` datetime /*!50601 DEFAULT CURRENT_TIMESTAMP*/,
  `edited_at` datetime /*!50601 DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP*/,
  PRIMARY KEY (`id`),
  KEY `user_created` (`user_id`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
create function funcnodefiner() RETURNS varchar(30) RETURN "hello";
CREATE DEFINER = CURRENT_USER() FUNCTION funccuruserparens() RETURNS int RETURN 42;
CREATE DEFINER=CURRENT_USER PROCEDURE proccurusernoparens() # this is a comment!
	SELECT 1;
create definer=foo@'localhost' /*lol*/ FUNCTION analytics.funcdefquote2() RETURNS int RETURN 42;
create DEFINER = 'foo'@localhost PROCEDURE `procdefquote1`() SELECT 42;
	delimiter    "💩💩💩"
CREATE TABLE uhoh (ummm varchar(20) default 'ok 💩💩💩 cool')💩💩💩
DELIMITER //
CREATE PROCEDURE whatever(name varchar(10))
BEGIN
	DECLARE v1 INT; -- comment with "normal space" in front!
	SET v1=loops;-- comment with `nbsp' in front?!?
	WHILE v1 > 0 DO
		INSERT INTO users (name) values ('\xF0\x9D\x8C\x86');
		SET v1 = v1 - (2 / 2); /* testing // testing */
	END WHILE;
END
//
delimiter ;

CREATE TABLE `uhoh` . tbl1 (id int unsigned not null primary key);
CREATE TABLE uhoh.tbl2 (id int unsigned not null primary key);
CREATE TABLE /*lol*/ uhoh  .  `tbl3` (id int unsigned not null primary key);
create definer=foo@'localhost' /*lol*/ FUNCTION foo.funcdefquote3() RETURNS int RETURN 42;

use /*wtf*/`analytics`;CREATE TABLE  if  NOT    eXiStS     `comments` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `post_id` bigint(20) unsigned NOT NULL,
  `user_id` bigint(20) unsigned NOT NULL,
  `created_at` datetime DEFAULT NULL,
  `body` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE subscriptions (id int unsigned not null primary key)


text:
void next_generation(int *current, int *next, int length);
int check_generation(int *current, int *next, int length);
void strcpy_int(int *current, int *next, int length);

int main()
{
	int array_lenght;
	do
    {
		scanf("%d",&array_lenght);
	}while(array_lenght < 0 || array_lenght > 20);
	int current[array_lenght];
	int next[array_lenght];
	int count,count_print;
	for(count = 0; count < array_lenght; count++)
		scanf ("%d",&current[count]);
  printf("\n");
	for(count_print = 0; count_print < array_lenght; count_print++)
	{
        if(current[count_print])
            printf("*");
        else
            printf(".");
	}
	printf("\n");
	for(count = 0; count < 4 && check_generation(current, next, array_lenght); count++)
	{
        next_generation(current, next, array_lenght);
        for(count_print = 0; count_print < array_lenght; count_print++)
        {
            if(next[count_print])
                printf("*");
            else
                printf(".");
        }
        printf("\n");
        strcpy_int(current, next, array_lenght);
	}
}

void next_generation(int *current, int *next, int length)
{
	int count;
	int count_print;
	*next = 0;
	for(count = 1; count < length; count++)
    {
		if((*(current + count + 1) == 1 && *(current + count - 1) == 0) || (*(current + count + 1) == 0 && *(current + count - 1) == 1))
			*(next + count) = 1;
		else
			*(next + count) = 0;
	}
}

int check_generation(int *current, int *next, int length)
{
	int count, count_zero = 0;
	for(count = 0; count < length; ++count)
    {
		if(*(current + count) == 0)
			count_zero++;
	}
	if(count_zero == length)
		return 0;
	else
		return 1;
}

void strcpy_int(int *current, int *next, int length)
{
	int count;
	for(count = 0; count <length; ++count)
		*(current + count) = *(next + count);
}


text:
package fr.openwide.core.jpa.more.infinispan.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Maps;

import fr.openwide.core.infinispan.model.INode;
import fr.openwide.core.infinispan.service.IInfinispanClusterService;
import fr.openwide.core.jpa.more.business.task.model.IQueueId;
import fr.openwide.core.jpa.more.business.task.service.IQueuedTaskHolderManager;
import fr.openwide.core.jpa.more.infinispan.action.QueueTaskManagerStartAction;
import fr.openwide.core.jpa.more.infinispan.action.QueueTaskManagerStatusAction;
import fr.openwide.core.jpa.more.infinispan.action.QueueTaskManagerStopAction;
import fr.openwide.core.jpa.more.infinispan.action.SwitchStatusQueueTaskManagerResult;
import fr.openwide.core.jpa.more.infinispan.model.QueueTaskManagerStatus;
import fr.openwide.core.jpa.more.infinispan.model.TaskQueueStatus;

public class InfinispanQueueTaskManagerServiceImpl implements IInfinispanQueueTaskManagerService {

	private static final Logger LOGGER = LoggerFactory.getLogger(InfinispanQueueTaskManagerServiceImpl.class);

	@Autowired
	private IInfinispanClusterService infinispanClusterService;

	@Autowired
	private IQueuedTaskHolderManager queuedTaskHolderManager;

	@Override
	public QueueTaskManagerStatus getQueueTaskManagerStatus(INode node) {

		QueueTaskManagerStatus result = null;

		try {
			result = infinispanClusterService.syncedAction(
					QueueTaskManagerStatusAction.get(node.getAddress()),
					10,
					TimeUnit.SECONDS);
		} catch (ExecutionException e) {
			LOGGER.error("Erreur lors de la récupération du QueueTaskManagerStatus", e);
		} catch (TimeoutException e) {
			LOGGER.error("Timeout lors de la récupération du QueueTaskManagerStatus");
		}
		return result;
	}

	@Override
	public QueueTaskManagerStatus createQueueTaskManagerStatus(){
		QueueTaskManagerStatus queueTaskManagerStatus = new QueueTaskManagerStatus();

		queueTaskManagerStatus.setQueueManagerActive(queuedTaskHolderManager.isActive());

		Map<String, IQueueId> queuesById = new HashMap<>();
		Map<String, TaskQueueStatus> taskQueueStatusById = Maps.newHashMap();

		for(IQueueId queueId : queuedTaskHolderManager.getQueueIds()){
			String id = queueId.getUniqueStringId();
			queuesById.put(id, queueId);
			taskQueueStatusById.put(
					id,
					new TaskQueueStatus(
							queueId.getUniqueStringId(),
							queuedTaskHolderManager.isTaskQueueActive(id),
							queuedTaskHolderManager.getNumberOfRunningTasks(id),
							queuedTaskHolderManager.getNumberOfWaitingTasks(id),
							queuedTaskHolderManager.getNumberOfTaskConsumer(id)
					)
			);
		}
		queueTaskManagerStatus.setQueuesById(queuesById);
		queueTaskManagerStatus.setTaskQueueStatusById(taskQueueStatusById);

		return queueTaskManagerStatus;
	}

	@Override
	public SwitchStatusQueueTaskManagerResult startQueueManager(INode node){
		SwitchStatusQueueTaskManagerResult result = null;

		try {
			result = infinispanClusterService.syncedAction(
					QueueTaskManagerStartAction.get(node.getAddress()),
					10,
					TimeUnit.SECONDS);
		} catch (ExecutionException e) {
			LOGGER.error("Erreur lors de la récupération du QueueTaskManagerStatus", e);
		} catch (TimeoutException e) {
			LOGGER.error("Timeout lors de la récupération du QueueTaskManagerStatus");
			result = SwitchStatusQueueTaskManagerResult.TIME_OUT;
		}
		return result;
	}

	@Override
	public SwitchStatusQueueTaskManagerResult stopQueueManager(INode node){
		SwitchStatusQueueTaskManagerResult result = null;

		try {
			result = infinispanClusterService.syncedAction(
					QueueTaskManagerStopAction.get(node.getAddress()),
					10,
					TimeUnit.SECONDS);
		} catch (ExecutionException e) {
			LOGGER.error("Erreur lors de la récupération du QueueTaskManagerStatus", e);
		} catch (TimeoutException e) {
			LOGGER.error("Timeout lors de la récupération du QueueTaskManagerStatus");
			result = SwitchStatusQueueTaskManagerResult.TIME_OUT;
		}
		return result;
	}

	@Override
	public SwitchStatusQueueTaskManagerResult start() {
		if(queuedTaskHolderManager.isActive()){
			return SwitchStatusQueueTaskManagerResult.ALREADY_STARTED;
		}
		queuedTaskHolderManager.start();
		return SwitchStatusQueueTaskManagerResult.STARTED;
	}

	@Override
	public SwitchStatusQueueTaskManagerResult stop() {
		if(!queuedTaskHolderManager.isActive()){
			return SwitchStatusQueueTaskManagerResult.ALREADY_STOPPED;
		}
		queuedTaskHolderManager.stop();
		return SwitchStatusQueueTaskManagerResult.STOPPED;
	}

	@Override
	public Boolean isOneQueueTaskManagerUp() {
		return infinispanClusterService.getNodes().stream().map(o -> getQueueTaskManagerStatus(o))
				.filter(o-> o!=null)
				.anyMatch(o->o.isQueueManagerActive());
	}
	@Override
	public Integer clearCache(){
		return queuedTaskHolderManager.clearCache();
	}
	}


text:
cask 'unity-android-support-for-editor' do
  version '2019.1.5f1,0ca0f5646614'
  sha256 '01850c1617f2dbd69fc4ce8800c550eec25fa4a4e72188a152234646f634031a'

  url "https://netstorage.unity3d.com/unity/#{version.after_comma}/MacEditorTargetInstaller/UnitySetup-Android-Support-for-Editor-#{version.before_comma}.pkg"
  appcast 'https://public-cdn.cloud.unity3d.com/hub/prod/releases-darwin.json'
  name 'Unity Android Build Support'
  homepage 'https://unity3d.com/unity/'

  depends_on cask: 'unity'

  pkg "UnitySetup-Android-Support-for-Editor-#{version.before_comma}.pkg"

  uninstall pkgutil: 'com.unity3d.AndroidPlayer'
end


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public SharePointProvisioningTemplateCustomActions CustomActions { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503.SharePointProvisioningTemplateCustomActions](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503.SharePointProvisioningTemplateCustomActions.md)

## See also
- [SharePointProvisioningTemplate](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503.SharePointProvisioningTemplate.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201503.md)


text:
module BeakerAnswers
  require 'stringify-hash'
  require 'require_all'
  require 'beaker-answers/answers'
  require 'beaker-answers/version'
end


text:
---
title: State management with Pinia
desc: (@quasar/app-vite) How to manage Pinia in a Quasar App.
scope:
  tree:
    { l: 'src',
      c: [
        { l: 'stores', e: 'Pinia',
          c: [
            { l: 'index.js', e: 'Pinia initialization' },
            { l: '<store>', e: 'Pinia store...' },
            { l: '<store>', e: 'Pinia store...' }
          ]
        }
      ]
    }
  newStore:
    { l: 'src',
      c: [
        { l: 'stores',
          c: [
            { l: 'index.js', e: 'Pinia initialization' },
            { l: 'counter.js', e: 'Pinia store' }
          ]
        }
      ]
    }
---
In large applications, state management often becomes complex due to multiple pieces of state scattered across many components and the interactions between them. It is often overlooked that the source of truth in Vue instances is the raw data object - a Vue instance simply proxies access to it. Therefore, if you have a piece of state that should be shared by multiple instances, you should avoid duplicating it and share it by identity.

The recommended way to go if you want components sharing state is Pinia. Take a look at its [documentation](https://pinia.vuejs.org/) before diving in. It has a great feature when used along the [Vue dev-tools](https://github.com/vuejs/vue-devtools) browser extension like Time Travel debugging.

We won't go into details on how to configure or use Pinia since it has great docs. Instead we'll just show you what the folder structure looks like when using it on a Quasar project.

<doc-tree :def="scope.tree" />

When you scaffold a Quasar project folder you can choose to add Pinia. It will create all the necessary configuration for you. Like for example the creation of `/src/stores` which handles all the Pinia related code that you need.

If you don't choose the Pinia option during project creation but would like to add it later then all you need to do is to check the next section and create the `src/stores/index.[js|ts]` file (it's automatically created when you run `quasar new store <name>`):

```js
// src/stores/index.js

import { store } from 'quasar/wrappers'
import { createPinia } from 'pinia'

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Store instance.
 */

export default store((/* { ssrContext } */) => {
  const pinia = createPinia()

  // You can add Pinia plugins here
  // pinia.use(SomePiniaPlugin)

  return pinia
})
```

## Adding a Pinia store
Adding a Pinia store is easy with Quasar CLI through the `$ quasar new` command.

```bash
$ quasar new store <store_name> [--format ts]
```

It will create a folder in `/src/stores` named by "store_name" from the command above. It will contain all the boilerplate that you need.

Let's say that you want to create a "counter" Pinia store. You issue `$ quasar new store counter`. You then notice the newly created `/src/stores/counter.[js|ts]` file:

<doc-tree :def="scope.newStore" />

Example of Pinia store:

```js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
  actions: {
    increment() {
      this.counter++;
    },
  },
})
```

We've created the new Pinia store, but we haven't yet used it in our app. In a Vue file:

```html
<template>
  <div>
    <!-- Option 1 -->
    <div>Direct store</div>
    <!-- Read the state value directly -->
    <div>{{ store.counter }}</div>
    <!-- Use getter directly -->
    <div>{{ store.doubleCount }}</div>

    <!-- Manipulate state directly -->
    <q-btn @click="store.counter--">-</q-btn>
    <!-- Use an action -->
    <q-btn @click="store.increment()">+</q-btn>
  </div>

  <div>
    <!-- Option 2 -->
    <div>Indirect store</div>
    <!-- Use the computed state -->
    <div>{{ count }}</div>
    <!-- Use the computed getter -->
    <div>{{ doubleCountValue }}</div>

    <!-- Use the exposed function -->
    <q-btn @click="decrementCount()">-</q-btn>
    <!-- Use the exposed function -->
    <q-btn @click="incrementCount()">+</q-btn>
  </div>

  <div>
    <!-- Option 3 -->
    <div>Destructured store</div>
    <!-- Use the destructured state -->
    <div>{{ counter }}</div>
    <!-- Use the destructured getter -->
    <div>{{ doubleCount }}</div>

    <!-- Manipulate state directly-->
    <q-btn @click="counter--">-</q-btn>
    <!-- Use an action -->
    <q-btn @click="increment()">+</q-btn>
  </div>
</template>

<script>
import { computed } from 'vue';
import { useCounterStore } from 'stores/counter';
import { storeToRefs } from 'pinia';

export default {
  setup() {
    const store = useCounterStore();

    // Option 2: use computed and functions to use the store
    const count = computed(() => store.counter);
    const doubleCountValue = computed(() => store.doubleCount);
    const incrementCount = () => store.increment(); // use action
    const decrementCount = () => store.counter--; // manipulate directly

    // Option 3: use destructuring to use the store in the template
    const { counter, doubleCount } = storeToRefs(store); // state and getters need "storeToRefs"
    const { increment } = store; // actions can be destructured directly

    return {
      // Option 1: return the store directly and couple it in the template
      store,

      // Option 2: use the store in functions and compute the state to use in the template
      count,
      doubleCountValue,
      incrementCount,
      decrementCount,

      // Option 3: pass the destructed state, getters and actions to the template
      counter,
      increment,
      doubleCount,
    };
  },
};
</script>
```

[More info on defining a Pinia store](https://pinia.vuejs.org/core-concepts/).

## Accessing the router in Pinia stores

Simply use `this.router` in Pinia stores to get access to the router.

Here is an example:
```js
import { defineStore } from 'pinia'

export const useWhateverStore = defineStore('whatever', {
  // ...
  actions: {
    whateverAction () {
      this.router.push('...')
    }
  }
}
```


text:
{% if site.data.extracurricular.extracurricular.size > 0 %}
  {% assign exp = site.data.extracurricular.extracurricular %}
  {% for item in exp %}

    {{ item.role }} of {{ item.group }}

    {{ item.location }}

     {{ item.duration }}

      {{item.about | join: '
 ' | newline_to_br | markdownify }}

  {% endfor %}
{% endif %}


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - cafiorin@gmail.com
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#if !defined(_InputArduino__INCLUDED_)
#define _InputArduino__INCLUDED_

#include "defines.h"
#include "Utils.h"
#include "Port.h"

class InputArduino : public Port
{

public:
	InputArduino(uint8_t portNumber, PinballObject *parent=NULL);
	virtual ~InputArduino();

	bool GetInput();
	void SetDebounceRead(uint8_t debounce){m_debounceRead = debounce;}
	bool SetInput(bool value);
	virtual void Loop();

private:
	uint8_t m_debounceRead;    // the debounce time; increase if the output flickers
	uint8_t m_debounceCount;
	bool m_InputValue;
	bool m_Edge;
	PinballObject *m_parent;

	void CheckDebounce();
};
#endif // !defined(_InputArduino__INCLUDED_)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Açupa</logradouro><bairro>Olaria</bairro><cidade>Rio de Janeiro</cidade><uf>RJ</uf><cep>21031510</cep></feed>


text:
    <?php echo $data['title'] ?>

      <?php echo $data['sub_title'] ?>

	<a href="<?php echo site_url('admin/category/create') ?>" class="btn btn-primary pull-right">Add category

						Name
						Description

						<?php foreach ($categories as $category): ?>

								<?php echo $category->name ?>
								<?php echo $category->description	?>

									<a href="<?php echo site_url('admin/category/'.$category->id) ?>" class="btn btn-xs btn-success">

									<a href="<?php echo site_url('admin/category/'.$category->id.'/edit') ?>" class="btn btn-xs btn-warning">

									<?php echo anchor("admin/category/delete/".$category->id, '', ['onclick' => "return confirm('Do you want delete this category?')", "class" => "btn btn-xs btn-danger"]);
									?>

						<?php endforeach ?>