text:
from sippy.UaStateGeneric import UaStateGeneric
from sippy.CCEvents import CCEventDisconnect, CCEventRing, CCEventConnect, CCEventFail, CCEventRedirect

class UacStateUpdating(UaStateGeneric):
    sname = 'Updating(UAC)'
    triedauth = False
    connected = True

    def recvRequest(self, req):
        if req.getMethod() == 'INVITE':
            self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(491, 'Request Pending', server = self.ua.local_ua))
            return None
        elif req.getMethod() == 'BYE':
            self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr)
            self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', server = self.ua.local_ua))
            #print 'BYE received in the Updating state, going to the Disconnected state'
            event = CCEventDisconnect(rtime = req.rtime, origin = self.ua.origin)
            try:
                event.reason = req.getHFBody('reason')
            except:
                pass
            self.ua.equeue.append(event)
            self.ua.cancelCreditTimer()
            self.ua.disconnect_ts = req.rtime
            return (UaStateDisconnected, self.ua.disc_cbs, req.rtime, self.ua.origin)
        #print 'wrong request %s in the state Updating' % req.getMethod()
        return None

    def recvResponse(self, resp, tr):
        body = resp.getBody()
        code, reason = resp.getSCode()
        scode = (code, reason, body)
        if code < 200:
            self.ua.equeue.append(CCEventRing(scode, rtime = resp.rtime, origin = self.ua.origin))
            return None
        if code >= 200 and code < 300:
            event = CCEventConnect(scode, rtime = resp.rtime, origin = self.ua.origin)
            if body != None:
                if self.ua.on_remote_sdp_change != None:
                    cb_func = lambda x: self.ua.delayed_remote_sdp_update(event, x)
                    try:
                        self.ua.on_remote_sdp_change(body, cb_func, en_excpt = True)
                    except Exception as e:
                        event = CCEventFail((502, 'Bad Gateway'), rtime = event.rtime)
                        event.setWarning('Malformed SDP Body received from ' \
                          'downstream: "%s"' % str(e))
                        return self.updateFailed(event)
                    return (UaStateConnected,)
                else:
                    self.ua.rSDP = body.getCopy()
            else:
                self.ua.rSDP = None
            self.ua.equeue.append(event)
            return (UaStateConnected,)
        if code in (301, 302) and resp.countHFs('contact') > 0:
            scode = (code, reason, body, (resp.getHFBody('contact').getUri().getCopy(),))
            event = CCEventRedirect(scode, rtime = resp.rtime, origin = self.ua.origin)
        elif code == 300 and resp.countHFs('contact') > 0:
            redirects = tuple(x.getUri().getCopy() for x in resp.getHFBodys('contact'))
            scode = (code, reason, body, redirects)
            event = CCEventRedirect(scode, rtime = resp.rtime, origin = self.ua.origin)
        else:
            event = CCEventFail(scode, rtime = resp.rtime, origin = self.ua.origin)
            try:
                event.reason = resp.getHFBody('reason')
            except:
                pass

        if code in (408, 481):
            # If the response for a request within a dialog is a 481
            # (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the
            # UAC SHOULD terminate the dialog.  A UAC SHOULD also terminate a
            # dialog if no response at all is received for the request (the
            # client transaction would inform the TU about the timeout.)
            return self.updateFailed(event)

        self.ua.equeue.append(event)
        return (UaStateConnected,)

    def updateFailed(self, event):
        self.ua.equeue.append(event)
        req = self.ua.genRequest('BYE', reason = event.reason)
        self.ua.lCSeq += 1
        self.ua.global_config['_sip_tm'].newTransaction(req, \
          laddress = self.ua.source_address, compact = self.ua.compact_sip)
        self.ua.cancelCreditTimer()
        self.ua.disconnect_ts = event.rtime
        self.ua.equeue.append(CCEventDisconnect(rtime = event.rtime, \
          origin = self.ua.origin))
        return (UaStateDisconnected, self.ua.disc_cbs, event.rtime, \
          event.origin)

    def recvEvent(self, event):
        if isinstance(event, CCEventDisconnect) or isinstance(event, CCEventFail) or isinstance(event, CCEventRedirect):
            self.ua.global_config['_sip_tm'].cancelTransaction(self.ua.tr)
            req = self.ua.genRequest('BYE', reason = event.reason)
            self.ua.lCSeq += 1
            self.ua.global_config['_sip_tm'].newTransaction(req, \
              laddress = self.ua.source_address, compact = self.ua.compact_sip)
            self.ua.cancelCreditTimer()
            self.ua.disconnect_ts = event.rtime
            return (UaStateDisconnected, self.ua.disc_cbs, event.rtime, event.origin)
        #print 'wrong event %s in the Updating state' % event
        return None

if not 'UaStateConnected' in globals():
    from sippy.UaStateConnected import UaStateConnected
if not 'UaStateDisconnected' in globals():
    from sippy.UaStateDisconnected import UaStateDisconnected


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/services/audience_insights_service.proto

package com.google.ads.googleads.v12.services;

/**
 *

 * An entity or category representing a topic that defines an audience.
 *

 *
 * Protobuf type {@code google.ads.googleads.v12.services.AudienceInsightsTopic}
 */
public final class AudienceInsightsTopic extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:google.ads.googleads.v12.services.AudienceInsightsTopic)
    AudienceInsightsTopicOrBuilder {
private static final long serialVersionUID = 0L;
  // Use AudienceInsightsTopic.newBuilder() to construct.
  private AudienceInsightsTopic(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private AudienceInsightsTopic() {
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(
      UnusedPrivateParameter unused) {
    return new AudienceInsightsTopic();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return this.unknownFields;
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return com.google.ads.googleads.v12.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v12_services_AudienceInsightsTopic_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.ads.googleads.v12.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v12_services_AudienceInsightsTopic_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.ads.googleads.v12.services.AudienceInsightsTopic.class, com.google.ads.googleads.v12.services.AudienceInsightsTopic.Builder.class);
  }

  private int topicCase_ = 0;
  private java.lang.Object topic_;
  public enum TopicCase
      implements com.google.protobuf.Internal.EnumLite,
          com.google.protobuf.AbstractMessage.InternalOneOfEnum {
    ENTITY(1),
    CATEGORY(2),
    TOPIC_NOT_SET(0);
    private final int value;
    private TopicCase(int value) {
      this.value = value;
    }
    /**
     * @param value The number of the enum to look for.
     * @return The enum associated with the given number.
     * @deprecated Use {@link #forNumber(int)} instead.
     */
    @java.lang.Deprecated
    public static TopicCase valueOf(int value) {
      return forNumber(value);
    }

    public static TopicCase forNumber(int value) {
      switch (value) {
        case 1: return ENTITY;
        case 2: return CATEGORY;
        case 0: return TOPIC_NOT_SET;
        default: return null;
      }
    }
    public int getNumber() {
      return this.value;
    }
  };

  public TopicCase
  getTopicCase() {
    return TopicCase.forNumber(
        topicCase_);
  }

  public static final int ENTITY_FIELD_NUMBER = 1;
  /**
   *

   * A Knowledge Graph entity
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
   * @return Whether the entity field is set.
   */
  @java.lang.Override
  public boolean hasEntity() {
    return topicCase_ == 1;
  }
  /**
   *

   * A Knowledge Graph entity
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
   * @return The entity.
   */
  @java.lang.Override
  public com.google.ads.googleads.v12.services.AudienceInsightsEntity getEntity() {
    if (topicCase_ == 1) {
       return (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_;
    }
    return com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
  }
  /**
   *

   * A Knowledge Graph entity
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
   */
  @java.lang.Override
  public com.google.ads.googleads.v12.services.AudienceInsightsEntityOrBuilder getEntityOrBuilder() {
    if (topicCase_ == 1) {
       return (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_;
    }
    return com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
  }

  public static final int CATEGORY_FIELD_NUMBER = 2;
  /**
   *

   * A Product & Service category
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
   * @return Whether the category field is set.
   */
  @java.lang.Override
  public boolean hasCategory() {
    return topicCase_ == 2;
  }
  /**
   *

   * A Product & Service category
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
   * @return The category.
   */
  @java.lang.Override
  public com.google.ads.googleads.v12.services.AudienceInsightsCategory getCategory() {
    if (topicCase_ == 2) {
       return (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_;
    }
    return com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
  }
  /**
   *

   * A Product & Service category
   *

   *
   * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
   */
  @java.lang.Override
  public com.google.ads.googleads.v12.services.AudienceInsightsCategoryOrBuilder getCategoryOrBuilder() {
    if (topicCase_ == 2) {
       return (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_;
    }
    return com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
  }

  private byte memoizedIsInitialized = -1;
  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (topicCase_ == 1) {
      output.writeMessage(1, (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_);
    }
    if (topicCase_ == 2) {
      output.writeMessage(2, (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_);
    }
    getUnknownFields().writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (topicCase_ == 1) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(1, (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_);
    }
    if (topicCase_ == 2) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(2, (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof com.google.ads.googleads.v12.services.AudienceInsightsTopic)) {
      return super.equals(obj);
    }
    com.google.ads.googleads.v12.services.AudienceInsightsTopic other = (com.google.ads.googleads.v12.services.AudienceInsightsTopic) obj;

    if (!getTopicCase().equals(other.getTopicCase())) return false;
    switch (topicCase_) {
      case 1:
        if (!getEntity()
            .equals(other.getEntity())) return false;
        break;
      case 2:
        if (!getCategory()
            .equals(other.getCategory())) return false;
        break;
      case 0:
      default:
    }
    if (!getUnknownFields().equals(other.getUnknownFields())) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    switch (topicCase_) {
      case 1:
        hash = (37 * hash) + ENTITY_FIELD_NUMBER;
        hash = (53 * hash) + getEntity().hashCode();
        break;
      case 2:
        hash = (37 * hash) + CATEGORY_FIELD_NUMBER;
        hash = (53 * hash) + getCategory().hashCode();
        break;
      case 0:
      default:
    }
    hash = (29 * hash) + getUnknownFields().hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      java.nio.ByteBuffer data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(com.google.ads.googleads.v12.services.AudienceInsightsTopic prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   * An entity or category representing a topic that defines an audience.
   *

   *
   * Protobuf type {@code google.ads.googleads.v12.services.AudienceInsightsTopic}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:google.ads.googleads.v12.services.AudienceInsightsTopic)
      com.google.ads.googleads.v12.services.AudienceInsightsTopicOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.google.ads.googleads.v12.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v12_services_AudienceInsightsTopic_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.ads.googleads.v12.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v12_services_AudienceInsightsTopic_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.ads.googleads.v12.services.AudienceInsightsTopic.class, com.google.ads.googleads.v12.services.AudienceInsightsTopic.Builder.class);
    }

    // Construct using com.google.ads.googleads.v12.services.AudienceInsightsTopic.newBuilder()
    private Builder() {

    }

    private Builder(
        com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);

    }
    @java.lang.Override
    public Builder clear() {
      super.clear();
      if (entityBuilder_ != null) {
        entityBuilder_.clear();
      }
      if (categoryBuilder_ != null) {
        categoryBuilder_.clear();
      }
      topicCase_ = 0;
      topic_ = null;
      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return com.google.ads.googleads.v12.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v12_services_AudienceInsightsTopic_descriptor;
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsTopic getDefaultInstanceForType() {
      return com.google.ads.googleads.v12.services.AudienceInsightsTopic.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsTopic build() {
      com.google.ads.googleads.v12.services.AudienceInsightsTopic result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsTopic buildPartial() {
      com.google.ads.googleads.v12.services.AudienceInsightsTopic result = new com.google.ads.googleads.v12.services.AudienceInsightsTopic(this);
      if (topicCase_ == 1) {
        if (entityBuilder_ == null) {
          result.topic_ = topic_;
        } else {
          result.topic_ = entityBuilder_.build();
        }
      }
      if (topicCase_ == 2) {
        if (categoryBuilder_ == null) {
          result.topic_ = topic_;
        } else {
          result.topic_ = categoryBuilder_.build();
        }
      }
      result.topicCase_ = topicCase_;
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return super.clone();
    }
    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return super.setField(field, value);
    }
    @java.lang.Override
    public Builder clearField(
        com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }
    @java.lang.Override
    public Builder clearOneof(
        com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }
    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        int index, java.lang.Object value) {
      return super.setRepeatedField(field, index, value);
    }
    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return super.addRepeatedField(field, value);
    }
    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.ads.googleads.v12.services.AudienceInsightsTopic) {
        return mergeFrom((com.google.ads.googleads.v12.services.AudienceInsightsTopic)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.ads.googleads.v12.services.AudienceInsightsTopic other) {
      if (other == com.google.ads.googleads.v12.services.AudienceInsightsTopic.getDefaultInstance()) return this;
      switch (other.getTopicCase()) {
        case ENTITY: {
          mergeEntity(other.getEntity());
          break;
        }
        case CATEGORY: {
          mergeCategory(other.getCategory());
          break;
        }
        case TOPIC_NOT_SET: {
          break;
        }
      }
      this.mergeUnknownFields(other.getUnknownFields());
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      if (extensionRegistry == null) {
        throw new java.lang.NullPointerException();
      }
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            case 10: {
              input.readMessage(
                  getEntityFieldBuilder().getBuilder(),
                  extensionRegistry);
              topicCase_ = 1;
              break;
            } // case 10
            case 18: {
              input.readMessage(
                  getCategoryFieldBuilder().getBuilder(),
                  extensionRegistry);
              topicCase_ = 2;
              break;
            } // case 18
            default: {
              if (!super.parseUnknownField(input, extensionRegistry, tag)) {
                done = true; // was an endgroup tag
              }
              break;
            } // default:
          } // switch (tag)
        } // while (!done)
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.unwrapIOException();
      } finally {
        onChanged();
      } // finally
      return this;
    }
    private int topicCase_ = 0;
    private java.lang.Object topic_;
    public TopicCase
        getTopicCase() {
      return TopicCase.forNumber(
          topicCase_);
    }

    public Builder clearTopic() {
      topicCase_ = 0;
      topic_ = null;
      onChanged();
      return this;
    }

    private com.google.protobuf.SingleFieldBuilderV3<
        com.google.ads.googleads.v12.services.AudienceInsightsEntity, com.google.ads.googleads.v12.services.AudienceInsightsEntity.Builder, com.google.ads.googleads.v12.services.AudienceInsightsEntityOrBuilder> entityBuilder_;
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     * @return Whether the entity field is set.
     */
    @java.lang.Override
    public boolean hasEntity() {
      return topicCase_ == 1;
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     * @return The entity.
     */
    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsEntity getEntity() {
      if (entityBuilder_ == null) {
        if (topicCase_ == 1) {
          return (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_;
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
      } else {
        if (topicCase_ == 1) {
          return entityBuilder_.getMessage();
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
      }
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    public Builder setEntity(com.google.ads.googleads.v12.services.AudienceInsightsEntity value) {
      if (entityBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        topic_ = value;
        onChanged();
      } else {
        entityBuilder_.setMessage(value);
      }
      topicCase_ = 1;
      return this;
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    public Builder setEntity(
        com.google.ads.googleads.v12.services.AudienceInsightsEntity.Builder builderForValue) {
      if (entityBuilder_ == null) {
        topic_ = builderForValue.build();
        onChanged();
      } else {
        entityBuilder_.setMessage(builderForValue.build());
      }
      topicCase_ = 1;
      return this;
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    public Builder mergeEntity(com.google.ads.googleads.v12.services.AudienceInsightsEntity value) {
      if (entityBuilder_ == null) {
        if (topicCase_ == 1 &&
            topic_ != com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance()) {
          topic_ = com.google.ads.googleads.v12.services.AudienceInsightsEntity.newBuilder((com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_)
              .mergeFrom(value).buildPartial();
        } else {
          topic_ = value;
        }
        onChanged();
      } else {
        if (topicCase_ == 1) {
          entityBuilder_.mergeFrom(value);
        } else {
          entityBuilder_.setMessage(value);
        }
      }
      topicCase_ = 1;
      return this;
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    public Builder clearEntity() {
      if (entityBuilder_ == null) {
        if (topicCase_ == 1) {
          topicCase_ = 0;
          topic_ = null;
          onChanged();
        }
      } else {
        if (topicCase_ == 1) {
          topicCase_ = 0;
          topic_ = null;
        }
        entityBuilder_.clear();
      }
      return this;
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    public com.google.ads.googleads.v12.services.AudienceInsightsEntity.Builder getEntityBuilder() {
      return getEntityFieldBuilder().getBuilder();
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsEntityOrBuilder getEntityOrBuilder() {
      if ((topicCase_ == 1) && (entityBuilder_ != null)) {
        return entityBuilder_.getMessageOrBuilder();
      } else {
        if (topicCase_ == 1) {
          return (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_;
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
      }
    }
    /**
     *

     * A Knowledge Graph entity
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsEntity entity = 1;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
        com.google.ads.googleads.v12.services.AudienceInsightsEntity, com.google.ads.googleads.v12.services.AudienceInsightsEntity.Builder, com.google.ads.googleads.v12.services.AudienceInsightsEntityOrBuilder>
        getEntityFieldBuilder() {
      if (entityBuilder_ == null) {
        if (!(topicCase_ == 1)) {
          topic_ = com.google.ads.googleads.v12.services.AudienceInsightsEntity.getDefaultInstance();
        }
        entityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
            com.google.ads.googleads.v12.services.AudienceInsightsEntity, com.google.ads.googleads.v12.services.AudienceInsightsEntity.Builder, com.google.ads.googleads.v12.services.AudienceInsightsEntityOrBuilder>(
                (com.google.ads.googleads.v12.services.AudienceInsightsEntity) topic_,
                getParentForChildren(),
                isClean());
        topic_ = null;
      }
      topicCase_ = 1;
      onChanged();;
      return entityBuilder_;
    }

    private com.google.protobuf.SingleFieldBuilderV3<
        com.google.ads.googleads.v12.services.AudienceInsightsCategory, com.google.ads.googleads.v12.services.AudienceInsightsCategory.Builder, com.google.ads.googleads.v12.services.AudienceInsightsCategoryOrBuilder> categoryBuilder_;
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     * @return Whether the category field is set.
     */
    @java.lang.Override
    public boolean hasCategory() {
      return topicCase_ == 2;
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     * @return The category.
     */
    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsCategory getCategory() {
      if (categoryBuilder_ == null) {
        if (topicCase_ == 2) {
          return (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_;
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
      } else {
        if (topicCase_ == 2) {
          return categoryBuilder_.getMessage();
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
      }
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    public Builder setCategory(com.google.ads.googleads.v12.services.AudienceInsightsCategory value) {
      if (categoryBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        topic_ = value;
        onChanged();
      } else {
        categoryBuilder_.setMessage(value);
      }
      topicCase_ = 2;
      return this;
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    public Builder setCategory(
        com.google.ads.googleads.v12.services.AudienceInsightsCategory.Builder builderForValue) {
      if (categoryBuilder_ == null) {
        topic_ = builderForValue.build();
        onChanged();
      } else {
        categoryBuilder_.setMessage(builderForValue.build());
      }
      topicCase_ = 2;
      return this;
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    public Builder mergeCategory(com.google.ads.googleads.v12.services.AudienceInsightsCategory value) {
      if (categoryBuilder_ == null) {
        if (topicCase_ == 2 &&
            topic_ != com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance()) {
          topic_ = com.google.ads.googleads.v12.services.AudienceInsightsCategory.newBuilder((com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_)
              .mergeFrom(value).buildPartial();
        } else {
          topic_ = value;
        }
        onChanged();
      } else {
        if (topicCase_ == 2) {
          categoryBuilder_.mergeFrom(value);
        } else {
          categoryBuilder_.setMessage(value);
        }
      }
      topicCase_ = 2;
      return this;
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    public Builder clearCategory() {
      if (categoryBuilder_ == null) {
        if (topicCase_ == 2) {
          topicCase_ = 0;
          topic_ = null;
          onChanged();
        }
      } else {
        if (topicCase_ == 2) {
          topicCase_ = 0;
          topic_ = null;
        }
        categoryBuilder_.clear();
      }
      return this;
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    public com.google.ads.googleads.v12.services.AudienceInsightsCategory.Builder getCategoryBuilder() {
      return getCategoryFieldBuilder().getBuilder();
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    @java.lang.Override
    public com.google.ads.googleads.v12.services.AudienceInsightsCategoryOrBuilder getCategoryOrBuilder() {
      if ((topicCase_ == 2) && (categoryBuilder_ != null)) {
        return categoryBuilder_.getMessageOrBuilder();
      } else {
        if (topicCase_ == 2) {
          return (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_;
        }
        return com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
      }
    }
    /**
     *

     * A Product & Service category
     *

     *
     * .google.ads.googleads.v12.services.AudienceInsightsCategory category = 2;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
        com.google.ads.googleads.v12.services.AudienceInsightsCategory, com.google.ads.googleads.v12.services.AudienceInsightsCategory.Builder, com.google.ads.googleads.v12.services.AudienceInsightsCategoryOrBuilder>
        getCategoryFieldBuilder() {
      if (categoryBuilder_ == null) {
        if (!(topicCase_ == 2)) {
          topic_ = com.google.ads.googleads.v12.services.AudienceInsightsCategory.getDefaultInstance();
        }
        categoryBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
            com.google.ads.googleads.v12.services.AudienceInsightsCategory, com.google.ads.googleads.v12.services.AudienceInsightsCategory.Builder, com.google.ads.googleads.v12.services.AudienceInsightsCategoryOrBuilder>(
                (com.google.ads.googleads.v12.services.AudienceInsightsCategory) topic_,
                getParentForChildren(),
                isClean());
        topic_ = null;
      }
      topicCase_ = 2;
      onChanged();;
      return categoryBuilder_;
    }
    @java.lang.Override
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    @java.lang.Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.ads.googleads.v12.services.AudienceInsightsTopic)
  }

  // @@protoc_insertion_point(class_scope:google.ads.googleads.v12.services.AudienceInsightsTopic)
  private static final com.google.ads.googleads.v12.services.AudienceInsightsTopic DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new com.google.ads.googleads.v12.services.AudienceInsightsTopic();
  }

  public static com.google.ads.googleads.v12.services.AudienceInsightsTopic getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<AudienceInsightsTopic>
      PARSER = new com.google.protobuf.AbstractParser<AudienceInsightsTopic>() {
    @java.lang.Override
    public AudienceInsightsTopic parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      Builder builder = newBuilder();
      try {
        builder.mergeFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(builder.buildPartial());
      } catch (com.google.protobuf.UninitializedMessageException e) {
        throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(e)
            .setUnfinishedMessage(builder.buildPartial());
      }
      return builder.buildPartial();
    }
  };

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

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

  @java.lang.Override
  public com.google.ads.googleads.v12.services.AudienceInsightsTopic getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}

redpajama_set_name: RedPajamaGithub


text:
import os
import subprocess
import uuid

from verst.pants.docker.docker_jvm_app_bundle_task import DockerJvmAppBundleTask
from verst.pants.docker.target import DockerJvmAppTarget
from verst_test.pants.docker.docker_bundle_test_mixin import DockerBundleTestMixin

from pants.backend.jvm.targets.jvm_app import JvmApp
from pants.backend.jvm.tasks.bundle_create import BundleCreate
from pants.backend.jvm.tasks.consolidate_classpath import ConsolidateClasspath
from pants.util.dirutil import safe_mkdir

from pants.backend.jvm.jar_dependency_utils import M2Coordinate, ResolvedJar
from pants.backend.jvm.targets.jvm_binary import JvmBinary
from pants.backend.jvm.tasks.classpath_products import ClasspathProducts
from pants.util.contextutil import open_zip
from pants_test.jvm.jvm_tool_task_test_base import JvmToolTaskTestBase

class JvmBinaryTaskTestBase(JvmToolTaskTestBase):
  """
  Copied from pantsbuild/pants because it's not exposed in testinfra
  TODO(todd): include ig.

  :API: public
  """

  def create_artifact(self, org, name, rev, classifier=None, ext=None, materialize=True):
    """
    :API: public
    :param string org: The maven dependency `groupId`.
    :param string name: The maven dependency `artifactId`.
    :param string rev: The maven dependency `version`.
    :param string classifier: The maven dependency `classifier`.
    :param string ext: There is no direct maven parallel, but the maven `packaging` value of the
                       depended-on artifact for simple cases, and in more complex cases the
                       extension of the artifact.  For example, 'bundle' packaging implies an
                       extension of 'jar'.  Defaults to 'jar'.
    :param bool materialize: `False` to populate the returned resolved_jar with a `pants_path` that
                             does not exist; defaults to `True` and `touch`es the `pants_path`.
    :returns: A resolved jar describing the artifact.
    :rtype: :class:`pants.java.jar.ResolvedJar`
    """
    coordinate = M2Coordinate(org=org, name=name, rev=rev, classifier=classifier, ext=ext)
    cache_path = 'not/a/real/cache/path'
    jar_name = coordinate.artifact_filename
    if materialize:
      pants_path = self.create_workdir_file(jar_name)
    else:
      pants_path = os.path.join(self.pants_workdir, jar_name)

    return ResolvedJar(coordinate=coordinate, cache_path=cache_path, pants_path=pants_path)

  def ensure_classpath_products(self, context):
    """Gets or creates the classpath products expected by `JvmBinaryTask`.
    :API: public
    :param context: The pants run context to get/create/associate classpath products with.
    :type context: :class:`pants.goal.context.Context`
    :returns: The classpath products associated with the given `context`
    :rtype: :class:`pants.backend.jvm.tasks.classpath_products.ClasspathProducts`
    """
    return context.products.get_data('runtime_classpath',
                                     init_func=ClasspathProducts.init_func(self.pants_workdir))

class TestDockerJvmBundleTask(JvmBinaryTaskTestBase, DockerBundleTestMixin):
  @classmethod
  def task_type(cls):
    return DockerJvmAppBundleTask

  def setUp(self):
    super(TestDockerJvmBundleTask, self).setUp()
    self.consolidate_classpath_type = self.synthesize_task_subtype(ConsolidateClasspath, 'cc_scope')
    self.bundle_create_type = self.synthesize_task_subtype(BundleCreate, 'bc_scope')

  def _create_context(self, target):
    self.test_context = self.context(
      for_task_types=[self.consolidate_classpath_type, self.bundle_create_type],
      target_roots=[target]
    )

    self.classpath_products = self.ensure_classpath_products(self.test_context)

  def _create_artifact(self, target, jarname):
    jar_artifact = self.create_artifact(org='org.example', name=jarname, rev='1.0.0')
    with open_zip(jar_artifact.pants_path, 'w') as jar:
      jar.writestr(jarname + '/Foo.class', '')
    self.classpath_products.add_jars_for_targets(targets=[target],
                                                 conf='default',
                                                 resolved_jars=[jar_artifact])

  def _execute(self):
    docker_jvm_bundle = self.prepare_execute(self.test_context)
    self.consolidate_classpath_type(
      self.test_context, os.path.join(self.pants_workdir, 'cc')).execute()
    self.bundle_create_type(self.test_context, os.path.join(self.pants_workdir, 'bc')).execute()
    docker_jvm_bundle.execute()

  def test_docker_image_products(self):
    expected_image_name = 'test-image-%s' % uuid.uuid4()
    expected_image = expected_image_name + ':foo-bar'
    binary_target = self.make_target(spec='//bar:bar-binary',
                                     target_type=JvmBinary,
                                     source='Bar.java')
    app_target = self.make_target(spec='//bar:bar-app',
                                  target_type=JvmApp,
                                  basename='foo-app',
                                  binary=':bar-binary')
    docker_target = self.make_target(spec='//bar:bar-image',
                                     target_type=DockerJvmAppTarget,
                                     image_name=expected_image_name,
                                     image_tag='foo-bar',
                                     base_image='scratch',
                                     dependencies=[app_target])

    safe_mkdir(os.path.join(self.build_root, 'bar'))
    with open(os.path.join(self.build_root, 'bar/Bar.java'), 'w') as f:
      f.write("""""")

    self._create_context(docker_target)

    self._create_artifact(binary_target, 'foo')

    self.add_to_runtime_classpath(
      self.test_context, binary_target, {'Bar.class': '', 'bar.txt': ''})

    try:
      self._execute()

      with self.parse_tar(self.test_context, docker_target, expected_image) as tar:
        self.assertIn('manifest.json', tar.getnames())
        # TODO test more properties if we can assure it's hermetic somehow
    finally:
      subprocess.call(['docker', 'rmi', expected_image])


text:
DELETE FROM eav_attribute WHERE attribute_code = 'pregunta' AND entity_type_id IN
                    (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product');
DROP TABLE IF EXISTS preguntas_products_pregunta_product;
DROP TABLE IF EXISTS preguntas_products_pregunta;
DELETE FROM core_resource WHERE code = 'preguntas_products_setup';
DELETE FROM core_config_data WHERE path like 'preguntas_products/%';


text:
var _      = require('lodash');
var markit = require('markit');
var slug   = require('./slug');

function fromIntro(markdown) {
  var current = null;
  var nav = [];
  var r = new markit.Renderer();
  r.header = function(text, level) {
    if (level === 1) {
      if (_.find(nav, {name: text}) == null) {
        current = {
          name: text,
          link: 'index.html',
          subnav: []
        };
        nav.push(current);
      }
    }
    if (level === 2 && current !== null) {
      current.subnav.push({
        name: text,
        link: 'index.html#' + slug.from(text),
        count: null
      });
    }
  };
  markit(markdown, {renderer: r});
  return nav;
}

function fromPages(pages) {
  var nav = pages.map(function(page) {
    var subnav = page.headings.map(function(heading) {
      return {
        name: heading.name,
        link: slug.from(page.name) + '.html#' + slug.from(heading.name),
        count: heading.samples.length
      };
    });
    return {
      name: page.name,
      link: slug.from(page.name) + '.html',
      subnav: subnav
    }
  });
  return nav;
}

exports.from = function(intro, samples) {
  var introNav = fromIntro(intro);
  var pagesNav = fromPages(samples);
  return introNav.concat(pagesNav);
};


text:
package org.jclouds.rackspace.clouddns.us.features;

import org.jclouds.rackspace.clouddns.v1.features.ReverseDNSApiLiveTest;
import org.testng.annotations.Test;

@Test(groups = "live", singleThreaded = true, testName = "CloudDNSUSReverseDNSApiLiveTest")
public class CloudDNSUSReverseDNSApiLiveTest extends ReverseDNSApiLiveTest {
   public CloudDNSUSReverseDNSApiLiveTest() {
      provider = "rackspace-clouddns-us";
   }
}


text:
Rails.application.configure do

  config.lograge.enabled = true

  config.lograge.formatter = Lograge::Formatters::Graylog2.new

  # add time to lograge
  config.lograge.custom_options = lambda do |event|
    {:time => event.time}
  end

end


text:
import sys, os, alsaaudio, time, audioop, numpy, glob,  scipy, subprocess, wave, cPickle, threading, shutil
import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
from scipy.fftpack import rfft
import audioFeatureExtraction as aF
import audioTrainTest as aT
import audioSegmentation as aS
from scipy.fftpack import fft
import matplotlib
matplotlib.use('TkAgg')

Fs = 16000

def recordAudioSegments(RecordPath, BLOCKSIZE):
	# This function is used for recording audio segments (until ctr+c is pressed)
	# ARGUMENTS:
	# - RecordPath:		the path where the wav segments will be stored
	# - BLOCKSIZE:		segment recording size (in seconds)
	#
	# NOTE: filenames are based on clock() value

	print "Press Ctr+C to stop recording"
	RecordPath += os.sep
	d = os.path.dirname(RecordPath)
	if os.path.exists(d) and RecordPath!=".":
		shutil.rmtree(RecordPath)
	os.makedirs(RecordPath)

	inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
	inp.setchannels(1)
	inp.setrate(Fs)
	inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
	inp.setperiodsize(512)
	midTermBufferSize = int(Fs*BLOCKSIZE)
	midTermBuffer = []
	curWindow = []
	elapsedTime = "%08.3f" % (time.time())
	while 1:
			l,data = inp.read()
		    	if l:
				for i in range(len(data)/2):
					curWindow.append(audioop.getsample(data, 2, i))

				if (len(curWindow)+len(midTermBuffer)>midTermBufferSize):
					samplesToCopyToMidBuffer = midTermBufferSize - len(midTermBuffer)
				else:
					samplesToCopyToMidBuffer = len(curWindow)

				midTermBuffer = midTermBuffer + curWindow[0:samplesToCopyToMidBuffer];
				del(curWindow[0:samplesToCopyToMidBuffer])

			if len(midTermBuffer) == midTermBufferSize:
				# allData = allData + midTermBuffer
				curWavFileName = RecordPath + os.sep + str(elapsedTime) + ".wav"
				midTermBufferArray = numpy.int16(midTermBuffer)
				wavfile.write(curWavFileName, Fs, midTermBufferArray)
				print "AUDIO  OUTPUT: Saved " + curWavFileName
				midTermBuffer = []
				elapsedTime = "%08.3f" % (time.time())

def recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType):
	'''
	recordAnalyzeAudio(duration, outputWavFile, midTermBufferSizeSec, modelName, modelType)

	This function is used to record and analyze audio segments, in a fix window basis.

	ARGUMENTS:
	- duration			total recording duration
	- outputWavFile			path of the output WAV file
	- midTermBufferSizeSec		(fix)segment length in seconds
	- modelName			classification model name
	- modelType			classification model type

	'''

	if modelType=='svm':
		[Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, computeBEAT] = aT.loadSVModel(modelName)
	elif modelType=='knn':
		[Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, computeBEAT] = aT.loadKNNModel(modelName)
	else:
		Classifier = None

	inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK)
	inp.setchannels(1)
	inp.setrate(Fs)
	inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
	inp.setperiodsize(512)
	midTermBufferSize = int(midTermBufferSizeSec * Fs)
	allData = []
	midTermBuffer = []
	curWindow = []
	count = 0

	while len(allData)<duration*Fs:
		# Read data from device
		l,data = inp.read()
	    	if l:
			for i in range(l):
				curWindow.append(audioop.getsample(data, 2, i))
			if (len(curWindow)+len(midTermBuffer)>midTermBufferSize):
				samplesToCopyToMidBuffer = midTermBufferSize - len(midTermBuffer)
			else:
				samplesToCopyToMidBuffer = len(curWindow)
			midTermBuffer = midTermBuffer + curWindow[0:samplesToCopyToMidBuffer];
			del(curWindow[0:samplesToCopyToMidBuffer])
		if len(midTermBuffer) == midTermBufferSize:
			count += 1
			if Classifier!=None:
				[mtFeatures, stFeatures] = aF.mtFeatureExtraction(midTermBuffer, Fs, 2.0*Fs, 2.0*Fs, 0.020*Fs, 0.020*Fs)
				curFV = (mtFeatures[:,0] - MEAN) / STD;
				[result, P] = aT.classifierWrapper(Classifier, modelType, curFV)
				print classNames[int(result)]
			allData = allData + midTermBuffer

			plt.clf()
			plt.plot(midTermBuffer)
			plt.show(block = False)
			plt.draw()

			midTermBuffer = []

	allDataArray = numpy.int16(allData)
	wavfile.write(outputWavFile, Fs, allDataArray)

def main(argv):
	if argv[1] == '-recordSegments':		# record input
		if (len(argv)==4): 			# record segments (until ctrl+c pressed)
			recordAudioSegments(argv[2], float(argv[3]))
		else:
			print "Error.\nSyntax: " + argv[0] + " -recordSegments <recordingPath> <segmentDuration>"

	if argv[1] == '-recordAndClassifySegments':	# record input
		if (len(argv)==6):			# recording + audio analysis
			duration = int(argv[2])
			outputWavFile = argv[3]
			modelName = argv[4]
			modelType = argv[5]
			if modelType not in ["svm", "knn"]:
				raise Exception("ModelType has to be either svm or knn!")
			if not os.path.isfile(modelName):
				raise Exception("Input modelName not found!")
			recordAnalyzeAudio(duration, outputWavFile, 2.0, modelName, modelType)
		else:
			print "Error.\nSyntax: " + argv[0] + " -recordAndClassifySegments <duration> <outputWafFile> <modelName> <modelType>"

if __name__ == '__main__':
	main(sys.argv)


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

ContactName
===========

Contains name properties of a `Contact` object.

Properties
----------

- __formatted:__ The complete name of the contact. _(DOMString)_
- __familyName:__ The contacts family name. _(DOMString)_
- __givenName:__ The contacts given name. _(DOMString)_
- __middleName:__ The contacts middle name. _(DOMString)_
- __honorificPrefix:__ The contacts prefix (example Mr. or Dr.) _(DOMString)_
- __honorificSuffix:__ The contacts suffix (example Esq.). _(DOMString)_

Details
-------

The `ContactName` object stores name properties of a contact.

Supported Platforms
-------------------

- Android 2.X
- BlackBerry WebWorks (OS 5.0 and higher)
- iOS
- Bada 1.2 & 2.0
- Windows Phone 7 and 8
- Windows 8

Quick Example
-------------

    function onSuccess(contacts) {
		for (var i=0; i<contacts.length; i++) {
			alert("Formatted: " + contacts[i].name.formatted + "\n" +
					"Family Name: "  + contacts[i].name.familyName + "\n" +
					"Given Name: "  + contacts[i].name.givenName + "\n" +
					"Middle Name: "  + contacts[i].name.middleName + "\n" +
					"Suffix: "  + contacts[i].name.honorificSuffix + "\n" +
					"Prefix: "  + contacts[i].name.honorificSuffix);
		}
    };

    function onError(contactError) {
        alert('onError!');
    };

    var options = new ContactFindOptions();
	options.filter="";
	filter = ["displayName","name"];
    navigator.contacts.find(filter, onSuccess, onError, options);

Full Example
------------

    <!DOCTYPE html>

        <title>Contact Example</title>

Example

Find Contacts

Android Quirks
------------
- __formatted:__ Partially supported.  Will return the concatenation of honorificPrefix, givenName, middleName, familyName and honorificSuffix but will not store.

BlackBerry WebWorks (OS 5.0 and higher) Quirks
---------------------------------------------

- __formatted:__ Partially supported.  Will return concatenation of BlackBerry __firstName__ and __lastName__ fields.
- __familyName:__ Supported.  Stored in BlackBerry __lastName__ field.
- __givenName:__ Supported.  Stored in BlackBerry __firstName__ field.
- __middleName:__ This property is not supported, and will always return `null`.
- __honorificPrefix:__ This property is not supported, and will always return `null`.
- __honorificSuffix:__ This property is not supported, and will always return `null`.

iOS Quirks
------------
- __formatted:__ Partially supported.  Will return iOS Composite Name but will not store.

Bada Quirks
-----------
- __formatted:__ Property not supported
- __middleName:__ Property not supported
_ __honorificPrefix:__ Property not supported
- __honorificSuffix:__ Property not supported


text:
#ifndef SkGaussFilter_DEFINED
#  define SkGaussFilter_DEFINED
#  include <cstddef>
// Define gaussian filters for values of sigma < 2. Produce values good to 1 part in 1,000,000.
// Produces values as defined in "Scale-Space for Discrete Signals" by Tony Lindeberg.
class SkGaussFilter
{
public:
  static constexpr int kGaussArrayMax = 6;
  explicit SkGaussFilter(double sigma);
  size_t size() const
  {
    return fN;
  }
  int radius() const
  {
    return fN - 1;
  }
  int width() const
  {
    return 2 * this->radius() + 1;
  }
    // Allow a filter to be used in a C++ ranged-for loop.
  const double* begin() const
  {
    return &fBasis[0];
  }
  const double* end() const
  {
    return &fBasis[fN];
  }
private:
  double fBasis[kGaussArrayMax];
  int fN;
};
#endif


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UIManager : IService
{
	/****************************************************************************************/
	/*										VARIABLES									  	*/
	/****************************************************************************************/

	//UI core
	private Dictionary<string, UIElement> uiStack;
	private DataLocator dataLocator;

	//Event System
	private const string eventSystemName = "EventSystem";
	public GameObject eventSystem;

	/****************************************************************************************/
	/*										ADD METHODS										*/
	/****************************************************************************************/

	public void Init ()
	{
		dataLocator = ServiceLocator.GetService<DataLocator>();
		uiStack = new Dictionary<string, UIElement>();
	}

	public UIElement MakeUI(string uiName)
	{
		GameObject uiObject = dataLocator.InstantiateLoadedResource(uiName);
		uiObject.name = uiName;
		UIElement uiScript = uiObject.GetComponent<UIElement>();
		uiScript.Init();
		if (eventSystem == null)
		{
			eventSystem = dataLocator.InstantiateLoadedResource(eventSystemName);
		}
		uiStack.Add(uiName, uiScript);
		return uiScript;
	}

	public UIElement GetUI(string uiName)
	{
		if (HasUI(uiName))
		{
			return uiStack[uiName];
		}
		return null;
	}

	public bool HasUI(string uiName)
	{
		if (!uiStack.ContainsKey(uiName))
		{
			return false;
		}
		return true;
	}

	/****************************************************************************************/
	/*										REMOVE METHODS									*/
	/****************************************************************************************/

	public void DeleteUI(string uiName)
	{
		if (uiStack.ContainsKey(uiName))
		{
			GameObject.Destroy(uiStack[uiName].gameObject);
			uiStack.Remove(uiName);
			if (uiStack.Count == 0 && eventSystem != null)
			{
				RemoveEventSystem();
			}
		}
	}

	public void ClearStack()
	{
		string[] keyArray = new string[uiStack.Count];
		int counter = 0;
		foreach(var key in uiStack.Keys)
		{
			keyArray[counter] = (string)key;
		}
		foreach(string keyToRemove in keyArray)
		{
			DeleteUI(keyToRemove);
		}
	}

	public void RemoveEventSystem()
	{
		GameObject.Destroy(eventSystem);
		eventSystem = null;
	}

}


text:
const nock = require('nock')

const dbs = require('../../lib/dbs')
const removeIfExists = require('../helpers/remove-if-exists')

describe('create initial branch', () => {
  beforeEach(() => {
    delete process.env.IS_ENTERPRISE
    delete process.env.BADGES_HOST
    jest.resetModules()
  })

  beforeAll(async () => {
    nock.disableNetConnect()
    nock.enableNetConnect('localhost:5984')
    const { installations, payments } = await dbs()

    await installations.put({
      _id: '123',
      installation: 137,
      plan: 'free'
    })

    await payments.put({
      _id: '123',
      stripeSubscriptionId: 'stripe123',
      plan: 'personal'
    })
  })

  afterAll(async () => {
    const { installations, repositories, payments } = await dbs()
    await Promise.all([
      removeIfExists(installations, '123'),
      removeIfExists(payments, '123'),
      removeIfExists(repositories, '42', '43', '44', '45', '46', '47', '48', '49', '42:branch:1234abcd', '47:branch:1234abcd', '48:branch:1234abcd', '49:branch:1234abcd')
    ])
  })

  test('create pull request for monorepo with one non-root package.json', async () => {
    const ignore = ['eslint', 'lodash']
    const packagePaths = ['package.json', 'frontend/package.json']
    const packageJsonContents = [{ devDependencies: { '@finnpauls/dep': '1.0.0' } }]
    const registryGet = () => {}
    const log = console

    const { repositories } = await dbs()
    await repositories.put({
      _id: '49',
      accountId: '123',
      fullName: 'finnp/test'
    })

    // mock relative dependencies
    jest.mock('../../utils/initial-branch-utils', () => {
      const utils = require.requireActual('../../utils/initial-branch-utils')
      utils.addNPMPackageData = async (dependencyInfo, registryGet, log) => {
        return [{
          name: '@finnpauls/dep',
          version: '1.0.0',
          type: 'devDependencies',
          data: {
            'dist-tags': {
              latest: '3.0.0-rc1'
            },
            versions: {
              '2.0.0-rc1': true,
              '2.0.0-rc2': true,
              '2.0.0': true,
              '3.0.0-rc1': true,
              '1.0.0': true
            }
          }
        }]
      }
      utils.getDependenciesFromPackageFiles = (packagePaths, packageJsonContents) => {
        return [{
          name: '@finnpauls/dep',
          version: '1.0.0',
          type: 'devDependencies'
        }]
      }
      return utils
    })
    const initialBranchUtils = require.requireMock('../../utils/initial-branch-utils')
    const updatedDependencies = await initialBranchUtils.getUpdatedDependenciesForFiles({ ignore, log, packagePaths, packageJsonContents, registryGet })
    expect(updatedDependencies[0].newVersion).toEqual('2.0.0')
  })
})

/*
function getDependenciesFromPackageFiles (packagePaths, packageJsonContents) {
*/

const { getDependenciesFromPackageFiles } = require('../../utils/initial-branch-utils')
describe('initial branch utils', () => {
  test('getDependenciesFromPackageFiles single devDependency', () => {
    const paths = [
      'foobar/package.json'
    ]
    const contents = { 'foobar/package.json': { devDependencies: { '@finnpauls/dep': '1.0.0' } } }
    const result = getDependenciesFromPackageFiles(paths, contents)
    expect(result).toMatchSnapshot()
  })

  test('getDependenciesFromPackageFiles duplicate dependency across dep type', () => {
    const paths = [
      'foobar/package.json',
      'bazquux/package.json'
    ]
    const contents = {
      'foobar/package.json': { devDependencies: { '@finnpauls/dep': '1.0.0' } },
      'bazquux/package.json': { devDependencies: { '@finnpauls/dep': '1.0.0' } }
    }
    const result = getDependenciesFromPackageFiles(paths, contents)
    expect(result).toMatchSnapshot()
  })

  test('getDependenciesFromPackageFiles workspace', () => {
    const paths = [
      'package.json',
      'bazquux/package.json'
    ]
    const contents = {
      'package.json': { devDependencies: { '@finnpauls/blup': '1.0.0' }, workspaces: 'bazquux/' },
      'bazquux/package.json': { devDependencies: { '@finnpauls/dep': '*' }, dependencies: { 'florp': '1.2.3' } }
    }
    const result = getDependenciesFromPackageFiles(paths, contents)
    expect(result).toMatchSnapshot()
  })
})


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

'use strict';

const {
  api: {
    youtube: {
      ListChannelsConfig,
      ListVideosConfig,
      ListCommentThreadsConfig,
      ListPlaylistConfig,
      ListSearchConfig,
      YouTube,
    }
  }
} = require('@google-cloud/nodejs-common');
const {Report} = require('./base_report.js');

/**
 * Types of implemented YouTube API.
 * @enum {string}
 */
const ReportTargets = Object.freeze({
  CHANNEL: 'CHANNEL',
  VIDEO: 'VIDEO',
  COMMENT: 'COMMENT',
  PLAYLIST: 'PLAYLIST',
  SEARCH: 'SEARCH',
});

/**
 * Configuration for YouTube API.
 * @typedef {!(
 *   ListChannelsConfig
 *   | ListVideosConfig
 *   | ListCommentThreadsConfig
 *   | ListPlaylistConfig
 *   | ListSearchConfig
 * )}
 */
let ListConfig;

/** YouTube Report class. */
class YouTubeReport extends Report {

  constructor(config, yt = new YouTube()) {
    super(config);
    this.yt = yt;
  }

  /** @override */
  generate(parameters) {
    return Promise.resolve();
  }

  /** @override */
  isReady(parameters) {
    return Promise.resolve(true);
  }

  /** @override */
  isAsynchronous() {
    return false;
  }

  /**
   * Map the supported YouTube API functions based on the source
   * YouTubeReportConfig.
   * @param  {string} target
   * @return {function(
   *   ListConfig): function(ListConfig): !Promise<!Array<!Object>>}
   * @private
   */
  getHandleFunction_(target) {
    switch (target) {
      case ReportTargets.CHANNEL:
        return (reportQuery) => {return this.yt.listChannels(reportQuery)};
      case ReportTargets.VIDEO:
        return (reportQuery) => {return this.yt.listVideos(reportQuery)};
      case ReportTargets.COMMENT:
        return (reportQuery) => {
          return this.yt.listCommentThreads(reportQuery);
        };
      case ReportTargets.PLAYLIST:
        return (reportQuery, resultLimit) => {
          return this.yt.listPlaylists(reportQuery, resultLimit);
        };
      case ReportTargets.SEARCH:
        return (reportQuery, resultLimit) => {
          return this.yt.listSearchResults(reportQuery, resultLimit);
        };
      default:
        throw new Error(
            `Fail to find the API for the target: ${target}`);
    }
  }

  /**
   * Get content from YouTube API based on the source YouTubeReportConfig.
   * @override
   */
  async getContent(parameters) {
    const handler = this.getHandleFunction_(this.config.target);
    const items = await handler(
      this.config.reportQuery,
      this.config.resultLimit);
    return items.map(JSON.stringify).join('\n');
  }
}

module.exports = {YouTubeReport};


text:
package com.travelex.alexa;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

import com.amazon.speech.speechlet.Session;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class WireSpeechletTest {

    @Test
    public void shouldGetTextForSendBase() {

        //Given
        Map<String, String> slots = new HashMap<>();
        slots.put("currency", "quid");
        slots.put("amount", "100");
        slots.put("beneficiary", "bob");

        OrderEstimateDetailDto detail = new OrderEstimateDetailDto(null, "2016-11-29", "0");
        Map<String, OrderEstimateDetailDto> details = Collections.singletonMap("priority", detail);
        OrderEstimateDto estimate = new OrderEstimateDto("0", "gbp", "eur", "100", "110", "base", details, "0", "0");

        //When
        WireSpeechlet wireSpeechlet = new WireSpeechlet("http://localhost");
        String text = wireSpeechlet.getResponse(slots::get, s -> estimate, () -> Pair.of("euros", "eur"), mock(Session.class));

        //Then
        assertEquals("you can send 100 pounds and bob would receive around 110 euros by TUESDAY, do you want to wire the money?", text);
    }

    @Test
    public void shouldGetTextForSendQuote() {

        //Given
        Map<String, String> slots = new HashMap<>();
        slots.put("currency", "yen");
        slots.put("amount", "10000");
        slots.put("beneficiary", "dave");

        OrderEstimateDetailDto detail = new OrderEstimateDetailDto(null, "2016-11-30", "0");
        Map<String, OrderEstimateDetailDto> details = Collections.singletonMap("priority", detail);
        OrderEstimateDto estimate = new OrderEstimateDto("0", "gbp", "jpy", "100.5", "10000", "quote", details, "0", "0");

        //When
        WireSpeechlet wireSpeechlet = new WireSpeechlet("http://localhost");
        String text = wireSpeechlet.getResponse(slots::get, s -> estimate, () -> Pair.of("euros", "eur"), mock(Session.class));

        //Then
        assertEquals("sending 10000 yen to dave would cost you around 100 pounds and would be delivered by WEDNESDAY, do you want to wire the money?",
                     text);
    }

}


text:
package test;

import io.netty.handler.ssl.OpenSslEngine;

public abstract class Hello2{

    public void eat(){
        OpenSslEngine openSslEngine = new OpenSslEngine(2, null, null);
    }
}


text:
<?php

namespace P2\Bundle\SecurityBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * Class P2SecurityExtension
 * @package P2\Bundle\SecurityBundle\DependencyInjection
 */
class P2SecurityExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        if (! isset($config['manager'])) {
            throw new InvalidArgumentException('manager must be set in p2_security configuration.');
        }

        $container->setAlias('p2_security.security.user_manager', $config['manager']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $userProviderDefinition = $container->getDefinition('p2_security.security.user_provider');
        $userProviderDefinition->setArguments(array(new Reference('p2_security.security.user_manager')));
    }

    /**
     * {@inheritDoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        $config = $container->getExtensionConfig($this->getAlias());
        $config = $this->processConfiguration(new Configuration(), $config);

        $bundles = $container->getParameter('kernel.bundles');

        if (! isset($bundles['SecurityBundle'])) {
            throw new \RuntimeException('The SecurityBundle is missing from your system.');
        }

        $securityConfig = array(
            'providers' => array(
                'p2_security' => array(
                    'id' => 'p2_security.security.user_provider'
                )
            )
        );

        $securityConfig['encoders'] = array();
        $securityConfig['encoders'][$config['document']] = array(
            'algorithm' => $config['encoder'],
            'encode_as_base64' => false,
            'iterations' => 1
        );

        $container->prependExtensionConfig('security', $securityConfig);
    }
}


text:
<?php

class BelongsToObjectRelation extends ObjectRelation
{
    public function get(Object $oObject, $aParams = array())
    {
        if (isset($this->aParams['ToModuleAlias']))
        {
            Core::import('Modules.'.$this->aParams['ToModuleAlias']);
        }

        $oMapper = Manager::getInstance()->getMapper($this->aParams['ToMapperAlias']);
        $sGetter = 'get'.$this->aParams['Field'];
        $nId = call_user_func(array($oObject, $sGetter));

        if (!count($aParams)) {
            $oData = $oObject->simpleGet($this->getAlias());

            if ($oData && $oData->getId() == $nId) {
                return $oData;
            } else {
                $oData = $oMapper->findById($nId, $aParams);
                $oObject->simpleSet($this->getAlias(), $oData);

                return $oData;
            }
        } else {
            return $oMapper->findById($nId, $aParams);
        }
    }

    public function set(Object $oObject, $mValue)
    {

        if ($mValue)
        {
            $oObject->aForSaveRelationsDataBefore[$this->aParams['Alias']] = array(
                'SetOne' => $mValue
            );
        }

       /*if (is_object($oValue))
        {
            if (!$oValue->getId()) {
                $oValue->save();
            }

            $oObject->simpleSet($this->getAlias(), $oValue);
        } else if (is_array($oValue))
        {

            if (!empty($oValue['Id']))
            {
                $val = $this->mapper()->findById($oValue['Id']);
                $val->import($oValue);

            } else {
                $val = $this->mapper()->create($oValue);
            }

            $val->save();

            $oObject->simpleSet($this->getAlias(), $val);
        }

        $sSetter = 'set'.$this->getField();

        call_user_func_array(array($oObject, $sSetter), array($oObject->getId()));

        return true;*/

        return true;
    }

    public function eagerFetching(DbFetcher $oQuery, ObjectMapper $oParentMapper, $sPrefix, $aParams = array(), $aLocalParams = array())
    {
    	if (isset($this->aParams['ToModuleAlias']))
        {
            Core::import('Modules.'.$this->aParams['ToModuleAlias']);
        }

        $oMapper = Manager::getInstance()->getMapper($this->aParams['ToMapperAlias']);

        //echo '<pre>', print_r($oMapper, true), '</pre>'; die();

        $aContainer = $oMapper->getContainer();

        if ($oMapper) {
            $oParentFields = $oParentMapper->getFields();

            $oQuery->addJoinTable($aContainer['TableName'], $sPrefix.'_'.$this->getAlias(), DbFetcher::JOIN_LEFT, $sPrefix.'.'.$oParentFields->get($this->getField())->getField().' = '.$sPrefix.'_'.$this->getAlias().'.id');

            $oFields = $oMapper->getFields();
            foreach ($oFields as $alias => $field) {
                if ($field->getType() != 'Object' && $field->getField()) {
                    $oQuery->addSelectField($sPrefix.'_'.$this->getAlias().'.'.$field->getField(), $sPrefix.'_'.$this->getAlias().'_'.$field->getField());
                }
            }

            // Условия выборки
            if (isset($aLocalParams['Criteria']) && is_object($aLocalParams['Criteria'])) {
                $oQuery->addCriteria(call_user_func(array($aLocalParams['Criteria'], 'renderWhere')));
            }

            if (isset($aLocalParams['Criteria']) && is_array($aLocalParams['Criteria']) && count($aLocalParams['Criteria']) > 0) {
                $oCriteria = new CriteriaGroup(Criteria::TYPE_AND);
                foreach ($aLocalParams['Criteria'] as $k => $itm) {
                    if (is_object($itm)) {
                        $oCriteria->addElement($itm);
                    } else if (is_array($itm)) {
                        $oCriteria->addElement(new CriteriaElement($k, $itm['Type'], $itm['Value']));
                    } else {
                        $oCriteria->addElement(new CriteriaElement($k, '=', $itm));
                    }

                }
                $oQuery->addCriteria($oMapper->parseFindCriteria($oCriteria->renderWhere(), $sPrefix.'_'.$this->getAlias()));
            }

            if (isset($aLocalParams['Criteria']) && is_string($aLocalParams['Criteria'])) {
                $oQuery->addCriteria($oMapper->parseFindCriteria($aLocalParams['Criteria'], $sPrefix.'_'.$this->getAlias()));
            }

            // Сортировка
            if (isset($aLocalParams['Order']) && is_array($aLocalParams['Order']) && count($aLocalParams['Order']) > 0) {
                foreach ($aLocalParams['Order'] as $k => $itm) {
                    $oQuery->addOrder($oMapper->parseFindField($k, $sPrefix.'_'.$this->getAlias()), $itm);
                }
            }

            if (isset($aLocalParams['With']) && is_array($aLocalParams['With']) && count($aLocalParams['With'])) {
                // TODO: Вложенные JOINы
            }

        }

        return $oQuery;
    }
}


text:
namespace caffe2 {

REGISTER_CPU_OPERATOR(
    PiecewiseLinearTransform,
    PiecewiseLinearTransformOp<float, CPUContext>);

OPERATOR_SCHEMA(PiecewiseLinearTransform)
    .NumInputs(1, 4)
    .NumOutputs(1)
    .SetDoc(R"DOC(
PiecewiseLinearTransform takes inputs -- predictions, a 2-D or 1-D tensor
(Tensor<float>) of size (batch_size x prediction_dimensions). The piecewise
linear functions are stored in bounds, slopes and intercepts. The output tensor
has the same shape of input `predictions` and contains the predictions
transformed by the piecewise linear functions. Each column of predictions has
its own piecewise linear transformation functions. Therefore the size of
piecewise function parameters are pieces x prediction_dimensions, except for
binary predictions where only the positive prediction needs them. Note that in
each piece, low bound is excluded while high bound is included. Also the
piecewise linear function must be continuous.

Notes
- If the input is binary predictions (Nx2 or Nx1 tensor), set the binary arg
to true so that one group of piecewise linear functions is needed (see
details below).
- The transform parameters (bounds, slopes, intercepts) can be passed either
through args or through input blobs.
- If we have multiple groups of piecewise linear functions, each group has the
same number of pieces.
- If a prediction is out of the bounds, it is capped to the smallest or largest
bound.
)DOC")
    .Arg(
        "bounds",
        "1-D vector of size (prediction_dimensions x (pieces+1)) contain the "
        "upper bounds of each piece of linear function. One special case is "
        "the first bound is the lower bound of whole piecewise function and we "
        "treat it the same as the left most functions. (bounds, slopes, "
        "intercepts) can be passed through either arg or input blobs.")
    .Arg(
        "slopes",
        "1-D vector of size (prediction_dimensions x pieces) containing the "
        "slopes of linear function")
    .Arg(
        "intercepts",
        "1-D vector of size (prediction_dimensions x pieces) containing the "
        "intercepts of linear function")
    .Arg(
        "binary",
        "If set true, we assume the input is a Nx1 or Nx2 tensor. If it is Nx1 "
        "tensor, it is positive predictions. If the input is Nx2 tensor, its "
        "first column is negative predictions and second column is positive "
        "and negative + positive = 1. We just need one group of piecewise "
        "linear functions for the positive predictions.")
    .Input(
        0,
        "predictions",
        "2-D tensor (Tensor<float>) of size "
        "(num_batches x num_classes) containing scores")
    .Input(
        1,
        "bounds (optional)",
        "See bounds in Arg. (bounds, slopes, intercepts) can be passed through "
        "either arg or input blobs.")
    .Input(
        2,
        "slopes (optional)",
        "See slopes in Arg. (bounds, slopes, intercepts) can be passed through "
        "either arg or input blobs.")
    .Input(
        3,
        "intercepts (optional)",
        "See intercepts in Arg. (bounds, slopes, intercepts) can be passed "
        "through either arg or input blobs.")
    .Output(
        0,
        "transforms",
        "2-D tensor (Tensor<float>) of size (num_batches x num_classes) "
        "containing transformed predictions");

SHOULD_NOT_DO_GRADIENT(PiecewiseLinearTransform);
} // namespace caffe2


text:
package com.kenzan.karyon.rxnetty.health;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import netflix.karyon.health.HealthCheckHandler;

public class HealthCheck implements HealthCheckHandler {

    private static final Logger logger = LoggerFactory.getLogger(HealthCheck.class);

    @Override
    public int getStatus() {
        logger.info("Health check called.");
        return 200;
    }

}


text:
#ifndef TENSORFLOW_CORE_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_
#define TENSORFLOW_CORE_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/lib/random/philox_random.h"
#include "tensorflow/core/lib/random/random_distributions_utils.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/tsl/lib/random/random_distributions.h"

namespace tensorflow {
namespace random {
// NOLINTBEGIN(misc-unused-using-decls)
using tsl::random::BoxMullerDouble;
using tsl::random::NormalDistribution;
using tsl::random::SignedAdd;
using tsl::random::SingleSampleAdapter;
using tsl::random::TruncatedNormalDistribution;
using tsl::random::Uint16ToGfloat16;
using tsl::random::Uint16ToHalf;
using tsl::random::UniformDistribution;
using tsl::random::UniformFullIntDistribution;
// NOLINTEND(misc-unused-using-decls)
}  // namespace random
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_


text:
using WampSharp.Core.Message;
using WampSharp.Tests.TestHelpers;

namespace WampSharp.Tests.Wampv2.Binding
{
    public class MockWampMessage : WampMessage<MockRaw>
    {
        public MockWampMessage()
        {
        }

        public MockWampMessage(WampMessage<MockRaw> other)
            : base(other)
        {
        }

        public override string ToString()
        {
            // Maybe use a debugger display instead.
            return WampMessagePrinter.ToString(this);
        }
    }
}


text:
.board
{
    margin-top: 2%;
    margin-left: auto;
    margin-right: auto;
    border: 2px solid black;
    font-weight: bold;
    font-size: 2em;
}

td
{
    padding: 0px;
}

.cell
{
    height: 50px;
    width: 100px;
    background-color: white;
    /*border: 1px solid black;*/
    text-align:center;
    -webkit-transition: background-color 0.2s ease-in-out;
    -moz-transition: background-color 0.2s ease-in-out;
    -o-transition: background-color 0.2s ease-in-out;
    -ms-transition: background-color 0.2s ease-in-out;
    transition: background-color 0.2s ease-in-out;

     -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none;   /* Chrome/Safari/Opera */
      -khtml-user-select: none;    /* Konqueror */
      -moz-user-select: none;      /* Firefox */
      -ms-user-select: none;       /* Internet Explorer/Edge */
      user-select: none;           /* Non-prefixed version, currently
                                      not supported by any browser */
}

#score
{
    text-align: center;
    color: white;
    font-weight: bold;
}

.selected
{
    background-color: rgb(255, 249, 142);
}

.rightcell
{
    background-color: rgb(200, 255, 155);
}

.foundedcell
{
    background-color: rgb(200, 255, 155);
}

.wrongcell
{
    background-color: rgb(255, 177, 0);
}

.word {

}

.wordfound
{
    color: green;
    font-weight: bold;
}

.wordnotfound
{
    color: #6e0000;
    font-weight: bold;
}

#wordsToSearchTitle
{
    font-size: 2em;
    font-weight: bold;
}

#entrywordsboxtitle
{
    visibility: hidden;
}

#entrywordsbox
{
    width: 350px;
    visibility: hidden;
    text-align: left;
}

#concedebutton
{
    transition: all 0.5s ease-out;
    visibility: hidden;
}

#submitscorebutton
{
    transition: all 0.5s ease-out;
    visibility: hidden;
    display: none;
}

#wordListDiv, #worldList{
    text-align: center;
    color:white;
}

.progress {
    width: 350px;
    visibility: hidden;
}

.scorebar
{
    color: black;
}

.remember{margin-top: 5%;}
.remember p{color:white}


text:
'use strict'

const trailingNewline = /.\n$/

export default function copyPlugin (editor) {
  const view = editor.require('view')

  function getSelectedParagraphs (sel) {
    if (!sel) return []

    let startPair = sel.absoluteStart
    let endPair = sel.absoluteEnd
    let paragraphs = view.paragraphs.slice(startPair[0], endPair[0] + 1)
    let last = paragraphs.length - 1

    if (paragraphs.length === 1) {
      paragraphs[0] = paragraphs[0].substring(startPair[1], endPair[1])
    } else {
      paragraphs[0] = paragraphs[0].substr(startPair[1])
      paragraphs[last] = paragraphs[last].substr(0, endPair[1])
    }

    return paragraphs
  }

  function trimTrailingNewline (p) {
    return trailingNewline.test(p.text) ? p.substr(0, p.length - 1) : p
  }

  function copyHTML (sel) {
    sel = sel || view.getSelection()

    if (sel.isCollapsed) return ''

    let paragraphs = getSelectedParagraphs(sel)
    paragraphs = paragraphs.map(p => {
      let trimmed = trimTrailingNewline(p)
      if (!trimmed.text) trimmed.text = '\n'
      return trimmed.toString()
    })

    return paragraphs.join('')
  }

  function copyText (sel) {
    sel = sel || view.getSelection()

    if (sel.isCollapsed) return ''

    let paragraphs = getSelectedParagraphs(sel)
    paragraphs = paragraphs.map(p => trimTrailingNewline(p).text)

    // TODO: should Windows get '\r\n\r\n'?
    return paragraphs.join('\n\n')
  }

  editor.provide('copy', {
    copyHTML,
    copyText
  })
}


text:
<meta charset="utf-8">

Pomocnik dla Destiny

Pomocnik - Menedżer przedmiotów dla Destiny, przenieś twoją broń szybko!

Coś nadzwyczajnego się wydarzyło? Potrzebujesz twojego touch of malice lub black spindle? Teraz jest tylko jedno kliknięcię do Ciebie!

Przenoś przedmioty ze skarbca lub od innych postaci do twojej aktualnej ,,like a boss''.

Aby mieć dostęp do dowolnej zbroi, broni lub przedmioty, po prosty wybierz do kogo chcesz ten przedmiot przenieść i tapnij. Nie jest ważne gdzie jest ten przedmiot, zostanie on przeniesiony tam gdzie chcesz za jednym tapnięciem.

Masz wiele przedmiotów? Użyj filtrów i szukania aby łatwo znaleźć to co potrzebujesz w tej chwili.

Masz ulubiony przedmiot? Zaznacz go gwiazdką, dzięki czemu zawsze będzie wyświetalny na początku listy.


text:
class Date
	def trading_day?
		return false unless (1..5).cover? self.wday
		return false if Holiday.on? self
		true
	end

  def reportable_day?
    return true if last_day_of_month?
    trading_day?
  end

  def last_day_of_month?
    month != (self+1).month
  end

	def previous_reportable_day
	  day = self.clone - 1.day
	  day -= 1.day until day.reportable_day?
	  day
	end
	alias_method :prev_reportable_day, :previous_reportable_day

	def previous_trading_day
	  day = self.clone - 1.day
	  day -= 1.day until day.trading_day?
	  day
	end
	alias_method :prev_trading_day, :previous_trading_day

	def next_trading_day
	  day = self.clone + 1.day
	  day += 1.day until day.trading_day?
	  day
	end

end


text:
package org.conqat.engine.core.bundle;

/**
 * Wrapper class for parameters passed to ANT tasks.
 *
 * @author Florian Deissenboeck
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 35CD1AA93B3D3A1F4FB4AEEBE9590D40
 */
public class AntElement {

	/** The name. */
	private String name;

	/** Name setter. */
	public void setName(String name) {
		this.name = name;
	}

	/** Name getter. */
	public String getName() {
		return name;
	}

	/** Returns name. */
	@Override
	public String toString() {
		return name;
	}
}


text:
package uk.co.inhealthcare.open.smsc.messages.logging;

public class SMSCInput {

 private String timestamp;
 private String conversationId;
 private String request;

public String getTimestamp() {
	return timestamp;
}
public void setTimestamp(String timestamp) {
	this.timestamp = timestamp;
}
public String getConversationId() {
	return conversationId;
}
public void setConversationId(String conversationId) {
	this.conversationId = conversationId;
}
public String getRequest() {
	return request;
}
public void setRequest(String request) {
	this.request = request;
}

}


text:
package org.seasar.doma.internal.jdbc.command;

import static org.junit.jupiter.api.Assertions.assertEquals;

import example.entity.Emp;
import example.entity._Emp;
import java.lang.reflect.Method;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.seasar.doma.internal.jdbc.mock.ColumnMetaData;
import org.seasar.doma.internal.jdbc.mock.MockConfig;
import org.seasar.doma.internal.jdbc.mock.MockResultSet;
import org.seasar.doma.internal.jdbc.mock.MockResultSetMetaData;
import org.seasar.doma.internal.jdbc.mock.RowData;
import org.seasar.doma.internal.jdbc.util.SqlFileUtil;
import org.seasar.doma.jdbc.IterationCallback;
import org.seasar.doma.jdbc.IterationContext;
import org.seasar.doma.jdbc.SqlLogType;
import org.seasar.doma.jdbc.query.SqlFileSelectQuery;

@SuppressWarnings("OptionalGetWithoutIsPresent")
public class EntityIterationHandlerTest {

  private final MockConfig runtimeConfig = new MockConfig();

  private Method method;

  @BeforeEach
  void setUp(TestInfo testInfo) {
    method = testInfo.getTestMethod().get();
  }

  @Test
  public void testHandle() throws Exception {
    MockResultSetMetaData metaData = new MockResultSetMetaData();
    metaData.columns.add(new ColumnMetaData("id"));
    metaData.columns.add(new ColumnMetaData("name"));
    MockResultSet resultSet = new MockResultSet(metaData);
    resultSet.rows.add(new RowData(1, "aaa"));
    resultSet.rows.add(new RowData(2, "bbb"));

    SqlFileSelectQuery query = new SqlFileSelectQuery();
    query.setConfig(runtimeConfig);
    query.setSqlFilePath(SqlFileUtil.buildPath(getClass().getName(), method.getName()));
    query.setCallerClassName("aaa");
    query.setCallerMethodName("bbb");
    query.setMethod(method);
    query.setSqlLogType(SqlLogType.FORMATTED);
    query.prepare();

    EntityIterationHandler<Emp, Integer> handler =
        new EntityIterationHandler<>(
            _Emp.getSingletonInternal(),
            new IterationCallback<Emp, Integer>() {

              private int count;

              @Override
              public Integer iterate(Emp target, IterationContext iterationContext) {
                count++;
                return count;
              }
            });
    Integer result = handler.handle(resultSet, query, (i, next) -> {}).get();
    assertEquals(new Integer(2), result);
  }

  @Test
  public void testHandle_exits() throws Exception {
    MockResultSetMetaData metaData = new MockResultSetMetaData();
    metaData.columns.add(new ColumnMetaData("id"));
    metaData.columns.add(new ColumnMetaData("name"));
    MockResultSet resultSet = new MockResultSet(metaData);
    resultSet.rows.add(new RowData(1, "aaa"));
    resultSet.rows.add(new RowData(2, "bbb"));

    SqlFileSelectQuery query = new SqlFileSelectQuery();
    query.setConfig(runtimeConfig);
    query.setSqlFilePath(SqlFileUtil.buildPath(getClass().getName(), method.getName()));
    query.setCallerClassName("aaa");
    query.setCallerMethodName("bbb");
    query.setMethod(method);
    query.setSqlLogType(SqlLogType.FORMATTED);
    query.prepare();

    EntityIterationHandler<Emp, Integer> handler =
        new EntityIterationHandler<>(
            _Emp.getSingletonInternal(),
            new IterationCallback<Emp, Integer>() {

              private int count;

              @Override
              public Integer iterate(Emp target, IterationContext iterationContext) {
                iterationContext.exit();
                count++;
                return count;
              }
            });
    Integer result = handler.handle(resultSet, query, (i, next) -> {}).get();
    assertEquals(new Integer(1), result);
  }
}


text:
"""
Provide authentication using a REST call

REST auth can be defined like any other eauth module:

.. code-block:: yaml

    external_auth:
      rest:
        ^url: https://url/for/rest/call
        fred:
          - .*
          - '@runner'

If there are entries underneath the ^url entry then they are merged with any responses
from the REST call.  In the above example, assuming the REST call does not return
any additional ACLs, this will authenticate Fred via a REST call and allow him to
run any execution module and all runners.

The REST call should return a JSON array that maps to a regular eauth YAML
structure of a user as above.

"""

import logging

import salt.utils.http

log = logging.getLogger(__name__)

__virtualname__ = "rest"

def __virtual__():
    return __virtualname__

def _rest_auth_setup():

    if "^url" in __opts__["external_auth"]["rest"]:
        return __opts__["external_auth"]["rest"]["^url"]
    else:
        return False

def fetch(username, password):
    """
    Call the rest authentication endpoint
    """
    url = _rest_auth_setup()

    data = {"username": username, "password": password}

    # Post to the API endpoint. If 200 is returned then the result will be the ACLs
    # for this user
    result = salt.utils.http.query(
        url, method="POST", data=data, status=True, decode=True
    )

    if result["status"] == 200:
        log.debug("eauth REST call returned 200: %s", result)
        # Call is successful if None no acl data
        if result["dict"] is not None:
            return result["dict"]
        else:
            return []
    else:
        log.debug("eauth REST call failed: %s", result)
        return False

def auth(username, password):
    """
    REST authentication
    """
    # Check auth on API endpoint
    result = fetch(username, password)
    if result is False:
        log.debug("eauth REST call failed: %s", result)
        return False
    else:
        log.debug("eauth REST call Ok: %s", result)
        return True

def acl(username, **kwargs):
    """
    REST authorization
    """
    salt_eauth_acl = __opts__["external_auth"]["rest"].get(username, [])
    log.debug("acl from salt for user %s: %s", username, salt_eauth_acl)

    # Get ACL from REST API
    eauth_rest_acl = []
    result = fetch(username, kwargs["password"])
    if result:
        eauth_rest_acl = result
        log.debug("acl from rest for user %s: %s", username, eauth_rest_acl)

    merged_acl = salt_eauth_acl + eauth_rest_acl

    log.debug("acl from salt and rest merged for user %s: %s", username, merged_acl)
    # We have to make the .get's above return [] since we can't merge a
    # possible list and None. So if merged_acl is falsey we return None so
    # other eauth's can return an acl.
    if not merged_acl:
        return None
    else:
        return merged_acl


text:
'use strict';

/** DOC
 *
 *  The purpose of the socket.io portion of this application
 *      is for the (mostly read-only) "explore" mode as well
 *      as the authenticated "create" mode.
 *
 */

const Location = require('../models').model('Location');
const sessionStore = require('./sessionStore');
const passportSocketIo = require('passport.socketio');
let processCommand = require('../controller/socket');

// global variables
let totalConnections = 0;
let io = null;

// global constants
const originOptions = {
    name : "The Origin",
    description : "The beginning of All Things."
};

//  Rather than instantiating and garbage collecting many functions
//      per socket, retain single instances of each needed function
//      where possible.
const func = {
    disconnect : function disconnectHandler() {
        io.emit('numClients', {
            clients : --totalConnections
        });
    },
    createOrigin : function createOrigin() {
        //  create origin if no Locations exist
        return Location.find({}).exec().then(function(locations) {
            if(locations.length > 0) {
                const msg = "New origin was about to be created while locations exist.";
                throw new Error(msg);
            }

            return Location.create(originOptions);
        });
    },
    incrementClients : function incrementClients() {
        io.emit('numClients', {
            clients : ++totalConnections
        });
    },
    auth : {
        success : function onAuthSuccess(data, accept) {
            return accept();
        },
        fail : function onAuthFail(data, message, error, accept) {
            if(error) {
                throw new Error(message);
            }

            return accept();
        }
    }
};

//  ensure that the session secret is at hand
process.env.SESSION_SECRET || require('dotenv').load();
const authorizer = passportSocketIo.authorize({
    key : 'ocmud.sid',
    secret : process.env.SESSION_SECRET,
    store : sessionStore,
    success : func.auth.success,
    fail : func.auth.fail
});
// end global constants

function setHandlers(socket) {
    socket.on('disconnect', func.disconnect);

    socket.on('command', function(cmd) {
        processCommand(socket, cmd);
    });
}

function onConnection(socket) {
    //  choose random starting point
    Location.getInitial().
        catch(func.createOrigin
        ).then(function(loc) {
            if(socket.request.user.logged_in) {
                socket.join(socket.request.user.id.toString());
            }
            socket.location = loc;
            socket.join('numClients');
            socket.join(loc.id.toString());

            let name;

            if(socket.request.user.logged_in) {
                name = socket.request.user.name;
            } else {
                name = "A stranger";
            }

            socket.broadcast.to(loc.id.toString()).emit(
                'travel',
                `${name} appears.`
            );

            processCommand(socket, {
                command : 'look'
            });
        }).then(function() {
            setHandlers(socket);
        }).then(func.incrementClients
        ).catch(function(err) {
            socket.emit('info', err.message);
            socket.disconnect();
        });
}

function setup(argIo) {
    //  set up globals
    io = argIo;
    processCommand = processCommand(argIo);

    //  set CORS origins
    // io.origins("https://pfbe.saad.rhoulam.com"); // for now

    //  use authentication
    io.use(authorizer);

    //  set connection handler
    io.on('connection', onConnection);
}

module.exports = setup;