text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: platform.proto

package edu.kit.ipd.crowdcontrol.objectservice.proto;

/**
 * Protobuf type {@code crowdcontrol.Platform}
 */
public  final class Platform extends
    com.google.protobuf.GeneratedMessage implements
    // @@protoc_insertion_point(message_implements:crowdcontrol.Platform)
    PlatformOrBuilder {
  // Use Platform.newBuilder() to construct.
  private Platform(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
    super(builder);
  }
  private Platform() {
    id_ = "";
    name_ = "";
    url_ = "";
    hasCalibrations_ = false;
    isInactive_ = false;
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
  }
  private Platform(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry) {
    this();
    int mutable_bitField0_ = 0;
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          default: {
            if (!input.skipField(tag)) {
              done = true;
            }
            break;
          }
          case 10: {
            String s = input.readStringRequireUtf8();

            id_ = s;
            break;
          }
          case 18: {
            String s = input.readStringRequireUtf8();

            name_ = s;
            break;
          }
          case 26: {
            String s = input.readStringRequireUtf8();

            url_ = s;
            break;
          }
          case 32: {

            hasCalibrations_ = input.readBool();
            break;
          }
          case 40: {

            isInactive_ = input.readBool();
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw new RuntimeException(e.setUnfinishedMessage(this));
    } catch (java.io.IOException e) {
      throw new RuntimeException(
          new com.google.protobuf.InvalidProtocolBufferException(
              e.getMessage()).setUnfinishedMessage(this));
    } finally {
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOuterClass.internal_static_crowdcontrol_Platform_descriptor;
  }

  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOuterClass.internal_static_crowdcontrol_Platform_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.class, edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.Builder.class);
  }

  public static final int ID_FIELD_NUMBER = 1;
  private volatile java.lang.Object id_;
  /**
   * optional string id = 1;
   */
  public java.lang.String getId() {
    java.lang.Object ref = id_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      id_ = s;
      return s;
    }
  }
  /**
   * optional string id = 1;
   */
  public com.google.protobuf.ByteString
      getIdBytes() {
    java.lang.Object ref = id_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      id_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int NAME_FIELD_NUMBER = 2;
  private volatile java.lang.Object name_;
  /**
   * optional string name = 2;
   */
  public java.lang.String getName() {
    java.lang.Object ref = name_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      name_ = s;
      return s;
    }
  }
  /**
   * optional string name = 2;
   */
  public com.google.protobuf.ByteString
      getNameBytes() {
    java.lang.Object ref = name_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      name_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int URL_FIELD_NUMBER = 3;
  private volatile java.lang.Object url_;
  /**
   * optional string url = 3;
   */
  public java.lang.String getUrl() {
    java.lang.Object ref = url_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      url_ = s;
      return s;
    }
  }
  /**
   * optional string url = 3;
   */
  public com.google.protobuf.ByteString
      getUrlBytes() {
    java.lang.Object ref = url_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      url_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int HAS_CALIBRATIONS_FIELD_NUMBER = 4;
  private boolean hasCalibrations_;
  /**
   * optional bool has_calibrations = 4;
   */
  public boolean getHasCalibrations() {
    return hasCalibrations_;
  }

  public static final int IS_INACTIVE_FIELD_NUMBER = 5;
  private boolean isInactive_;
  /**
   * optional bool is_inactive = 5;
   */
  public boolean getIsInactive() {
    return isInactive_;
  }

  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (!getIdBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessage.writeString(output, 1, id_);
    }
    if (!getNameBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessage.writeString(output, 2, name_);
    }
    if (!getUrlBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessage.writeString(output, 3, url_);
    }
    if (hasCalibrations_ != false) {
      output.writeBool(4, hasCalibrations_);
    }
    if (isInactive_ != false) {
      output.writeBool(5, isInactive_);
    }
  }

  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!getIdBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessage.computeStringSize(1, id_);
    }
    if (!getNameBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessage.computeStringSize(2, name_);
    }
    if (!getUrlBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessage.computeStringSize(3, url_);
    }
    if (hasCalibrations_ != false) {
      size += com.google.protobuf.CodedOutputStream
        .computeBoolSize(4, hasCalibrations_);
    }
    if (isInactive_ != false) {
      size += com.google.protobuf.CodedOutputStream
        .computeBoolSize(5, isInactive_);
    }
    memoizedSize = size;
    return size;
  }

  private static final long serialVersionUID = 0L;
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return PARSER.parseFrom(input);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return PARSER.parseFrom(input, extensionRegistry);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return PARSER.parseDelimitedFrom(input);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return PARSER.parseDelimitedFrom(input, extensionRegistry);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return PARSER.parseFrom(input);
  }
  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return PARSER.parseFrom(input, extensionRegistry);
  }

  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(edu.kit.ipd.crowdcontrol.objectservice.proto.Platform prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   * Protobuf type {@code crowdcontrol.Platform}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:crowdcontrol.Platform)
      edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOuterClass.internal_static_crowdcontrol_Platform_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOuterClass.internal_static_crowdcontrol_Platform_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.class, edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.Builder.class);
    }

    // Construct using edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
      }
    }
    public Builder clear() {
      super.clear();
      id_ = "";

      name_ = "";

      url_ = "";

      hasCalibrations_ = false;

      isInactive_ = false;

      return this;
    }

    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return edu.kit.ipd.crowdcontrol.objectservice.proto.PlatformOuterClass.internal_static_crowdcontrol_Platform_descriptor;
    }

    public edu.kit.ipd.crowdcontrol.objectservice.proto.Platform getDefaultInstanceForType() {
      return edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.getDefaultInstance();
    }

    public edu.kit.ipd.crowdcontrol.objectservice.proto.Platform build() {
      edu.kit.ipd.crowdcontrol.objectservice.proto.Platform result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    public edu.kit.ipd.crowdcontrol.objectservice.proto.Platform buildPartial() {
      edu.kit.ipd.crowdcontrol.objectservice.proto.Platform result = new edu.kit.ipd.crowdcontrol.objectservice.proto.Platform(this);
      result.id_ = id_;
      result.name_ = name_;
      result.url_ = url_;
      result.hasCalibrations_ = hasCalibrations_;
      result.isInactive_ = isInactive_;
      onBuilt();
      return result;
    }

    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof edu.kit.ipd.crowdcontrol.objectservice.proto.Platform) {
        return mergeFrom((edu.kit.ipd.crowdcontrol.objectservice.proto.Platform)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(edu.kit.ipd.crowdcontrol.objectservice.proto.Platform other) {
      if (other == edu.kit.ipd.crowdcontrol.objectservice.proto.Platform.getDefaultInstance()) return this;
      if (!other.getId().isEmpty()) {
        id_ = other.id_;
        onChanged();
      }
      if (!other.getName().isEmpty()) {
        name_ = other.name_;
        onChanged();
      }
      if (!other.getUrl().isEmpty()) {
        url_ = other.url_;
        onChanged();
      }
      if (other.getHasCalibrations() != false) {
        setHasCalibrations(other.getHasCalibrations());
      }
      if (other.getIsInactive() != false) {
        setIsInactive(other.getIsInactive());
      }
      onChanged();
      return this;
    }

    public final boolean isInitialized() {
      return true;
    }

    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      edu.kit.ipd.crowdcontrol.objectservice.proto.Platform parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (edu.kit.ipd.crowdcontrol.objectservice.proto.Platform) e.getUnfinishedMessage();
        throw e;
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private java.lang.Object id_ = "";
    /**
     * optional string id = 1;
     */
    public java.lang.String getId() {
      java.lang.Object ref = id_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        id_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string id = 1;
     */
    public com.google.protobuf.ByteString
        getIdBytes() {
      java.lang.Object ref = id_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        id_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string id = 1;
     */
    public Builder setId(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }

      id_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string id = 1;
     */
    public Builder clearId() {

      id_ = getDefaultInstance().getId();
      onChanged();
      return this;
    }
    /**
     * optional string id = 1;
     */
    public Builder setIdBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

      id_ = value;
      onChanged();
      return this;
    }

    private java.lang.Object name_ = "";
    /**
     * optional string name = 2;
     */
    public java.lang.String getName() {
      java.lang.Object ref = name_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        name_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string name = 2;
     */
    public com.google.protobuf.ByteString
        getNameBytes() {
      java.lang.Object ref = name_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        name_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string name = 2;
     */
    public Builder setName(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }

      name_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string name = 2;
     */
    public Builder clearName() {

      name_ = getDefaultInstance().getName();
      onChanged();
      return this;
    }
    /**
     * optional string name = 2;
     */
    public Builder setNameBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

      name_ = value;
      onChanged();
      return this;
    }

    private java.lang.Object url_ = "";
    /**
     * optional string url = 3;
     */
    public java.lang.String getUrl() {
      java.lang.Object ref = url_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        url_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string url = 3;
     */
    public com.google.protobuf.ByteString
        getUrlBytes() {
      java.lang.Object ref = url_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        url_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string url = 3;
     */
    public Builder setUrl(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }

      url_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string url = 3;
     */
    public Builder clearUrl() {

      url_ = getDefaultInstance().getUrl();
      onChanged();
      return this;
    }
    /**
     * optional string url = 3;
     */
    public Builder setUrlBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

      url_ = value;
      onChanged();
      return this;
    }

    private boolean hasCalibrations_ ;
    /**
     * optional bool has_calibrations = 4;
     */
    public boolean getHasCalibrations() {
      return hasCalibrations_;
    }
    /**
     * optional bool has_calibrations = 4;
     */
    public Builder setHasCalibrations(boolean value) {

      hasCalibrations_ = value;
      onChanged();
      return this;
    }
    /**
     * optional bool has_calibrations = 4;
     */
    public Builder clearHasCalibrations() {

      hasCalibrations_ = false;
      onChanged();
      return this;
    }

    private boolean isInactive_ ;
    /**
     * optional bool is_inactive = 5;
     */
    public boolean getIsInactive() {
      return isInactive_;
    }
    /**
     * optional bool is_inactive = 5;
     */
    public Builder setIsInactive(boolean value) {

      isInactive_ = value;
      onChanged();
      return this;
    }
    /**
     * optional bool is_inactive = 5;
     */
    public Builder clearIsInactive() {

      isInactive_ = false;
      onChanged();
      return this;
    }
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    // @@protoc_insertion_point(builder_scope:crowdcontrol.Platform)
  }

  // @@protoc_insertion_point(class_scope:crowdcontrol.Platform)
  private static final edu.kit.ipd.crowdcontrol.objectservice.proto.Platform DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new edu.kit.ipd.crowdcontrol.objectservice.proto.Platform();
  }

  public static edu.kit.ipd.crowdcontrol.objectservice.proto.Platform getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<Platform>
      PARSER = new com.google.protobuf.AbstractParser<Platform>() {
    public Platform parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      try {
        return new Platform(input, extensionRegistry);
      } catch (RuntimeException e) {
        if (e.getCause() instanceof
            com.google.protobuf.InvalidProtocolBufferException) {
          throw (com.google.protobuf.InvalidProtocolBufferException)
              e.getCause();
        }
        throw e;
      }
    }
  };

  public static com.google.protobuf.Parser<Platform> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<Platform> getParserForType() {
    return PARSER;
  }

  public edu.kit.ipd.crowdcontrol.objectservice.proto.Platform getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>pro.beam.api.response.channels (api 1.3.19-SNAPSHOT API)</title>
<meta name="date" content="2015-07-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

pro.beam.api.response.channels

Classes

ShowChannelsResponse

ShowSlugsRepsonse

Enums

ShowChannelsResponse.Attributes

ShowChannelsResponse.Ordering

ShowChannelsResponse.Scope

ShowSlugsRepsonse.OnlineRestriction

redpajama_set_name: RedPajamaGithub


text:
package admit

import (
	"io"

	"k8s.io/kubernetes/pkg/admission"
)

func init() {
	admission.RegisterPlugin("AlwaysAdmit", func(config io.Reader) (admission.Interface, error) {
		return NewAlwaysAdmit(), nil
	})
}

// alwaysAdmit is an implementation of admission.Interface which always says yes to an admit request.
// It is useful in tests and when using kubernetes in an open manner.
type alwaysAdmit struct{}

func (alwaysAdmit) Admit(a admission.Attributes) (err error) {
	return nil
}

func (alwaysAdmit) Handles(operation admission.Operation) bool {
	return true
}

// NewAlwaysAdmit creates a new always admit admission handler
func NewAlwaysAdmit() admission.Interface {
	return new(alwaysAdmit)
}


text:
import logging
from datetime import datetime, timedelta
from datetime import time as dttime
import time
import math

# Our imports
from emission.core.get_database import get_section_db, get_uuid_db
import emission.analysis.result.carbon as carbon
import emission.core.common as common
import emission.net.api.stats as stats
from emission.core.wrapper.user import User
from emission.analysis.result import userclient

# sb375 is a weekly goal - we convert it to daily by dividing by 7
sb375DailyGoal = 40.142892/7

# BEGIN: Code to get and set client specific fields in the profile (currentScore and previousScore)
def getStoredScore(user):
    profile = user.getProfile()
    if profile is None:
        return (0, 0)
    currScore = profile.get('currentScore', 0)
    prevScore = profile.get('previousScore', 0)
    return (prevScore, currScore)

def setScores(user, prevScore, newScore):
    logging.debug("Changing score for user %s from %s to %s" % (user.uuid, prevScore, newScore))
    user.setClientSpecificProfileFields({'previousScore': prevScore,
                                         'currentScore': newScore})
    # TODO: Add a server side stat here so that we can know for sure how the score varies over time
# END: Code to get and set client specific fields in the profile (currentScore and previousScore)

# Returns the components on which the score is based. These will be combined in
# getScore later, but it is useful to see them to decide how to set up the
# weights

def getScoreComponents(user_uuid, start, end):
  # The score is based on the following components:
  # - Percentage of trips classified. We are not auto-classifying high
  # confidence trips, so don't need to handle those here
  user = User.fromUUID(user_uuid)

  pctClassified = common.getClassifiedRatio(user_uuid, start, end)

  (myModeShareCount, avgModeShareCount,
   myModeShareDistance, avgModeShareDistance,
   myModeCarbonFootprint, avgModeCarbonFootprint,
   myModeCarbonFootprintNoLongMotorized, avgModeCarbonFootprintNoLongMotorized,
   myOptimalCarbonFootprint, avgOptimalCarbonFootprint,
   myOptimalCarbonFootprintNoLongMotorized, avgOptimalCarbonFootprintNoLongMotorized) = carbon.getFootprintCompareForRange(user.uuid, start, end)

  carbon.delLongMotorizedModes(myModeShareDistance)
  myAllDrive = carbon.getAllDrive(user.uuid, myModeShareDistance)
  myCarbonFootprintSum = sum(myModeCarbonFootprintNoLongMotorized.values())
  myOptimalFootprintSum = sum(myOptimalCarbonFootprintNoLongMotorized.values())
  logging.debug("myCarbonFootprintSum = %s, myOptimalFootprintSum = %s, myAllDrive = %s" %
        (myCarbonFootprintSum, myOptimalFootprintSum, myAllDrive))
  handleZero = lambda x, y: 0 if y == 0 else float(x)/y
  components = [pctClassified,
                handleZero(myCarbonFootprintSum - myOptimalFootprintSum, myOptimalFootprintSum),
                handleZero(myAllDrive - myCarbonFootprintSum, myAllDrive),
                handleZero(sb375DailyGoal - myCarbonFootprintSum, sb375DailyGoal)]
  return components

def calcScore(componentArr):
  [pctClassified, mineMinusOptimal, allDriveMinusMine, sb375DailyGoal] = componentArr
  # We want the ratio between the three components to be 5 : 3 : 2
  # Let's just convert everything to percentages to keep the ratios consistent
  # Also, we subtract the mineMinusOptimal term, since being way above optimal
  # should lower your score
  return 50 * pctClassified + 30 * allDriveMinusMine - 20 * mineMinusOptimal + 10 * sb375DailyGoal

def getScore(user_uuid, start, end):
    components = getScoreComponents(user_uuid, start, end)
    [pctClassified, mineMinusOptimal, allDriveMinusMine, sb375DailyGoal] = components
    stats.storeResultEntry(user_uuid, stats.STAT_PCT_CLASSIFIED, time.time(), pctClassified)
    stats.storeResultEntry(user_uuid, stats.STAT_MINE_MINUS_OPTIMAL, time.time(), mineMinusOptimal)
    stats.storeResultEntry(user_uuid, stats.STAT_ALL_DRIVE_MINUS_MINE, time.time(), allDriveMinusMine)
    stats.storeResultEntry(user_uuid, stats.STAT_SB375_DAILY_GOAL, time.time(), sb375DailyGoal)
    return calcScore(components)

# Ok so this is a big tricky to get right.
# We want this to be in increments of a day, so that the SB375 target
# calculation makes sense.
# The high level plan is to run it around midnight everyday and update the
# score based on the day that just passed. But what exactly does "around
# midnight" mean?
# It can't be just before midnight, because then we will skip trips around midnight
# I guess we start right after midnight
# Couple of other challenges:
# - What to do about trips that span days?
# - What to do about people in other time zones who have a different midnight?
# In order to handle both of these, we should really have task scheduled from
# the app instead of a cronjob, and have it track the last time it was run. But
# let's do the cheap solution for now so that we know whether it works at all.
def updateScore(user_uuid):
    today = datetime.now().date()
    updateScoreForDay(user_uuid, today)

def updateScoreForDay(user_uuid, today):
    yesterday = today - timedelta(days = 1)
    dayBeforeYesterday = today - timedelta(days = 2)

    dayBeforeYesterdayStart = datetime.combine(dayBeforeYesterday, dttime.min)
    yesterdayStart = datetime.combine(yesterday, dttime.min)
    todayStart = datetime.combine(today, dttime.min)

    user = User.fromUUID(user_uuid)
    (discardedScore, prevScore) = getStoredScore(user)
    # Using score from dayBeforeYesterday instead of yesterday because there is
    # currently a significant lag in the time for e-mission to prompt for
    # entries, so people might not confirm yesterday's trips until sometime
    # today, which means that it won't be counted in their score
    newScore = prevScore + getScore(user_uuid, dayBeforeYesterdayStart, yesterdayStart)
    if newScore < 0:
        newScore = 0
    stats.storeResultEntry(user_uuid, stats.STAT_GAME_SCORE, time.time(), newScore)
    setScores(user, prevScore, newScore)

def getLevel(score):
  if score < 100:
    level = 1
    sublevel = math.floor(score / 20) + 1
  elif score < 1000:
    level = 2
    sublevel = math.floor(score / 200) + 1
  elif score < 10000:
    level = 3
    sublevel = math.floor(score / 2000) + 1
  else:
    # Off the charts, stay at the top image
    level = 3
    sublevel = 5
  return (level, sublevel)

def getFileName(level, sublevel):
    return "level_%s_%s.png" % (int(level), int(sublevel))

def getResult(user_uuid):
  # This is in here, as opposed to the top level as recommended by the PEP
  # because then we don't have to worry about loading bottle in the unit tests
  from bottle import template
  (prevScore, currScore) = getStoredScore(User.fromUUID(user_uuid))
  (level, sublevel) = getLevel(currScore)

  otherCurrScoreList = []
  for user_uuid_dict in get_uuid_db().find({}, {'uuid': 1, '_id': 0}):
    (currPrevScore, currCurrScore) = getStoredScore(User.fromUUID(user_uuid_dict['uuid']))
    otherCurrScoreList.append(currCurrScore)

  otherCurrScoreList.sort()
  renderedTemplate = template("clients/leaderboard/result_template.html",
                               level_picture_filename = getFileName(level, sublevel),
                               prevScore = prevScore,
                               currScore = currScore,
                               otherCurrScoreList = otherCurrScoreList)
  return renderedTemplate

# These are copy/pasted from our first client, the carshare study
def getSectionFilter(uuid):
  # We are not planning to do any filtering for this study. Bring on the worst!
  return []

def clientSpecificSetters(uuid, sectionId, predictedModeMap):
  return None

def getClientConfirmedModeField():
  return None

def runBackgroundTasks(uuid):
  today = datetime.now().date()
  runBackgroundTasksForDay(uuid, today)

def runBackgroundTasksForDay(uuid, today):
  updateScoreForDay(uuid, today)


text:
require_relative '../integration_test_helper'

class FlowVisualisationTest < ActionDispatch::IntegrationTest
  SmartAnswer::FlowRegistry.instance.flows.each do |flow|
    should "be able to visualise #{flow.name}" do
      presenter = GraphPresenter.new(flow)
      assertion_message = "The #{flow.name} Smart Answers isn't visualisable"

      assert presenter.visualisable?, assertion_message
    end
  end
end


text:
import * as Faker from 'faker';

import { ios } from './ios';

declare const global: any;

describe('Node info', () => {

    let warnMock: jest.Mock<any>;

    beforeEach(() => {
        warnMock = jest.fn();
        global.warn = jest.fn(warnMock);
        global.message = jest.fn();
        global.fail = jest.fn();
        global.markdown = jest.fn();
    });

    afterEach(() => {
        global.warn = undefined;
        global.message = undefined;
        global.fail = undefined;
        global.markdown = undefined;
    });

    const plistFile = 'file.plist';

    describe('Cakefile or settings.yml.erb or Fastfile', () => {

        it('Should warn when Cakefile is modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Cakefile', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedCakefileOrSettingsYmlOrFastlane();

            expect(global.warn).toBeCalled();
        });

        it('Should warn when settings.yml.erb is modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['settings.yml.erb', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedCakefileOrSettingsYmlOrFastlane();

            expect(global.warn).toBeCalled();
        });

        it('Should warn when Fastfile is modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Fastfile', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedCakefileOrSettingsYmlOrFastlane();

            expect(global.warn).toBeCalled();
        });

        it('Should warn when Cakefile and settings.yml.erb and Fastfile are modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Cakefile', 'settings.yml.erb', 'Fastfile', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedCakefileOrSettingsYmlOrFastlane();

            expect(global.warn).toHaveBeenCalledTimes(3);
        });

        it('Should not warn when Cakefile or settings.yml.erb or Fastfile are not modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedCakefileOrSettingsYmlOrFastlane();

            expect(global.warn).not.toBeCalled();
        });
    });

    describe('Podfile was modified and Podfile.lock was not', () => {

        it('Should warn when Podfile is modified and Podfile.lock is not', async () => {
            global.danger = {
                git: {
                    modified_files: ['Podfile', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedPodfileAndNotModifiedPodfileLock();

            expect(global.warn).toBeCalled();
        });

        it('Should not warn when Podfile is not modified and Podfile.lock is modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Podfile.lock', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedPodfileAndNotModifiedPodfileLock();

            expect(global.warn).not.toBeCalled();
        });

        it('Should not warn when Podfile and Podfile.lock are modified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Podfile', 'Podfile.lock', 'any'],
                    created_files: ['any'],
                },
            };

            await ios.modifiedPodfileAndNotModifiedPodfileLock();

            expect(global.warn).not.toBeCalled();
        });
    });

    describe('plist checks', () => {

        it('Should warn if a plist file has ATS exception', async () => {
            global.danger = {
                git: {
                    modified_files: plistFile,
                    created_files: [],
                    diffForFile: jest.fn(() => ({
                        added: `
                            some text
                            <key>NSAppTransportSecurity</key>
                            more text
                        `,
                    })),
                },
            };

            await ios.atsException();

            expect(global.warn).toBeCalled();
        });

        it('Should warn if landscape orientation is set in plist', async () => {
            global.danger = {
                git: {
                    modified_files: plistFile,
                    created_files: [],
                    diffForFile: jest.fn(() => ({
                        added: `
                            some text
                            <string>UIInterfaceOrientationLandscape</string>
                            more text
                        `,
                    })),
                },
            };

            await ios.landscapeOrientation();

            expect(global.warn).toBeCalled();
        });

    });

    describe('podfile checks', () => {

        it('Should warn when pods are loaded from external git repos', async () => {
            global.danger = {
                git: {
                    modified_files: ['Podfile'],
                    created_files: [],
                    diffForFile: jest.fn(() => ({
                        added: `
                            pod 'GoogleAnalytics',      '3.14.0'
                            pod 'TQ1SDK',               :git => 'https://github.com/tq1/taqtile-sdk-ios.git'
                            pod 'Firebase/Core',        '4.0.0'
                        `,
                    })),
                },
            };

            await ios.podFromExternalRepo();

            expect(global.warn).toBeCalled();
        });

        it('Should warn when pods do not have version specified', async () => {
            global.danger = {
                git: {
                    modified_files: ['Podfile'],
                    created_files: [],
                    diffForFile: jest.fn(() => ({
                        added: `
                            pod 'HCSStarRatingView',        '~> 1.5'
                            pod 'Alamofire',                '4.6.0'
                            pod 'AlamofireImage',           '3.3.0'
                        `,
                    })),
                },
            };

            await ios.podWithoutFixedVersion();

            expect(global.warn).toBeCalled();
        });

    });
});


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/usb/cros_usb_detector.h"

#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
#include "chrome/browser/chromeos/crostini/crostini_pref_names.h"
#include "chrome/browser/chromeos/crostini/crostini_test_helper.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/notifications/notification_display_service.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/system_notification_helper.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_cicerone_client.h"
#include "chromeos/dbus/fake_concierge_client.h"
#include "components/arc/arc_util.h"
#include "services/device/public/cpp/test/fake_usb_device_info.h"
#include "services/device/public/cpp/test/fake_usb_device_manager.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#include "services/device/public/mojom/usb_manager.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/message_center/public/cpp/notification.h"
#include "url/gurl.h"

namespace {

const char* kProfileName = "test@example.com";

// USB device product name.
const char* kProductName_1 = "Google Product A";
const char* kProductName_2 = "Google Product B";
const char* kProductName_3 = "Google Product C";
const char* kUnknownProductName = "USB device";
const char* kManufacturerName = "Google";

const int kUsbConfigWithInterfaces = 1;

struct InterfaceCodes {
  InterfaceCodes(uint8_t device_class,
                 uint8_t subclass_code,
                 uint8_t protocol_code)
      : device_class(device_class),
        subclass_code(subclass_code),
        protocol_code(protocol_code) {}
  uint8_t device_class;
  uint8_t subclass_code;
  uint8_t protocol_code;
};

scoped_refptr<device::FakeUsbDeviceInfo> CreateTestDeviceFromCodes(
    uint8_t device_class,
    const std::vector<InterfaceCodes>& interface_codes) {
  auto config = device::mojom::UsbConfigurationInfo::New();
  config->configuration_value = kUsbConfigWithInterfaces;
  // The usb_utils do not filter by device class, only by configurations, and
  // the FakeUsbDeviceInfo does not set up configurations for a fake device's
  // class code. This helper sets up a configuration to match a devices class
  // code so that USB devices can be filtered out.
  for (size_t i = 0; i < interface_codes.size(); ++i) {
    auto alternate = device::mojom::UsbAlternateInterfaceInfo::New();
    alternate->alternate_setting = 0;
    alternate->class_code = interface_codes[i].device_class;
    alternate->subclass_code = interface_codes[i].subclass_code;
    alternate->protocol_code = interface_codes[i].protocol_code;

    auto interface = device::mojom::UsbInterfaceInfo::New();
    interface->interface_number = i;
    interface->alternates.push_back(std::move(alternate));

    config->interfaces.push_back(std::move(interface));
  }

  std::vector<device::mojom::UsbConfigurationInfoPtr> configs;
  configs.push_back(std::move(config));

  scoped_refptr<device::FakeUsbDeviceInfo> device =
      new device::FakeUsbDeviceInfo(/*vendor_id*/ 0, /*product_id*/ 1,
                                    device_class, std::move(configs));
  device->SetActiveConfig(kUsbConfigWithInterfaces);
  return device;
}

scoped_refptr<device::FakeUsbDeviceInfo> CreateTestDeviceOfClass(
    uint8_t device_class) {
  return CreateTestDeviceFromCodes(device_class,
                                   {InterfaceCodes(device_class, 0xff, 0xff)});
}

class TestCrosUsbDeviceObserver : public chromeos::CrosUsbDeviceObserver {
 public:
  void OnUsbDevicesChanged() override { ++notify_count_; }

  int notify_count() const { return notify_count_; }

 private:
  int notify_count_ = 0;
};

}  // namespace

class CrosUsbDetectorTest : public BrowserWithTestWindowTest {
 public:
  CrosUsbDetectorTest() {
    chromeos::DBusThreadManager::Initialize();
    fake_cicerone_client_ = static_cast<chromeos::FakeCiceroneClient*>(
        chromeos::DBusThreadManager::Get()->GetCiceroneClient());
    fake_concierge_client_ = static_cast<chromeos::FakeConciergeClient*>(
        chromeos::DBusThreadManager::Get()->GetConciergeClient());
    cros_usb_detector_ = std::make_unique<chromeos::CrosUsbDetector>();
  }

  ~CrosUsbDetectorTest() override { chromeos::DBusThreadManager::Shutdown(); }

  TestingProfile* CreateProfile() override {
    return profile_manager()->CreateTestingProfile(kProfileName);
  }

  void SetUp() override {
    BrowserWithTestWindowTest::SetUp();
    crostini_test_helper_.reset(new crostini::CrostiniTestHelper(profile()));
    scoped_feature_list_.InitWithFeatures(
        {chromeos::features::kCrostiniUsbAllowUnsupported}, {});

    TestingBrowserProcess::GetGlobal()->SetSystemNotificationHelper(
        std::make_unique<SystemNotificationHelper>());
    display_service_ = std::make_unique<NotificationDisplayServiceTester>(
        nullptr /* profile */);

    // Set a fake USB device manager before ConnectToDeviceManager().
    mojo::PendingRemote<device::mojom::UsbDeviceManager> device_manager;
    device_manager_.AddReceiver(
        device_manager.InitWithNewPipeAndPassReceiver());
    chromeos::CrosUsbDetector::Get()->SetDeviceManagerForTesting(
        std::move(device_manager));
    // Create a default VM instance which is running.
    crostini::CrostiniManager::GetForProfile(profile())->AddRunningVmForTesting(
        crostini::kCrostiniDefaultVmName);
  }

  void TearDown() override {
    scoped_feature_list_.Reset();
    crostini_test_helper_.reset();
    BrowserWithTestWindowTest::TearDown();
  }

  void ConnectToDeviceManager() {
    chromeos::CrosUsbDetector::Get()->ConnectToDeviceManager();
  }

  void AttachDeviceToVm(const std::string& vm_name, const std::string& guid) {
    cros_usb_detector_->AttachUsbDeviceToVm(
        vm_name, guid,
        base::BindOnce([](bool result) { EXPECT_TRUE(result); }));
    base::RunLoop().RunUntilIdle();
  }

  void DetachDeviceFromVm(const std::string& vm_name, const std::string& guid) {
    cros_usb_detector_->DetachUsbDeviceFromVm(
        vm_name, guid,
        base::BindOnce([](bool result) { EXPECT_TRUE(result); }));
    base::RunLoop().RunUntilIdle();
  }

  chromeos::CrosUsbDeviceInfo GetSingleDeviceInfo() const {
    auto devices = cros_usb_detector_->GetConnectedDevices();
    EXPECT_EQ(1U, devices.size());
    return devices.size() == 1 ? devices.front()
                               : chromeos::CrosUsbDeviceInfo();
  }

  chromeos::CrosUsbDeviceInfo GetSingleDeviceSharableWithCrostini() const {
    auto devices = cros_usb_detector_->GetDevicesSharableWithCrostini();
    EXPECT_EQ(1U, devices.size());
    if (devices.empty()) {
      return chromeos::CrosUsbDeviceInfo();
    }
    EXPECT_TRUE(devices.front().sharable_with_crostini);
    return devices.front();
  }

  static bool IsSharedWithCrostini(
      const chromeos::CrosUsbDeviceInfo& device_info) {
    const auto it = device_info.vm_sharing_info.find(
        crostini::kCrostiniDefaultVmName);
    return it != device_info.vm_sharing_info.end() && it->second.shared;
  }

 protected:
  base::string16 connection_message(const char* product_name) {
    return base::ASCIIToUTF16(base::StringPrintf(
        "Open Settings to connect %s to Linux", product_name));
  }

  base::string16 expected_title() {
    return base::ASCIIToUTF16("USB device detected");
  }

  device::FakeUsbDeviceManager device_manager_;
  std::unique_ptr<NotificationDisplayServiceTester> display_service_;

  // Owned by chromeos::DBusThreadManager
  chromeos::FakeCiceroneClient* fake_cicerone_client_;
  chromeos::FakeConciergeClient* fake_concierge_client_;

  TestCrosUsbDeviceObserver usb_device_observer_;
  std::unique_ptr<chromeos::CrosUsbDetector> cros_usb_detector_;

  base::test::ScopedFeatureList scoped_feature_list_;

  std::unique_ptr<crostini::CrostiniTestHelper> crostini_test_helper_;

 private:
  DISALLOW_COPY_AND_ASSIGN(CrosUsbDetectorTest);
};

TEST_F(CrosUsbDetectorTest, UsbDeviceAddedAndRemoved) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());

  base::Optional<message_center::Notification> notification =
      display_service_->GetNotification(notification_id);
  ASSERT_TRUE(notification);

  EXPECT_EQ(expected_title(), notification->title());
  EXPECT_EQ(connection_message(kProductName_1), notification->message());
  EXPECT_TRUE(notification->delegate());

  device_manager_.RemoveDevice(device);
  base::RunLoop().RunUntilIdle();
  // Device is removed, so notification should be removed too.
  EXPECT_FALSE(display_service_->GetNotification(notification_id));
}

TEST_F(CrosUsbDetectorTest, UsbNotificationClicked) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());

  base::Optional<message_center::Notification> notification =
      display_service_->GetNotification(notification_id);
  ASSERT_TRUE(notification);

  notification->delegate()->Click(0, base::nullopt);
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(fake_concierge_client_->attach_usb_device_called());
  // Notification should close.
  EXPECT_FALSE(display_service_->GetNotification(notification_id));
}

TEST_F(CrosUsbDetectorTest, UsbDeviceClassBlockedAdded) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  scoped_refptr<device::FakeUsbDeviceInfo> device =
      CreateTestDeviceOfClass(/* USB_CLASS_HID */ 0x03);

  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());
  ASSERT_FALSE(display_service_->GetNotification(notification_id));
  EXPECT_EQ(0U, cros_usb_detector_->GetDevicesSharableWithCrostini().size());
}

TEST_F(CrosUsbDetectorTest, UsbDeviceClassAdbAdded) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  const int kAdbClass = 0xff;
  const int kAdbSubclass = 0x42;
  const int kAdbProtocol = 0x1;
  // Adb interface as well as a forbidden interface
  scoped_refptr<device::FakeUsbDeviceInfo> device = CreateTestDeviceFromCodes(
      /* USB_CLASS_HID */ 0x03,
      {InterfaceCodes(kAdbClass, kAdbSubclass, kAdbProtocol),
       InterfaceCodes(0x03, 0xff, 0xff)});

  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());
  ASSERT_TRUE(display_service_->GetNotification(notification_id));
  // ADB interface wins.
  EXPECT_EQ(1U, cros_usb_detector_->GetDevicesSharableWithCrostini().size());
}

TEST_F(CrosUsbDetectorTest, UsbDeviceClassWithoutNotificationAdded) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  scoped_refptr<device::FakeUsbDeviceInfo> device =
      CreateTestDeviceOfClass(/* USB_CLASS_AUDIO */ 0x01);

  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());
  ASSERT_FALSE(display_service_->GetNotification(notification_id));
  EXPECT_EQ(1U, cros_usb_detector_->GetDevicesSharableWithCrostini().size());
}

TEST_F(CrosUsbDetectorTest, UsbDeviceWithoutProductNameAddedAndRemoved) {
  std::string product_name;
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, product_name, "002");
  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());

  base::Optional<message_center::Notification> notification =
      display_service_->GetNotification(notification_id);
  ASSERT_TRUE(notification);

  EXPECT_EQ(expected_title(), notification->title());
  EXPECT_EQ(connection_message("USB device from Google"),
            notification->message());
  EXPECT_TRUE(notification->delegate());

  device_manager_.RemoveDevice(device);
  base::RunLoop().RunUntilIdle();
  // Device is removed, so notification should be removed too.
  EXPECT_FALSE(display_service_->GetNotification(notification_id));
}

TEST_F(CrosUsbDetectorTest,
       UsbDeviceWithoutProductNameOrManufacturerNameAddedAndRemoved) {
  std::string product_name;
  std::string manufacturer_name;
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, manufacturer_name, product_name, "002");
  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());

  base::Optional<message_center::Notification> notification =
      display_service_->GetNotification(notification_id);
  ASSERT_TRUE(notification);
  EXPECT_EQ(expected_title(), notification->title());
  EXPECT_EQ(connection_message(kUnknownProductName), notification->message());
  EXPECT_TRUE(notification->delegate());

  device_manager_.RemoveDevice(device);
  base::RunLoop().RunUntilIdle();
  // Device is removed, so notification should be removed too.
  EXPECT_FALSE(display_service_->GetNotification(notification_id));
}

TEST_F(CrosUsbDetectorTest, UsbDeviceWasThereBeforeAndThenRemoved) {
  // USB device was added before cros_usb_detector was created.
  auto device = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device);
  base::RunLoop().RunUntilIdle();

  std::string notification_id =
      chromeos::CrosUsbDetector::MakeNotificationId(device->guid());

  EXPECT_FALSE(display_service_->GetNotification(notification_id));

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  device_manager_.RemoveDevice(device);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id));
}

TEST_F(
    CrosUsbDetectorTest,
    ThreeUsbDevicesWereThereBeforeAndThenRemovedBeforeUsbDetectorWasCreated) {
  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  std::string notification_id_1 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_1->guid());

  auto device_2 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      3, 4, kManufacturerName, kProductName_2, "005");
  std::string notification_id_2 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_2->guid());

  auto device_3 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      6, 7, kManufacturerName, kProductName_3, "008");
  std::string notification_id_3 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_3->guid());

  // Three usb devices were added and removed before cros_usb_detector was
  // created.
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.AddDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));

  device_manager_.RemoveDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.RemoveDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));
}

TEST_F(CrosUsbDetectorTest,
       ThreeUsbDevicesWereThereBeforeAndThenRemovedAfterUsbDetectorWasCreated) {
  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  std::string notification_id_1 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_1->guid());

  auto device_2 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      3, 4, kManufacturerName, kProductName_2, "005");
  std::string notification_id_2 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_2->guid());

  auto device_3 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      6, 7, kManufacturerName, kProductName_3, "008");
  std::string notification_id_3 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_3->guid());

  // Three usb devices were added before cros_usb_detector was created.
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.AddDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));

  device_manager_.RemoveDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.RemoveDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));
}

TEST_F(CrosUsbDetectorTest,
       TwoUsbDevicesWereThereBeforeAndThenRemovedAndNewUsbDeviceAdded) {
  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  std::string notification_id_1 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_1->guid());

  auto device_2 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      3, 4, kManufacturerName, kProductName_2, "005");
  std::string notification_id_2 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_2->guid());

  // Two usb devices were added before cros_usb_detector was created.
  device_manager_.AddDevice(device_1);
  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.RemoveDevice(device_1);
  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification =
      display_service_->GetNotification(notification_id_2);
  ASSERT_TRUE(notification);

  EXPECT_EQ(expected_title(), notification->title());
  EXPECT_EQ(connection_message(kProductName_2), notification->message());
  EXPECT_TRUE(notification->delegate());

  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));
}

TEST_F(CrosUsbDetectorTest, ThreeUsbDevicesAddedAndRemoved) {
  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  std::string notification_id_1 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_1->guid());

  auto device_2 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      3, 4, kManufacturerName, kProductName_2, "005");
  std::string notification_id_2 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_2->guid());

  auto device_3 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      6, 7, kManufacturerName, kProductName_3, "008");
  std::string notification_id_3 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_3->guid());

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_1 =
      display_service_->GetNotification(notification_id_1);
  ASSERT_TRUE(notification_1);

  EXPECT_EQ(expected_title(), notification_1->title());
  EXPECT_EQ(connection_message(kProductName_1), notification_1->message());
  EXPECT_TRUE(notification_1->delegate());

  device_manager_.RemoveDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_2 =
      display_service_->GetNotification(notification_id_2);
  ASSERT_TRUE(notification_2);

  EXPECT_EQ(expected_title(), notification_2->title());
  EXPECT_EQ(connection_message(kProductName_2), notification_2->message());
  EXPECT_TRUE(notification_2->delegate());

  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.AddDevice(device_3);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_3 =
      display_service_->GetNotification(notification_id_3);
  ASSERT_TRUE(notification_3);

  EXPECT_EQ(expected_title(), notification_3->title());
  EXPECT_EQ(connection_message(kProductName_3), notification_3->message());
  EXPECT_TRUE(notification_3->delegate());

  device_manager_.RemoveDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));
}

TEST_F(CrosUsbDetectorTest, ThreeUsbDeviceAddedAndRemovedDifferentOrder) {
  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  std::string notification_id_1 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_1->guid());

  auto device_2 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      3, 4, kManufacturerName, kProductName_2, "005");
  std::string notification_id_2 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_2->guid());

  auto device_3 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      6, 7, kManufacturerName, kProductName_3, "008");
  std::string notification_id_3 =
      chromeos::CrosUsbDetector::MakeNotificationId(device_3->guid());

  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_1 =
      display_service_->GetNotification(notification_id_1);
  ASSERT_TRUE(notification_1);

  EXPECT_EQ(expected_title(), notification_1->title());
  EXPECT_EQ(connection_message(kProductName_1), notification_1->message());
  EXPECT_TRUE(notification_1->delegate());

  device_manager_.AddDevice(device_2);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_2 =
      display_service_->GetNotification(notification_id_2);
  ASSERT_TRUE(notification_2);

  EXPECT_EQ(expected_title(), notification_2->title());
  EXPECT_EQ(connection_message(kProductName_2), notification_2->message());
  EXPECT_TRUE(notification_2->delegate());

  device_manager_.RemoveDevice(device_2);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_2));

  device_manager_.AddDevice(device_3);
  base::RunLoop().RunUntilIdle();
  base::Optional<message_center::Notification> notification_3 =
      display_service_->GetNotification(notification_id_3);
  ASSERT_TRUE(notification_3);

  EXPECT_EQ(expected_title(), notification_3->title());
  EXPECT_EQ(connection_message(kProductName_3), notification_3->message());
  EXPECT_TRUE(notification_3->delegate());

  device_manager_.RemoveDevice(device_1);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_1));

  device_manager_.RemoveDevice(device_3);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(display_service_->GetNotification(notification_id_3));
}

TEST_F(CrosUsbDetectorTest, AttachDeviceToVmSetsGuestPort) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();
  auto device_info = GetSingleDeviceInfo();

  AttachDeviceToVm(crostini::kCrostiniDefaultVmName, device_info.guid);
  EXPECT_FALSE(
      chromeos::CrosUsbDeviceInfo::VmSharingInfo().guest_port.has_value());
  device_info = GetSingleDeviceSharableWithCrostini();
  EXPECT_EQ(1U, device_info.vm_sharing_info.size());
  auto crostini_info =
      device_info.vm_sharing_info[crostini::kCrostiniDefaultVmName];
  EXPECT_TRUE(crostini_info.shared);
  EXPECT_TRUE(crostini_info.guest_port.has_value());
  EXPECT_EQ(0U, *crostini_info.guest_port);
}

TEST_F(CrosUsbDetectorTest, AttachingAlreadyAttachedDeviceIsANoOp) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();

  auto device_info = GetSingleDeviceInfo();
  EXPECT_EQ(0U, device_info.vm_sharing_info.size());

  AttachDeviceToVm(crostini::kCrostiniDefaultVmName, device_info.guid);
  cros_usb_detector_->AddUsbDeviceObserver(&usb_device_observer_);
  AttachDeviceToVm(crostini::kCrostiniDefaultVmName, device_info.guid);
  EXPECT_EQ(0, usb_device_observer_.notify_count());
  device_info = GetSingleDeviceInfo();
  EXPECT_EQ(1U, device_info.vm_sharing_info.size());
  EXPECT_TRUE(IsSharedWithCrostini(device_info));
}

TEST_F(CrosUsbDetectorTest, DeviceCanBeAttachedToArcVmWhenCrostiniIsDisabled) {
  scoped_feature_list_.Reset();  // Clears Crostini flags.
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();

  AttachDeviceToVm(arc::kArcVmName, GetSingleDeviceInfo().guid);
  EXPECT_TRUE(GetSingleDeviceInfo().vm_sharing_info[arc::kArcVmName].shared);
}

TEST_F(CrosUsbDetectorTest, SharedDevicesGetAttachedOnStartup) {
  ConnectToDeviceManager();
  base::RunLoop().RunUntilIdle();

  auto device_1 = base::MakeRefCounted<device::FakeUsbDeviceInfo>(
      0, 1, kManufacturerName, kProductName_1, "002");
  device_manager_.AddDevice(device_1);
  base::RunLoop().RunUntilIdle();

  cros_usb_detector_->ConnectSharedDevicesOnVmStartup(
      crostini::kCrostiniDefaultVmName);
  base::RunLoop().RunUntilIdle();
  // No device is shared with Crostini, yet.
  EXPECT_EQ(0, usb_device_observer_.notify_count());
  auto device = GetSingleDeviceInfo();
  EXPECT_EQ(0U, device.vm_sharing_info.size());

  device = GetSingleDeviceInfo();
  AttachDeviceToVm(crostini::kCrostiniDefaultVmName, device.guid);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(IsSharedWithCrostini(GetSingleDeviceInfo()));

  cros_usb_detector_->AddUsbDeviceObserver(&usb_device_observer_);
  cros_usb_detector_->ConnectSharedDevicesOnVmStartup(
      crostini::kCrostiniDefaultVmName);
  base::RunLoop().RunUntilIdle();
  // Attaching an already attached device is a no-op currently.
  EXPECT_EQ(0, usb_device_observer_.notify_count());
  EXPECT_TRUE(IsSharedWithCrostini(GetSingleDeviceInfo()));
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;

using Internal.TypeSystem;

namespace ILCompiler.DependencyAnalysis
{
    using DependencyListEntry = DependencyAnalysisFramework.DependencyNodeCore<NodeFactory>.DependencyListEntry;

    /// <summary>
    /// Represents a node whose dependencies are runtime determined (they depend on the generic context)
    /// and which provides means to compute concrete dependencies when given the generic context.
    /// </summary>
    public interface INodeWithRuntimeDeterminedDependencies
    {
        /// <summary>
        /// Instantiates runtime determined dependencies of this node using the supplied generic context.
        /// </summary>
        IEnumerable<DependencyListEntry> InstantiateDependencies(NodeFactory factory, Instantiation typeInstantiation, Instantiation methodInstantiation);
    }
}


text:
require 'spec_helper'

describe Redch::Setup do
  let(:device_id) { 1 }
  let(:location) { [1.2, 2.1] }
  let(:required_fields) { [:id, :sensor_type, :observation_type, :foi_type, :observable_prop_name, :observable_prop] }

  let(:file) { double 'file' }
  let(:filename) { Redch::Config.filename }

  before do
    allow(File).to receive(:open).with(filename, 'w').and_yield(file)
    allow(file).to receive(:write)
  end

  describe '#new' do
    it 'configures the SOS client' do
      expect(Redch::SOS::Client).to receive(:configure)
      Redch::Setup.new
    end

    it 'instanciates a SOS::Client Sensor' do
      expect(Redch::SOS::Client::Sensor).to receive(:new)
      Redch::Setup.new
    end
  end

  describe '#sensor' do
    it 'builds up a sensor payload' do
      sensor = subject.sensor(device_id)
      expect([sensor.keys]).to include required_fields
    end
  end

  describe '#register_device' do
    it 'requests to store the device in the SOS' do
      expect_any_instance_of(Redch::SOS::Client::Sensor).to receive(:create)
      subject.register_device(device_id, location)
    end
  end

  describe '#done?' do
    it 'returns true if the configuration can be loaded' do
      allow(Redch::Config).to receive(:load)
      expect(subject.done?).to be true
    end

    it 'returns false otherwise' do
      allow(Redch::Config).to receive(:load).and_raise(StandardError)
      expect(subject.done?).to be false
    end
  end

  describe '#run' do
    context 'when there\'s no stored configuration' do
      let(:config) { Hashr.new }

      before do
        allow(Redch::Config).to receive(:load).and_raise(StandardError.new)
      end

      it 'raises if either device_id or location are not set' do
        expect { subject.run }.to raise_error StandardError
      end

      context 'when all params are set' do
        before :each do
          subject.device_id= device_id
          subject.location= location
        end

        it 'requests to create the sensor in the SOS' do
          expect_any_instance_of(Redch::SOS::Client::Sensor).to receive(:create)
          subject.run
        end

        it 'stores the configuration on successful request' do
          allow_any_instance_of(Redch::SOS::Client::Sensor).to receive(:create)
          expect(Redch::Config).to receive(:save).with(subject.config)
          subject.run
        end

        context 'when the sensor can\'t be created' do
          before do
            allow_any_instance_of(Redch::SOS::Client::Sensor).to receive(:create).and_raise
          end

          it 'does not store the configuration' do
            expect(Redch::Config).to_not receive(:save)
            expect { subject.run }.to raise_error
          end
        end

      end
    end

    context 'when the stored configuration is not empty' do
      let(:config) { Hashr.new(sos: { location: location, device_id: device_id }) }

      before do
        allow(Redch::Config).to receive(:load).and_return(config)
      end

      it 'loads the device_id from it' do
        expect(device_id).to eq config.sos.device_id
        subject.run
      end

      it 'loads the location from it' do
        expect(location).to eq config.sos.location
        subject.run
      end

      it 'does not request to create the sensor in the SOS again' do
        expect_any_instance_of(Redch::SOS::Client::Sensor).to_not receive(:create)
        subject.run
      end
    end
  end

end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Lucha Libre Style: Faster Stronger"</title>
		<link>http://bvs.wikidot.com/forum/t-174238/lucha-libre-style:faster-stronger</link>
		<description>Posts in the discussion thread "Lucha Libre Style: Faster Stronger"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:59:15 +0000</lastBuildDate>

				</channel>
</rss>


text:
module Discordrb
  # Server emoji
  class Emoji
    include IDObject

    # @return [String] the emoji name
    attr_reader :name

    # @return [Server, nil] the server of this emoji
    attr_reader :server

    # @return [Array<Role>, nil] roles this emoji is active for, or nil if the emoji's server is unknown
    attr_reader :roles

    # @return [true, false] if the emoji is animated
    attr_reader :animated
    alias_method :animated?, :animated

    # @!visibility private
    def initialize(data, bot, server = nil)
      @bot = bot
      @roles = nil

      @name = data['name']
      @server = server
      @id = data['id'].nil? ? nil : data['id'].to_i
      @animated = data['animated']

      process_roles(data['roles']) if server
    end

    # ID or name based comparison
    def ==(other)
      return false unless other.is_a? Emoji
      return Discordrb.id_compare(@id, other) if @id

      name == other.name
    end

    alias_method :eql?, :==

    # @return [String] the layout to mention it (or have it used) in a message
    def mention
      return name if id.nil?

      "<#{'a' if animated}:#{name}:#{id}>"
    end

    alias_method :use, :mention
    alias_method :to_s, :mention

    # @return [String] the layout to use this emoji in a reaction
    def to_reaction
      return name if id.nil?

      "#{name}:#{id}"
    end

    # @return [String] the icon URL of the emoji
    def icon_url
      API.emoji_icon_url(id)
    end

    # The inspect method is overwritten to give more useful output
    def inspect
      "<Emoji name=#{name} id=#{id} animated=#{animated}>"
    end

    # @!visibility private
    def process_roles(roles)
      @roles = []
      return unless roles

      roles.each do |role_id|
        role = server.role(role_id)
        @roles << role
      end
    end
  end
end


text:
public class Test25 {

    public static void main(String[] args) {
        Lestvica lestvica = new Lestvica(new Nota(2, 8), 6);
        System.out.println(lestvica.toString());
    }
}


text:
/*jslint newcap: true, browser: true */
/*global angular, iSeeIt*/
iSeeIt.mainApp.controller('RegisterController', ['$rootScope', '$scope', '$state',
    function ($rootScope, $scope, $state) {
        'use strict';

        $scope.registerForm = {};
        $scope.user = {};

        /**
         * Method used to register a new user
         */
        $scope.register = function () {
            $scope.submitted = true;
            console.log("the user has been register", $scope.user);
        };

        $scope.setFullRegister = function () {
            $rootScope.fullRegister = true;
        };

        $rootScope.fullRegister = false;

        $scope.cancel = function () {
            $state.go('anon.login');
        };
    }]);


text:
//
//  AppDelegate.m
//  ALLocalLife
//
//  Created by 王可成 on 15/11/21.
//  Copyright © 2015年 AL. All rights reserved.
/*-----------------------------------*/
//  umeng:5655dea1e0f55a9608003239
/*-----------------------------------*/
#import "AppDelegate.h"
#import "ALTabBarController.h"
#import "ALGuideViewController.h"
//#import "UMSocial.h"
//#import "UMSocialSinaSSOHandler.h"
#import "SSKeychain.h"
#import "ALBasicViewController.h"
#import "ALNavigationController.h"

@interface AppDelegate ()<WeiboSDKDelegate>

@end

@implementation AppDelegate
@synthesize wbtoken;
@synthesize wbCurrentUserID;
@synthesize wbRefreshToken;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    self.window = [[UIWindow alloc] initWithFrame:kScreenBounds];

    [self chooseRootViewController];

    //第三方登录授权
//    [self SSOAuth];
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kSinaWeiBoAppKey];
    [self.window makeKeyAndVisible];

    return YES;
}

-(void)chooseRootViewController{

    BOOL isFirstTime = [[NSUserDefaults standardUserDefaults] boolForKey:kFirstLogin];

    ALTabBarController *tabBarVc = [[ALTabBarController alloc] init];

    self.tabVc = tabBarVc;

    if (!isFirstTime) {
        self.window.rootViewController = tabBarVc;
    }else{
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

        ALGuideViewController *guideView = [[ALGuideViewController alloc] initWithCollectionViewLayout:layout];
        self.window.rootViewController = guideView;

        guideView.loginBlock = ^(BOOL login){
            self.window.rootViewController = tabBarVc;
        };

    }
}

//umeng 未使用
-(void)SSOAuth{

//    [UMSocialData setAppKey:@"5655dea1e0f55a9608003239"];
//
//    //打开新浪微博的SSO开关,设置新浪微博回调地址,这里必须要和你在新浪微博后台设置的回调地址一致。若在新浪后台设置我们的回调地址,"http://sns.whalecloud.com/sina2/callback",这里可以传nil ,需要 #import "UMSocialSinaHandler.h"

//    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"2866356252" RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];

}

#pragma mark - Sina WeiboSDKDelegate
//
//-(WBMessageObject *)messageShareToWeibo{
//    WBMessageObject *message = [WBMessageObject message];
//
//    message.text = @"微博分享测试";
//
//    return message;
//}
//
-(void)didReceiveWeiboRequest:(WBBaseRequest *)request{
//    WBProvideMessageForWeiboResponse *response = [WBProvideMessageForWeiboResponse responseWithMessage:[self messageShareToWeibo]];
//    [WeiboSDK sendResponse:response];
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    //分享到微博
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = NSLocalizedString(@"发送结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];

        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
        [alert show];
    }
    //SSO授权登录
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = NSLocalizedString(@"认证结果", nil);
        NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@",
                             NSLocalizedString(@"响应状态", nil), (int)response.statusCode,
                             [(WBAuthorizeResponse *)response userID],
                             [(WBAuthorizeResponse *)response accessToken],
                             NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo,
                             NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                              otherButtonTitles:nil];

        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
        self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
        [alert show];
        //如果登录成功,则退出登录页面,否则不退出

        if ((int)response.statusCode == 0) {
            [self loginSucceed];
        }

//        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        ALTabBarController *tabVc = (ALTabBarController *)myDelegate.window.rootViewController;
//        ALNavigationController *navVc = (ALNavigationController *)tabVc.navigationController;

        /*保存用户信息并登录*/
        //保存当前用户名为userID
        [[NSUserDefaults standardUserDefaults] setValue:[(WBAuthorizeResponse *)response userID] forKey:@"username"];

        //在钥匙串中为 userID 设置 密码为 accessToken
        [SSKeychain setPassword:[(WBAuthorizeResponse *)response accessToken] forService:[NSBundle mainBundle].bundleIdentifier account:[(WBAuthorizeResponse *)response userID]];

        //登录过后修改rootVc 的登录状态 <无法自动修改>
        ALTabBarController *tabVc = (ALTabBarController *)self.window.rootViewController;
        UINavigationController *navVc = tabVc.viewControllers[0];
        ALBasicViewController *basicVc = navVc.viewControllers[0];

        [basicVc changeRightBtnWithLoginStatus];
    }
}

-(void)loginSucceed{
    ALTabBarController *tabVc = (ALTabBarController *)self.window.rootViewController;
    UINavigationController *navVc = tabVc.viewControllers[0];
    [navVc popViewControllerAnimated:YES];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
        <button class="pull-right visible-xs dk" ui-toggle-class="show" data-target=".navbar-collapse">

        </button>
        <button class="pull-right visible-xs" ui-toggle-class="off-screen" data-target=".app-aside" ui-scroll-to="app">

        </button>

          {{app.name}}

        <form class="navbar-form navbar-form-sm navbar-left shift" ui-shift="prependTo" target=".navbar-collapse" role="search" ng-controller="TypeaheadDemoCtrl">

              <input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control input-sm bg-light no-border rounded padder" placeholder="Search decks...">

                <button type="submit" class="btn btn-sm bg-light rounded"></button>

        </form>

              {{selectLang}}

                {{label}}

             Login

             Create Account

              {{app.user.username}}

300mb of 500mb used

                <progressbar value="60" class="progress-xs m-b-none bg-white"></progressbar>

                  30%
                  Settings

                Profile

                  new
                  Help

                Logout