code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
int length() const {
return m_str ? m_str->size() : 0;
} | Base | 1 |
MpdCantataMounterInterface * RemoteFsDevice::mounter()
{
if (!mounterIface) {
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {
QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());
}
mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),
"/Mounter", QDBusConnection::systemBus(), this);
connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));
connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));
}
return mounterIface;
} | Class | 2 |
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (!sz) {
return NULL;
}
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;
// if (buffer + offset > buffer + sz) return NULL;
attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
return attr;
} | Base | 1 |
int PackLinuxElf64::canUnpack()
{
if (super::canUnpack()) {
return true;
}
if (Elf64_Ehdr::ET_DYN==get_te16(&ehdri.e_type)) {
PackLinuxElf64help1(fi);
Elf64_Phdr const *phdr = phdri, *last_LOAD = nullptr;
for (unsigned j = 0; j < e_phnum; ++phdr, ++j)
if (Elf64_Phdr::PT_LOAD==get_te32(&phdr->p_type)) {
last_LOAD = phdr;
}
if (!last_LOAD)
return false;
off_t offset = get_te64(&last_LOAD->p_offset);
unsigned filesz = get_te64(&last_LOAD->p_filesz);
fi->seek(filesz+offset, SEEK_SET);
MemBuffer buf(32 + sizeof(overlay_offset));
fi->readx(buf, buf.getSize());
return PackUnix::find_overlay_offset(buf);
}
return false;
} | Base | 1 |
int nego_recv(rdpTransport* transport, wStream* s, void* extra)
{
BYTE li;
BYTE type;
UINT16 length;
rdpNego* nego = (rdpNego*)extra;
if (!tpkt_read_header(s, &length))
return -1;
if (!tpdu_read_connection_confirm(s, &li, length))
return -1;
if (li > 6)
{
/* rdpNegData (optional) */
Stream_Read_UINT8(s, type); /* Type */
switch (type)
{
case TYPE_RDP_NEG_RSP:
nego_process_negotiation_response(nego, s);
WLog_DBG(TAG, "selected_protocol: %" PRIu32 "", nego->SelectedProtocol);
/* enhanced security selected ? */
if (nego->SelectedProtocol)
{
if ((nego->SelectedProtocol == PROTOCOL_HYBRID) &&
(!nego->EnabledProtocols[PROTOCOL_HYBRID]))
{
nego->state = NEGO_STATE_FAIL;
}
if ((nego->SelectedProtocol == PROTOCOL_SSL) &&
(!nego->EnabledProtocols[PROTOCOL_SSL]))
{
nego->state = NEGO_STATE_FAIL;
}
}
else if (!nego->EnabledProtocols[PROTOCOL_RDP])
{
nego->state = NEGO_STATE_FAIL;
}
break;
case TYPE_RDP_NEG_FAILURE:
nego_process_negotiation_failure(nego, s);
break;
}
}
else if (li == 6)
{
WLog_DBG(TAG, "no rdpNegData");
if (!nego->EnabledProtocols[PROTOCOL_RDP])
nego->state = NEGO_STATE_FAIL;
else
nego->state = NEGO_STATE_FINAL;
}
else
{
WLog_ERR(TAG, "invalid negotiation response");
nego->state = NEGO_STATE_FAIL;
}
if (!tpkt_ensure_stream_consumed(s, length))
return -1;
return 0;
} | Base | 1 |
int ZlibInStream::pos()
{
return offset + ptr - start;
} | Base | 1 |
ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
}
return res;
} | Class | 2 |
void Compute(OpKernelContext* ctx) override {
const Tensor& handle = ctx->input(0);
const string& name = handle.scalar<tstring>()();
OP_REQUIRES_OK(ctx, ctx->session_state()->DeleteTensor(name));
} | Base | 1 |
void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)
{
QWriteLocker locker(&lock);
Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };
m_peers.push_back(temp);
if (m_peers.size() >= MAX_LOG_MESSAGES)
m_peers.pop_front();
emit newLogPeer(temp);
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (input1->type) {
case kTfLiteInt32: {
return EvalImpl<int32_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteInt64: {
return EvalImpl<int64_t>(context, data->requires_broadcast, input1,
input2, output);
}
case kTfLiteFloat32: {
return EvalImpl<float>(context, data->requires_broadcast, input1, input2,
output);
}
default: {
context->ReportError(context, "Type '%s' is not supported by floor_mod.",
TfLiteTypeGetName(input1->type));
return kTfLiteError;
}
}
} | Base | 1 |
void PrivateThreadPoolDatasetOp::MakeDatasetFromOptions(OpKernelContext* ctx,
DatasetBase* input,
int32_t num_threads,
DatasetBase** output) {
OP_REQUIRES(ctx, num_threads >= 0,
errors::InvalidArgument("`num_threads` must be >= 0"));
*output = new Dataset(ctx,
DatasetContext(DatasetContext::Params(
{PrivateThreadPoolDatasetOp::kDatasetType,
PrivateThreadPoolDatasetOp::kDatasetOp})),
input, num_threads);
} | Base | 1 |
void Init(bool hi)
{
for(int i = 0;i < 18;i++) {
char string[5] = "xl00";
string[1] = (hi)?('h'):('l');
string[2] = (i / 10) + '0';
string[3] = (i % 10) + '0';
X[i].Init(string);
string[0] = 'm';
M[i].Init(string);
}
} | Class | 2 |
bool remoteComplete() const { return state_.remote_complete_; } | Variant | 0 |
void FdOutStream::flush()
{
while (sentUpTo < ptr) {
int n = writeWithTimeout((const void*) sentUpTo,
ptr - sentUpTo,
blocking? timeoutms : 0);
// Timeout?
if (n == 0) {
// If non-blocking then we're done here
if (!blocking)
break;
throw TimedOut();
}
sentUpTo += n;
offset += n;
}
// Managed to flush everything?
if (sentUpTo == ptr)
ptr = sentUpTo = start;
} | Base | 1 |
TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);
const int num_dimensions = NumDimensions(input);
const int num_multipliers = NumElements(multipliers);
TF_LITE_ENSURE_EQ(context, num_dimensions, num_multipliers);
switch (multipliers->type) {
case kTfLiteInt32:
return context->ResizeTensor(
context, output,
MultiplyShapeDims<int32_t>(*input->dims, multipliers,
num_dimensions));
case kTfLiteInt64:
return context->ResizeTensor(
context, output,
MultiplyShapeDims<int64_t>(*input->dims, multipliers,
num_dimensions));
default:
context->ReportError(
context, "Multipliers of type '%s' are not supported by tile.",
TfLiteTypeGetName(multipliers->type));
return kTfLiteError;
}
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpContext op_context(context, node);
switch (op_context.output->type) {
case kTfLiteFloat32:
TFLiteOperation<kernel_type, float, OpType>(context, node, op_context);
break;
case kTfLiteUInt8:
TFLiteOperation<kernel_type, uint8_t, OpType>(context, node,
op_context);
break;
case kTfLiteInt8:
TFLiteOperation<kernel_type, int8_t, OpType>(context, node, op_context);
break;
case kTfLiteInt32:
TFLiteOperation<kernel_type, int32_t, OpType>(context, node,
op_context);
break;
case kTfLiteInt64:
TFLiteOperation<kernel_type, int64_t, OpType>(context, node,
op_context);
break;
case kTfLiteInt16:
TFLiteOperation<kernel_type, int16_t, OpType>(context, node,
op_context);
break;
default:
context->ReportError(context,
"Type %d is currently not supported by Maximum.",
op_context.output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
// There are two ways in which the 'output' can be made dynamic: it could be
// a string tensor, or its shape cannot be calculated during Prepare(). In
// either case, we now have all the information to calculate its shape.
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));
}
// Note that string tensors are always "dynamic" in the sense that their size
// is not known until we have all the content. This applies even when their
// shape is known ahead of time. As a result, a string tensor is never given
// any memory by ResizeOutput(), and we need to do it manually here. Since
// reshape doesn't change the data, the output tensor needs exactly as many
// bytes as the input tensor.
if (output->type == kTfLiteString) {
auto bytes_required = input->bytes;
TfLiteTensorRealloc(bytes_required, output);
output->bytes = bytes_required;
}
memcpy(output->data.raw, input->data.raw, input->bytes);
return kTfLiteOk;
} | Base | 1 |
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;
} | Variant | 0 |
Http::FilterDataStatus Context::onResponseBody(int body_buffer_length, bool end_of_stream) {
if (!wasm_->onResponseBody_) {
return Http::FilterDataStatus::Continue;
}
switch (wasm_
->onResponseBody_(this, id_, static_cast<uint32_t>(body_buffer_length),
static_cast<uint32_t>(end_of_stream))
.u64_) {
case 0:
return Http::FilterDataStatus::Continue;
case 1:
return Http::FilterDataStatus::StopIterationAndBuffer;
case 2:
return Http::FilterDataStatus::StopIterationAndWatermark;
default:
return Http::FilterDataStatus::StopIterationNoBuffer;
}
} | Base | 1 |
static char *pool_strdup(const char *s)
{
char *r = pool_alloc(strlen(s) + 1);
strcpy(r, s);
return r;
} | Class | 2 |
TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") {
vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint32_t encLen = 0;
PRINT_SRC_LINE
auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32);
REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS);
vector<char> secret(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0);
status = trustedDecryptDkgSecretAES(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
encLen, (uint8_t *) secret.data());
REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS);
} | Base | 1 |
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (tuple[index].has_value()) {
return Status(errors::InvalidArgument(
"The tensor for index '", index, "' for key '", key.scalar<int64>()(),
"' was already initialized '", dtypes_.size(), "'."));
}
return Status::OK();
} | Base | 1 |
R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (!se) {
return NULL;
}
se->tag = type;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = (ut16) value;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
/*if (bin->offset_sz == 4) {
se->info.uninit_offset = value;
} else {
se->info.uninit_offset = (ut16) value;
}*/
se->info.uninit_offset = (ut16) value;
}
return se;
} | Base | 1 |
bool HexInStream::hexStrToBin(const char* s, char** data, int* length) {
int l=strlen(s);
if ((l % 2) == 0) {
delete [] *data;
*data = 0; *length = 0;
if (l == 0)
return true;
*data = new char[l/2];
*length = l/2;
for(int i=0;i<l;i+=2) {
int byte = 0;
if (!readHexAndShift(s[i], &byte) ||
!readHexAndShift(s[i+1], &byte))
goto decodeError;
(*data)[i/2] = byte;
}
return true;
}
decodeError:
delete [] *data;
*data = 0;
*length = 0;
return false;
} | Base | 1 |
check_owner_password_V4(std::string& user_password,
std::string const& owner_password,
QPDF::EncryptionData const& data)
{
// Algorithm 3.7 from the PDF 1.7 Reference Manual
unsigned char key[OU_key_bytes_V4];
compute_O_rc4_key(user_password, owner_password, data, key);
unsigned char O_data[key_bytes];
memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);
iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),
(data.getR() >= 3) ? 20 : 1, true);
std::string new_user_password =
std::string(reinterpret_cast<char*>(O_data), key_bytes);
bool result = false;
if (check_user_password(new_user_password, data))
{
result = true;
user_password = new_user_password;
}
return result;
} | Base | 1 |
int pnm_validate(jas_stream_t *in)
{
uchar buf[2];
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, buf, 2)) < 0) {
return -1;
}
/* Put these characters back to the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < 2) {
return -1;
}
/* Is this the correct signature for a PNM file? */
if (buf[0] == 'P' && isdigit(buf[1])) {
return 0;
}
return -1;
} | Class | 2 |
TfLiteStatus EluPrepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// Use LUT to handle quantized elu path.
if (input->type == kTfLiteInt8) {
PopulateLookupTable<int8_t>(data, input, output, [](float value) {
return value < 0.0 ? std::exp(value) - 1.0f : value;
});
}
return GenericPrepare(context, node);
} | Base | 1 |
void pb_controller::play_file(const std::string& file) {
std::string cmdline;
std::string player = cfg->get_configvalue("player");
if (player == "")
return;
cmdline.append(player);
cmdline.append(" \"");
cmdline.append(utils::replace_all(file,"\"", "\\\""));
cmdline.append("\"");
stfl::reset();
utils::run_interactively(cmdline, "pb_controller::play_file");
} | Base | 1 |
bool PackLinuxElf64::calls_crt1(Elf64_Rela const *rela, int sz)
{
if (!dynsym || !dynstr) {
return false;
}
for (unsigned relnum= 0; 0 < sz; (sz -= sizeof(Elf64_Rela)), ++rela, ++relnum) {
unsigned const symnum = get_te64(&rela->r_info) >> 32;
char const *const symnam = get_dynsym_name(symnum, relnum);
if (0==strcmp(symnam, "__libc_start_main") // glibc
|| 0==strcmp(symnam, "__libc_init") // Android
|| 0==strcmp(symnam, "__uClibc_main")
|| 0==strcmp(symnam, "__uClibc_start_main"))
return true;
}
return false;
} | Base | 1 |
void AOClient::pktRemoveEvidence(AreaData* area, int argc, QStringList argv, AOPacket packet)
{
if (!checkEvidenceAccess(area))
return;
bool is_int = false;
int idx = argv[0].toInt(&is_int);
if (is_int && idx <= area->evidence().size() && idx >= 0) {
area->deleteEvidence(idx);
}
sendEvidenceList(area);
} | Variant | 0 |
inline void aligned_free(void* ptr) {
folly::detail::aligned_free(ptr);
} | Base | 1 |
void RemoteFsDevice::unmount()
{
if (details.isLocalFile()) {
return;
}
if (!isConnected() || proc) {
return;
}
if (messageSent) {
return;
}
if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {
mounter()->umount(mountPoint(details, false), getpid());
setStatusMessage(tr("Disconnecting..."));
messageSent=true;
return;
}
QString cmd;
QStringList args;
if (!details.isLocalFile()) {
QString mp=mountPoint(details, false);
if (!mp.isEmpty()) {
cmd=Utils::findExe("fusermount");
if (!cmd.isEmpty()) {
args << QLatin1String("-u") << QLatin1String("-z") << mp;
} else {
emit error(tr("\"fusermount\" is not installed!"));
}
}
}
if (!cmd.isEmpty()) {
setStatusMessage(tr("Disconnecting..."));
proc=new QProcess(this);
proc->setProperty("unmount", true);
connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));
proc->start(cmd, args, QIODevice::ReadOnly);
}
} | Base | 1 |
bool ConstantFolding::SimplifyReshape(const GraphProperties& properties,
bool use_shape_info, NodeDef* node) {
if (!use_shape_info || node->attr().count("T") == 0 ||
!IsSimplifiableReshape(*node, properties)) {
return false;
}
DataType output_type = node->attr().at("T").type();
node->set_op("Identity");
EraseRegularNodeAttributes(node);
(*node->mutable_attr())["T"].set_type(output_type);
*node->mutable_input(1) = AsControlDependency(node->input(1));
return true;
} | Base | 1 |
bool TemporaryFile::deleteTemporaryFile() const
{
// Have a few attempts at deleting the file before giving up..
for (int i = 5; --i >= 0;)
{
if (temporaryFile.deleteFile())
return true;
Thread::sleep (50);
}
return false;
}
| Base | 1 |
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();
} | Class | 2 |
CbrDetectorRemote::Result CbrDetectorRemote::Decrypt(cricket::MediaType media_type,
const std::vector<uint32_t>& csrcs,
rtc::ArrayView<const uint8_t> additional_data,
rtc::ArrayView<const uint8_t> encrypted_frame,
rtc::ArrayView<uint8_t> frame)
{
const uint8_t *src = encrypted_frame.data();
uint8_t *dst = frame.data();
uint32_t data_len = encrypted_frame.size();
if (media_type == cricket::MEDIA_TYPE_AUDIO) {
if (data_len == frame_size && frame_size >= 40) {
frame_count++;
if (frame_count > 200 && !detected) {
info("CBR detector: remote cbr detected\n");
detected = true;
}
}
else {
frame_count = 0;
frame_size = data_len;
if (detected) {
info("CBR detector: remote cbr detected disabled\n");
detected = false;
}
}
}
memcpy(dst, src, data_len);
out:
return CbrDetectorRemote::Result(CbrDetectorRemote::Status::kOk, data_len);
} | Base | 1 |
R_API RBinJavaAttrInfo *r_bin_java_rti_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.rtv_annotations_attr.num_annotations; i++) {
if (offset >= sz) {
break;
}
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
}
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
attr->size = offset;
}
return attr;
} | Base | 1 |
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;
} | Class | 2 |
void RegKey::getBinary(const TCHAR* valname, void** data, int* length) const {
TCharArray hex(getRepresentation(valname));
if (!rdr::HexInStream::hexStrToBin(CStr(hex.buf), (char**)data, length))
throw rdr::Exception("getBinary failed");
} | Base | 1 |
Pl_Count::write(unsigned char* buf, size_t len)
{
if (len)
{
this->m->count += QIntC::to_offset(len);
getNext()->write(buf, len);
this->m->last_char = buf[len - 1];
}
} | Base | 1 |
int GetS16BE (int nPos, bool *pbSuccess)
{
//*pbSuccess = true;
if ( nPos < 0 || nPos + 1 >= m_nLen )
{
*pbSuccess = false;
return 0;
}
int nRes = m_sFile[nPos];
nRes = (nRes << 8) + m_sFile[ nPos + 1 ];
if ( nRes & 0x8000 )
nRes |= ~0xffff;
return nRes;
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteAddParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32) {
EvalAdd<kernel_type>(context, node, params, data, input1, input2, output);
} else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||
output->type == kTfLiteInt16) {
TF_LITE_ENSURE_OK(context,
EvalAddQuantized<kernel_type>(context, node, params, data,
input1, input2, output));
} else {
TF_LITE_UNSUPPORTED_TYPE(context, output->type, "Add");
}
return kTfLiteOk;
} | Base | 1 |
int TLSInStream::pos()
{
return offset + ptr - start;
} | Base | 1 |
TfLiteStatus EvalHashtableFind(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
const TfLiteTensor* default_value_tensor =
GetInput(context, node, kDefaultValueTensor);
TfLiteTensor* output_tensor = GetOutput(context, node, 0);
Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
auto& resources = subgraph->resources();
auto* lookup = resource::GetHashtableResource(&resources, resource_id);
TF_LITE_ENSURE(context, lookup != nullptr);
TF_LITE_ENSURE_STATUS(
lookup->CheckKeyAndValueTypes(context, key_tensor, output_tensor));
auto result =
lookup->Lookup(context, key_tensor, output_tensor, default_value_tensor);
return result;
} | Base | 1 |
void ValidateInputTensors(OpKernelContext* ctx, const Tensor& in0,
const Tensor& in1) override {
OP_REQUIRES(
ctx, in0.dims() >= 2,
errors::InvalidArgument("In[0] ndims must be >= 2: ", in0.dims()));
OP_REQUIRES(
ctx, in1.dims() >= 2,
errors::InvalidArgument("In[0] ndims must be >= 2: ", in1.dims()));
} | Base | 1 |
static UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
rdpPrintJob* printjob = NULL;
UINT error = CHANNEL_RC_OK;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
Stream_Seek(irp->input, 20); /* Padding */
if (printer_dev->printer)
printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);
if (!printjob)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
}
else
{
error = printjob->Write(printjob, Stream_Pointer(irp->input), Length);
}
if (error)
{
WLog_ERR(TAG, "printjob->Write failed with error %" PRIu32 "!", error);
return error;
}
Stream_Write_UINT32(irp->output, Length);
Stream_Write_UINT8(irp->output, 0); /* Padding */
return irp->Complete(irp);
} | Base | 1 |
TfLiteStatus ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
int max_index = -1;
const int segment_id_size = segment_ids->dims->data[0];
if (segment_id_size > 0) {
max_index = segment_ids->data.i32[segment_id_size - 1];
}
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | Base | 1 |
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;
} | Class | 2 |
std::string TarFileReader::extract(const string &_path) {
if (_path.empty()) THROW("path cannot be empty");
if (!hasMore()) THROW("No more tar files");
string path = _path;
if (SystemUtilities::isDirectory(path)) path += "/" + getFilename();
LOG_DEBUG(5, "Extracting: " << path);
return extract(*SystemUtilities::oopen(path));
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLiteSubParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt32 ||
output->type == kTfLiteInt64) {
EvalSub<kernel_type>(context, node, params, data, input1, input2, output);
} else if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 ||
output->type == kTfLiteInt16) {
EvalQuantized<kernel_type>(context, node, params, data, input1, input2,
output);
} else {
context->ReportError(
context,
"output type %d is not supported, requires float|uint8|int32 types.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,
HeaderString&& value) {
StreamImpl* stream = getStream(frame->hd.stream_id);
if (!stream) {
// We have seen 1 or 2 crashes where we get a headers callback but there is no associated
// stream data. I honestly am not sure how this can happen. However, from reading the nghttp2
// code it looks possible that inflate_header_block() can safely inflate headers for an already
// closed stream, but will still call the headers callback. Since that seems possible, we should
// ignore this case here.
// TODO(mattklein123): Figure out a test case that can hit this.
stats_.headers_cb_no_stream_.inc();
return 0;
}
stream->saveHeader(std::move(name), std::move(value));
if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {
// This will cause the library to reset/close the stream.
stats_.header_overflow_.inc();
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
} else {
return 0;
}
} | Class | 2 |
String StringUtil::Crypt(const String& input, const char *salt /* = "" */) {
if (salt && salt[0] == '\0') {
raise_notice("crypt(): No salt parameter was specified."
" You must use a randomly generated salt and a strong"
" hash function to produce a secure hash.");
}
return String(string_crypt(input.c_str(), salt), AttachString);
} | Base | 1 |
void AveragePool(const float* input_data, const Dims<4>& input_dims,
int stride_width, int stride_height, int pad_width,
int pad_height, int kwidth, int kheight, float* output_data,
const Dims<4>& output_dims) {
float output_activation_min, output_activation_max;
GetActivationMinMax(Ac, &output_activation_min, &output_activation_max);
AveragePool(input_data, input_dims, stride_width, stride_height, pad_width,
pad_height, kwidth, kheight, output_activation_min,
output_activation_max, output_data, output_dims);
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output_index_tensor = GetOutput(context, node, 1);
TF_LITE_ENSURE_EQ(context, NumElements(output_index_tensor),
NumElements(input));
switch (input->type) {
case kTfLiteInt8:
TF_LITE_ENSURE_STATUS(EvalImpl<int8_t>(context, input, node));
break;
case kTfLiteInt16:
TF_LITE_ENSURE_STATUS(EvalImpl<int16_t>(context, input, node));
break;
case kTfLiteInt32:
TF_LITE_ENSURE_STATUS(EvalImpl<int32_t>(context, input, node));
break;
case kTfLiteInt64:
TF_LITE_ENSURE_STATUS(EvalImpl<int64_t>(context, input, node));
break;
case kTfLiteFloat32:
TF_LITE_ENSURE_STATUS(EvalImpl<float>(context, input, node));
break;
case kTfLiteUInt8:
TF_LITE_ENSURE_STATUS(EvalImpl<uint8_t>(context, input, node));
break;
default:
context->ReportError(context, "Currently Unique doesn't support type: %s",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
bool RepeatedAttrDefEqual(
const protobuf::RepeatedPtrField<OpDef::AttrDef>& a1,
const protobuf::RepeatedPtrField<OpDef::AttrDef>& a2) {
std::unordered_map<string, const OpDef::AttrDef*> a1_set;
for (const OpDef::AttrDef& def : a1) {
DCHECK(a1_set.find(def.name()) == a1_set.end())
<< "AttrDef names must be unique, but '" << def.name()
<< "' appears more than once";
a1_set[def.name()] = &def;
}
for (const OpDef::AttrDef& def : a2) {
auto iter = a1_set.find(def.name());
if (iter == a1_set.end()) return false;
if (!AttrDefEqual(*iter->second, def)) return false;
a1_set.erase(iter);
}
if (!a1_set.empty()) return false;
return true;
} | Base | 1 |
int64_t MemFile::readImpl(char *buffer, int64_t length) {
assertx(m_len != -1);
assertx(length > 0);
int64_t remaining = m_len - m_cursor;
if (remaining < length) length = remaining;
if (length > 0) {
memcpy(buffer, (const void *)(m_data + m_cursor), length);
}
m_cursor += length;
return length;
} | Base | 1 |
inline bool checkNoWait(int length) { return check(length, 1, false)!=0; } | Base | 1 |
State()
: remote_complete_(false), local_complete_(false), has_1xx_headers_(false),
created_filter_chain_(false), is_head_request_(false), is_grpc_request_(false),
non_100_response_headers_encoded_(false), under_on_local_reply_(false),
decoder_filter_chain_aborted_(false), encoder_filter_chain_aborted_(false),
saw_downstream_reset_(false) {} | Variant | 0 |
static void setAppend(SetType& set, const VariantType& v) {
auto value_type = type(v);
if (value_type != HPHP::serialize::Type::INT64 &&
value_type != HPHP::serialize::Type::STRING) {
throw HPHP::serialize::UnserializeError(
"Unsupported keyset element of type " +
folly::to<std::string>(value_type));
}
set.append(v);
} | Class | 2 |
bool SPIFFEValidator::matchSubjectAltName(X509& leaf_cert) {
bssl::UniquePtr<GENERAL_NAMES> san_names(static_cast<GENERAL_NAMES*>(
X509_get_ext_d2i(&leaf_cert, NID_subject_alt_name, nullptr, nullptr)));
// We must not have san_names == nullptr here because this function is called after the
// SPIFFE cert validation algorithm succeeded, which requires exactly one URI SAN in the leaf
// cert.
ASSERT(san_names != nullptr,
"san_names should have at least one name after SPIFFE cert validation");
// Only match against URI SAN since SPIFFE specification does not restrict values in other SAN
// types. See the discussion: https://github.com/envoyproxy/envoy/issues/15392
for (const GENERAL_NAME* general_name : san_names.get()) {
if (general_name->type == GEN_URI) {
const std::string san = Utility::generalNameAsString(general_name);
for (const auto& config_san_matcher : subject_alt_name_matchers_) {
if (config_san_matcher.match(san)) {
return true;
}
}
}
}
return false;
} | Base | 1 |
HexInStream::HexInStream(InStream& is, int bufSize_)
: bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_LEN), offset(0), in_stream(is)
{
ptr = end = start = new U8[bufSize];
} | Base | 1 |
static size_t ntlm_av_pair_get_next_offset(NTLM_AV_PAIR* pAvPair)
{
return ntlm_av_pair_get_len(pAvPair) + sizeof(NTLM_AV_PAIR);
} | Base | 1 |
void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
} | Class | 2 |
ALWAYS_INLINE String serialize_impl(const Variant& value,
const SerializeOptions& opts) {
switch (value.getType()) {
case KindOfClass:
case KindOfLazyClass:
case KindOfPersistentString:
case KindOfString: {
auto const str =
isStringType(value.getType()) ? value.getStringData() :
isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :
lazyClassToStringHelper(value.toLazyClassVal());
auto const size = str->size();
if (size >= RuntimeOption::MaxSerializedStringSize) {
throw Exception("Size of serialized string (%d) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, true);
} | Base | 1 |
TfLiteStatus EvalLogic(TfLiteContext* context, TfLiteNode* node,
OpContext* op_context, T init_value,
T reducer(const T current, const T in)) {
int64_t num_axis = NumElements(op_context->axis);
TfLiteTensor* temp_index = GetTemporary(context, node, /*index=*/0);
TfLiteTensor* resolved_axis = GetTemporary(context, node, /*index=*/1);
// Resize the output tensor if the output tensor is dynamic.
if (IsDynamicTensor(op_context->output)) {
TF_LITE_ENSURE_OK(context,
ResizeTempAxis(context, op_context, resolved_axis));
TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, op_context));
}
if (op_context->input->type == kTfLiteUInt8 ||
op_context->input->type == kTfLiteInt8) {
TF_LITE_ENSURE_EQ(context, op_context->input->params.scale,
op_context->output->params.scale);
TF_LITE_ENSURE_EQ(context, op_context->input->params.zero_point,
op_context->output->params.zero_point);
}
TF_LITE_ENSURE(
context,
reference_ops::ReduceGeneric<T>(
GetTensorData<T>(op_context->input), op_context->input->dims->data,
op_context->input->dims->size, GetTensorData<T>(op_context->output),
op_context->output->dims->data, op_context->output->dims->size,
GetTensorData<int>(op_context->axis), num_axis,
op_context->params->keep_dims, GetTensorData<int>(temp_index),
GetTensorData<int>(resolved_axis), init_value, reducer));
return kTfLiteOk;
} | Base | 1 |
void TensorSliceReader::LoadShard(int shard) const {
CHECK_LT(shard, sss_.size());
if (sss_[shard] || !status_.ok()) {
return; // Already loaded, or invalid.
}
string value;
SavedTensorSlices sts;
const string fname = fnames_[shard];
VLOG(1) << "Reading meta data from file " << fname << "...";
Table* table;
Status s = open_function_(fname, &table);
if (!s.ok()) {
status_ = errors::DataLoss("Unable to open table file ", fname, ": ",
s.ToString());
return;
}
sss_[shard].reset(table);
if (!(table->Get(kSavedTensorSlicesKey, &value) &&
ParseProtoUnlimited(&sts, value))) {
status_ = errors::Internal(
"Failed to find the saved tensor slices at the beginning of the "
"checkpoint file: ",
fname);
return;
}
status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,
TF_CHECKPOINT_VERSION_MIN_PRODUCER, "Checkpoint",
"checkpoint");
if (!status_.ok()) return;
for (const SavedSliceMeta& ssm : sts.meta().tensor()) {
TensorShape ssm_shape(ssm.shape());
for (const TensorSliceProto& tsp : ssm.slice()) {
TensorSlice ss_slice(tsp);
status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,
ss_slice, &tensors_);
if (!status_.ok()) return;
}
}
} | Class | 2 |
int DummyOutStream::overrun(int itemSize, int nItems)
{
flush();
if (itemSize * nItems > end - ptr)
nItems = (end - ptr) / itemSize;
return nItems;
} | Base | 1 |
void CommandData::ProcessCommand()
{
#ifndef SFX_MODULE
const wchar *SingleCharCommands=L"FUADPXETK";
if (Command[0]!=0 && Command[1]!=0 && wcschr(SingleCharCommands,Command[0])!=NULL || *ArcName==0)
OutHelp(*Command==0 ? RARX_SUCCESS:RARX_USERERROR); // Return 'success' for 'rar' without parameters.
const wchar *ArcExt=GetExt(ArcName);
#ifdef _UNIX
if (ArcExt==NULL && (!FileExist(ArcName) || IsDir(GetFileAttr(ArcName))))
wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#else
if (ArcExt==NULL)
wcsncatz(ArcName,L".rar",ASIZE(ArcName));
#endif
// Treat arcname.part1 as arcname.part1.rar.
if (ArcExt!=NULL && wcsnicomp(ArcExt,L".part",5)==0 && IsDigit(ArcExt[5]) &&
!FileExist(ArcName))
{
wchar Name[NM];
wcsncpyz(Name,ArcName,ASIZE(Name));
wcsncatz(Name,L".rar",ASIZE(Name));
if (FileExist(Name))
wcsncpyz(ArcName,Name,ASIZE(ArcName));
}
if (wcschr(L"AFUMD",*Command)==NULL)
{
if (GenerateArcName)
GenerateArchiveName(ArcName,ASIZE(ArcName),GenerateMask,false);
StringList ArcMasks;
ArcMasks.AddString(ArcName);
ScanTree Scan(&ArcMasks,Recurse,SaveSymLinks,SCAN_SKIPDIRS);
FindData FindData;
while (Scan.GetNext(&FindData)==SCAN_SUCCESS)
AddArcName(FindData.Name);
}
else
AddArcName(ArcName);
#endif
switch(Command[0])
{
case 'P':
case 'X':
case 'E':
case 'T':
case 'I':
{
CmdExtract Extract(this);
Extract.DoExtract();
}
break;
#ifndef SILENT
case 'V':
case 'L':
ListArchive(this);
break;
default:
OutHelp(RARX_USERERROR);
#endif
}
if (!BareOutput)
mprintf(L"\n");
} | Base | 1 |
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;
} | Class | 2 |
vector <string> genECDSAKey() {
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
vector <uint8_t> encr_pr_key(BUF_LEN, 0);
vector<char> pub_key_x(BUF_LEN, 0);
vector<char> pub_key_y(BUF_LEN, 0);
uint32_t enc_len = 0;
sgx_status_t status = trustedGenerateEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
vector <string> keys(3);
vector<char> hexEncrKey(BUF_LEN * 2, 0);
carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data(),
BUF_LEN * 2);
keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer);
vector<char> rand_str(BUF_LEN, 0);
carray2Hex(randBuffer.data(), 32, rand_str.data(), BUF_LEN);
keys.at(2) = rand_str.data();
CHECK_STATE(keys.at(2).size() == 64);
return keys;
} | Base | 1 |
void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
} | Base | 1 |
static int stszin(int size)
{
int cnt;
uint32_t ofs;
// version/flags
u32in();
// Sample size
u32in();
// Number of entries
mp4config.frame.ents = u32in();
// fixme: check atom size
mp4config.frame.data = malloc(sizeof(*mp4config.frame.data)
* (mp4config.frame.ents + 1));
if (!mp4config.frame.data)
return ERR_FAIL;
ofs = 0;
mp4config.frame.data[0] = ofs;
for (cnt = 0; cnt < mp4config.frame.ents; cnt++)
{
uint32_t fsize = u32in();
ofs += fsize;
if (mp4config.frame.maxsize < fsize)
mp4config.frame.maxsize = fsize;
mp4config.frame.data[cnt + 1] = ofs;
if (ofs < mp4config.frame.data[cnt])
return ERR_FAIL;
}
return size;
} | Base | 1 |
bool DNP3_Base::ParseAppLayer(Endpoint* endp)
{
bool orig = (endp == &orig_state);
binpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow();
u_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems.
int len = endp->pkt_length - 5;
// DNP3 Packet : DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer
// DNP3 Serial Transport Layer data is always 1 byte.
// Get FIN FIR seq field in transport header.
// FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not.
// FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not.
int is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet.
int is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet.
int transport = PSEUDO_TRANSPORT_LEN;
int i = 0;
while ( len > 0 )
{
int n = min(len, 16);
// Make sure chunk has a correct checksum.
if ( ! CheckCRC(n, data, data + n, "app_chunk") )
return false;
// Pass on to BinPAC.
assert(data + n < endp->buffer + endp->buffer_len);
flow->flow_buffer()->BufferData(data + transport, data + n);
transport = 0;
data += n + 2;
len -= n;
}
if ( is_first )
endp->encountered_first_chunk = true;
if ( ! is_first && ! endp->encountered_first_chunk )
{
// We lost the first chunk.
analyzer->Weird("dnp3_first_application_layer_chunk_missing");
return false;
}
if ( is_last )
{
flow->flow_buffer()->FinishBuffer();
flow->FlowEOF();
ClearEndpointState(orig);
}
return true;
} | Class | 2 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
auto* params = reinterpret_cast<TfLiteShapeParams*>(node->builtin_data);
switch (params->out_type) {
case kTfLiteInt32:
output->type = kTfLiteInt32;
break;
case kTfLiteInt64:
output->type = kTfLiteInt64;
break;
default:
context->ReportError(context, "Unknown shape output data type: %d",
params->out_type);
return kTfLiteError;
}
// By design, the input shape is always known at the time of Prepare, even
// if the preceding op that generates |input| is dynamic. Thus, we can
// always compute the shape immediately, without waiting for Eval.
SetTensorToPersistentRo(output);
// Shape always produces a 1-dimensional output tensor, where each output
// element is the length of the corresponding input tensor's dimension.
TfLiteIntArray* output_size = TfLiteIntArrayCreate(1);
output_size->data[0] = NumDimensions(input);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));
TFLITE_DCHECK_EQ(NumDimensions(output), 1);
TFLITE_DCHECK_EQ(SizeOfDimension(output, 0), NumDimensions(input));
// Immediately propagate the known shape to the output tensor. This allows
// downstream ops that rely on the value to use it during prepare.
switch (output->type) {
case kTfLiteInt32:
ExtractShape(input, GetTensorData<int32_t>(output));
break;
case kTfLiteInt64:
ExtractShape(input, GetTensorData<int64_t>(output));
break;
default:
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
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;
}
} | Class | 2 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLitePackParams* data =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
return PackImpl<float>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteUInt8: {
return PackImpl<uint8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt8: {
return PackImpl<int8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt16: {
return PackImpl<int16_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt32: {
return PackImpl<int32_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt64: {
return PackImpl<int64_t>(context, node, output, data->values_count,
data->axis);
}
default: {
context->ReportError(context, "Type '%s' is not supported by pack.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | Base | 1 |
void nego_process_negotiation_response(rdpNego* nego, wStream* s)
{
UINT16 length;
WLog_DBG(TAG, "RDP_NEG_RSP");
if (Stream_GetRemainingLength(s) < 7)
{
WLog_ERR(TAG, "Invalid RDP_NEG_RSP");
nego->state = NEGO_STATE_FAIL;
return;
}
Stream_Read_UINT8(s, nego->flags);
Stream_Read_UINT16(s, length);
Stream_Read_UINT32(s, nego->SelectedProtocol);
nego->state = NEGO_STATE_FINAL;
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteLocalResponseNormParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32) {
#define TF_LITE_LOCAL_RESPONSE_NORM(type) \
tflite::LocalResponseNormalizationParams op_params; \
op_params.range = params->radius; \
op_params.bias = params->bias; \
op_params.alpha = params->alpha; \
op_params.beta = params->beta; \
type::LocalResponseNormalization( \
op_params, GetTensorShape(input), GetTensorData<float>(input), \
GetTensorShape(output), GetTensorData<float>(output))
if (kernel_type == kReference) {
TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);
}
if (kernel_type == kGenericOptimized) {
TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);
}
#undef TF_LITE_LOCAL_RESPONSE_NORM
} else {
context->ReportError(context, "Output type is %d, requires float.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
TfLiteStatus UseDynamicOutputTensors(TfLiteContext* context, TfLiteNode* node) {
for (int i = 0; i < NumOutputs(node); ++i) {
SetTensorToDynamic(GetOutput(context, node, i));
}
return kTfLiteOk;
} | Base | 1 |
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
int errStatus = 0;
vector<char> errMsg(BUF_LEN, 0);
uint32_t encLen;
string key = SAMPLE_AES_KEY;
vector <uint8_t> encrypted_key(BUF_LEN, 0);
PRINT_SRC_LINE
auto status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen);
REQUIRE(status == 0);
REQUIRE(errStatus == 0);
vector<char> decr_key(BUF_LEN, 0);
PRINT_SRC_LINE
status = trustedDecryptKeyAES(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
REQUIRE(status == 0);
REQUIRE(errStatus == 0);
REQUIRE(key.compare(decr_key.data()) == 0);
} | Base | 1 |
static Variant HHVM_FUNCTION(bcdiv, const String& left, const String& right,
int64_t scale /* = -1 */) {
if (scale < 0) scale = BCG(bc_precision);
bc_num first, second, result;
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&result);
SCOPE_EXIT {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
};
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
if (bc_divide(first, second, &result, scale) == -1) {
raise_warning("Division by zero");
return init_null();
}
String ret(bc_num2str(result), AttachString);
return ret;
} | Base | 1 |
bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {
assertx(m_len != -1);
if (whence == SEEK_CUR) {
if (offset > 0 && offset < bufferedLen()) {
setReadPosition(getReadPosition() + offset);
setPosition(getPosition() + offset);
return true;
}
offset += getPosition();
whence = SEEK_SET;
}
// invalidate the current buffer
setWritePosition(0);
setReadPosition(0);
if (whence == SEEK_SET) {
m_cursor = offset;
} else {
assertx(whence == SEEK_END);
m_cursor = m_len + offset;
}
setPosition(m_cursor);
return true;
} | Base | 1 |
void runTest() override
{
beginTest ("ZIP");
ZipFile::Builder builder;
StringArray entryNames { "first", "second", "third" };
HashMap<String, MemoryBlock> blocks;
for (auto& entryName : entryNames)
{
auto& block = blocks.getReference (entryName);
MemoryOutputStream mo (block, false);
mo << entryName;
mo.flush();
builder.addEntry (new MemoryInputStream (block, false), 9, entryName, Time::getCurrentTime());
}
MemoryBlock data;
MemoryOutputStream mo (data, false);
builder.writeToStream (mo, nullptr);
MemoryInputStream mi (data, false);
ZipFile zip (mi);
expectEquals (zip.getNumEntries(), entryNames.size());
for (auto& entryName : entryNames)
{
auto* entry = zip.getEntry (entryName);
std::unique_ptr<InputStream> input (zip.createStreamForEntry (*entry));
expectEquals (input->readEntireStreamAsString(), entryName);
}
}
| Base | 1 |
void Compute(OpKernelContext* context) override {
const Tensor& data = context->input(0);
const Tensor& segment_ids = context->input(1);
const Tensor& num_segments = context->input(2);
if (!UnsortedSegmentReductionDoValidation(this, context, data, segment_ids,
num_segments)) {
return;
}
const auto segment_flat = segment_ids.flat<Index>();
const Index output_rows = internal::SubtleMustCopy(static_cast<Index>(
num_segments.dtype() == DT_INT32 ? num_segments.scalar<int32>()()
: num_segments.scalar<int64>()()));
OP_REQUIRES(context, output_rows >= 0,
errors::InvalidArgument("Input num_segments == ", output_rows,
" must not be negative."));
TensorShape output_shape;
output_shape.AddDim(output_rows);
for (int i = segment_ids.dims(); i < data.dims(); i++) {
output_shape.AddDim(data.dim_size(i));
}
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_flat = output->flat_outer_dims<T>();
auto data_ptr = data.template flat<T>().data();
reduction_functor_(context, output_rows, segment_ids.shape(), segment_flat,
data.NumElements(), data_ptr, output_flat);
} | Base | 1 |
static inline long decode_twos_comp(ulong c, int prec)
{
long result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
// NOTE: Is this correct?
result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
return result;
} | Base | 1 |
Java_org_tensorflow_lite_InterpreterTest_getNativeHandleForDelegate(
JNIEnv* env, jclass clazz) {
// A simple op which outputs a tensor with values of 7.
static TfLiteRegistration registration = {
.init = nullptr,
.free = nullptr,
.prepare =
[](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = tflite::GetInput(context, node, 0);
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims);
output->type = kTfLiteFloat32;
return context->ResizeTensor(context, output, output_dims);
},
.invoke =
[](TfLiteContext* context, TfLiteNode* node) {
TfLiteTensor* output = tflite::GetOutput(context, node, 0);
std::fill(output->data.f,
output->data.f + tflite::NumElements(output), 7.0f);
return kTfLiteOk;
},
.profiling_string = nullptr,
.builtin_code = 0,
.custom_name = "",
.version = 1,
};
static TfLiteDelegate delegate = {
.data_ = nullptr,
.Prepare = [](TfLiteContext* context,
TfLiteDelegate* delegate) -> TfLiteStatus {
TfLiteIntArray* execution_plan;
TF_LITE_ENSURE_STATUS(
context->GetExecutionPlan(context, &execution_plan));
context->ReplaceNodeSubsetsWithDelegateKernels(
context, registration, execution_plan, delegate);
// Now bind delegate buffer handles for all tensors.
for (size_t i = 0; i < context->tensors_size; ++i) {
context->tensors[i].delegate = delegate;
context->tensors[i].buffer_handle = static_cast<int>(i);
}
return kTfLiteOk;
},
.CopyFromBufferHandle = nullptr,
.CopyToBufferHandle = nullptr,
.FreeBufferHandle = nullptr,
.flags = kTfLiteDelegateFlagsAllowDynamicTensors,
};
return reinterpret_cast<jlong>(&delegate);
} | Base | 1 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
OpContext op_context(context, node);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), op_context.params->num_splits);
auto input_type = op_context.input->type;
TF_LITE_ENSURE(context,
input_type == kTfLiteFloat32 || input_type == kTfLiteUInt8 ||
input_type == kTfLiteInt8 || input_type == kTfLiteInt16 ||
input_type == kTfLiteInt32);
for (int i = 0; i < NumOutputs(node); ++i) {
GetOutput(context, node, i)->type = input_type;
}
// If we know the contents of the 'axis' tensor, resize all outputs.
// Otherwise, wait until Eval().
if (IsConstantTensor(op_context.axis)) {
return ResizeOutputTensors(context, node, op_context.axis, op_context.input,
op_context.params->num_splits);
} else {
return UseDynamicOutputTensors(context, node);
}
} | Base | 1 |
void writeStats(Array& /*ret*/) override {
fprintf(stderr, "writeStats start\n");
// RetSame: the return value is the same instance every time
// HasThis: call has a this argument
// AllSame: all returns were the same data even though args are different
// MemberCount: number of different arg sets (including this)
fprintf(stderr, "Count Function MinSerLen MaxSerLen RetSame HasThis "
"AllSame MemberCount\n");
for (auto& me : m_memos) {
if (me.second.m_ignore) continue;
if (me.second.m_count == 1) continue;
int min_ser_len = 999999999;
int max_ser_len = 0;
int count = 0;
int member_count = 0;
bool all_same = true;
if (me.second.m_has_this) {
bool any_multiple = false;
auto& fr = me.second.m_member_memos.begin()->second.m_return_value;
member_count = me.second.m_member_memos.size();
for (auto& mme : me.second.m_member_memos) {
if (mme.second.m_return_value != fr) all_same = false;
count += mme.second.m_count;
auto ser_len = mme.second.m_return_value.length();
min_ser_len = std::min(min_ser_len, ser_len);
max_ser_len = std::max(max_ser_len, ser_len);
if (mme.second.m_count > 1) any_multiple = true;
}
if (!any_multiple && !all_same) continue;
} else {
min_ser_len = max_ser_len = me.second.m_return_value.length();
count = me.second.m_count;
all_same = me.second.m_ret_tv_same;
}
fprintf(stderr, "%d %s %d %d %s %s %s %d\n",
count, me.first.data(),
min_ser_len, max_ser_len,
me.second.m_ret_tv_same ? " true" : "false",
me.second.m_has_this ? " true" : "false",
all_same ? " true" : "false",
member_count
);
}
fprintf(stderr, "writeStats end\n");
} | Base | 1 |
void CarbonProtocolReader::skip(const FieldType ft) {
switch (ft) {
case FieldType::True:
case FieldType::False: {
break;
}
case FieldType::Int8: {
readRaw<int8_t>();
break;
}
case FieldType::Int16: {
readRaw<int16_t>();
break;
}
case FieldType::Int32: {
readRaw<int32_t>();
break;
}
case FieldType::Int64: {
readRaw<int64_t>();
break;
}
case FieldType::Double: {
readRaw<double>();
break;
}
case FieldType::Float: {
readRaw<float>();
break;
}
case FieldType::Binary: {
readRaw<std::string>();
break;
}
case FieldType::List: {
skipLinearContainer();
break;
}
case FieldType::Struct: {
readStructBegin();
while (true) {
const auto fieldType = readFieldHeader().first;
if (fieldType == FieldType::Stop) {
break;
}
skip(fieldType);
}
readStructEnd();
break;
}
case FieldType::Set: {
skipLinearContainer();
break;
}
case FieldType::Map: {
skipKVContainer();
break;
}
default: { break; }
}
} | Class | 2 |
int LibarchivePlugin::extractionFlags() const
{
int result = ARCHIVE_EXTRACT_TIME;
result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
// TODO: Don't use arksettings here
/*if ( ArkSettings::preservePerms() )
{
result &= ARCHIVE_EXTRACT_PERM;
}
if ( !ArkSettings::extractOverwrite() )
{
result &= ARCHIVE_EXTRACT_NO_OVERWRITE;
}*/
return result;
} | Base | 1 |
void readDataAvailable(size_t len) noexcept override {
std::cerr << "readDataAvailable, len " << len << std::endl;
currentBuffer.length = len;
wcb_->setSocket(socket_);
// Write back the same data.
socket_->write(wcb_, currentBuffer.buffer, len, writeFlags);
buffers.push_back(currentBuffer);
currentBuffer.reset();
state = STATE_SUCCEEDED;
} | Base | 1 |
TfLiteStatus EvalImpl(TfLiteContext* context, const TfLiteTensor* input,
TfLiteNode* node) {
// Map from value, to index in the unique elements vector.
// Note that we prefer to use map than unordered_map as it showed less
// increase in the binary size.
std::map<T, int> unique_values;
TfLiteTensor* output_indexes = GetOutput(context, node, 1);
std::vector<T> output_values;
I* indexes = GetTensorData<I>(output_indexes);
const T* data = GetTensorData<T>(input);
const int num_elements = NumElements(input);
for (int i = 0; i < num_elements; ++i) {
const auto element_it = unique_values.find(data[i]);
if (element_it != unique_values.end()) {
indexes[i] = element_it->second;
} else {
const int unique_index = unique_values.size();
unique_values[data[i]] = unique_index;
indexes[i] = unique_index;
output_values.push_back(data[i]);
}
}
// Allocate output tensor.
TfLiteTensor* unique_output = GetOutput(context, node, 0);
std::unique_ptr<TfLiteIntArray, void (*)(TfLiteIntArray*)> shape(
TfLiteIntArrayCreate(NumDimensions(input)), TfLiteIntArrayFree);
shape->data[0] = unique_values.size();
TF_LITE_ENSURE_STATUS(
context->ResizeTensor(context, unique_output, shape.release()));
// Set the values in the output tensor.
T* output_unique_values = GetTensorData<T>(unique_output);
for (int i = 0; i < output_values.size(); ++i) {
output_unique_values[i] = output_values[i];
}
return kTfLiteOk;
} | Base | 1 |
AP4_VisualSampleEntry::ReadFields(AP4_ByteStream& stream)
{
// sample entry
AP4_Result result = AP4_SampleEntry::ReadFields(stream);
if (result < 0) return result;
// read fields from this class
stream.ReadUI16(m_Predefined1);
stream.ReadUI16(m_Reserved2);
stream.Read(m_Predefined2, sizeof(m_Predefined2));
stream.ReadUI16(m_Width);
stream.ReadUI16(m_Height);
stream.ReadUI32(m_HorizResolution);
stream.ReadUI32(m_VertResolution);
stream.ReadUI32(m_Reserved3);
stream.ReadUI16(m_FrameCount);
char compressor_name[33];
compressor_name[32] = 0;
stream.Read(compressor_name, 32);
int name_length = compressor_name[0];
if (name_length < 32) {
compressor_name[name_length+1] = 0; // force null termination
m_CompressorName = &compressor_name[1];
}
stream.ReadUI16(m_Depth);
stream.ReadUI16(m_Predefined3);
return AP4_SUCCESS;
} | Base | 1 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteLocalResponseNormParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
if (output->type == kTfLiteFloat32) {
#define TF_LITE_LOCAL_RESPONSE_NORM(type) \
tflite::LocalResponseNormalizationParams op_params; \
op_params.range = params->radius; \
op_params.bias = params->bias; \
op_params.alpha = params->alpha; \
op_params.beta = params->beta; \
type::LocalResponseNormalization( \
op_params, GetTensorShape(input), GetTensorData<float>(input), \
GetTensorShape(output), GetTensorData<float>(output))
if (kernel_type == kReference) {
TF_LITE_LOCAL_RESPONSE_NORM(reference_ops);
}
if (kernel_type == kGenericOptimized) {
TF_LITE_LOCAL_RESPONSE_NORM(optimized_ops);
}
#undef TF_LITE_LOCAL_RESPONSE_NORM
} else {
context->ReportError(context, "Output type is %d, requires float.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
MONGO_EXPORT int bson_buffer_size( const bson *b ) {
return (b->cur - b->data + 1);
} | Base | 1 |
Pl_ASCII85Decoder::flush()
{
if (this->pos == 0)
{
QTC::TC("libtests", "Pl_ASCII85Decoder no-op flush");
return;
}
unsigned long lval = 0;
for (int i = 0; i < 5; ++i)
{
lval *= 85;
lval += (this->inbuf[i] - 33U);
}
unsigned char outbuf[4];
memset(outbuf, 0, 4);
for (int i = 3; i >= 0; --i)
{
outbuf[i] = lval & 0xff;
lval >>= 8;
}
QTC::TC("libtests", "Pl_ASCII85Decoder partial flush",
(this->pos == 5) ? 0 : 1);
getNext()->write(outbuf, this->pos - 1);
this->pos = 0;
memset(this->inbuf, 117, 5);
} | Base | 1 |
Pong(const std::string& cookie, const std::string& server = "")
: ClientProtocol::Message("PONG", ServerInstance->Config->GetServerName())
{
PushParamRef(ServerInstance->Config->GetServerName());
if (!server.empty())
PushParamRef(server);
PushParamRef(cookie);
} | Class | 2 |
inline void StringData::setSize(int len) {
assertx(!isImmutable() && !hasMultipleRefs());
assertx(len >= 0 && len <= capacity());
mutableData()[len] = 0;
m_lenAndHash = len;
assertx(m_hash == 0);
assertx(checkSane());
} | Base | 1 |
TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,
TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
// Make sure that the input is in uint8_t with at least 1 data entry.
const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);
if (input->type != kTfLiteUInt8) return kTfLiteError;
if (NumElements(input->dims) == 0) return kTfLiteError;
// Allocate a temporary buffer with the same size of input for sorting.
TF_LITE_ENSURE_STATUS(context->RequestScratchBufferInArena(
context, sizeof(uint8_t) * NumElements(input->dims),
&data->sorting_buffer));
// We can interleave scratch / persistent buffer allocation.
data->invoke_count = reinterpret_cast<int*>(
context->AllocatePersistentBuffer(context, sizeof(int)));
*data->invoke_count = 0;
return kTfLiteOk;
} | Base | 1 |
TfLiteStatus LessEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
bool requires_broadcast = !HaveSameShapes(input1, input2);
switch (input1->type) {
case kTfLiteFloat32:
Comparison<float, reference_ops::LessFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt32:
Comparison<int32_t, reference_ops::LessFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteInt64:
Comparison<int64_t, reference_ops::LessFn>(input1, input2, output,
requires_broadcast);
break;
case kTfLiteUInt8:
ComparisonQuantized<uint8_t, reference_ops::LessFn>(
input1, input2, output, requires_broadcast);
break;
case kTfLiteInt8:
ComparisonQuantized<int8_t, reference_ops::LessFn>(input1, input2, output,
requires_broadcast);
break;
default:
context->ReportError(context,
"Does not support type %d, requires float|int|uint8",
input1->type);
return kTfLiteError;
}
return kTfLiteOk;
} | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.