text:
/**
 * Container for a voice hint
 * (both input- and result data for voice hint processing)
 *
 * @author ab
 */
package btools.router;

import java.util.ArrayList;
import java.util.List;

public class VoiceHintList {
  private String transportMode;
  int turnInstructionMode;
  List<VoiceHint> list = new ArrayList<VoiceHint>();

  public void setTransportMode(boolean isCar, boolean isBike) {
    transportMode = isCar ? "car" : (isBike ? "bike" : "foot");
  }

  public String getTransportMode() {
    return transportMode;
  }

  public int getLocusRouteType() {
    if ("car".equals(transportMode)) {
      return 0;
    }
    if ("bike".equals(transportMode)) {
      return 5;
    }
    return 3; // foot
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="f6f533cc-cf0e-4a8d-a5b9-545954222977">
    <WebsiteUrl />
    <UserAgent />
    <UserNotes />
    <LastFileSize>66591701</LastFileSize>
    <LastFileDate>2016-02-04T18:42:58.6026271</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <HashVariable />
    <HashType>None</HashType>
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>nopush</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>--nopush</TextualContent>
            <Name>nopush</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <Url />
            <TextualContent>{urlPath:regex:(?<=kodi-)[\d\.]{3,\}(?=-)}</TextualContent>
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>RegularExpression</VariableType>
            <Regex>(?<=ResponseUri: )[^\r\n]+</Regex>
            <Url>{urlPath}</Url>
            <TextualContent />
            <Name>url</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>urlPath</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>RegularExpression</VariableType>
            <Regex>[^ "'<>\*]+\.exe</Regex>
            <Url>http://kodi.tv/download/</Url>
            <Name>urlPath</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>cscript</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>2</TextualContent>
            <Name>cscript</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url64</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <Url />
            <TextualContent>{urlPath}</TextualContent>
            <Name>url64</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation>F:\exe\kodi-15.2-Isengard.exe</PreviousLocation>
    <DeletePreviousFile>false</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2016-02-04T18:42:58.6026271</LastUpdated>
    <TargetPath>{workdir}\</TargetPath>
    <FixedDownloadUrl>{url}</FixedDownloadUrl>
    <Name>kodi</Name>
  </ApplicationJob>
</Jobs>


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.FSharp.Collections;
using FsCheck;

namespace Sharper.C.Testing.Arbitraries
{

public static partial class SystemArbitrariesModule
{
    public static Arbitrary<IEnumerable<A>> AnySeq<A>(Arbitrary<A> arbA)
    =>
        Arb.From
          ( Gen.ListOf(arbA.Generator)
          , Arb.Default.FsList<A>().Shrinker
          )
        .Convert(fsList => fsList.AsEnumerable(), ListModule.OfSeq);
}

}


text:
namespace boost {

namespace detail{

#ifndef BOOST_NO_CXX11_NOEXCEPT

template <class T, class Enable = void>
struct false_or_cpp11_noexcept_move_constructible: public ::boost::false_type {};

template <class T>
struct false_or_cpp11_noexcept_move_constructible <
        T,
        typename ::boost::enable_if_c<sizeof(T) && BOOST_NOEXCEPT_EXPR(T(::boost::declval<T>()))>::type
    > : public ::boost::integral_constant<bool, BOOST_NOEXCEPT_EXPR(T(::boost::declval<T>()))>
{};

template <class T>
struct is_nothrow_move_constructible_imp{
   BOOST_STATIC_CONSTANT(bool, value =
        (::boost::type_traits::ice_and<
            ::boost::type_traits::ice_not< ::boost::is_volatile<T>::value >::value,
            ::boost::type_traits::ice_not< ::boost::is_reference<T>::value >::value,
            ::boost::detail::false_or_cpp11_noexcept_move_constructible<T>::value
        >::value));
};

#else

template <class T>
struct is_nothrow_move_constructible_imp{
    BOOST_STATIC_CONSTANT(bool, value =(
        ::boost::type_traits::ice_and<
            ::boost::type_traits::ice_or<
                ::boost::has_trivial_move_constructor<T>::value,
                ::boost::has_nothrow_copy<T>::value
            >::value,
            ::boost::type_traits::ice_not< ::boost::is_array<T>::value >::value
        >::value));
};

#endif

#ifdef BOOST_NO_NOEXCEPT
//
// The above logic doesn't quite work in the absense of noexcept,
// this is really to improve things with VC13:
//
template <class T>
struct is_nothrow_move_constructible_imp<T&>{ BOOST_STATIC_CONSTANT(bool, value = false); };
#endif

}

BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_nothrow_move_constructible,T,::boost::detail::is_nothrow_move_constructible_imp<T>::value)

BOOST_TT_AUX_BOOL_TRAIT_SPEC1(is_nothrow_move_constructible,void,false)
#ifndef BOOST_NO_CV_VOID_SPECIALIZATIONS
BOOST_TT_AUX_BOOL_TRAIT_SPEC1(is_nothrow_move_constructible,void const,false)
BOOST_TT_AUX_BOOL_TRAIT_SPEC1(is_nothrow_move_constructible,void const volatile,false)
BOOST_TT_AUX_BOOL_TRAIT_SPEC1(is_nothrow_move_constructible,void volatile,false)
#endif

} // namespace boost

#include <boost/type_traits/detail/bool_trait_undef.hpp>

#endif // BOOST_TT_IS_NOTHROW_MOVE_CONSTRUCTIBLE_HPP_INCLUDED


text:
Reports redundant character escape sequences that can be replaced with unescaped characters preserving the meaning.
Many escape sequences that are necessary outside of a character class are redundant inside square brackets [] of a character class.

  Although unescaped opening curly braces { outside of character classes are allowed in some dialects (JavaScript, Python, and so on),
  it can cause confusion and make the pattern less portable, because there are dialects that require escaping curly braces as characters.
  For this reason the inspection does not report escaped opening curly braces.

Example:

  \-\;[\.]

After the quick-fix is applied:

  -;[.]

The Ignore escaped closing brackets '}' and ']' option specifies whether to report \} and \] outside of a character class
when they are allowed to be unescaped by the RegExp dialect.

New in 2017.3


text:
package io.opencensus.exporter.trace.stackdriver;

import static com.google.api.client.util.Preconditions.checkNotNull;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.Credentials;
import com.google.cloud.trace.v2.TraceServiceClient;
import com.google.cloud.trace.v2.TraceServiceSettings;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.cloudtrace.v2.AttributeValue;
import com.google.devtools.cloudtrace.v2.ProjectName;
import com.google.devtools.cloudtrace.v2.Span;
import com.google.devtools.cloudtrace.v2.Span.Attributes;
import com.google.devtools.cloudtrace.v2.Span.Link;
import com.google.devtools.cloudtrace.v2.Span.Links;
import com.google.devtools.cloudtrace.v2.Span.TimeEvent;
import com.google.devtools.cloudtrace.v2.Span.TimeEvent.MessageEvent;
import com.google.devtools.cloudtrace.v2.SpanName;
import com.google.devtools.cloudtrace.v2.TruncatableString;
import com.google.protobuf.BoolValue;
import com.google.protobuf.Int32Value;
import com.google.rpc.Status;
import io.opencensus.common.Function;
import io.opencensus.common.Functions;
import io.opencensus.common.OpenCensusLibraryInformation;
import io.opencensus.common.Scope;
import io.opencensus.common.Timestamp;
import io.opencensus.contrib.resource.util.ResourceUtils;
import io.opencensus.resource.Resource;
import io.opencensus.trace.Annotation;
import io.opencensus.trace.EndSpanOptions;
import io.opencensus.trace.MessageEvent.Type;
import io.opencensus.trace.Sampler;
import io.opencensus.trace.Span.Kind;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.export.SpanData;
import io.opencensus.trace.export.SpanData.TimedEvent;
import io.opencensus.trace.export.SpanData.TimedEvents;
import io.opencensus.trace.export.SpanExporter;
import io.opencensus.trace.samplers.Samplers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/*>>>
import org.checkerframework.checker.nullness.qual.Nullable;
*/

/** Exporter to Stackdriver Trace API v2. */
final class StackdriverV2ExporterHandler extends SpanExporter.Handler {

  private static final Tracer tracer = Tracing.getTracer();
  private static final Sampler probabilitySampler = Samplers.probabilitySampler(0.0001);
  private static final String AGENT_LABEL_KEY = "g.co/agent";
  private static final String AGENT_LABEL_VALUE_STRING =
      "opencensus-java [" + OpenCensusLibraryInformation.VERSION + "]";
  private static final String SERVER_PREFIX = "Recv.";
  private static final String CLIENT_PREFIX = "Sent.";
  private static final AttributeValue AGENT_LABEL_VALUE =
      AttributeValue.newBuilder()
          .setStringValue(toTruncatableStringProto(AGENT_LABEL_VALUE_STRING))
          .build();

  private static final ImmutableMap<String, String> HTTP_ATTRIBUTE_MAPPING =
      ImmutableMap.<String, String>builder()
          .put("http.host", "/http/host")
          .put("http.method", "/http/method")
          .put("http.path", "/http/path")
          .put("http.route", "/http/route")
          .put("http.user_agent", "/http/user_agent")
          .put("http.status_code", "/http/status_code")
          .build();

  // Only initialize once.
  private static final Map<String, AttributeValue> RESOURCE_LABELS =
      getResourceLabels(ResourceUtils.detectResource());

  // Constant functions for AttributeValue.
  private static final Function<String, /*@Nullable*/ AttributeValue> stringAttributeValueFunction =
      new Function<String, /*@Nullable*/ AttributeValue>() {
        @Override
        public AttributeValue apply(String stringValue) {
          return AttributeValue.newBuilder()
              .setStringValue(toTruncatableStringProto(stringValue))
              .build();
        }
      };
  private static final Function<Boolean, /*@Nullable*/ AttributeValue>
      booleanAttributeValueFunction =
          new Function<Boolean, /*@Nullable*/ AttributeValue>() {
            @Override
            public AttributeValue apply(Boolean booleanValue) {
              return AttributeValue.newBuilder().setBoolValue(booleanValue).build();
            }
          };
  private static final Function<Long, /*@Nullable*/ AttributeValue> longAttributeValueFunction =
      new Function<Long, /*@Nullable*/ AttributeValue>() {
        @Override
        public AttributeValue apply(Long longValue) {
          return AttributeValue.newBuilder().setIntValue(longValue).build();
        }
      };
  private static final Function<Double, /*@Nullable*/ AttributeValue> doubleAttributeValueFunction =
      new Function<Double, /*@Nullable*/ AttributeValue>() {
        @Override
        public AttributeValue apply(Double doubleValue) {
          AttributeValue.Builder attributeValueBuilder = AttributeValue.newBuilder();
          // TODO: set double value if Stackdriver Trace support it in the future.
          attributeValueBuilder.setStringValue(
              toTruncatableStringProto(String.valueOf(doubleValue)));
          return attributeValueBuilder.build();
        }
      };
  private static final String EXPORT_STACKDRIVER_TRACES = "ExportStackdriverTraces";
  private static final EndSpanOptions END_SPAN_OPTIONS =
      EndSpanOptions.builder().setSampleToLocalSpanStore(true).build();

  private final Map<String, AttributeValue> fixedAttributes;
  private final String projectId;
  private final TraceServiceClient traceServiceClient;
  private final ProjectName projectName;

  private StackdriverV2ExporterHandler(
      String projectId,
      TraceServiceClient traceServiceClient,
      @javax.annotation.Nullable Map<String, io.opencensus.trace.AttributeValue> fixedAttributes) {
    this.projectId = checkNotNull(projectId, "projectId");
    this.traceServiceClient = traceServiceClient;
    if (fixedAttributes == null) {
      this.fixedAttributes = Collections.emptyMap();
    } else {
      this.fixedAttributes = new HashMap<>();
      for (Map.Entry<String, io.opencensus.trace.AttributeValue> label :
          fixedAttributes.entrySet()) {
        AttributeValue value = toAttributeValueProto(label.getValue());
        if (value != null) {
          this.fixedAttributes.put(label.getKey(), value);
        }
      }
    }
    projectName = ProjectName.of(this.projectId);
  }

  static StackdriverV2ExporterHandler createWithStub(
      String projectId,
      TraceServiceClient traceServiceClient,
      @javax.annotation.Nullable Map<String, io.opencensus.trace.AttributeValue> fixedAttributes) {
    return new StackdriverV2ExporterHandler(projectId, traceServiceClient, fixedAttributes);
  }

  static StackdriverV2ExporterHandler createWithCredentials(
      String projectId,
      Credentials credentials,
      @javax.annotation.Nullable Map<String, io.opencensus.trace.AttributeValue> fixedAttributes)
      throws IOException {
    TraceServiceSettings traceServiceSettings =
        TraceServiceSettings.newBuilder()
            .setCredentialsProvider(
                FixedCredentialsProvider.create(checkNotNull(credentials, "credentials")))
            .build();
    return new StackdriverV2ExporterHandler(
        projectId, TraceServiceClient.create(traceServiceSettings), fixedAttributes);
  }

  @VisibleForTesting
  Span generateSpan(
      SpanData spanData,
      Map<String, AttributeValue> resourceLabels,
      Map<String, AttributeValue> fixedAttributes) {
    SpanContext context = spanData.getContext();
    final String spanIdHex = context.getSpanId().toLowerBase16();
    SpanName spanName =
        SpanName.newBuilder()
            .setProject(projectId)
            .setTrace(context.getTraceId().toLowerBase16())
            .setSpan(spanIdHex)
            .build();
    Span.Builder spanBuilder =
        Span.newBuilder()
            .setName(spanName.toString())
            .setSpanId(spanIdHex)
            .setDisplayName(
                toTruncatableStringProto(toDisplayName(spanData.getName(), spanData.getKind())))
            .setStartTime(toTimestampProto(spanData.getStartTimestamp()))
            .setAttributes(
                toAttributesProto(spanData.getAttributes(), resourceLabels, fixedAttributes))
            .setTimeEvents(
                toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()));
    io.opencensus.trace.Status status = spanData.getStatus();
    if (status != null) {
      spanBuilder.setStatus(toStatusProto(status));
    }
    Timestamp end = spanData.getEndTimestamp();
    if (end != null) {
      spanBuilder.setEndTime(toTimestampProto(end));
    }
    spanBuilder.setLinks(toLinksProto(spanData.getLinks()));
    Integer childSpanCount = spanData.getChildSpanCount();
    if (childSpanCount != null) {
      spanBuilder.setChildSpanCount(Int32Value.newBuilder().setValue(childSpanCount).build());
    }
    if (spanData.getParentSpanId() != null && spanData.getParentSpanId().isValid()) {
      spanBuilder.setParentSpanId(spanData.getParentSpanId().toLowerBase16());
    }
    /*@Nullable*/ Boolean hasRemoteParent = spanData.getHasRemoteParent();
    if (hasRemoteParent != null) {
      spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
    }
    return spanBuilder.build();
  }

  private static Span.TimeEvents toTimeEventsProto(
      TimedEvents<Annotation> annotationTimedEvents,
      TimedEvents<io.opencensus.trace.MessageEvent> messageEventTimedEvents) {
    Span.TimeEvents.Builder timeEventsBuilder = Span.TimeEvents.newBuilder();
    timeEventsBuilder.setDroppedAnnotationsCount(annotationTimedEvents.getDroppedEventsCount());
    for (TimedEvent<Annotation> annotation : annotationTimedEvents.getEvents()) {
      timeEventsBuilder.addTimeEvent(toTimeAnnotationProto(annotation));
    }
    timeEventsBuilder.setDroppedMessageEventsCount(messageEventTimedEvents.getDroppedEventsCount());
    for (TimedEvent<io.opencensus.trace.MessageEvent> networkEvent :
        messageEventTimedEvents.getEvents()) {
      timeEventsBuilder.addTimeEvent(toTimeMessageEventProto(networkEvent));
    }
    return timeEventsBuilder.build();
  }

  private static TimeEvent toTimeAnnotationProto(TimedEvent<Annotation> timedEvent) {
    TimeEvent.Builder timeEventBuilder =
        TimeEvent.newBuilder().setTime(toTimestampProto(timedEvent.getTimestamp()));
    Annotation annotation = timedEvent.getEvent();
    timeEventBuilder.setAnnotation(
        TimeEvent.Annotation.newBuilder()
            .setDescription(toTruncatableStringProto(annotation.getDescription()))
            .setAttributes(toAttributesBuilderProto(annotation.getAttributes(), 0))
            .build());
    return timeEventBuilder.build();
  }

  private static TimeEvent toTimeMessageEventProto(
      TimedEvent<io.opencensus.trace.MessageEvent> timedEvent) {
    TimeEvent.Builder timeEventBuilder =
        TimeEvent.newBuilder().setTime(toTimestampProto(timedEvent.getTimestamp()));
    io.opencensus.trace.MessageEvent messageEvent = timedEvent.getEvent();
    timeEventBuilder.setMessageEvent(
        TimeEvent.MessageEvent.newBuilder()
            .setId(messageEvent.getMessageId())
            .setCompressedSizeBytes(messageEvent.getCompressedMessageSize())
            .setUncompressedSizeBytes(messageEvent.getUncompressedMessageSize())
            .setType(toMessageEventTypeProto(messageEvent))
            .build());
    return timeEventBuilder.build();
  }

  private static TimeEvent.MessageEvent.Type toMessageEventTypeProto(
      io.opencensus.trace.MessageEvent messageEvent) {
    if (messageEvent.getType() == Type.RECEIVED) {
      return MessageEvent.Type.RECEIVED;
    } else {
      return MessageEvent.Type.SENT;
    }
  }

  // These are the attributes of the Span, where usually we may add more attributes like the agent.
  private static Attributes toAttributesProto(
      io.opencensus.trace.export.SpanData.Attributes attributes,
      Map<String, AttributeValue> resourceLabels,
      Map<String, AttributeValue> fixedAttributes) {
    Attributes.Builder attributesBuilder =
        toAttributesBuilderProto(
            attributes.getAttributeMap(), attributes.getDroppedAttributesCount());
    attributesBuilder.putAttributeMap(AGENT_LABEL_KEY, AGENT_LABEL_VALUE);
    for (Entry<String, AttributeValue> entry : resourceLabels.entrySet()) {
      attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue());
    }
    for (Entry<String, AttributeValue> entry : fixedAttributes.entrySet()) {
      attributesBuilder.putAttributeMap(entry.getKey(), entry.getValue());
    }
    return attributesBuilder.build();
  }

  private static Attributes.Builder toAttributesBuilderProto(
      Map<String, io.opencensus.trace.AttributeValue> attributes, int droppedAttributesCount) {
    Attributes.Builder attributesBuilder =
        Attributes.newBuilder().setDroppedAttributesCount(droppedAttributesCount);
    for (Map.Entry<String, io.opencensus.trace.AttributeValue> label : attributes.entrySet()) {
      AttributeValue value = toAttributeValueProto(label.getValue());
      if (value != null) {
        attributesBuilder.putAttributeMap(mapKey(label.getKey()), value);
      }
    }
    return attributesBuilder;
  }

  @VisibleForTesting
  static Map<String, AttributeValue> getResourceLabels(
      @javax.annotation.Nullable Resource resource) {
    if (resource == null) {
      return Collections.emptyMap();
    }
    Map<String, AttributeValue> resourceLabels = new LinkedHashMap<String, AttributeValue>();
    for (Map.Entry<String, String> entry : resource.getLabels().entrySet()) {
      putToResourceAttributeMap(resourceLabels, entry.getKey(), entry.getValue());
    }
    return Collections.unmodifiableMap(resourceLabels);
  }

  private static void putToResourceAttributeMap(
      Map<String, AttributeValue> map, String attributeName, String attributeValue) {
    map.put(createResourceLabelKey(attributeName), toStringAttributeValueProto(attributeValue));
  }

  @VisibleForTesting
  static String createResourceLabelKey(String resourceAttribute) {
    return "g.co/r/" + resourceAttribute;
  }

  @VisibleForTesting
  static AttributeValue toStringAttributeValueProto(String value) {
    return AttributeValue.newBuilder().setStringValue(toTruncatableStringProto(value)).build();
  }

  private static String mapKey(String key) {
    if (HTTP_ATTRIBUTE_MAPPING.containsKey(key)) {
      return HTTP_ATTRIBUTE_MAPPING.get(key);
    } else {
      return key;
    }
  }

  private static Status toStatusProto(io.opencensus.trace.Status status) {
    Status.Builder statusBuilder = Status.newBuilder().setCode(status.getCanonicalCode().value());
    if (status.getDescription() != null) {
      statusBuilder.setMessage(status.getDescription());
    }
    return statusBuilder.build();
  }

  private static TruncatableString toTruncatableStringProto(String string) {
    return TruncatableString.newBuilder().setValue(string).setTruncatedByteCount(0).build();
  }

  private static com.google.protobuf.Timestamp toTimestampProto(Timestamp timestamp) {
    return com.google.protobuf.Timestamp.newBuilder()
        .setSeconds(timestamp.getSeconds())
        .setNanos(timestamp.getNanos())
        .build();
  }

  @javax.annotation.Nullable
  private static AttributeValue toAttributeValueProto(
      io.opencensus.trace.AttributeValue attributeValue) {
    return attributeValue.match(
        stringAttributeValueFunction,
        booleanAttributeValueFunction,
        longAttributeValueFunction,
        doubleAttributeValueFunction,
        Functions.</*@Nullable*/ AttributeValue>returnNull());
  }

  private static Link.Type toLinkTypeProto(io.opencensus.trace.Link.Type type) {
    if (type == io.opencensus.trace.Link.Type.PARENT_LINKED_SPAN) {
      return Link.Type.PARENT_LINKED_SPAN;
    } else {
      return Link.Type.CHILD_LINKED_SPAN;
    }
  }

  private static String toDisplayName(String spanName, @javax.annotation.Nullable Kind spanKind) {
    if (spanKind == Kind.SERVER && !spanName.startsWith(SERVER_PREFIX)) {
      return SERVER_PREFIX + spanName;
    }

    if (spanKind == Kind.CLIENT && !spanName.startsWith(CLIENT_PREFIX)) {
      return CLIENT_PREFIX + spanName;
    }

    return spanName;
  }

  private static Link toLinkProto(io.opencensus.trace.Link link) {
    checkNotNull(link);
    return Link.newBuilder()
        .setTraceId(link.getTraceId().toLowerBase16())
        .setSpanId(link.getSpanId().toLowerBase16())
        .setType(toLinkTypeProto(link.getType()))
        .setAttributes(toAttributesBuilderProto(link.getAttributes(), 0))
        .build();
  }

  private static Links toLinksProto(io.opencensus.trace.export.SpanData.Links links) {
    final Links.Builder linksBuilder =
        Links.newBuilder().setDroppedLinksCount(links.getDroppedLinksCount());
    for (io.opencensus.trace.Link link : links.getLinks()) {
      linksBuilder.addLink(toLinkProto(link));
    }
    return linksBuilder.build();
  }

  @Override
  public void export(Collection<SpanData> spanDataList) {
    // Start a new span with explicit 1/10000 sampling probability to avoid the case when user
    // sets the default sampler to always sample and we get the gRPC span of the stackdriver
    // export call always sampled and go to an infinite loop.
    io.opencensus.trace.Span span =
        tracer
            .spanBuilder(EXPORT_STACKDRIVER_TRACES)
            .setSampler(probabilitySampler)
            .setRecordEvents(true)
            .startSpan();
    Scope scope = tracer.withSpan(span);
    try {
      List<Span> spans = new ArrayList<>(spanDataList.size());
      for (SpanData spanData : spanDataList) {
        spans.add(generateSpan(spanData, RESOURCE_LABELS, fixedAttributes));
      }
      // Sync call because it is already called for a batch of data, and on a separate thread.
      // TODO(bdrutu): Consider to make this async in the future.
      traceServiceClient.batchWriteSpans(projectName, spans);
    } finally {
      scope.close();
      span.end(END_SPAN_OPTIONS);
    }
  }
}


text:
        Teinte
        <input name="colorHue" class="color-selector-slider color-selector-slider--hue" ng-change="$ctrl.updateColor($ctrl.currentColor)" ng-model="$ctrl.currentColor.h" type="range" min="0" max="360" step="1">
        Saturation
        <input name="colorSaturation" class="color-selector-slider color-selector-slider--saturation" ng-change="$ctrl.updateColor($ctrl.currentColor)" ng-model="$ctrl.currentColor.s" type="range" min="0" max="1" step="0.01">
        Luminosité
        <input name="colorLuminosity" class="color-selector-slider color-selector-slider--luminosity" ng-change="$ctrl.updateColor($ctrl.currentColor)" ng-model="$ctrl.currentColor.l" type="range" min="0" max="1" step="0.01">


text:
@interface SNPSource : MTLModel
<MTLJSONSerializing>

@property (nonatomic, nonnull, copy) NSString* name;
@property (nonatomic, nonnull, copy) NSURL* link;
@property (nonatomic, nonnull, copy) NSString* clientId;

@end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Veröff. Inst. Meeresf. Bremerhaven 2: 94 (1953)

#### Original name
Pythium aquatile Höhnk, 1953

### Remarks
null


text:
<?php
header("Content-Type: application/json"); //Set header for outputing the JSON information
require_once $_SERVER['DOCUMENT_ROOT'] . 'autoload.php';
$request = file_get_contents('php://input');
$data = json_decode($request);
$date_id = $data->date_id;
try {
	$user = User::get_current_user();
	if (is_numeric($date_id) && ($user instanceof CurrentUser)) {
		$date = new SomeDate(array(
			'date_id' => $date_id)
		);
		$date->get_times();
		$result = $user->leave_date($date);
		if ($result) {
			http_response_code(200);
		}
		else {
			throw new OutOfBoundsException('OutOfBoundsException occured on request, the left deadline has already passed');
		}
	}
	else {
		throw new UnexpectedValueException('UnexpectedValueException occured on request, parameters are not numeric or no user is not logged in currently');
	}
}
catch (Exception $e) {
	http_response_code(400);
	Database::print_exception($e);
}


text:
using Ploeh.AutoFixture.Kernel;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ploeh.AutoFixture
{
    /// <summary>
    /// Creates a sequence of random, unique, numbers starting at 1.
    /// </summary>
    public class RandomNumericSequenceGenerator : ISpecimenBuilder
    {
        private readonly long[] limits;
        private readonly object syncRoot;
        private readonly Random random;
        private readonly HashSet<long> numbers;
        private long lower;
        private long upper;
        private long count;

        /// <summary>
        /// Initializes a new instance of the <see cref="RandomNumericSequenceGenerator" /> class
        /// with the default limits, 255, 32767, and 2147483647.
        /// </summary>
        public RandomNumericSequenceGenerator()
            : this(1, Byte.MaxValue, Int16.MaxValue, Int32.MaxValue)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RandomNumericSequenceGenerator" /> class.
        /// </summary>
        /// <param name="limits">A sequence of at least two ascending numbers.</param>
        public RandomNumericSequenceGenerator(IEnumerable<long> limits)
            : this(limits.ToArray())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RandomNumericSequenceGenerator" /> class.
        /// </summary>
        /// <param name="limits">An array of at least two ascending numbers.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentException"></exception>
        public RandomNumericSequenceGenerator(params long[] limits)
        {
            if (limits == null)
            {
                throw new ArgumentNullException(nameof(limits));
            }

            if (limits.Length < 2)
            {
                throw new ArgumentException("Limits must be at least two ascending numbers.", nameof(limits));
            }

            ValidateThatLimitsAreStrictlyAscending(limits);

            this.limits = limits;
            this.syncRoot = new object();
            this.random = new Random();
            this.numbers = new HashSet<long>();
            this.CreateRange();
        }

        /// <summary>
        /// Gets the sequence of limits.
        /// </summary>
        /// <value>
        /// The sequence of limits.
        /// </value>
        public IEnumerable<long> Limits
        {
            get { return this.limits; }
        }

        /// <summary>
        /// Creates an anonymous number.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The next random number in a sequence, if <paramref name="request"/> is a request
        /// for a numeric value; otherwise, a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            var type = request as Type;
            if (type == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return this.CreateRandom(type);
        }

        private static void ValidateThatLimitsAreStrictlyAscending(long[] limits)
        {
            if (limits.Zip(limits.Skip(1), (a, b) => a >= b).Any(b => b))
            {
                throw new ArgumentOutOfRangeException(nameof(limits), "Limits must be ascending numbers.");
            }
        }

        private object CreateRandom(Type request)
        {
            switch (Type.GetTypeCode(request))
            {
                case TypeCode.Byte:
                    return (byte)
                        this.GetNextRandom();

                case TypeCode.Decimal:
                    return (decimal)
                        this.GetNextRandom();

                case TypeCode.Double:
                    return (double)
                        this.GetNextRandom();

                case TypeCode.Int16:
                    return (short)
                        this.GetNextRandom();

                case TypeCode.Int32:
                    return (int)
                        this.GetNextRandom();

                case TypeCode.Int64:
                    return
                        this.GetNextRandom();

                case TypeCode.SByte:
                    return (sbyte)
                        this.GetNextRandom();

                case TypeCode.Single:
                    return (float)
                        this.GetNextRandom();

                case TypeCode.UInt16:
                    return (ushort)
                        this.GetNextRandom();

                case TypeCode.UInt32:
                    return (uint)
                        this.GetNextRandom();

                case TypeCode.UInt64:
                    return (ulong)
                        this.GetNextRandom();

                default:
#pragma warning disable 618
                    return new NoSpecimen(request);
#pragma warning restore 618
            }
        }

        private long GetNextRandom()
        {
            lock (this.syncRoot)
            {
                this.EvaluateRange();

                long result;
                do
                {
                    if (this.lower >= int.MinValue &&
                        this.upper <= int.MaxValue)
                    {
                        result = this.random.Next((int)this.lower, (int)this.upper);
                    }
                    else
                    {
                        result = this.GetNextInt64InRange();
                    }
                }
                while (this.numbers.Contains(result));

                this.numbers.Add(result);
                return result;
            }
        }

        private void EvaluateRange()
        {
            if (this.count == (this.upper - this.lower))
            {
                this.count = 0;
                this.CreateRange();
            }

            this.count++;
        }

        private void CreateRange()
        {
            var remaining = this.limits.Where(x => x > this.upper - 1).ToArray();
            if (remaining.Any() && this.numbers.Any())
            {
                this.lower = this.upper;
                this.upper = remaining.Min() + 1;
            }
            else
            {
                this.lower = limits[0];
                this.upper = this.GetUpperRangeFromLimits();
            }

            this.numbers.Clear();
        }

        /// <summary>
        /// Returns upper limit + 1 when expecting to use upper as max value in Random.Next(Int32,Int32).
        /// This ensures that the upper limit is included in the possible values returned by Random.Next(Int32,Int32)
        ///
        /// When not expecting to use Random.Next(Int32,Int32).  It returns the original upper limit.
        /// </summary>
        /// <returns></returns>
        private long GetUpperRangeFromLimits()
        {
            return limits[1] >= Int32.MaxValue
                    ? limits[1]
                    : limits[1] + 1;
        }

        private long GetNextInt64InRange()
        {
            var range = (ulong)(this.upper - this.lower);
            ulong limit = ulong.MaxValue - ulong.MaxValue % range;
            ulong number;
            do
            {
                var buffer = new byte[sizeof(ulong)];
                this.random.NextBytes(buffer);
                number = BitConverter.ToUInt64(buffer, 0);
            } while (number > limit);
            return (long)(number % range + (ulong)this.lower);
        }
    }
}


text:
import React, { Component } from 'react';

export default class OnlineUsers extends Component {
    render() {
        return (

                {(() => Object.keys(this.props.users).length > 0 ?
{'Online users'}
 : null)()}
                {Object.keys(this.props.users).map((id) => {
                    const estimate = this.props.estimates[id];
                    const name = this.props.names[id]
                    return
{name}: {estimate !== undefined ? estimate : '-'}
;
                })}

        );
    }
}


text:
package br.com.javace.javou.model.Resume;

/**
 * Created by danielbaccin on 27/11/15.
 */
public class Resume {

    private int totalRegistrations;
    private int totalAttendance;
    private int totalRaffled;

    public int getTotalRegistrations() {
        return totalRegistrations;
    }

    public void setTotalRegistrations(int totalRegistrations) {
        this.totalRegistrations = totalRegistrations;
    }

    public int getTotalAttendance() {
        return totalAttendance;
    }

    public void setTotalAttendance(int totalAttendance) {
        this.totalAttendance = totalAttendance;
    }

    public int getTotalRaffled() {
        return totalRaffled;
    }

    public void setTotalRaffled(int totalRaffled) {
        this.totalRaffled = totalRaffled;
    }
}


text:
title: War Story 4- The Best Report is... Quirky
published: true
---

In which humans jumped out of their chairs... cause we told them something that make sense to them.

Reference:

- B. Turhan and K. Kuutti, [Simpler Questions Can Lead To Better Insights](https://github.com/ds4se/chapters/blob/master/turhanb/theGraph.md)  in Perspectives on Data Science for Software Engineering, eds. Tim Menzies, Laurie Williams, Thomas Zimmermann, Morgan Kaufmann Publishers, 2016


text:
.class Lcom/sec/android/app/camera/AbstractCameraActivity$7;
.super Ljava/lang/Object;
.source "AbstractCameraActivity.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/sec/android/app/camera/AbstractCameraActivity;->finishOnError(I)V
.end annotation

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

# instance fields
.field final synthetic this$0:Lcom/sec/android/app/camera/AbstractCameraActivity;

# direct methods
.method constructor <init>(Lcom/sec/android/app/camera/AbstractCameraActivity;)V
    .locals 0
    .parameter

    .prologue
    .line 1387
    iput-object p1, p0, Lcom/sec/android/app/camera/AbstractCameraActivity$7;->this$0:Lcom/sec/android/app/camera/AbstractCameraActivity;

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

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 1
    .parameter "dialog"
    .parameter "which"

    .prologue
    .line 1389
    iget-object v0, p0, Lcom/sec/android/app/camera/AbstractCameraActivity$7;->this$0:Lcom/sec/android/app/camera/AbstractCameraActivity;

    invoke-virtual {v0}, Lcom/sec/android/app/camera/AbstractCameraActivity;->finish()V

    .line 1390
    return-void
.end method


text:
```php
<?php

$card = new \Payum\Core\Model\CreditCard();
$card->setNumber('4111111111111111');
$card->setExpireAt(new \DateTime('2018-10-10'));
$card->setSecurityCode('123');

$model = new \Payum\Model\Order();
$model->setCurrencyCode('USD');
$model->setTotalAmount(1);
$model->setCreditCard($card);

$payment->execute(new \Payum\Core\Request\Capture($model);
```


text:
- [/statistics/chartData](https://github.com/robflop/megumin.love/wiki/GetChartData)
- [/statistics/milestones](https://github.com/robflop/megumin.love/wiki/GetMilestones)
- [/statistics](https://github.com/robflop/megumin.love/wiki/GetStatistics)
- [/statistics/summary](https://github.com/robflop/megumin.love/wiki/GetSummary)


text:
<?php
/**
 * LogApi
 * PHP version 5
 *
 * @category Class
 * @package  BumbalClient
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Bumbal Client Api
 *
 * Bumbal API documentation
 *
 * OpenAPI spec version: 2.0
 * Contact: gerb@bumbal.eu
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace BumbalClient\API;

use \BumbalClient\ApiClient;
use \BumbalClient\ApiException;
use \BumbalClient\Configuration;
use \BumbalClient\ObjectSerializer;

/**
 * LogApi Class Doc Comment
 *
 * @category Class
 * @package  BumbalClient
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class LogApi
{
    /**
     * API Client
     *
     * @var \BumbalClient\ApiClient instance of the ApiClient
     */
    protected $apiClient;

    /**
     * Constructor
     *
     * @param \BumbalClient\ApiClient|null $apiClient The api client to use
     */
    public function __construct(\BumbalClient\ApiClient $apiClient = null)
    {
        if ($apiClient === null) {
            $apiClient = new ApiClient();
        }

        $this->apiClient = $apiClient;
    }

    /**
     * Get API client
     *
     * @return \BumbalClient\ApiClient get the API client
     */
    public function getApiClient()
    {
        return $this->apiClient;
    }

    /**
     * Set the API client
     *
     * @param \BumbalClient\ApiClient $apiClient set the API client
     *
     * @return LogApi
     */
    public function setApiClient(\BumbalClient\ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
        return $this;
    }

    /**
     * Operation retrieveListLog
     *
     * Retrieve List of Log messages
     *
     * @param \BumbalClient\Model\LogRetrieveListArguments $arguments Log RetrieveList Arguments (required)
     * @throws \BumbalClient\ApiException on non-2xx response
     * @return \BumbalClient\Model\LogListResponse
     */
    public function retrieveListLog($arguments)
    {
        list($response) = $this->retrieveListLogWithHttpInfo($arguments);
        return $response;
    }

    /**
     * Operation retrieveListLogWithHttpInfo
     *
     * Retrieve List of Log messages
     *
     * @param \BumbalClient\Model\LogRetrieveListArguments $arguments Log RetrieveList Arguments (required)
     * @throws \BumbalClient\ApiException on non-2xx response
     * @return array of \BumbalClient\Model\LogListResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function retrieveListLogWithHttpInfo($arguments)
    {
        // verify the required parameter 'arguments' is set
        if ($arguments === null) {
            throw new \InvalidArgumentException('Missing the required parameter $arguments when calling retrieveListLog');
        }
        // parse inputs
        $resourcePath = "/log";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/json', 'application/xml']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']);

        // body params
        $_tempBody = null;
        if (isset($arguments)) {
            $_tempBody = $arguments;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('ApiKey');
        if (strlen($apiKey) !== 0) {
            $headerParams['ApiKey'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'PUT',
                $queryParams,
                $httpBody,
                $headerParams,
                '\BumbalClient\Model\LogListResponse',
                '/log'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\BumbalClient\Model\LogListResponse', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\BumbalClient\Model\LogListResponse', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }

    /**
     * Operation setLog
     *
     * Post a Log message
     *
     * @param \BumbalClient\Model\LogModel $body Log object (required)
     * @throws \BumbalClient\ApiException on non-2xx response
     * @return \BumbalClient\Model\ApiResponse
     */
    public function setLog($body)
    {
        list($response) = $this->setLogWithHttpInfo($body);
        return $response;
    }

    /**
     * Operation setLogWithHttpInfo
     *
     * Post a Log message
     *
     * @param \BumbalClient\Model\LogModel $body Log object (required)
     * @throws \BumbalClient\ApiException on non-2xx response
     * @return array of \BumbalClient\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function setLogWithHttpInfo($body)
    {
        // verify the required parameter 'body' is set
        if ($body === null) {
            throw new \InvalidArgumentException('Missing the required parameter $body when calling setLog');
        }
        // parse inputs
        $resourcePath = "/log/set";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/json', 'application/xml']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']);

        // body params
        $_tempBody = null;
        if (isset($body)) {
            $_tempBody = $body;
        }

        // for model (json/xml)
        if (isset($_tempBody)) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = $formParams; // for HTTP post (form)
        }
        // this endpoint requires API key authentication
        $apiKey = $this->apiClient->getApiKeyWithPrefix('ApiKey');
        if (strlen($apiKey) !== 0) {
            $headerParams['ApiKey'] = $apiKey;
        }
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\BumbalClient\Model\ApiResponse',
                '/log/set'
            );

            return [$this->apiClient->getSerializer()->deserialize($response, '\BumbalClient\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\BumbalClient\Model\ApiResponse', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            throw $e;
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.authorization.fluent.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** shiftPreferences. */
@Fluent
public final class MicrosoftGraphShiftPreferences extends MicrosoftGraphChangeTrackedEntity {
    /*
     * Availability of the user to be scheduled for work and its recurrence pattern.
     */
    @JsonProperty(value = "availability")
    private List<MicrosoftGraphShiftAvailability> availability;

    /*
     * shiftPreferences
     */
    @JsonIgnore private Map<String, Object> additionalProperties;

    /** Creates an instance of MicrosoftGraphShiftPreferences class. */
    public MicrosoftGraphShiftPreferences() {
    }

    /**
     * Get the availability property: Availability of the user to be scheduled for work and its recurrence pattern.
     *
     * @return the availability value.
     */
    public List<MicrosoftGraphShiftAvailability> availability() {
        return this.availability;
    }

    /**
     * Set the availability property: Availability of the user to be scheduled for work and its recurrence pattern.
     *
     * @param availability the availability value to set.
     * @return the MicrosoftGraphShiftPreferences object itself.
     */
    public MicrosoftGraphShiftPreferences withAvailability(List<MicrosoftGraphShiftAvailability> availability) {
        this.availability = availability;
        return this;
    }

    /**
     * Get the additionalProperties property: shiftPreferences.
     *
     * @return the additionalProperties value.
     */
    @JsonAnyGetter
    public Map<String, Object> additionalProperties() {
        return this.additionalProperties;
    }

    /**
     * Set the additionalProperties property: shiftPreferences.
     *
     * @param additionalProperties the additionalProperties value to set.
     * @return the MicrosoftGraphShiftPreferences object itself.
     */
    public MicrosoftGraphShiftPreferences withAdditionalProperties(Map<String, Object> additionalProperties) {
        this.additionalProperties = additionalProperties;
        return this;
    }

    @JsonAnySetter
    void withAdditionalProperties(String key, Object value) {
        if (additionalProperties == null) {
            additionalProperties = new HashMap<>();
        }
        additionalProperties.put(key, value);
    }

    /** {@inheritDoc} */
    @Override
    public MicrosoftGraphShiftPreferences withCreatedDateTime(OffsetDateTime createdDateTime) {
        super.withCreatedDateTime(createdDateTime);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public MicrosoftGraphShiftPreferences withLastModifiedBy(MicrosoftGraphIdentitySet lastModifiedBy) {
        super.withLastModifiedBy(lastModifiedBy);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public MicrosoftGraphShiftPreferences withLastModifiedDateTime(OffsetDateTime lastModifiedDateTime) {
        super.withLastModifiedDateTime(lastModifiedDateTime);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public MicrosoftGraphShiftPreferences withId(String id) {
        super.withId(id);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (availability() != null) {
            availability().forEach(e -> e.validate());
        }
    }
}


text:
namespace fileapi {

namespace {

const GURL kOrigin("http://example.com");
const FileSystemType kFileSystemType = kFileSystemTypeTest;

class Result {
 public:
  Result()
      : status_(base::PLATFORM_FILE_OK),
        bytes_written_(0),
        write_status_(FileWriterDelegate::SUCCESS_IO_PENDING) {}

  base::PlatformFileError status() const { return status_; }
  int64 bytes_written() const { return bytes_written_; }
  FileWriterDelegate::WriteProgressStatus write_status() const {
    return write_status_;
  }

  void DidWrite(base::PlatformFileError status, int64 bytes,
                FileWriterDelegate::WriteProgressStatus write_status) {
    write_status_ = write_status;
    if (status == base::PLATFORM_FILE_OK) {
      bytes_written_ += bytes;
      if (write_status_ != FileWriterDelegate::SUCCESS_IO_PENDING)
        base::MessageLoop::current()->Quit();
    } else {
      EXPECT_EQ(base::PLATFORM_FILE_OK, status_);
      status_ = status;
      base::MessageLoop::current()->Quit();
    }
  }

 private:
  // For post-operation status.
  base::PlatformFileError status_;
  int64 bytes_written_;
  FileWriterDelegate::WriteProgressStatus write_status_;
};

const char kData[] = "The quick brown fox jumps over the lazy dog.\n";
const int kDataSize = ARRAYSIZE_UNSAFE(kData) - 1;

}  // namespace (anonymous)

class FileWriterDelegateTest : public PlatformTest {
 public:
  FileWriterDelegateTest()
      : loop_(base::MessageLoop::TYPE_IO) {}

 protected:
  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

  FileSystemFileUtil* file_util() {
    return file_system_context_->GetFileUtil(kFileSystemType);
  }

  int64 usage() {
    return file_system_context_->GetQuotaUtil(kFileSystemType)->
        GetOriginUsageOnFileThread(file_system_context_,
                                   kOrigin,
                                   kFileSystemType);
  }

  int64 GetFileSizeOnDisk(const char* test_file_path) {
    // There might be in-flight flush/write.
    base::MessageLoop::current()->PostTask(
        FROM_HERE, base::Bind(&base::DoNothing));
    base::MessageLoop::current()->RunUntilIdle();

    FileSystemURL url = GetFileSystemURL(test_file_path);
    base::PlatformFileInfo file_info;
    base::FilePath platform_path;
    EXPECT_EQ(base::PLATFORM_FILE_OK,
              file_util()->GetFileInfo(NewOperationContext().get(), url,
                                       &file_info, &platform_path));
    return file_info.size;
  }

  FileSystemURL GetFileSystemURL(const char* file_name) const {
    return file_system_context_->CreateCrackedFileSystemURL(
        kOrigin, kFileSystemType, base::FilePath().FromUTF8Unsafe(file_name));
  }

  scoped_ptr<FileSystemOperationContext> NewOperationContext() {
    FileSystemOperationContext* context =
      new FileSystemOperationContext(file_system_context_);
    context->set_update_observers(
        *file_system_context_->GetUpdateObservers(kFileSystemType));
    return make_scoped_ptr(context);
  }

  FileWriterDelegate* CreateWriterDelegate(
      const char* test_file_path,
      int64 offset,
      int64 allowed_growth,
      Result* result) {
    SandboxFileStreamWriter* writer = new SandboxFileStreamWriter(
        file_system_context_,
        GetFileSystemURL(test_file_path),
        offset,
        *file_system_context_->GetUpdateObservers(kFileSystemType));
    writer->set_default_quota(allowed_growth);
    return new FileWriterDelegate(
        base::Bind(&Result::DidWrite, base::Unretained(result)),
        scoped_ptr<FileStreamWriter>(writer));
  }

  // Creates and sets up a FileWriterDelegate for writing the given |blob_url|,
  // and creates a new FileWriterDelegate for the file.
  void PrepareForWrite(const char* test_file_path,
                       const GURL& blob_url,
                       int64 offset,
                       int64 allowed_growth) {
    result_.reset(new Result());
    file_writer_delegate_.reset(
        CreateWriterDelegate(test_file_path, offset, allowed_growth,
                             result_.get()));
    request_.reset(empty_context_.CreateRequest(
        blob_url, file_writer_delegate_.get()));
  }

  static net::URLRequest::ProtocolFactory Factory;

  // This should be alive until the very end of this instance.
  base::MessageLoop loop_;

  scoped_refptr<FileSystemContext> file_system_context_;

  net::URLRequestContext empty_context_;
  scoped_ptr<FileWriterDelegate> file_writer_delegate_;
  scoped_ptr<net::URLRequest> request_;
  scoped_ptr<Result> result_;

  base::ScopedTempDir dir_;

  static const char* content_;
};

const char* FileWriterDelegateTest::content_ = NULL;

namespace {

static std::string g_content;

class FileWriterDelegateTestJob : public net::URLRequestJob {
 public:
  FileWriterDelegateTestJob(net::URLRequest* request,
                            net::NetworkDelegate* network_delegate,
                            const std::string& content)
      : net::URLRequestJob(request, network_delegate),
        content_(content),
        remaining_bytes_(content.length()),
        cursor_(0) {
  }

  virtual void Start() OVERRIDE {
    base::MessageLoop::current()->PostTask(
        FROM_HERE,
        base::Bind(&FileWriterDelegateTestJob::NotifyHeadersComplete, this));
  }

  virtual bool ReadRawData(net::IOBuffer* buf,
                           int buf_size,
                           int *bytes_read) OVERRIDE {
    if (remaining_bytes_ < buf_size)
      buf_size = static_cast<int>(remaining_bytes_);

    for (int i = 0; i < buf_size; ++i)
      buf->data()[i] = content_[cursor_++];
    remaining_bytes_ -= buf_size;

    SetStatus(net::URLRequestStatus());
    *bytes_read = buf_size;
    return true;
  }

  virtual int GetResponseCode() const OVERRIDE {
    return 200;
  }

 protected:
  virtual ~FileWriterDelegateTestJob() {}

 private:
  std::string content_;
  int remaining_bytes_;
  int cursor_;
};

}  // namespace (anonymous)

// static
net::URLRequestJob* FileWriterDelegateTest::Factory(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const std::string& scheme) {
  return new FileWriterDelegateTestJob(
      request, network_delegate, FileWriterDelegateTest::content_);
}

void FileWriterDelegateTest::SetUp() {
  ASSERT_TRUE(dir_.CreateUniqueTempDir());

  file_system_context_ = CreateFileSystemContextForTesting(
      NULL, dir_.path());

  bool created = false;
  scoped_ptr<FileSystemOperationContext> context = NewOperationContext();
  context->set_allowed_bytes_growth(kint64max);
  base::PlatformFileError error = file_util()->EnsureFileExists(
      context.get(),
      GetFileSystemURL("test"),
      &created);
  ASSERT_EQ(base::PLATFORM_FILE_OK, error);
  ASSERT_TRUE(created);
  net::URLRequest::Deprecated::RegisterProtocolFactory("blob", &Factory);
}

void FileWriterDelegateTest::TearDown() {
  net::URLRequest::Deprecated::RegisterProtocolFactory("blob", NULL);
  file_system_context_ = NULL;
  base::MessageLoop::current()->RunUntilIdle();
}

TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimit) {
  const GURL kBlobURL("blob:nolimit");
  content_ = kData;

  PrepareForWrite("test", kBlobURL, 0, kint64max);

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();

  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  ASSERT_EQ(kDataSize, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());
}

TEST_F(FileWriterDelegateTest, WriteSuccessWithJustQuota) {
  const GURL kBlobURL("blob:just");
  content_ = kData;
  const int64 kAllowedGrowth = kDataSize;
  PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth);

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  ASSERT_EQ(kAllowedGrowth, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());

  EXPECT_EQ(kAllowedGrowth, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());
}

TEST_F(FileWriterDelegateTest, DISABLED_WriteFailureByQuota) {
  const GURL kBlobURL("blob:failure");
  content_ = kData;
  const int64 kAllowedGrowth = kDataSize - 1;
  PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth);

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result_->write_status());
  file_writer_delegate_.reset();

  ASSERT_EQ(kAllowedGrowth, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());

  EXPECT_EQ(kAllowedGrowth, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NO_SPACE, result_->status());
  ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result_->write_status());
}

TEST_F(FileWriterDelegateTest, WriteZeroBytesSuccessfullyWithZeroQuota) {
  const GURL kBlobURL("blob:zero");
  content_ = "";
  int64 kAllowedGrowth = 0;
  PrepareForWrite("test", kBlobURL, 0, kAllowedGrowth);

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  ASSERT_EQ(kAllowedGrowth, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());

  EXPECT_EQ(kAllowedGrowth, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
}

TEST_F(FileWriterDelegateTest, WriteSuccessWithoutQuotaLimitConcurrent) {
  scoped_ptr<FileWriterDelegate> file_writer_delegate2;
  scoped_ptr<net::URLRequest> request2;
  scoped_ptr<Result> result2;

  bool created = false;
  file_util()->EnsureFileExists(NewOperationContext().get(),
                                GetFileSystemURL("test2"),
                                &created);
  ASSERT_TRUE(created);

  const GURL kBlobURL("blob:nolimitconcurrent");
  const GURL kBlobURL2("blob:nolimitconcurrent2");
  content_ = kData;

  PrepareForWrite("test", kBlobURL, 0, kint64max);

  // Credate another FileWriterDelegate for concurrent write.
  result2.reset(new Result());
  file_writer_delegate2.reset(CreateWriterDelegate(
      "test2", 0, kint64max, result2.get()));
  request2.reset(empty_context_.CreateRequest(
      kBlobURL2, file_writer_delegate2.get()));

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  file_writer_delegate2->Start(request2.Pass());
  base::MessageLoop::current()->Run();
  if (result_->write_status() == FileWriterDelegate::SUCCESS_IO_PENDING ||
      result2->write_status() == FileWriterDelegate::SUCCESS_IO_PENDING)
    base::MessageLoop::current()->Run();

  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result2->write_status());
  file_writer_delegate_.reset();
  file_writer_delegate2.reset();

  ASSERT_EQ(kDataSize * 2, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test") + GetFileSizeOnDisk("test2"), usage());

  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());
  EXPECT_EQ(kDataSize, result2->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result2->status());
}

TEST_F(FileWriterDelegateTest, WritesWithQuotaAndOffset) {
  const GURL kBlobURL("blob:failure-with-updated-quota");
  content_ = kData;

  // Writing kDataSize (=45) bytes data while allowed_growth is 100.
  int64 offset = 0;
  int64 allowed_growth = 100;
  ASSERT_LT(kDataSize, allowed_growth);
  PrepareForWrite("test", kBlobURL, offset, allowed_growth);

  ASSERT_EQ(0, usage());
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  ASSERT_EQ(kDataSize, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());

  // Trying to overwrite kDataSize bytes data while allowed_growth is 20.
  offset = 0;
  allowed_growth = 20;
  PrepareForWrite("test", kBlobURL, offset, allowed_growth);

  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  EXPECT_EQ(kDataSize, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());

  // Trying to write kDataSize bytes data from offset 25 while
  // allowed_growth is 55.
  offset = 25;
  allowed_growth = 55;
  PrepareForWrite("test", kBlobURL, offset, allowed_growth);

  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  EXPECT_EQ(offset + kDataSize, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());

  // Trying to overwrite 45 bytes data while allowed_growth is -20.
  offset = 0;
  allowed_growth = -20;
  PrepareForWrite("test", kBlobURL, offset, allowed_growth);

  int64 pre_write_usage = GetFileSizeOnDisk("test");
  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::SUCCESS_COMPLETED, result_->write_status());
  file_writer_delegate_.reset();

  EXPECT_EQ(pre_write_usage, usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kDataSize, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, result_->status());

  // Trying to overwrite 45 bytes data with offset pre_write_usage - 20,
  // while allowed_growth is 10.
  const int kOverlap = 20;
  offset = pre_write_usage - kOverlap;
  allowed_growth = 10;
  PrepareForWrite("test", kBlobURL, offset, allowed_growth);

  file_writer_delegate_->Start(request_.Pass());
  base::MessageLoop::current()->Run();
  ASSERT_EQ(FileWriterDelegate::ERROR_WRITE_STARTED, result_->write_status());
  file_writer_delegate_.reset();

  EXPECT_EQ(pre_write_usage + allowed_growth,
            usage());
  EXPECT_EQ(GetFileSizeOnDisk("test"), usage());
  EXPECT_EQ(kOverlap + allowed_growth, result_->bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NO_SPACE, result_->status());
}

}  // namespace fileapi


text:
fab target.skrapat app.main.setup app.service.setup app.checker.setup
fab target.skrapat app.admin.all app.main.all app.checker.all app.service.all

EXIT_STATUS=$?
if [ $EXIT_STATUS -ne 0 ];then
   echo "fabric returned $EXIT_STATUS! Exiting!"
   exit $EXIT_STATUS
fi

fab target.skrapat -R main server.restart_tomcat


text:
package com.yahoo.pulsar.admin.cli;

import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.stream.JsonWriter;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.yahoo.pulsar.client.admin.PulsarAdmin;
import com.yahoo.pulsar.common.stats.AllocatorStats;
import com.yahoo.pulsar.common.util.ObjectMapperFactory;

@Parameters(commandDescription = "Operations to collect broker statistics")
public class CmdBrokerStats extends CmdBase {
    public static final String DEFAULT_INDENTATION = "    ";
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    public static Writer out = new OutputStreamWriter(System.out, UTF_8);

    @Parameters(commandDescription = "dump metrics for Monitoring")
    class CmdMonitoringMetrics extends CliCommand {
        @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
        boolean indent = false;

        @Override
        void run() throws Exception {
            JsonArray metrics = admin.brokerStats().getMetrics();

            for (int i = 0; i < metrics.size(); i++) {
                JsonObject m = (JsonObject) metrics.get(i);
                JsonWriter jsonWriter = new JsonWriter(out);
                if (indent) {
                    jsonWriter.setIndent(DEFAULT_INDENTATION);
                    new Gson().toJson(m, jsonWriter);
                    out.write('\n');
                    out.write('\n');
                } else {
                    new Gson().toJson(m, jsonWriter);
                }
                out.flush();
            }
        }
    }

    @Parameters(commandDescription = "dump mbean stats")
    public class CmdDumpMBeans extends CliCommand {
        @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
        boolean indent = false;

        @Override
        void run() throws Exception {
            JsonArray result = admin.brokerStats().getMBeans();
            JsonWriter jsonWriter = new JsonWriter(out);
            if (indent) {
                jsonWriter.setIndent(DEFAULT_INDENTATION);
            }
            new Gson().toJson(result, jsonWriter);
            out.flush();
        }

    }

    @Parameters(commandDescription = "dump destination stats")
    public class CmdDestinations extends CliCommand {
        @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
        boolean indent = false;

        @Override
        void run() throws Exception {
            JsonObject result = admin.brokerStats().getDestinations();
            JsonWriter jsonWriter = new JsonWriter(out);
            if (indent) {
                jsonWriter.setIndent(DEFAULT_INDENTATION);
            }
            new Gson().toJson(result, jsonWriter);
            out.flush();
        }

    }

    @Parameters(commandDescription = "dump allocator stats")
    public class CmdAllocatorStats extends CliCommand {
        @Parameter(description = "allocator-name\n", required = true)
        List<String> params;

        @Override
        void run() throws Exception {
            AllocatorStats stats = admin.brokerStats().getAllocatorStats(params.get(0));
            ObjectMapper mapper = ObjectMapperFactory.create();
            ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
            out.write(writer.writeValueAsString(stats));
            out.flush();
        }

    }

    public CmdBrokerStats(PulsarAdmin admin) {
        super("broker-stats", admin);
        jcommander.addCommand("monitoring-metrics", new CmdMonitoringMetrics());
        jcommander.addCommand("mbeans", new CmdDumpMBeans());
        jcommander.addCommand("destinations", new CmdDestinations());
        jcommander.addCommand("allocator-stats", new CmdAllocatorStats());
    }

    public void addCommands(String commandName, CliCommand cliCommand) {
        jcommander.addCommand(commandName, cliCommand);
    }

}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['assumingcertainty'] = '你沒有選擇一個確定程度。所以假定為:{$a}';
$string['certainty1'] = '不太有信心(少於67%)';
$string['certainty2'] = '通(多於67%)';
$string['certainty3'] = '非常有信心(大於80%)';
$string['howcertainareyou'] = '你有多少信心說你的答案是對的?{$a}';
$string['markadjustment'] = '基於你表達的信心程度,你的基本分數{$a->rawmark}已被停整成 {$a->mark}。';
$string['pluginname'] = '信心加權法';


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HyperIoC.Lifetime;
using HyperIoC.Logging;
// ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local

namespace HyperIoC
{
    /// <summary>
    /// Provides registration of items in the factory for resolving via interfaces and abstract classes.
    /// </summary>
    public class Factory : IFactoryBuilder, IFactoryResolver, IFactoryLocator
    {
        private readonly List<Item> _items = new List<Item>();

        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public Factory()
        {
            // Add self to the IoC (as resolver) for dependency resolution patterns.
            var item = new Item(typeof (IFactoryResolver));
            item.AddType(GetType().FullName, GetType());
            item.SetLifetimeTo(new SingletonLifetimeManager(this));
            _items.Add(item);
        }

        private IFactoryLocator Locator => this;

        /// <summary>
        /// Adds an item into the IoC.
        /// </summary>
        /// <typeparam name="TInterface">Interface to register</typeparam>
        /// <typeparam name="TType">Type to register with interface</typeparam>
        /// <param name="key">Optional key</param>
        /// <returns>Register item</returns>
        public Item Add<TInterface, TType>(string key = null) where TType : TInterface
        {
            return Add(typeof (TInterface), typeof (TType), key);
        }

        /// <summary>
        /// Adds an item into the IoC.
        /// </summary>
        /// <param name="interfaceType">Interface to register</param>
        /// <param name="instanceType">Type to register with interface</param>
        /// <param name="key">Optional key</param>
        /// <returns>Register item</returns>
        public Item Add(Type interfaceType, Type instanceType, string key = null)
        {
            CheckInterfaceType(interfaceType);
            CheckInstanceType(instanceType);

            var item = Locator.FindItem(interfaceType);

            key = key ?? instanceType.FullName;

            if (item == null) _items.Add(new Item(interfaceType));

            item = Locator.FindItem(interfaceType);

            if (key != null && !item.InstanceTypes.ContainsKey(key))
            {
                item.AddType(key, instanceType);
            }

            return item;
        }

        /// <summary>
        /// Adds an item into the IoC.
        /// </summary>
        /// <typeparam name="TInterface">Interface to register</typeparam>
        /// <typeparam name="TAssemblyType">Type in assembly to discover TInterface implementations</typeparam>
        /// <returns>Register item list</returns>
        public ItemList AddAll<TInterface, TAssemblyType>()
        {
            var interfaceType = typeof(TInterface);

            CheckInterfaceType(interfaceType);

            var items = new ItemList();

            var asm = typeof(TAssemblyType).Assembly;

            foreach (var type in asm.GetTypes().Where(t => interfaceType.IsAssignableFrom(t)))
            {
                if (!CanAddInstanceType(type)) continue;

                var item = Add(interfaceType, type);
                items.Items.Add(item);
            }

            return items;
        }

        /// <summary>
        /// Gets an item from the IoC for the requesting interface.
        /// </summary>
        /// <typeparam name="TInterface">Interface to resolve type for</typeparam>
        /// <param name="key">Optional key</param>
        /// <returns>Instance if found else null</returns>
        public TInterface Get<TInterface>(string key = null)
        {
            var interfaceType = typeof(TInterface);
            return (TInterface)Get(interfaceType, key);
        }

        /// <summary>
        /// Gets an item from the IoC for the requesting interface.
        /// </summary>
        /// <param name="interfaceType">Interface to resolve type for</param>
        /// <param name="key">Optional key</param>
        /// <returns>Instance if found else null</returns>
        public object Get(Type interfaceType, string key = null)
        {
            CheckInterfaceType(interfaceType);

            var item = Locator.FindItem(interfaceType);

            if (item == null) return null;

            // If no key supplied then use the first one
            if (string.IsNullOrWhiteSpace(key))
            {
                key = item.InstanceTypes.Keys.First();
            }

            // If we have a type that matches the key then use this else return null
            return item.InstanceTypes.ContainsKey(key)
                ? item.InstanceTypes[key].LifetimeManager.Get(item.InstanceTypes[key].Type, this, this)
                : null;
        }

        /// <summary>
        /// Gets all the instances of the interface from the IoC.
        /// </summary>
        /// <param name="interfaceType">Interface to resolve types for</param>
        /// <returns>Resolved instances</returns>
        public object[] GetAll(Type interfaceType)
        {
            CheckInterfaceType(interfaceType);

            var item = Locator.FindItem(interfaceType);

            if (item == null) return null;

            var instanceTypes = new List<object>();

            foreach (var detail in item.InstanceTypes.Values)
            {
                var instance = detail.LifetimeManager.Get(detail.Type, this, this);
                instanceTypes.Add(instance);
            }

            return instanceTypes.ToArray();
        }

        /// <summary>
        /// Gets all the instances of the interface from the IoC.
        /// </summary>
        /// <typeparam name="TInterface">Interface to resolve type for</typeparam>
        /// <returns>Resolved instances</returns>
        public TInterface[] GetAll<TInterface>()
        {
            var instances = GetAll(typeof (TInterface)).ToList();
            var castInstances = new List<TInterface>();
            instances.ForEach(i => castInstances.Add((TInterface)i));
            return castInstances.ToArray();
        }

        /// <summary>
        /// Logs the configured registration.
        /// </summary>
        /// <param name="logger">Logger to write to. If null then the debug logger will be used.</param>
        public void Log(IConfigLogger logger = null)
        {
            var config = new StringBuilder();

            config.AppendLine("Logging the registration...");
            config.AppendLine();

            foreach (var item in _items)
            {
                config.AppendFormat("Registered type: '{0}' contains...", item.InterfaceType.FullName);
                config.AppendLine();

                foreach (var instanceType in item.InstanceTypes)
                {
                    config.AppendFormat("Type: '{0}' with key '{1}' as '{2}' lifetime",
                        instanceType.Value.Type, instanceType.Key, instanceType.Value.LifetimeManager);
                    config.AppendLine();
                }

                config.AppendFormat("Registered type: '{0}' complete.", item.InterfaceType.FullName);
                config.AppendLine();
                config.AppendLine();
            }

            config.AppendLine("Registration log complete.");

            var theLogger = logger ?? new DebugConfigLogger();
            theLogger.Log(config.ToString());
        }

        /// <summary>
        /// Locates an item in the IoC registration list.
        /// </summary>
        /// <param name="interfaceType">Interface type to find</param>
        /// <returns>Item if found else null</returns>
        Item IFactoryLocator.FindItem(Type interfaceType)
        {
            return _items.FirstOrDefault(i => i.InterfaceType == interfaceType);
        }

        private static void CheckInterfaceType(Type interfaceType)
        {
            if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType));

            if (!(interfaceType.IsInterface || interfaceType.IsAbstract))
                throw new ArgumentException("Type is not interface.", nameof(interfaceType));
        }

        private static void CheckInstanceType(Type instanceType)
        {
            if (instanceType == null) throw new ArgumentNullException(nameof(instanceType));

            if (instanceType.IsInterface || instanceType.IsAbstract)
                throw new ArgumentException("Instance is not a concrete type.", nameof(instanceType));
        }

        private static bool CanAddInstanceType(Type instanceType)
        {
            if (instanceType == null) return false;

            return !instanceType.IsInterface && !instanceType.IsAbstract;
        }
    }
}


text:
package com.feicent.zhang.util.weixin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.http.client.ClientProtocolException;

/**
 * 微信支付工具类
 * https://my.oschina.net/langxSpirit/blog/488435
 * @version 2015年8月2日
 */
public class WxUtils {

    /**
     * 随机字符串,不长于32 位
     *
     * @return
     * @author 蔡政滦 modify by 2015年8月2日
     */
    public static String randomStr() {
        String template = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();
        while (buffer.length() < 32) {
            int index = random.nextInt(36);
            char c = template.charAt(index);
            buffer.append(c);
        }
        return buffer.toString();
    }

    /**
     * 签名
     *
     * @param map 数据
     * @param password 密钥
     * @return
     * @author 蔡政滦 modify by 2015年8月2日
     * @throws Exception
     */
    public static String getSign(Map<String, Object> map, String password) throws Exception {
        return getSign(map, password, "");
    }

    /**
     * 签名
     *
     * @param map 数据
     * @param password 密钥
     * @param ignore_keys 忽略的key
     * @return
     * @author 蔡政滦 modify by 2015年8月2日
     * @throws Exception
     */
    public static String getSign(Map<String, Object> map, String password, String... ignoreKeys) throws Exception {
        String result = "";
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (ignoreKeys!=null && ignoreKeys.length>0) {
                for (int i = 0; i < ignoreKeys.length; i++) {
                    if (ignoreKeys[i].equals(entry.getKey())) {
                        continue;
                    }
                }
            }
            if (entry.getValue() != null && !"".equals(entry.getValue())) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        if (size > 0) {
            String[] arrayToSort = list.toArray(new String[size]);
            Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                sb.append(arrayToSort[i]);
            }
            result = sb.toString();
            result += "key=" + password;
            result = PayUtils.md5Digest(result);
            result = result.toUpperCase();
        }
        return result;
    }

    /**
     * 组装请求数据字符串
     *
     * @param postData 请求数据
     * @return
     * @author 蔡政滦 modify by 2015年8月2日
     */
    public static String toXml(Map<String, String> postData) {
        return HttpsUtils.toXml("xml", postData);
    }

    /**
     * 提交http请求,获取响应数据字符串
     *
     * @param url 请求URL
     * @param xml 请求数据字符串
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @author 蔡政滦 modify by 2015年8月2日
     */
    public static String postXml(String url, String xml) throws Exception {
        Map<String, String> headerInfo = new HashMap<String, String>();
        headerInfo.put("Content-Type", "text/xml");
        headerInfo.put("Connection", "keep-alive");
        headerInfo.put("Accept", "*/*");
        headerInfo.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headerInfo.put("Host", "api.mch.weixin.qq.com");
        headerInfo.put("X-Requested-With", "XMLHttpRequest");
        headerInfo.put("Cache-Control", "max-age=0");
        headerInfo.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        return HttpsUtils.postXml(url, headerInfo, xml);
    }

    /**
     * 提交https请求,获取响应数据字符串
     *
     * @param url 请求URL
     * @param xml 请求数据字符串
     * @keyStorePath 证书存放路径
     * @keysecret 证书密码
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @author 蔡政滦 modify by 2015年8月2日
     */
    public static String postXmlSSL(String url, String xml, String keyStorePath, String keysecret) throws IllegalStateException, IOException, Exception {
        Map<String, String> headerInfo = new HashMap<String, String>();
        headerInfo.put("Content-Type", "text/xml");
        headerInfo.put("Connection", "keep-alive");
        headerInfo.put("Accept", "*/*");
        headerInfo.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        headerInfo.put("Host", "api.mch.weixin.qq.com");
        headerInfo.put("X-Requested-With", "XMLHttpRequest");
        headerInfo.put("Cache-Control", "max-age=0");
        headerInfo.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        return HttpsUtils.postXmlSSL(url, headerInfo, xml, keyStorePath, keysecret);
    }
}


text:
using System;
using System.Collections.Generic;
using Orleans.Runtime.Configuration;

namespace Orleans.Runtime.GrainDirectory
{
    internal static class GrainDirectoryCacheFactory<TValue>
    {
        internal static IGrainDirectoryCache<TValue> CreateGrainDirectoryCache(GlobalConfiguration cfg)
        {
            if (cfg.CacheSize <= 0)
                return new NullGrainDirectoryCache<TValue>();

            switch (cfg.DirectoryCachingStrategy)
            {
                case GlobalConfiguration.DirectoryCachingStrategyType.None:
                    return new NullGrainDirectoryCache<TValue>();
                case GlobalConfiguration.DirectoryCachingStrategyType.LRU:
                    return new LRUBasedGrainDirectoryCache<TValue>(cfg.CacheSize, cfg.MaximumCacheTTL);
                default:
                    return new AdaptiveGrainDirectoryCache<TValue>(cfg.InitialCacheTTL, cfg.MaximumCacheTTL, cfg.CacheTTLExtensionFactor, cfg.CacheSize);
            }
        }

        internal static AsynchAgent CreateGrainDirectoryCacheMaintainer(
            LocalGrainDirectory router,
            IGrainDirectoryCache<TValue> cache,
            Func<List<ActivationAddress>, TValue> updateFunc,
            IInternalGrainFactory grainFactory)
        {
            var adaptiveCache = cache as AdaptiveGrainDirectoryCache<TValue>;
            return adaptiveCache != null
                ? new AdaptiveDirectoryCacheMaintainer<TValue>(router, adaptiveCache, updateFunc, grainFactory)
                : null;
        }
    }

    internal class NullGrainDirectoryCache<TValue> : IGrainDirectoryCache<TValue>
    {
        private static readonly List<Tuple<GrainId, TValue, int>> EmptyList = new List<Tuple<GrainId, TValue, int>>();

        public void AddOrUpdate(GrainId key, TValue value, int version)
        {
        }

        public bool Remove(GrainId key)
        {
            return false;
        }

        public void Clear()
        {
        }

        public bool LookUp(GrainId key, out TValue result, out int version)
        {
            result = default(TValue);
            version = default(int);
            return false;
        }

        public IReadOnlyList<Tuple<GrainId, TValue, int>> KeyValues
        {
            get { return EmptyList; }
        }
    }
}


text:
namespace WebApp.Data
{
    using AvgIdentity.Models;

    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;

    public class WebAppDbContext : IdentityDbContext<AvgIdentityUser>
    {
        public WebAppDbContext(DbContextOptions options)
            : base(options)
        {
        }
    }
}


text:
package org.hisp.dhis.android.core.dataset;

import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.arch.repositories.collection.internal.ReadOnlyIdentifiableCollectionRepositoryImpl;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.BooleanFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.EnumFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.FilterConnectorFactory;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.IntegerFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.StringFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope;
import org.hisp.dhis.android.core.common.IdentifiableColumns;
import org.hisp.dhis.android.core.dataset.internal.DataSetFields;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit;
import org.hisp.dhis.android.core.period.PeriodType;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkTableInfo;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import dagger.Reusable;

import static org.hisp.dhis.android.core.dataset.DataSetTableInfo.Columns;

@Reusable
public class DataSetCollectionRepository
            extends ReadOnlyIdentifiableCollectionRepositoryImpl<DataSet, DataSetCollectionRepository> {

    @Inject
    DataSetCollectionRepository(final IdentifiableObjectStore<DataSet> store,
                                final Map<String, ChildrenAppender<DataSet>> childrenAppenders,
                                final RepositoryScope scope) {
        super(store, childrenAppenders, scope, new FilterConnectorFactory<>(scope,
                s -> new DataSetCollectionRepository(store, childrenAppenders, s)));
    }

    public EnumFilterConnector<DataSetCollectionRepository, PeriodType> byPeriodType() {
        return cf.enumC(Columns.PERIOD_TYPE);
    }

    public StringFilterConnector<DataSetCollectionRepository> byCategoryComboUid() {
        return cf.string(Columns.CATEGORY_COMBO);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byMobile() {
        return cf.bool(Columns.MOBILE);
    }

    public IntegerFilterConnector<DataSetCollectionRepository> byVersion() {
        return cf.integer(Columns.VERSION);
    }

    public IntegerFilterConnector<DataSetCollectionRepository> byExpiryDays() {
        return cf.integer(Columns.EXPIRY_DAYS);
    }

    public IntegerFilterConnector<DataSetCollectionRepository> byTimelyDays() {
        return cf.integer(Columns.TIMELY_DAYS);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byNotifyCompletingUser() {
        return cf.bool(Columns.NOTIFY_COMPLETING_USER);
    }

    public IntegerFilterConnector<DataSetCollectionRepository> byOpenFuturePeriods() {
        return cf.integer(Columns.OPEN_FUTURE_PERIODS);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byFieldCombinationRequired() {
        return cf.bool(Columns.FIELD_COMBINATION_REQUIRED);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byValidCompleteOnly() {
        return cf.bool(Columns.VALID_COMPLETE_ONLY);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byNoValueRequiresComment() {
        return cf.bool(Columns.NO_VALUE_REQUIRES_COMMENT);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> bySkipOffline() {
        return cf.bool(Columns.SKIP_OFFLINE);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byDataElementDecoration() {
        return cf.bool(Columns.DATA_ELEMENT_DECORATION);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byRenderAsTabs() {
        return cf.bool(Columns.RENDER_AS_TABS);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byRenderHorizontally() {
        return cf.bool(Columns.RENDER_HORIZONTALLY);
    }

    public BooleanFilterConnector<DataSetCollectionRepository> byAccessDataWrite() {
        return cf.bool(Columns.ACCESS_DATA_WRITE);
    }

    public StringFilterConnector<DataSetCollectionRepository> byColor() {
        return cf.string(Columns.COLOR);
    }

    public StringFilterConnector<DataSetCollectionRepository> byIcon() {
        return cf.string(Columns.ICON);
    }

    public DataSetCollectionRepository byOrganisationUnitUid(String uid) {
        return byOrganisationUnitList(Collections.singletonList(uid));
    }

    public DataSetCollectionRepository byOrganisationUnitList(List<String> uids) {
        return cf.subQuery(IdentifiableColumns.UID).inLinkTable(
                DataSetOrganisationUnitLinkTableInfo.TABLE_INFO.name(),
                DataSetOrganisationUnitLinkTableInfo.Columns.DATA_SET,
                DataSetOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
                uids);
    }

    public DataSetCollectionRepository byOrganisationUnitScope(OrganisationUnit.Scope scope) {
        return cf.subQuery(IdentifiableColumns.UID).inTwoLinkTable(
                DataSetOrganisationUnitLinkTableInfo.TABLE_INFO.name(),
                DataSetOrganisationUnitLinkTableInfo.Columns.DATA_SET,
                DataSetOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
                UserOrganisationUnitLinkTableInfo.TABLE_INFO.name(),
                UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
                UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
                Collections.singletonList(scope.name())
        );
    }

    public DataSetCollectionRepository withCompulsoryDataElementOperands() {
        return cf.withChild(DataSetFields.COMPULSORY_DATA_ELEMENT_OPERANDS);
    }

    public DataSetCollectionRepository withDataInputPeriods() {
        return cf.withChild(DataSetFields.DATA_INPUT_PERIODS);
    }

    public DataSetCollectionRepository withDataSetElements() {
        return cf.withChild(DataSetFields.DATA_SET_ELEMENTS);
    }

    public DataSetCollectionRepository withIndicators() {
        return cf.withChild(DataSetFields.INDICATORS);
    }
}


text:
.PHONY:	build

PREFIX = gcr.io/fluentd-elasticsearch
IMAGE = fluentd
TAG = v2.5.1

build:
	gcloud builds submit --tag $(PREFIX)/$(IMAGE):$(TAG)


text:
import pytest

@pytest.fixture(scope='function', autouse=True)
def mock_settings(monkeypatch):
    class Settings:
        ALIASES = ''

        def __getattr__(self, item):
            return None

    settings = Settings()
    monkeypatch.setattr('slackbot.settings', settings)
    monkeypatch.setattr('slackbot.dispatcher.settings', settings)


text:
;(function($) {

  // plugin name
  var pluginName = 'loadGist';

  // reserved for later update
  var defaults = {};

  // catch for
  var $head = $('head');

  // load css if not exist
  function loadCSS(src) {
    if ($head.find('link[rel="stylesheet"][href="' + src + '"]').length < 1) {
      $head.append('<link rel="stylesheet" href="'+ src +'">');
    }
  }

  $.fn[pluginName] = function(options) {
    options = $.extend({}, defaults, options);

    // find embed gists
    var $gists = this.find('script[src^="https://gist.github.com/"]');

    return $gists.each(function() {
      var $this = $(this);
      // make json request url
      var src = $this.attr('src') + 'on?callback=?';

      $.getJSON(src, function(data) {
        $this.replaceWith(data.div);
        loadCSS(data.stylesheet);
      }).fail(function() {
        var gist = $this.attr('src').substring(0, $this.attr('src').length - 3);
        $this.replaceWith('' + gist+ '');
      });
    });
  };

  $.fn[pluginName].defaults = defaults;

})(jQuery);