mcanoglu/cwe-class-group huggingface dataset:
void LibRaw::exp_bef(float shift, float smooth)
{
    // params limits
    if(shift>8) shift = 8;
    if(shift<0.25) shift = 0.25;
    if(smooth < 0.0) smooth = 0.0;
    if(smooth > 1.0) smooth = 1.0;
    
    unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short));

    if(shift <=1.0)
        {
            for(int i=0;i<=TBLN;i++)
                lut[i] = (unsigned short)((float)i*shift);
        }
    else
        {
            float x1,x2,y1,y2;

            float cstops = log(shift)/log(2.0f);
            float room = cstops*2;
            float roomlin = powf(2.0f,room);
            x2 = (float)TBLN;
            x1 = (x2+1)/roomlin-1;
            y1 = x1*shift;
            y2 = x2*(1+(1-smooth)*(shift-1));
            float sq3x=powf(x1*x1*x2,1.0f/3.0f);
            float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x);
            float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f);
            float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2;
            for(int i=0;i<=TBLN;i++)
                {
                    float X = (float)i;
                    float Y = A*powf(X,1.0f/3.0f)+B*X+CC;
                    if(i<x1)
                        lut[i] = (unsigned short)((float)i*shift);
                    else
                        lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y));
                }
        }
    for(int i=0; i< S.height*S.width; i++)
        {
            imgdata.image[i][0] = lut[imgdata.image[i][0]];
            imgdata.image[i][1] = lut[imgdata.image[i][1]];
            imgdata.image[i][2] = lut[imgdata.image[i][2]];
            imgdata.image[i][3] = lut[imgdata.image[i][3]];
        }

    C.data_maximum = lut[C.data_maximum];
    C.maximum = lut[C.maximum];
    // no need to adjust the minumum, black is already subtracted
    free(lut);
}

// Vulnerability class: CWE-119
mptctl_eventreport (unsigned long arg)
{
	struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;
	struct mpt_ioctl_eventreport	 karg;
	MPT_ADAPTER		 *ioc;
	int			 iocnum;
	int			 numBytes, maxEvents, max;

	if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
		printk(KERN_ERR MYNAM "%s@%d::mptctl_eventreport - "
			"Unable to read in mpt_ioctl_eventreport struct @ %p\n",
				__FILE__, __LINE__, uarg);
		return -EFAULT;
	}

	if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
	    (ioc == NULL)) {
		printk(KERN_DEBUG MYNAM "%s::mptctl_eventreport() @%d - ioc%d not found!\n",
				__FILE__, __LINE__, iocnum);
		return -ENODEV;
	}
	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventreport called.\n",
	    ioc->name));

	numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
	maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);


	max = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;

	/* If fewer than 1 event is requested, there must have
	 * been some type of error.
	 */
	if ((max < 1) || !ioc->events)
		return -ENODATA;

	/* reset this flag so SIGIO can restart */
	ioc->aen_event_read_flag=0;

	/* Copy the data from kernel memory to user memory
	 */
	numBytes = max * sizeof(MPT_IOCTL_EVENTS);
	if (copy_to_user(uarg->eventData, ioc->events, numBytes)) {
		printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventreport - "
			"Unable to write out mpt_ioctl_eventreport struct @ %p\n",
			ioc->name, __FILE__, __LINE__, ioc->events);
		return -EFAULT;
	}

	return 0;
}

// Vulnerability class: CWE-362
jas_matrix_t *jas_seq2d_input(FILE *in)
{
	jas_matrix_t *matrix;
	int i;
	int j;
	long x;
	int numrows;
	int numcols;
	int xoff;
	int yoff;

	if (fscanf(in, "%d %d", &xoff, &yoff) != 2)
		return 0;
	if (fscanf(in, "%d %d", &numcols, &numrows) != 2)
		return 0;
	if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows)))
		return 0;

	if (jas_matrix_numrows(matrix) != numrows ||
	  jas_matrix_numcols(matrix) != numcols) {
		abort();
	}

	/* Get matrix data. */
	for (i = 0; i < jas_matrix_numrows(matrix); i++) {
		for (j = 0; j < jas_matrix_numcols(matrix); j++) {
			if (fscanf(in, "%ld", &x) != 1) {
				jas_matrix_destroy(matrix);
				return 0;
			}
			jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x));
		}
	}

	return matrix;
}

// Vulnerability class: CWE-20
void Ogg::XiphComment::parse(const ByteVector &data)
{
  // The first thing in the comment data is the vendor ID length, followed by a
  // UTF8 string with the vendor ID.

  int pos = 0;

  int vendorLength = data.mid(0, 4).toUInt(false);
  pos += 4;

  d->vendorID = String(data.mid(pos, vendorLength), String::UTF8);
  pos += vendorLength;

  // Next the number of fields in the comment vector.

  int commentFields = data.mid(pos, 4).toUInt(false);
  pos += 4;

  for(int i = 0; i < commentFields; i++) {

    // Each comment field is in the format "KEY=value" in a UTF8 string and has
    // 4 bytes before the text starts that gives the length.

    int commentLength = data.mid(pos, 4).toUInt(false);
    pos += 4;

    String comment = String(data.mid(pos, commentLength), String::UTF8);
    pos += commentLength;

    int commentSeparatorPosition = comment.find("=");

    String key = comment.substr(0, commentSeparatorPosition);
    String value = comment.substr(commentSeparatorPosition + 1);

    addField(key, value, false);
  }
}

// Vulnerability class: CWE-20
TEST_F(SQLiteUtilTests, test_column_type_determination) {
  // Correct identification of text and ints
  testTypesExpected("select path, inode from file where path like '%'",
                    TypeMap({{"path", TEXT_TYPE}, {"inode", INTEGER_TYPE}}));
  // Correctly treating BLOBs as text
  testTypesExpected("select CAST(seconds AS BLOB) as seconds FROM time",
                    TypeMap({{"seconds", TEXT_TYPE}}));
  // Correctly treating ints cast as double as doubles
  testTypesExpected("select CAST(seconds AS DOUBLE) as seconds FROM time",
                    TypeMap({{"seconds", DOUBLE_TYPE}}));
  // Correctly treating bools as ints
  testTypesExpected("select CAST(seconds AS BOOLEAN) as seconds FROM time",
                    TypeMap({{"seconds", INTEGER_TYPE}}));
  // Correctly recognizing values from columns declared double as double, even
  // if they happen to have integer value.  And also test multi-statement
  // queries.
  testTypesExpected(
      "CREATE TABLE test_types_table (username varchar(30) primary key, age "
      "double);INSERT INTO test_types_table VALUES (\"mike\", 23); SELECT age "
      "from test_types_table",
      TypeMap({{"age", DOUBLE_TYPE}}));
}

// Vulnerability class: CWE-77
void skip(Protocol_& prot, TType arg_type) {
  switch (arg_type) {
    case TType::T_BOOL: {
      bool boolv;
      prot.readBool(boolv);
      return;
    }
    case TType::T_BYTE: {
      int8_t bytev;
      prot.readByte(bytev);
      return;
    }
    case TType::T_I16: {
      int16_t i16;
      prot.readI16(i16);
      return;
    }
    case TType::T_I32: {
      int32_t i32;
      prot.readI32(i32);
      return;
    }
    case TType::T_I64: {
      int64_t i64;
      prot.readI64(i64);
      return;
    }
    case TType::T_DOUBLE: {
      double dub;
      prot.readDouble(dub);
      return;
    }
    case TType::T_FLOAT: {
      float flt;
      prot.readFloat(flt);
      return;
    }
    case TType::T_STRING: {
      std::string str;
      prot.readBinary(str);
      return;
    }
    case TType::T_STRUCT: {
      std::string name;
      int16_t fid;
      TType ftype;
      prot.readStructBegin(name);
      while (true) {
        prot.readFieldBegin(name, ftype, fid);
        if (ftype == TType::T_STOP) {
          break;
        }
        apache::thrift::skip(prot, ftype);
        prot.readFieldEnd();
      }
      prot.readStructEnd();
      return;
    }
    case TType::T_MAP: {
      TType keyType;
      TType valType;
      uint32_t i, size;
      prot.readMapBegin(keyType, valType, size);
      for (i = 0; i < size; i++) {
        apache::thrift::skip(prot, keyType);
        apache::thrift::skip(prot, valType);
      }
      prot.readMapEnd();
      return;
    }
    case TType::T_SET: {
      TType elemType;
      uint32_t i, size;
      prot.readSetBegin(elemType, size);
      for (i = 0; i < size; i++) {
        apache::thrift::skip(prot, elemType);
      }
      prot.readSetEnd();
      return;
    }
    case TType::T_LIST: {
      TType elemType;
      uint32_t i, size;
      prot.readListBegin(elemType, size);
      for (i = 0; i < size; i++) {
        apache::thrift::skip(prot, elemType);
      }
      prot.readListEnd();
      return;
    }
    default:
      return;
  }
}

// Vulnerability class: CWE-755
mptctl_eventquery (unsigned long arg)
{
	struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;
	struct mpt_ioctl_eventquery	 karg;
	MPT_ADAPTER *ioc;
	int iocnum;

	if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {
		printk(KERN_ERR MYNAM "%s@%d::mptctl_eventquery - "
			"Unable to read in mpt_ioctl_eventquery struct @ %p\n",
				__FILE__, __LINE__, uarg);
		return -EFAULT;
	}

	if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
	    (ioc == NULL)) {
		printk(KERN_DEBUG MYNAM "%s::mptctl_eventquery() @%d - ioc%d not found!\n",
				__FILE__, __LINE__, iocnum);
		return -ENODEV;
	}

	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventquery called.\n",
	    ioc->name));
	karg.eventEntries = MPTCTL_EVENT_LOG_SIZE;
	karg.eventTypes = ioc->eventTypes;

	/* Copy the data from kernel memory to user memory
	 */
	if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {
		printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventquery - "
			"Unable to write out mpt_ioctl_eventquery struct @ %p\n",
			ioc->name, __FILE__, __LINE__, uarg);
		return -EFAULT;
	}
	return 0;
}

// Vulnerability class: CWE-362
HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector<uint64_t>& upstream_indices) {
  uint64_t upstream_with_request;
  // If there is no upstream connection, wait for it to be established.
  if (!fake_upstream_connection_) {

    AssertionResult result = AssertionFailure();
    for (auto upstream_index : upstream_indices) {
      result = fake_upstreams_[upstream_index]->waitForHttpConnection(
          *dispatcher_, fake_upstream_connection_, TestUtility::DefaultTimeout,
          max_request_headers_kb_);
      if (result) {
        upstream_with_request = upstream_index;
        break;
      }
    }
    RELEASE_ASSERT(result, result.message());
  }
  // Wait for the next stream on the upstream connection.
  AssertionResult result =
      fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);
  RELEASE_ASSERT(result, result.message());
  // Wait for the stream to be completely received.
  result = upstream_request_->waitForEndStream(*dispatcher_);
  RELEASE_ASSERT(result, result.message());

  return upstream_with_request;
}

// Vulnerability class: CWE-400
static Status ValidateSavedTensors(const GraphDef& graph_def) {
  for (const auto& node : graph_def.node()) {
    const auto node_iterator = node.attr().find("value");
    if (node_iterator != node.attr().end()) {
      AttrValue node_value = node_iterator->second;
      if (node_value.has_tensor()) {
        const PartialTensorShape node_shape(node_value.tensor().tensor_shape());
        if (node_shape.num_elements() < 0) {
          return errors::FailedPrecondition(
              "Saved model contains node \"", node.name(), "\" (op \"",
              node.op(), "\") which initializes from a tensor with ",
              node_shape.num_elements(), " elements");
        }
      }
    } else if (node.op() == "Const") {
      return errors::FailedPrecondition(
          "Saved model contains node \"", node.name(),
          "\" which is a constant tensor but no value has been provided");
    }
  }
  return Status::OK();
}

// Vulnerability class: CWE-20
TEST_F(QuantizedConv2DTest, OddPaddingBatch) {
  const int stride = 2;
  TF_ASSERT_OK(NodeDefBuilder("quantized_conv_op", "QuantizedConv2D")
                   .Input(FakeInput(DT_QUINT8))
                   .Input(FakeInput(DT_QUINT8))
                   .Input(FakeInput(DT_FLOAT))
                   .Input(FakeInput(DT_FLOAT))
                   .Input(FakeInput(DT_FLOAT))
                   .Input(FakeInput(DT_FLOAT))
                   .Attr("out_type", DataTypeToEnum<qint32>::v())
                   .Attr("strides", {1, stride, stride, 1})
                   .Attr("padding", "SAME")
                   .Finalize(node_def()));
  TF_ASSERT_OK(InitOp());

  const int depth = 1;
  const int image_width = 4;
  const int image_height = 4;
  const int image_batch_count = 3;
  AddInputFromArray<quint8>(
      TensorShape({image_batch_count, image_height, image_width, depth}),
      {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
       1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
       1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
  const int filter_size = 3;
  const int filter_count = 1;
  AddInputFromArray<quint8>(
      TensorShape({filter_size, filter_size, depth, filter_count}),
      {1, 2, 3, 4, 5, 6, 7, 8, 9});
  AddInputFromArray<float>(TensorShape({1}), {0});
  AddInputFromArray<float>(TensorShape({1}), {255.0f});
  AddInputFromArray<float>(TensorShape({1}), {0});
  AddInputFromArray<float>(TensorShape({1}), {255.0f});

  TF_ASSERT_OK(RunOpKernel());
  const int expected_width = image_width / stride;
  const int expected_height = (image_height * filter_count) / stride;
  Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,
                                          expected_width, filter_count}));
  test::FillValues<qint32>(&expected, {348, 252, 274, 175,  //
                                       348, 252, 274, 175,  //
                                       348, 252, 274, 175});
  test::ExpectTensorEqual<qint32>(expected, *GetOutput(0));
}

// Vulnerability class: CWE-20
ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) {
  if (streamId == 0) {
    goawayErrorMessage_ = folly::to<string>(
        "GOAWAY error: received streamID=", streamId,
        " as invalid new stream for lastStreamID_=", lastStreamID_);
    VLOG(4) << goawayErrorMessage_;
    return ErrorCode::PROTOCOL_ERROR;
  }
  parsingDownstreamTrailers_ = trailersAllowed && (streamId <= lastStreamID_);
  if (parsingDownstreamTrailers_) {
    VLOG(4) << "Parsing downstream trailers streamId=" << streamId;
  }

  if (sessionClosing_ != ClosingState::CLOSED) {
    lastStreamID_ = streamId;
  }

  if (isInitiatedStream(streamId)) {
    // this stream should be initiated by us, not by peer
    goawayErrorMessage_ = folly::to<string>(
        "GOAWAY error: invalid new stream received with streamID=", streamId);
    VLOG(4) << goawayErrorMessage_;
    return ErrorCode::PROTOCOL_ERROR;
  } else {
    return ErrorCode::NO_ERROR;
  }
}

// Vulnerability class: CWE-20
static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
  int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
  int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
  uint_fast32_t inmem)
{
	jas_image_cmpt_t *cmpt;
	size_t size;

	cmpt = 0;
	if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
		goto error;
	}
	if (!jas_safe_intfast32_add(tlx, width, 0) ||
	  !jas_safe_intfast32_add(tly, height, 0)) {
		goto error;
	}

	if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
		goto error;
	}

	cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
	cmpt->tlx_ = tlx;
	cmpt->tly_ = tly;
	cmpt->hstep_ = hstep;
	cmpt->vstep_ = vstep;
	cmpt->width_ = width;
	cmpt->height_ = height;
	cmpt->prec_ = depth;
	cmpt->sgnd_ = sgnd;
	cmpt->stream_ = 0;
	cmpt->cps_ = (depth + 7) / 8;

	// Compute the number of samples in the image component, while protecting
	// against overflow.
	// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;
	if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
	  !jas_safe_size_mul(size, cmpt->cps_, &size)) {
		goto error;
	}
	cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :
	  jas_stream_tmpfile();
	if (!cmpt->stream_) {
		goto error;
	}

	/* Zero the component data.  This isn't necessary, but it is
	convenient for debugging purposes. */
	/* Note: conversion of size - 1 to long can overflow */
	if (size > 0) {
		if (size - 1 > LONG_MAX) {
			goto error;
		}
		if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
		  jas_stream_putc(cmpt->stream_, 0) == EOF ||
		  jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
			goto error;
		}
	}

	return cmpt;

error:
	if (cmpt) {
		jas_image_cmpt_destroy(cmpt);
	}
	return 0;
}

// Vulnerability class: CWE-20
bool PamBackend::start(const QString &user) {
        bool result;

        QString service = QStringLiteral("sddm");

        if (user == QStringLiteral("sddm") && m_greeter)
            service = QStringLiteral("sddm-greeter");
        else if (m_app->session()->path().isEmpty())
            service = QStringLiteral("sddm-check");
        else if (m_autologin)
            service = QStringLiteral("sddm-autologin");
        result = m_pam->start(service, user);

        if (!result)
            m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL);

        return result;
    }

// Vulnerability class: CWE-287
set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers)
{
  char *startCur = ciphers;
  int algCount = 0;
  static ALG_ID algIds[45]; /*There are 45 listed in the MS headers*/
  while(startCur && (0 != *startCur) && (algCount < 45)) {
    long alg = strtol(startCur, 0, 0);
    if(!alg)
      alg = get_alg_id_by_name(startCur);
    if(alg)
      algIds[algCount++] = alg;
    else if(!strncmp(startCur, "USE_STRONG_CRYPTO",
                     sizeof("USE_STRONG_CRYPTO") - 1) ||
            !strncmp(startCur, "SCH_USE_STRONG_CRYPTO",
                     sizeof("SCH_USE_STRONG_CRYPTO") - 1))
      schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO;
    else
      return CURLE_SSL_CIPHER;
    startCur = strchr(startCur, ':');
    if(startCur)
      startCur++;
  }
  schannel_cred->palgSupportedAlgs = algIds;
  schannel_cred->cSupportedAlgs = algCount;
  return CURLE_OK;
}

// Vulnerability class: CWE-668
TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) {
  EXPECT_CALL(mock_cb_, onComplete(Status::Ok));
  auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}};
  context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);
  verifier_->verify(context_);
  EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kExampleHeader));
}

// Vulnerability class: CWE-287
bool CSecurityTLS::processMsg(CConnection* cc)
{
  rdr::InStream* is = cc->getInStream();
  rdr::OutStream* os = cc->getOutStream();
  client = cc;

  initGlobal();

  if (!session) {
    if (!is->checkNoWait(1))
      return false;

    if (is->readU8() == 0) {
      rdr::U32 result = is->readU32();
      CharArray reason;
      if (result == secResultFailed || result == secResultTooMany)
        reason.buf = is->readString();
      else
        reason.buf = strDup("Authentication failure (protocol error)");
      throw AuthFailureException(reason.buf);
    }

    if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS)
      throw AuthFailureException("gnutls_init failed");

    if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)
      throw AuthFailureException("gnutls_set_default_priority failed");

    setParam();
  }

  rdr::TLSInStream *tlsis = new rdr::TLSInStream(is, session);
  rdr::TLSOutStream *tlsos = new rdr::TLSOutStream(os, session);

  int err;
  err = gnutls_handshake(session);
  if (err != GNUTLS_E_SUCCESS) {
    delete tlsis;
    delete tlsos;

    if (!gnutls_error_is_fatal(err))
      return false;

    vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err));
    shutdown(false);
    throw AuthFailureException("TLS Handshake failed");
  }

  checkSession();

  cc->setStreams(fis = tlsis, fos = tlsos);

  return true;
}

// Vulnerability class: CWE-119
int Bind(const Node& node, int max_retry) override {
    receiver_ = zmq_socket(context_, ZMQ_ROUTER);
    CHECK(receiver_ != NULL)
        << "create receiver socket failed: " << zmq_strerror(errno);
    int local = GetEnv("DMLC_LOCAL", 0);
    std::string addr = local ? "ipc:///tmp/" : "tcp://*:";
    int port = node.port;
    unsigned seed = static_cast<unsigned>(time(NULL)+port);
    for (int i = 0; i < max_retry+1; ++i) {
      auto address = addr + std::to_string(port);
      if (zmq_bind(receiver_, address.c_str()) == 0) break;
      if (i == max_retry) {
        port = -1;
      } else {
        port = 10000 + rand_r(&seed) % 40000;
      }
    }
    return port;
  }

// Vulnerability class: CWE-200
TEST_P(Http2CodecImplTest, TestLargeRequestHeadersAtLimitAccepted) {
  uint32_t codec_limit_kb = 64;
  max_request_headers_kb_ = codec_limit_kb;
  initialize();

  TestHeaderMapImpl request_headers;
  HttpTestUtility::addDefaultHeaders(request_headers);
  std::string key = "big";
  uint32_t head_room = 77;
  uint32_t long_string_length =
      codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room;
  std::string long_string = std::string(long_string_length, 'q');
  request_headers.addCopy(key, long_string);

  // The amount of data sent to the codec is not equivalent to the size of the
  // request headers that Envoy computes, as the codec limits based on the
  // entire http2 frame. The exact head room needed (76) was found through iteration.
  ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024);

  EXPECT_CALL(request_decoder_, decodeHeaders_(_, _));
  request_encoder_->encodeHeaders(request_headers, true);
}

// Vulnerability class: CWE-400
void jslGetTokenString(char *str, size_t len) {
  if (lex->tk == LEX_ID) {
    strncpy(str, "ID:", len);
    strncat(str, jslGetTokenValueAsString(), len);
  } else if (lex->tk == LEX_STR) {
    strncpy(str, "String:'", len);
    strncat(str, jslGetTokenValueAsString(), len);
    strncat(str, "'", len);
  } else
    jslTokenAsString(lex->tk, str, len);
}

// Vulnerability class: CWE-119
mptctl_replace_fw (unsigned long arg)
{
	struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;
	struct mpt_ioctl_replace_fw	 karg;
	MPT_ADAPTER		 *ioc;
	int			 iocnum;
	int			 newFwSize;

	if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {
		printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - "
			"Unable to read in mpt_ioctl_replace_fw struct @ %p\n",
				__FILE__, __LINE__, uarg);
		return -EFAULT;
	}

	if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
	    (ioc == NULL)) {
		printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n",
				__FILE__, __LINE__, iocnum);
		return -ENODEV;
	}

	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n",
	    ioc->name));
	/* If caching FW, Free the old FW image
	 */
	if (ioc->cached_fw == NULL)
		return 0;

	mpt_free_fw_memory(ioc);

	/* Allocate memory for the new FW image
	 */
	newFwSize = ALIGN(karg.newImageSize, 4);

	mpt_alloc_fw_memory(ioc, newFwSize);
	if (ioc->cached_fw == NULL)
		return -ENOMEM;

	/* Copy the data from user memory to kernel space
	 */
	if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {
		printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - "
				"Unable to read in mpt_ioctl_replace_fw image "
				"@ %p\n", ioc->name, __FILE__, __LINE__, uarg);
		mpt_free_fw_memory(ioc);
		return -EFAULT;
	}

	/* Update IOCFactsReply
	 */
	ioc->facts.FWImageSize = newFwSize;
	return 0;
}

// Vulnerability class: CWE-362
USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
    USHORT Res;
    auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
                                       GetDataLength(), __FUNCTION__);
    if (ppr.ipStatus != ppresNotIP)
    {
        Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
    }
    else
    {
        DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
        Res = 0;
    }
    return Res;
}

// Vulnerability class: CWE-20
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
    gint64 *data_offset)
{
	gint64	offset;
	int	pkt_len;
	char	line[COSINE_LINE_LENGTH];

	/* Find the next packet */
	offset = cosine_seek_next_packet(wth, err, err_info, line);
	if (offset < 0)
		return FALSE;
	*data_offset = offset;

	/* Parse the header */
	pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);
	if (pkt_len == -1)
		return FALSE;

	/* Convert the ASCII hex dump to binary data */
	return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,
	    wth->frame_buffer, err, err_info);
}

// Vulnerability class: CWE-119
static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
{
	struct fxregs_state fx_state;
	int rc;

	rc = check_fxsr(ctxt);
	if (rc != X86EMUL_CONTINUE)
		return rc;

	rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
	if (rc != X86EMUL_CONTINUE)
		return rc;

	if (fx_state.mxcsr >> 16)
		return emulate_gp(ctxt, 0);

	ctxt->ops->get_fpu(ctxt);

	if (ctxt->mode < X86EMUL_MODE_PROT64)
		rc = fxrstor_fixup(ctxt, &fx_state);

	if (rc == X86EMUL_CONTINUE)
		rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));

	ctxt->ops->put_fpu(ctxt);

	return rc;
}

// Vulnerability class: CWE-200
static inline ulong encode_twos_comp(long n, int prec)
{
	ulong result;
	assert(prec >= 2);
	jas_eprintf("warning: support for signed data is untested\n");
	// NOTE: Is this correct?
	if (n < 0) {
		result = -n;
		result = (result ^ 0xffffffffUL) + 1;
		result &= (1 << prec) - 1;
	} else {
		result = n;
	}
	return result;
}

// Vulnerability class: CWE-20
int ecall_restore(const char *input, uint64_t input_len, char **output,
                  uint64_t *output_len) {
  if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,
                                                              input_len)) {
    asylo::primitives::TrustedPrimitives::BestEffortAbort(
        "ecall_restore: input found to not be in untrusted memory.");
  }
  int result = 0;
  size_t tmp_output_len;
  try {
    result = asylo::Restore(input, static_cast<size_t>(input_len), output,
                            &tmp_output_len);
  } catch (...) {
    LOG(FATAL) << "Uncaught exception in enclave";
  }

  if (output_len) {
    *output_len = static_cast<uint64_t>(tmp_output_len);
  }
  return result;
}

// Vulnerability class: CWE-119
boost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(
    const SaplingEncCiphertext &ciphertext,
    const uint256 &epk,
    const uint256 &esk,
    const uint256 &pk_d,
    const uint256 &cmu
)
{
    auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);
    if (!pt) {
        return boost::none;
    }

    // Deserialize from the plaintext
    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    ss << pt.get();

    SaplingNotePlaintext ret;
    ss >> ret;

    uint256 cmu_expected;
    if (!librustzcash_sapling_compute_cm(
        ret.d.data(),
        pk_d.begin(),
        ret.value(),
        ret.rcm.begin(),
        cmu_expected.begin()
    ))
    {
        return boost::none;
    }

    if (cmu_expected != cmu) {
        return boost::none;
    }

    assert(ss.size() == 0);

    return ret;
}

// Vulnerability class: CWE-755
void InferenceContext::PreInputInit(
    const OpDef& op_def, const std::vector<const Tensor*>& input_tensors,
    const std::vector<ShapeHandle>& input_tensors_as_shapes) {
  // TODO(mdan): This is also done at graph construction. Run only here instead?
  const auto ret = full_type::SpecializeType(attrs_, op_def);
  DCHECK(ret.status().ok()) << "while instantiating types: " << ret.status();
  ret_types_ = ret.ValueOrDie();

  input_tensors_ = input_tensors;
  input_tensors_as_shapes_ = input_tensors_as_shapes;

  construction_status_ =
      NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_);
  if (!construction_status_.ok()) return;

  int num_outputs = 0;
  for (const auto& e : output_name_map_) {
    num_outputs = std::max(num_outputs, e.second.second);
  }
  outputs_.assign(num_outputs, nullptr);
  output_handle_shapes_and_types_.resize(num_outputs);
}

// Vulnerability class: CWE-754
DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
                                  RandomNumberGenerator& rng)
   {
   const BigInt& q = m_group.get_q();

   BigInt i(msg, msg_len, q.bits());

   while(i >= q)
      i -= q;

#if defined(BOTAN_HAS_RFC6979_GENERATOR)
   BOTAN_UNUSED(rng);
   const BigInt k = generate_rfc6979_nonce(m_x, q, i, m_rfc6979_hash);
#else
   const BigInt k = BigInt::random_integer(rng, 1, q);
#endif

   BigInt s = inverse_mod(k, q);
   const BigInt r = m_mod_q.reduce(m_group.power_g_p(k));

   s = m_mod_q.multiply(s, mul_add(m_x, r, i));

   // With overwhelming probability, a bug rather than actual zero r/s
   if(r.is_zero() || s.is_zero())
      throw Internal_Error("Computed zero r/s during DSA signature");

   return BigInt::encode_fixed_length_int_pair(r, s, q.bytes());
   }

// Vulnerability class: CWE-200
error_t tcpAddOption(TcpHeader *segment, uint8_t kind, const void *value,
   uint8_t length)
{
   uint_t i;
   size_t paddingSize;
   TcpOption *option;

   //Length of the complete option field
   length += sizeof(TcpOption);

   //Make sure there is enough space to add the specified option
   if((segment->dataOffset * 4 + length) > TCP_MAX_HEADER_LENGTH)
      return ERROR_FAILURE;

   //Index of the first available byte
   i = segment->dataOffset * 4 - sizeof(TcpHeader);

   //Calculate the number of padding bytes
   paddingSize = (length % 4) ? 4 - (length % 4) : 0;
   //Write padding bytes
   while(paddingSize--)
      segment->options[i++] = TCP_OPTION_NOP;

   //Point to the current location
   option = (TcpOption *) (segment->options + i);
   //Write specified option
   option->kind = kind;
   option->length = length;
   osMemcpy(option->value, value, length - sizeof(TcpOption));
   //Adjust index value
   i += length;

   //Update TCP header length
   segment->dataOffset = (sizeof(TcpHeader) + i) / 4;

   //Option successfully added
   return NO_ERROR;
}

// Vulnerability class: CWE-20
mptctl_readtest (unsigned long arg)
{
	struct mpt_ioctl_test __user *uarg = (void __user *) arg;
	struct mpt_ioctl_test	 karg;
	MPT_ADAPTER *ioc;
	int iocnum;

	if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
		printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - "
			"Unable to read in mpt_ioctl_test struct @ %p\n",
				__FILE__, __LINE__, uarg);
		return -EFAULT;
	}

	if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
	    (ioc == NULL)) {
		printk(KERN_DEBUG MYNAM "%s::mptctl_readtest() @%d - ioc%d not found!\n",
				__FILE__, __LINE__, iocnum);
		return -ENODEV;
	}

	dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n",
	    ioc->name));
	/* Fill in the data and return the structure to the calling
	 * program
	 */

#ifdef MFCNT
	karg.chip_type = ioc->mfcnt;
#else
	karg.chip_type = ioc->pcidev->device;
#endif
	strncpy (karg.name, ioc->name, MPT_MAX_NAME);
	karg.name[MPT_MAX_NAME-1]='\0';
	strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
	karg.product[MPT_PRODUCT_LENGTH-1]='\0';

	/* Copy the data from kernel memory to user memory
	 */
	if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
		printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - "
			"Unable to write out mpt_ioctl_test struct @ %p\n",
			ioc->name, __FILE__, __LINE__, uarg);
		return -EFAULT;
	}

	return 0;
}

// Vulnerability class: CWE-362
jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,
  int clrspc)
{
	jas_image_t *image;
	uint_fast32_t rawsize;
	uint_fast32_t inmem;
	int cmptno;
	jas_image_cmptparm_t *cmptparm;

	if (!(image = jas_image_create0())) {
		return 0;
	}

	image->clrspc_ = clrspc;
	image->maxcmpts_ = numcmpts;
	image->inmem_ = true;

	/* Allocate memory for the per-component information. */
	if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
	  sizeof(jas_image_cmpt_t *)))) {
		jas_image_destroy(image);
		return 0;
	}
	/* Initialize in case of failure. */
	for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
		image->cmpts_[cmptno] = 0;
	}

	/* Compute the approximate raw size of the image. */
	rawsize = 0;
	for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
	  ++cmptparm) {
		rawsize += cmptparm->width * cmptparm->height *
		  (cmptparm->prec + 7) / 8;
	}
	/* Decide whether to buffer the image data in memory, based on the
	  raw size of the image. */
	inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);

	/* Create the individual image components. */
	for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
	  ++cmptparm) {
		if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
		  cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
		  cmptparm->width, cmptparm->height, cmptparm->prec,
		  cmptparm->sgnd, inmem))) {
			jas_image_destroy(image);
			return 0;
		}
		++image->numcmpts_;
	}

	/* Determine the bounding box for all of the components on the
	  reference grid (i.e., the image area) */
	jas_image_setbbox(image);

	return image;
}

// Vulnerability class: CWE-20
error_t coapServerFormatReset(CoapServerContext *context, uint16_t mid)
{
   CoapMessageHeader *header;

   //Point to the CoAP response header
   header = (CoapMessageHeader *) context->response.buffer;

   //Format Reset message
   header->version = COAP_VERSION_1;
   header->type = COAP_TYPE_RST;
   header->tokenLen = 0;
   header->code = COAP_CODE_EMPTY;

   //The Reset message message must echo the message ID of the confirmable
   //message and must be empty (refer to RFC 7252, section 4.2)
   header->mid = htons(mid);

   //Set the length of the CoAP message
   context->response.length = sizeof(CoapMessageHeader);

   //Sucessful processing
   return NO_ERROR;
}

// Vulnerability class: CWE-20
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
    tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
    PrintOutParsingResult(res, 1, caller);
    return res;
}

// Vulnerability class: CWE-20
void JavascriptArray::SliceHelper(JavascriptArray* pArr,  JavascriptArray* pnewArr, uint32 start, uint32 newLen)
    {
        SparseArraySegment<T>* headSeg = (SparseArraySegment<T>*)pArr->head;
        SparseArraySegment<T>* pnewHeadSeg = (SparseArraySegment<T>*)pnewArr->head;

        // Fill the newly created sliced array
        js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);
        pnewHeadSeg->length = newLen;

        Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
        // Prototype lookup for missing elements
        if (!pArr->HasNoMissingValues())
        {
            for (uint32 i = 0; i < newLen; i++)
            {
                // array type might be changed in the below call to DirectGetItemAtFull
                // need recheck array type before checking array item [i + start]
                if (pArr->IsMissingItem(i + start))
                {
                    Var element;
                    pnewArr->SetHasNoMissingValues(false);
                    if (pArr->DirectGetItemAtFull(i + start, &element))
                    {
                        pnewArr->SetItem(i, element, PropertyOperation_None);
                    }
                }
            }
        }
#ifdef DBG
        else
        {
            for (uint32 i = 0; i < newLen; i++)
            {
                AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
            }
        }

#endif
    }

// Vulnerability class: CWE-200
TEST_F(HttpConnectionManagerImplTest, OverlyLongHeadersAcceptedIfConfigured) {
  max_request_headers_kb_ = 62;
  setup(false, "");

  EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> void {
    StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_);
    HeaderMapPtr headers{
        new TestHeaderMapImpl{{":authority", "host"}, {":path", "/"}, {":method", "GET"}}};
    headers->addCopy(LowerCaseString("Foo"), std::string(60 * 1024, 'a'));

    EXPECT_CALL(response_encoder_, encodeHeaders(_, _)).Times(0);
    decoder->decodeHeaders(std::move(headers), true);
    conn_manager_->newStream(response_encoder_);
  }));

  Buffer::OwnedImpl fake_input("1234");
  conn_manager_->onData(fake_input, false); // kick off request
}

// Vulnerability class: CWE-400
DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa) :
         PK_Ops::Signature_with_EMSA(emsa),
         m_group(dsa.get_group()),
         m_x(dsa.get_x()),
         m_mod_q(dsa.group_q())
         {
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
         m_rfc6979_hash = hash_for_emsa(emsa);
#endif
         }

// Vulnerability class: CWE-200
GetRunner(
			const ReferenceHandle& that,
			Local<Value> key_handle,
			MaybeLocal<Object> maybe_options,
			bool inherit
		) :
				context{that.context},
				reference{that.reference},
				options{maybe_options, inherit ?
					TransferOptions::Type::DeepReference : TransferOptions::Type::Reference},
				inherit{inherit} {
			that.CheckDisposed();
			key = ExternalCopy::CopyIfPrimitive(key_handle);
			if (!key) {
				throw RuntimeTypeError("Invalid `key`");
			}
		}

// Vulnerability class: CWE-913
void onComplete(const Status& status, ContextImpl& context) const override {
    auto& completion_state = context.getCompletionState(this);
    if (completion_state.is_completed_) {
      return;
    }

    // If any of children is OK, return OK
    if (Status::Ok == status) {
      completion_state.is_completed_ = true;
      completeWithStatus(status, context);
      return;
    }

    // Then wait for all children to be done.
    if (++completion_state.number_completed_children_ == verifiers_.size()) {
      // Aggregate all children status into a final status.
      // JwtMissing should be treated differently than other failure status
      // since it simply means there is not Jwt token for the required provider.
      // If there is a failure status other than JwtMissing in the children,
      // it should be used as the final status.
      Status final_status = Status::JwtMissed;
      for (const auto& it : verifiers_) {
        // If a Jwt is extracted from a location not specified by the required provider,
        // the authenticator returns JwtUnknownIssuer. It should be treated the same as
        // JwtMissed.
        Status child_status = context.getCompletionState(it.get()).status_;
        if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) {
          final_status = child_status;
        }
      }

      if (is_allow_missing_or_failed_) {
        final_status = Status::Ok;
      } else if (is_allow_missing_ && final_status == Status::JwtMissed) {
        final_status = Status::Ok;
      }
      completion_state.is_completed_ = true;
      completeWithStatus(final_status, context);
    }
  }

// Vulnerability class: CWE-287
int linenoiseHistorySave(const char* filename) {
    FILE* fp = fopen(filename, "wt");
    if (fp == NULL) {
        return -1;
    }

    for (int j = 0; j < historyLen; ++j) {
        if (history[j][0] != '\0') {
            fprintf(fp, "%s\n", history[j]);
        }
    }
    fclose(fp);
    return 0;
}

// Vulnerability class: CWE-200
int jas_memdump(FILE *out, void *data, size_t len)
{
	size_t i;
	size_t j;
	uchar *dp;
	dp = data;
	for (i = 0; i < len; i += 16) {
		fprintf(out, "%04zx:", i);
		for (j = 0; j < 16; ++j) {
			if (i + j < len) {
				fprintf(out, " %02x", dp[i + j]);
			}
		}
		fprintf(out, "\n");
	}
	return 0;
}

// Vulnerability class: CWE-20
def package_index
    valid_http_methods :get
    required_parameters :project, :repository, :arch, :package

    # read access permission check
    if params[:package] == "_repository"
      prj = DbProject.get_by_name params[:project], use_source=false
    else
      pkg = DbPackage.get_by_project_and_name params[:project], params[:package], use_source=false
    end

    pass_to_backend
  end

// Vulnerability class: CWE-20
it "updates the record matching selector with change" do
      session.should_receive(:with, :consistency => :strong).
        and_yield(session)

      session.should_receive(:execute).with do |update|
        update.flags.should eq []
        update.selector.should eq query.operation.selector
        update.update.should eq change
      end

      query.update change
    end

// Vulnerability class: CWE-20
def self.reminders(options={})
    days = options[:days] || 7
    project = options[:project] ? Project.find(options[:project]) : nil
    tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil
    target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil
    if options[:version] && target_version_id.blank?
      raise ActiveRecord::RecordNotFound.new("Couldn't find Version with named #{options[:version]}")
    end
    user_ids = options[:users]

    scope = Issue.open.where("#{Issue.table_name}.assigned_to_id IS NOT NULL" +
      " AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}" +
      " AND #{Issue.table_name}.due_date <= ?", days.day.from_now.to_date
    )
    scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?
    scope = scope.where(:project_id => project.id) if project
    scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?
    scope = scope.where(:tracker_id => tracker.id) if tracker
    issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).
                              group_by(&:assigned_to)
    issues_by_assignee.keys.each do |assignee|
      if assignee.is_a?(Group)
        assignee.users.each do |user|
          issues_by_assignee[user] ||= []
          issues_by_assignee[user] += issues_by_assignee[assignee]
        end
      end
    end

    issues_by_assignee.each do |assignee, issues|
      reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?
    end
  end

// Vulnerability class: CWE-200
def index
    valid_http_methods :get, :post, :put

    # for permission check
    if params[:package] and not ["_repository", "_jobhistory"].include?(params[:package])
      pkg = DbPackage.get_by_project_and_name( params[:project], params[:package], use_source=false )
    else
      prj = DbProject.get_by_name params[:project]
    end

    pass_to_backend 
  end

// Vulnerability class: CWE-20
def bulk_unread_topic_ids
    topic_query = TopicQuery.new(current_user)

    if inbox = params[:private_message_inbox]
      filter = private_message_filter(topic_query, inbox)
      topic_query.options[:limit] = false

      topic_query
        .filter_private_messages_unread(current_user, filter)
        .distinct(false)
        .pluck(:id)
    else
      topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics
      topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == "true"

      if params[:category_id]
        if params[:include_subcategories]
          topics = topics.where(<<~SQL, category_id: params[:category_id])
            category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR
            category_id = :category_id
          SQL
        else
          topics = topics.where('category_id = ?', params[:category_id])
        end
      end

      if params[:tag_name].present?
        topics = topics.joins(:tags).where("tags.name": params[:tag_name])
      end

      topics.pluck(:id)
    end
  end

// Vulnerability class: CWE-863
it "should unstage user" do
      staged_user = Fabricate(:staged, email: 'staged@account.com', active: true, username: 'staged1', name: 'Stage Name')
      invite = Fabricate(:invite, email: 'staged@account.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')

      expect(user.id).to eq(staged_user.id)
      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.staged).to eq(false)
      expect(user.email).to eq('staged@account.com')
      expect(user.approved).to eq(true)
    end

// Vulnerability class: CWE-863
it 'does not log in with incorrect two factor' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(response.status).to eq(200)

              expect(CGI.unescapeHTML(response.body)).to include(I18n.t(
                "login.invalid_second_factor_code"
              ))
            end

// Vulnerability class: CWE-287
def test_update_valid
    Subnet.any_instance.stubs(:valid?).returns(true)
    put :update, {:id => Subnet.first, :subnet => {:network => '192.168.100.10'}}, set_session_user
    assert_equal '192.168.100.10', Subnet.first.network
    assert_redirected_to subnets_url
  end

// Vulnerability class: CWE-200
it 'does not log in with incorrect backup code' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:backup_codes]
              }

              expect(response.status).to eq(200)
              expect(CGI.unescapeHTML(response.body)).to include(I18n.t(
                "login.invalid_second_factor_code"
              ))
            end

// Vulnerability class: CWE-287
def private_message_reset_new
    topic_query = TopicQuery.new(current_user, limit: false)

    if params[:topic_ids].present?
      unless Array === params[:topic_ids]
        raise Discourse::InvalidParameters.new(
          "Expecting topic_ids to contain a list of topic ids"
        )
      end

      topic_scope = topic_query
        .private_messages_for(current_user, :all)
        .where("topics.id IN (?)", params[:topic_ids].map(&:to_i))
    else
      params.require(:inbox)
      inbox = params[:inbox].to_s
      filter = private_message_filter(topic_query, inbox)
      topic_scope = topic_query.filter_private_message_new(current_user, filter)
    end

    topic_ids = TopicsBulkAction.new(
      current_user,
      topic_scope.distinct(false).pluck(:id),
      type: "dismiss_topics"
    ).perform!

    render json: success_json.merge(topic_ids: topic_ids)
  end

// Vulnerability class: CWE-863
def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false)
        unless input.count('.') + 1 == NUM_OF_SEGMENTS
          raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.")
        end
        header, claims, signature = input.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment|
          Base64.urlsafe_decode64 segment.to_s
        end
        header = JSON.parse(header).with_indifferent_access
        if allow_blank_payload && claims == ''
          claims = nil
        else
          claims = JSON.parse(claims).with_indifferent_access
        end
        jws = new claims
        jws.header = header
        jws.signature = signature
        jws.signature_base_string = input.split('.')[0, JWS::NUM_OF_SEGMENTS - 1].join('.')
        jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification
        jws
      end

// Vulnerability class: CWE-287
def piped_category_name(category_id)
      return "-" unless category_id
      category = Category.find_by(id: category_id)
      return "#{category_id}" unless category
      categories = [category.name]
      while category.parent_category_id && category = category.parent_category
        categories << category.name
      end
      categories.reverse.join("|")
    end

// Vulnerability class: CWE-200
def one_time_password
    otp_username = $redis.get "otp_#{params[:token]}"

    if otp_username && user = User.find_by_username(otp_username)
      log_on_user(user)
      $redis.del "otp_#{params[:token]}"
      return redirect_to path("/")
    else
      @error = I18n.t('user_api_key.invalid_token')
    end

    render layout: 'no_ember'
  end

// Vulnerability class: CWE-287