code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
int HttpFileImpl::save(const std::string &path) const
{
assert(!path.empty());
if (fileName_.empty())
return -1;
filesystem::path fsPath(utils::toNativePath(path));
if (!fsPath.is_absolute() &&
(!fsPath.has_parent_path() ||
(fsPath.begin()->string() != "." && fsPath.begin()->string() != "..")))
{
filesystem::path fsUploadPath(utils::toNativePath(
HttpAppFrameworkImpl::instance().getUploadPath()));
fsPath = fsUploadPath / fsPath;
}
filesystem::path fsFileName(utils::toNativePath(fileName_));
if (!filesystem::exists(fsPath))
{
LOG_TRACE << "create path:" << fsPath;
drogon::error_code err;
filesystem::create_directories(fsPath, err);
if (err)
{
LOG_SYSERR;
return -1;
}
}
return saveTo(fsPath / fsFileName);
} | CWE-552 | 69 |
static String HHVM_FUNCTION(bcsub, 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);
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
bc_sub(first, second, &result, scale);
if (result->n_scale > scale) {
result->n_scale = scale;
}
String ret(bc_num2str(result), AttachString);
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&result);
return ret;
} | CWE-190 | 19 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data);
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
const TfLiteTensor* size = GetInput(context, node, kSizeTensor);
if (IsDynamicTensor(output)) {
TF_LITE_ENSURE_OK(context,
ResizeOutputTensor(context, input, size, output));
}
if (output->type == kTfLiteFloat32) {
#define TF_LITE_RESIZE_BILINEAR(type, datatype) \
tflite::ResizeBilinearParams op_params; \
op_params.align_corners = params->align_corners; \
op_params.half_pixel_centers = params->half_pixel_centers; \
type::ResizeBilinear(op_params, GetTensorShape(input), \
GetTensorData<datatype>(input), GetTensorShape(size), \
GetTensorData<int32>(size), GetTensorShape(output), \
GetTensorData<datatype>(output))
if (kernel_type == kReference) {
TF_LITE_RESIZE_BILINEAR(reference_ops, float);
}
if (kernel_type == kGenericOptimized || kernel_type == kNeonOptimized) {
TF_LITE_RESIZE_BILINEAR(optimized_ops, float);
}
} else if (output->type == kTfLiteUInt8) {
if (kernel_type == kReference) {
TF_LITE_RESIZE_BILINEAR(reference_ops, uint8_t);
}
if (kernel_type == kGenericOptimized || kernel_type == kNeonOptimized) {
TF_LITE_RESIZE_BILINEAR(optimized_ops, uint8_t);
}
} else if (output->type == kTfLiteInt8) {
TF_LITE_RESIZE_BILINEAR(reference_ops, int8_t);
#undef TF_LITE_RESIZE_BILINEAR
} else {
context->ReportError(context, "Output type is %d, requires float.",
output->type);
return kTfLiteError;
}
return kTfLiteOk;
} | CWE-125 | 47 |
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());
} | CWE-125 | 47 |
static bool MR_primality_test(UnsignedBigInteger n, const Vector<UnsignedBigInteger, 256>& tests)
{
// Written using Wikipedia:
// https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Miller%E2%80%93Rabin_test
ASSERT(!(n < 4));
auto predecessor = n.minus({ 1 });
auto d = predecessor;
size_t r = 0;
{
auto div_result = d.divided_by(2);
while (div_result.remainder == 0) {
d = div_result.quotient;
div_result = d.divided_by(2);
++r;
}
}
if (r == 0) {
// n - 1 is odd, so n was even. But there is only one even prime:
return n == 2;
}
for (auto a : tests) {
// Technically: ASSERT(2 <= a && a <= n - 2)
ASSERT(a < n);
auto x = ModularPower(a, d, n);
if (x == 1 || x == predecessor)
continue;
bool skip_this_witness = false;
// r − 1 iterations.
for (size_t i = 0; i < r - 1; ++i) {
x = ModularPower(x, 2, n);
if (x == predecessor) {
skip_this_witness = true;
break;
}
}
if (skip_this_witness)
continue;
return false; // "composite"
}
return true; // "probably prime"
} | CWE-120 | 44 |
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;
} | CWE-125 | 47 |
inline int StringData::size() const { return m_len; } | CWE-190 | 19 |
const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,
const TfLiteNode* node, int index) {
const bool use_tensor = index < node->inputs->size &&
node->inputs->data[index] != kTfLiteOptionalTensor;
if (use_tensor) {
return GetMutableInput(context, node, index);
}
return nullptr;
} | CWE-787 | 24 |
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;
} | CWE-787 | 24 |
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);
} | CWE-22 | 2 |
TfLiteStatus LeakyReluEval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
const auto* params =
reinterpret_cast<TfLiteLeakyReluParams*>(node->builtin_data);
const LeakyReluOpData* data =
reinterpret_cast<LeakyReluOpData*>(node->user_data);
LeakyReluParams op_params;
switch (input->type) {
case kTfLiteFloat32: {
op_params.alpha = params->alpha;
optimized_ops::LeakyRelu(
op_params, GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
return kTfLiteOk;
} break;
case kTfLiteUInt8: {
QuantizeLeakyRelu<uint8_t>(input, output, data);
return kTfLiteOk;
} break;
case kTfLiteInt8: {
QuantizeLeakyRelu<int8_t>(input, output, data);
return kTfLiteOk;
} break;
case kTfLiteInt16: {
QuantizeLeakyRelu<int16_t>(input, output, data);
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context,
"Only float32, int8, int16 and uint8 is supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | CWE-125 | 47 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
// Reinterprete the opaque data provided by user.
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);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
const TfLiteType type = input1->type;
switch (type) {
case kTfLiteFloat32:
case kTfLiteInt32:
break;
default:
context->ReportError(context, "Type '%s' is not supported by floor_div.",
TfLiteTypeGetName(type));
return kTfLiteError;
}
output->type = type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | CWE-125 | 47 |
void pcre_dump_cache(const std::string& filename) {
s_pcreCache.dump(filename);
} | CWE-22 | 2 |
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;
} | CWE-843 | 43 |
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;
} | CWE-125 | 47 |
int overrun(int itemSize, int nItems) {
int len = ptr - start + itemSize * nItems;
if (len < (end - start) * 2)
len = (end - start) * 2;
U8* newStart = new U8[len];
memcpy(newStart, start, ptr - start);
ptr = newStart + (ptr - start);
delete [] start;
start = newStart;
end = newStart + len;
return nItems;
} | CWE-787 | 24 |
int TLSOutStream::length()
{
return offset + ptr - start;
} | CWE-787 | 24 |
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
} | CWE-908 | 48 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
output->type = input->type;
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_size);
} | CWE-125 | 47 |
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;
} | CWE-125 | 47 |
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;
}
| CWE-59 | 36 |
Network::FilterStatus Context::onDownstreamData(int data_length, bool end_of_stream) {
if (!wasm_->onDownstreamData_) {
return Network::FilterStatus::Continue;
}
auto result = wasm_->onDownstreamData_(this, id_, static_cast<uint32_t>(data_length),
static_cast<uint32_t>(end_of_stream));
// TODO(PiotrSikora): pull Proxy-WASM's FilterStatus values.
return result.u64_ == 0 ? Network::FilterStatus::Continue : Network::FilterStatus::StopIteration;
} | CWE-476 | 46 |
otError Commissioner::GeneratePskc(const char * aPassPhrase,
const char * aNetworkName,
const Mac::ExtendedPanId &aExtPanId,
Pskc & aPskc)
{
otError error = OT_ERROR_NONE;
const char *saltPrefix = "Thread";
uint8_t salt[OT_PBKDF2_SALT_MAX_LEN];
uint16_t saltLen = 0;
VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) &&
(strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) &&
(strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE),
error = OT_ERROR_INVALID_ARGS);
memset(salt, 0, sizeof(salt));
memcpy(salt, saltPrefix, strlen(saltPrefix));
saltLen += static_cast<uint16_t>(strlen(saltPrefix));
memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId));
saltLen += OT_EXT_PAN_ID_SIZE;
memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName));
saltLen += static_cast<uint16_t>(strlen(aNetworkName));
otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), static_cast<uint16_t>(strlen(aPassPhrase)),
reinterpret_cast<const uint8_t *>(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8);
exit:
return error;
} | CWE-787 | 24 |
static INLINE UINT16 ntlm_av_pair_get_id(const NTLM_AV_PAIR* pAvPair)
{
UINT16 AvId;
Data_Read_UINT16(&pAvPair->AvId, AvId);
return AvId;
} | CWE-125 | 47 |
int DummyOutStream::length()
{
flush();
return offset;
} | CWE-787 | 24 |
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 kTfLiteFloat32: {
return EvalImpl<float>(context, data->requires_broadcast, input1, input2,
output);
}
default: {
context->ReportError(context, "Type '%s' is not supported by floor_div.",
TfLiteTypeGetName(input1->type));
return kTfLiteError;
}
}
} | CWE-787 | 24 |
MONGO_EXPORT int bson_append_regex( bson *b, const char *name, const char *pattern, const char *opts ) {
const int plen = strlen( pattern )+1;
const int olen = strlen( opts )+1;
if ( bson_append_estart( b, BSON_REGEX, name, plen + olen ) == BSON_ERROR )
return BSON_ERROR;
if ( bson_check_string( b, pattern, plen - 1 ) == BSON_ERROR )
return BSON_ERROR;
bson_append( b , pattern , plen );
bson_append( b , opts , olen );
return BSON_OK;
} | CWE-190 | 19 |
virtual ~CxFile() { };
| CWE-770 | 37 |
TfLiteStatus EvalHashtableImport(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
const int resource_id = input_resource_id_tensor->data.i32[0];
const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
const TfLiteTensor* value_tensor = GetInput(context, node, kValueTensor);
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, value_tensor));
// The hashtable resource will only be initialized once, attempting to
// initialize it multiple times will be a no-op.
auto result = lookup->Import(context, key_tensor, value_tensor);
return result;
} | CWE-787 | 24 |
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;
} | CWE-788 | 87 |
unsigned int GetUVarBE(int nPos, int nSize, bool *pbSuccess)
{
//*pbSuccess = true;
if ( nPos < 0 || nPos + nSize > m_nLen )
{
*pbSuccess = false;
return 0;
}
unsigned int nRes = 0;
for ( int nIndex = 0; nIndex < nSize; ++nIndex )
nRes = (nRes << 8) + m_sFile[nPos + nIndex];
return nRes;
} | CWE-787 | 24 |
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;
} | CWE-125 | 47 |
void PrivateThreadPoolDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase* input,
DatasetBase** output) {
int64_t num_threads = 0;
OP_REQUIRES_OK(
ctx, ParseScalarArgument<int64_t>(ctx, "num_threads", &num_threads));
OP_REQUIRES(ctx, num_threads >= 0,
errors::InvalidArgument("`num_threads` must be >= 0"));
*output = new Dataset(ctx, input, num_threads);
} | CWE-770 | 37 |
inline int StringData::size() const { return m_len; } | CWE-787 | 24 |
TEST(ImmutableConstantOpTest, FromFile) {
const TensorShape kFileTensorShape({1000, 1});
Env* env = Env::Default();
auto root = Scope::NewRootScope().ExitOnError();
string two_file, three_file;
TF_ASSERT_OK(CreateTempFile(env, 2.0f, 1000, &two_file));
TF_ASSERT_OK(CreateTempFile(env, 3.0f, 1000, &three_file));
auto node1 = ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, two_file);
auto node2 =
ops::ImmutableConst(root, DT_FLOAT, kFileTensorShape, three_file);
auto result = ops::MatMul(root, node1, node2, ops::MatMul::TransposeB(true));
GraphDef graph_def;
TF_ASSERT_OK(root.ToGraphDef(&graph_def));
SessionOptions session_options;
session_options.config.mutable_graph_options()
->mutable_optimizer_options()
->set_opt_level(OptimizerOptions::L0);
std::unique_ptr<Session> session(NewSession(session_options));
ASSERT_TRUE(session != nullptr) << "Failed to create session";
TF_ASSERT_OK(session->Create(graph_def)) << "Can't create test graph";
std::vector<Tensor> outputs;
TF_ASSERT_OK(session->Run({}, {result.node()->name() + ":0"}, {}, &outputs));
ASSERT_EQ(outputs.size(), 1);
EXPECT_EQ(outputs.front().flat<float>()(0), 2.0f * 3.0f);
EXPECT_EQ(outputs.front().flat<float>()(1), 2.0f * 3.0f);
EXPECT_EQ(outputs.front().flat<float>()(2), 2.0f * 3.0f);
} | CWE-125 | 47 |
TEST_F(EncryptedRecordTest, TestAllPaddingHandshake) {
addToQueue("17030100050123456789");
EXPECT_CALL(*readAead_, _decrypt(_, _, 0))
.WillOnce(Invoke([](std::unique_ptr<IOBuf>& buf, const IOBuf*, uint64_t) {
expectSame(buf, "0123456789");
return getBuf("16000000");
}));
EXPECT_NO_THROW(read_.read(queue_));
} | CWE-770 | 37 |
TEST_F(TestSPIFFEValidator, TestGetTrustBundleStore) {
initialize();
// No SAN
auto cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/extensions_cert.pem"));
EXPECT_FALSE(validator().getTrustBundleStore(cert.get()));
// Non-SPIFFE SAN
cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/non_spiffe_san_cert.pem"));
EXPECT_FALSE(validator().getTrustBundleStore(cert.get()));
// SPIFFE SAN
cert = readCertFromFile(TestEnvironment::substitute(
"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/spiffe_san_cert.pem"));
// Trust bundle not provided.
EXPECT_FALSE(validator().getTrustBundleStore(cert.get()));
// Trust bundle provided.
validator().trustBundleStores().emplace("example.com", X509StorePtr(X509_STORE_new()));
EXPECT_TRUE(validator().getTrustBundleStore(cert.get()));
} | CWE-295 | 52 |
void pcre_dump_cache(const std::string& filename) {
s_pcreCache.dump(filename);
} | CWE-787 | 24 |
QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly)
{
QString mount_point = mountPoint(device);
if (!mount_point.isEmpty())
return mount_point;
mount_point = "%1/.%2/mount/%3";
const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()).arg(qApp->applicationName()).arg(name);
if (!QDir::current().mkpath(mount_point)) {
dCError("mkpath \"%s\" failed", qPrintable(mount_point));
return QString();
}
if (!mountDevice(device, mount_point, readonly)) {
dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point));
return QString();
}
return mount_point;
} | CWE-59 | 36 |
TfLiteStatus ReverseSequenceImpl(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* seq_lengths_tensor =
GetInput(context, node, kSeqLengthsTensor);
const TS* seq_lengths = GetTensorData<TS>(seq_lengths_tensor);
auto* params =
reinterpret_cast<TfLiteReverseSequenceParams*>(node->builtin_data);
int seq_dim = params->seq_dim;
int batch_dim = params->batch_dim;
TF_LITE_ENSURE(context, seq_dim >= 0);
TF_LITE_ENSURE(context, batch_dim >= 0);
TF_LITE_ENSURE(context, seq_dim != batch_dim);
TF_LITE_ENSURE(context, seq_dim < NumDimensions(input));
TF_LITE_ENSURE(context, batch_dim < NumDimensions(input));
TF_LITE_ENSURE_EQ(context, SizeOfDimension(seq_lengths_tensor, 0),
SizeOfDimension(input, batch_dim));
for (int i = 0; i < NumDimensions(seq_lengths_tensor); ++i) {
TF_LITE_ENSURE(context, seq_lengths[i] <= SizeOfDimension(input, seq_dim));
}
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
reference_ops::ReverseSequence<T, TS>(
seq_lengths, seq_dim, batch_dim, GetTensorShape(input),
GetTensorData<T>(input), GetTensorShape(output),
GetTensorData<T>(output));
return kTfLiteOk;
} | CWE-125 | 47 |
void CharToWideMap(const char *Src,wchar *Dest,size_t DestSize,bool &Success)
{
// Map inconvertible characters to private use Unicode area 0xE000.
// Mark such string by placing special non-character code before
// first inconvertible character.
Success=false;
bool MarkAdded=false;
uint SrcPos=0,DestPos=0;
while (DestPos<DestSize)
{
if (Src[SrcPos]==0)
{
Success=true;
break;
}
mbstate_t ps;
memset(&ps,0,sizeof(ps));
if (mbrtowc(Dest+DestPos,Src+SrcPos,MB_CUR_MAX,&ps)==-1)
{
// For security reasons we do not want to map low ASCII characters,
// so we do not have additional .. and path separator codes.
if (byte(Src[SrcPos])>=0x80)
{
if (!MarkAdded)
{
Dest[DestPos++]=MappedStringMark;
MarkAdded=true;
if (DestPos>=DestSize)
break;
}
Dest[DestPos++]=byte(Src[SrcPos++])+MapAreaStart;
}
else
break;
}
else
{
memset(&ps,0,sizeof(ps));
int Length=mbrlen(Src+SrcPos,MB_CUR_MAX,&ps);
SrcPos+=Max(Length,1);
DestPos++;
}
}
Dest[Min(DestPos,DestSize-1)]=0;
} | CWE-787 | 24 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const TfLiteTensor* axis_tensor = GetInput(context, node, kAxisTensor);
int axis = GetTensorData<int32_t>(axis_tensor)[0];
const int rank = NumDimensions(input);
if (axis < 0) {
axis += rank;
}
TF_LITE_ENSURE(context, axis >= 0 && axis < rank);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
reference_ops::Reverse<float>(
axis, GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
break;
}
case kTfLiteUInt8: {
reference_ops::Reverse<uint8_t>(
axis, GetTensorShape(input), GetTensorData<uint8_t>(input),
GetTensorShape(output), GetTensorData<uint8_t>(output));
break;
}
case kTfLiteInt16: {
reference_ops::Reverse<int16_t>(
axis, GetTensorShape(input), GetTensorData<int16_t>(input),
GetTensorShape(output), GetTensorData<int16_t>(output));
break;
}
case kTfLiteInt32: {
reference_ops::Reverse<int32_t>(
axis, GetTensorShape(input), GetTensorData<int32_t>(input),
GetTensorShape(output), GetTensorData<int32_t>(output));
break;
}
case kTfLiteInt64: {
reference_ops::Reverse<int64_t>(
axis, GetTensorShape(input), GetTensorData<int64_t>(input),
GetTensorShape(output), GetTensorData<int64_t>(output));
break;
}
case kTfLiteBool: {
reference_ops::Reverse<bool>(
axis, GetTensorShape(input), GetTensorData<bool>(input),
GetTensorShape(output), GetTensorData<bool>(output));
break;
}
default: {
context->ReportError(context, "Type '%s' is not supported by reverse.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | CWE-125 | 47 |
Pl_AES_PDF::flush(bool strip_padding)
{
assert(this->offset == this->buf_size);
if (first)
{
first = false;
bool return_after_init = false;
if (this->cbc_mode)
{
if (encrypt)
{
// Set cbc_block to the initialization vector, and if
// not zero, write it to the output stream.
initializeVector();
if (! (this->use_zero_iv || this->use_specified_iv))
{
getNext()->write(this->cbc_block, this->buf_size);
}
}
else if (this->use_zero_iv || this->use_specified_iv)
{
// Initialize vector with zeroes; zero vector was not
// written to the beginning of the input file.
initializeVector();
}
else
{
// Take the first block of input as the initialization
// vector. There's nothing to write at this time.
memcpy(this->cbc_block, this->inbuf, this->buf_size);
this->offset = 0;
return_after_init = true;
}
}
this->crypto->rijndael_init(
encrypt, this->key.get(), key_bytes,
this->cbc_mode, this->cbc_block);
if (return_after_init)
{
return;
}
}
if (this->encrypt)
{
this->crypto->rijndael_process(this->inbuf, this->outbuf);
}
else
{
this->crypto->rijndael_process(this->inbuf, this->outbuf);
}
unsigned int bytes = this->buf_size;
if (strip_padding)
{
unsigned char last = this->outbuf[this->buf_size - 1];
if (last <= this->buf_size)
{
bool strip = true;
for (unsigned int i = 1; i <= last; ++i)
{
if (this->outbuf[this->buf_size - i] != last)
{
strip = false;
break;
}
}
if (strip)
{
bytes -= last;
}
}
}
getNext()->write(this->outbuf, bytes);
this->offset = 0;
} | CWE-787 | 24 |
void MainWindow::on_actionUpgrade_triggered()
{
if (Settings.askUpgradeAutmatic()) {
QMessageBox dialog(QMessageBox::Question,
qApp->applicationName(),
tr("Do you want to automatically check for updates in the future?"),
QMessageBox::No |
QMessageBox::Yes,
this);
dialog.setWindowModality(QmlApplication::dialogModality());
dialog.setDefaultButton(QMessageBox::Yes);
dialog.setEscapeButton(QMessageBox::No);
dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "Automatic upgrade check dialog")));
Settings.setCheckUpgradeAutomatic(dialog.exec() == QMessageBox::Yes);
if (dialog.checkBox()->isChecked())
Settings.setAskUpgradeAutomatic(false);
}
showStatusMessage("Checking for upgrade...");
m_network.get(QNetworkRequest(QUrl("http://check.shotcut.org/version.json")));
} | CWE-295 | 52 |
Status CalculateOutputIndex(OpKernelContext* context, int dimension,
const vector<INDEX_TYPE>& parent_output_index,
INDEX_TYPE output_index_multiplier,
INDEX_TYPE output_size,
vector<INDEX_TYPE>* result) {
const RowPartitionTensor row_partition_tensor =
GetRowPartitionTensor(context, dimension);
auto partition_type = GetRowPartitionTypeByDimension(dimension);
switch (partition_type) {
case RowPartitionType::VALUE_ROWIDS:
CalculateOutputIndexValueRowID(
row_partition_tensor, parent_output_index, output_index_multiplier,
output_size, result);
return tensorflow::Status::OK();
case RowPartitionType::ROW_SPLITS:
CalculateOutputIndexRowSplit(row_partition_tensor, parent_output_index,
output_index_multiplier, output_size,
result);
return tensorflow::Status::OK();
default:
return errors::InvalidArgument(
"Unsupported partition type:",
RowPartitionTypeToString(partition_type));
}
} | CWE-131 | 88 |
bool RequestParser::OnHeadersEnd() {
bool matched = view_matcher_(request_->method(), request_->url().path(),
&stream_);
if (!matched) {
LOG_WARN("No view matches the request: %s %s", request_->method().c_str(),
request_->url().path().c_str());
}
return matched;
} | CWE-22 | 2 |
static int64_t HHVM_FUNCTION(bccomp, const String& left, const String& right,
int64_t scale /* = -1 */) {
if (scale < 0) scale = BCG(bc_precision);
bc_num first, second;
bc_init_num(&first);
bc_init_num(&second);
bc_str2num(&first, (char*)left.data(), scale);
bc_str2num(&second, (char*)right.data(), scale);
int64_t ret = bc_compare(first, second);
bc_free_num(&first);
bc_free_num(&second);
return ret;
} | CWE-190 | 19 |
void CalculateOutputIndexRowSplit(
OpKernelContext* context, const RowPartitionTensor& row_split,
const vector<INDEX_TYPE>& parent_output_index,
INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size,
vector<INDEX_TYPE>* result) {
INDEX_TYPE row_split_size = row_split.size();
if (row_split_size > 0) {
result->reserve(row_split(row_split_size - 1));
}
for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) {
INDEX_TYPE row_length = row_split(i + 1) - row_split(i);
INDEX_TYPE real_length = std::min(output_size, row_length);
INDEX_TYPE parent_output_index_current = parent_output_index[i];
if (parent_output_index_current == -1) {
real_length = 0;
}
for (INDEX_TYPE j = 0; j < real_length; ++j) {
result->push_back(parent_output_index_current);
parent_output_index_current += output_index_multiplier;
}
for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) {
result->push_back(-1);
}
}
if (row_split_size > 0) {
OP_REQUIRES(context, result->size() == row_split(row_split_size - 1),
errors::InvalidArgument("Invalid row split size."));
}
} | CWE-131 | 88 |
parse_memory(VALUE klass, VALUE data, VALUE encoding)
{
htmlParserCtxtPtr ctxt;
if (NIL_P(data)) {
rb_raise(rb_eArgError, "data cannot be nil");
}
if (!(int)RSTRING_LEN(data)) {
rb_raise(rb_eRuntimeError, "data cannot be empty");
}
ctxt = htmlCreateMemoryParserCtxt(StringValuePtr(data),
(int)RSTRING_LEN(data));
if (ctxt->sax) {
xmlFree(ctxt->sax);
ctxt->sax = NULL;
}
if (RTEST(encoding)) {
xmlCharEncodingHandlerPtr enc = xmlFindCharEncodingHandler(StringValueCStr(encoding));
if (enc != NULL) {
xmlSwitchToEncoding(ctxt, enc);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
rb_raise(rb_eRuntimeError, "Unsupported encoding %s",
StringValueCStr(encoding));
}
}
}
return Data_Wrap_Struct(klass, NULL, deallocate, ctxt);
} | CWE-241 | 68 |
static Variant HHVM_FUNCTION(bcpowmod, const String& left, const String& right,
const String& modulus, int64_t scale /* = -1 */) {
if (scale < 0) scale = BCG(bc_precision);
bc_num first, second, mod, result;
bc_init_num(&first);
bc_init_num(&second);
bc_init_num(&mod);
bc_init_num(&result);
SCOPE_EXIT {
bc_free_num(&first);
bc_free_num(&second);
bc_free_num(&mod);
bc_free_num(&result);
};
php_str2num(&first, (char*)left.data());
php_str2num(&second, (char*)right.data());
php_str2num(&mod, (char*)modulus.data());
if (bc_raisemod(first, second, mod, &result, scale) == -1) {
return false;
}
if (result->n_scale > scale) {
result->n_scale = scale;
}
String ret(bc_num2str(result), AttachString);
return ret;
} | CWE-190 | 19 |
TfLiteStatus PrepareHashtableFind(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);
const TfLiteTensor* default_value_tensor =
GetInput(context, node, kDefaultValueTensor);
const TfLiteTensor* key_tensor = GetInput(context, node, kKeyTensor);
TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, default_value_tensor->type, output_tensor->type);
TF_LITE_ENSURE(context, (key_tensor->type == kTfLiteInt64 &&
output_tensor->type == kTfLiteString) ||
(key_tensor->type == kTfLiteString &&
output_tensor->type == kTfLiteInt64));
return context->ResizeTensor(context, output_tensor,
TfLiteIntArrayCopy(key_tensor->dims));
} | CWE-125 | 47 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input_tensor = GetInput(context, node, 0);
const TfLiteTensor* padding_matrix = GetInput(context, node, 1);
TfLiteTensor* output_tensor = GetOutput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(padding_matrix), 2);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(padding_matrix, 0),
NumDimensions(input_tensor));
if (!IsConstantTensor(padding_matrix)) {
SetTensorToDynamic(output_tensor);
return kTfLiteOk;
}
// We have constant padding, so we can infer output size.
auto output_size = GetPaddedOutputShape(input_tensor, padding_matrix);
if (output_size == nullptr) {
return kTfLiteError;
}
return context->ResizeTensor(context, output_tensor, output_size.release());
} | CWE-787 | 24 |
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");
} | CWE-190 | 19 |
TfLiteRegistration GetPassthroughOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.init = [](TfLiteContext* context, const char*, size_t) -> void* {
auto* first_new_tensor = new int;
context->AddTensors(context, 2, first_new_tensor);
return first_new_tensor;
};
reg.free = [](TfLiteContext* context, void* buffer) {
delete static_cast<int*>(buffer);
};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
auto* first_new_tensor = static_cast<int*>(node->user_data);
const TfLiteTensor* tensor0 = GetInput(context, node, 0);
TfLiteTensor* tensor1 = GetOutput(context, node, 0);
TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, tensor1, newSize));
TfLiteIntArrayFree(node->temporaries);
node->temporaries = TfLiteIntArrayCreate(2);
for (int i = 0; i < 2; ++i) {
node->temporaries->data[i] = *(first_new_tensor) + i;
}
auto setup_temporary = [&](int id) {
TfLiteTensor* tmp = &context->tensors[id];
tmp->type = kTfLiteFloat32;
tmp->allocation_type = kTfLiteArenaRw;
return context->ResizeTensor(context, tmp,
TfLiteIntArrayCopy(tensor0->dims));
};
TF_LITE_ENSURE_STATUS(setup_temporary(node->temporaries->data[0]));
TF_LITE_ENSURE_STATUS(setup_temporary(node->temporaries->data[1]));
return kTfLiteOk;
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* a0 = GetInput(context, node, 0);
auto populate = [&](int id) {
TfLiteTensor* t = &context->tensors[id];
int num = a0->dims->data[0];
for (int i = 0; i < num; i++) {
t->data.f[i] = a0->data.f[i];
}
};
populate(node->outputs->data[0]);
populate(node->temporaries->data[0]);
populate(node->temporaries->data[1]);
return kTfLiteOk;
};
return reg;
} | CWE-125 | 47 |
TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = tflite::GetInput(context, node, 0);
const int32_t* input_data = input->data.i32;
const TfLiteTensor* weight = tflite::GetInput(context, node, 1);
const uint8_t* weight_data = weight->data.uint8;
TfLiteTensor* output = GetOutput(context, node, 0);
int32_t* output_data = output->data.i32;
output_data[0] =
0; // Catch output tensor sharing memory with an input tensor
output_data[0] = input_data[0] + weight_data[0];
return kTfLiteOk;
} | CWE-787 | 24 |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAnnotation *annotation = NULL;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | CWE-805 | 63 |
int64_t OpLevelCostEstimator::CalculateOutputSize(const OpInfo& op_info,
bool* found_unknown_shapes) {
int64_t total_output_size = 0;
// Use float as default for calculations.
for (const auto& output : op_info.outputs()) {
DataType dt = output.dtype();
const auto& original_output_shape = output.shape();
int64_t output_size = DataTypeSize(BaseType(dt));
int num_dims = std::max(1, original_output_shape.dim_size());
auto output_shape = MaybeGetMinimumShape(original_output_shape, num_dims,
found_unknown_shapes);
for (const auto& dim : output_shape.dim()) {
output_size *= dim.size();
}
total_output_size += output_size;
VLOG(1) << "Output Size: " << output_size
<< " Total Output Size:" << total_output_size;
}
return total_output_size;
} | CWE-190 | 19 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
auto* params =
reinterpret_cast<TfLiteDepthToSpaceParams*>(node->builtin_data);
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);
TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);
auto data_type = output->type;
TF_LITE_ENSURE(context,
data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 ||
data_type == kTfLiteInt8 || data_type == kTfLiteInt32 ||
data_type == kTfLiteInt64);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
const int block_size = params->block_size;
const int input_height = input->dims->data[1];
const int input_width = input->dims->data[2];
const int input_channels = input->dims->data[3];
int output_height = input_height * block_size;
int output_width = input_width * block_size;
int output_channels = input_channels / block_size / block_size;
TF_LITE_ENSURE_EQ(context, input_height, output_height / block_size);
TF_LITE_ENSURE_EQ(context, input_width, output_width / block_size);
TF_LITE_ENSURE_EQ(context, input_channels,
output_channels * block_size * block_size);
TfLiteIntArray* output_size = TfLiteIntArrayCreate(4);
output_size->data[0] = input->dims->data[0];
output_size->data[1] = output_height;
output_size->data[2] = output_width;
output_size->data[3] = output_channels;
return context->ResizeTensor(context, output, output_size);
} | CWE-125 | 47 |
TypedValue HHVM_FUNCTION(substr_compare,
const String& main_str,
const String& str,
int offset,
int length /* = INT_MAX */,
bool case_insensitivity /* = false */) {
int s1_len = main_str.size();
int s2_len = str.size();
if (length <= 0) {
raise_warning("The length must be greater than zero");
return make_tv<KindOfBoolean>(false);
}
if (offset < 0) {
offset = s1_len + offset;
if (offset < 0) offset = 0;
}
if (offset >= s1_len) {
raise_warning("The start position cannot exceed initial string length");
return make_tv<KindOfBoolean>(false);
}
int cmp_len = s1_len - offset;
if (cmp_len < s2_len) cmp_len = s2_len;
if (cmp_len > length) cmp_len = length;
const char *s1 = main_str.data();
if (case_insensitivity) {
return tvReturn(bstrcasecmp(s1 + offset, cmp_len, str.data(), cmp_len));
}
return tvReturn(string_ncmp(s1 + offset, str.data(), cmp_len));
} | CWE-125 | 47 |
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;
} | CWE-125 | 47 |
TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context,
TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
*data->invoke_count += 1;
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
const uint8_t* input_data = GetTensorData<uint8_t>(input);
int size = NumElements(input->dims);
uint8_t* sorting_buffer = reinterpret_cast<uint8_t*>(
context->GetScratchBuffer(context, data->sorting_buffer));
// Copy inputs data to the sorting buffer. We don't want to mutate the input
// tensor as it might be used by a another node.
for (int i = 0; i < size; i++) {
sorting_buffer[i] = input_data[i];
}
// In place insertion sort on `sorting_buffer`.
for (int i = 1; i < size; i++) {
for (int j = i; j > 0 && sorting_buffer[j] < sorting_buffer[j - 1]; j--) {
std::swap(sorting_buffer[j], sorting_buffer[j - 1]);
}
}
TfLiteTensor* median = GetOutput(context, node, kMedianTensor);
uint8_t* median_data = GetTensorData<uint8_t>(median);
TfLiteTensor* invoke_count = GetOutput(context, node, kInvokeCount);
int32_t* invoke_count_data = GetTensorData<int32_t>(invoke_count);
median_data[0] = sorting_buffer[size / 2];
invoke_count_data[0] = *data->invoke_count;
return kTfLiteOk;
} | CWE-787 | 24 |
void gen_SEK() {
vector<char> errMsg(1024, 0);
int err_status = 0;
vector <uint8_t> encrypted_SEK(1024, 0);
uint32_t enc_len = 0;
SAFE_CHAR_BUF(SEK, 65);
spdlog::info("Generating backup key. Will be stored in backup_key.txt ... ");
sgx_status_t status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
if (strnlen(SEK, 33) != 32) {
throw SGXException(-1, "strnlen(SEK,33) != 32");
}
vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_SEK.data(), enc_len, hexEncrKey.data(), 2 * enc_len + 1);
spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data());
ofstream sek_file(BACKUP_PATH);
sek_file.clear();
sek_file << SEK;
cout << "ATTENTION! YOUR BACKUP KEY HAS BEEN WRITTEN INTO sgx_data/backup_key.txt \n" <<
"PLEASE COPY IT TO THE SAFE PLACE AND THEN DELETE THE FILE MANUALLY BY RUNNING THE FOLLOWING COMMAND:\n" <<
"apt-get install secure-delete && srm -vz sgx_data/backup_key.txt" << endl;
if (!autoconfirm) {
string confirm_str = "I confirm";
string buffer;
do {
cout << " DO YOU CONFIRM THAT YOU COPIED THE KEY? (if you confirm type - I confirm)"
<< endl;
getline(cin, buffer);
} while (case_insensitive_match(confirm_str, buffer));
}
LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data());
create_test_key();
validate_SEK();
shared_ptr <string> encrypted_SEK_ptr = LevelDB::getLevelDb()->readString("SEK");
setSEK(encrypted_SEK_ptr);
validate_SEK();
} | CWE-787 | 24 |
def test_put
uri = URI('http://localhost:6470/makeme')
req = Net::HTTP::Put.new(uri)
# Set the headers the way we want them.
req['Accept-Encoding'] = '*'
req['Accept'] = 'application/json'
req['User-Agent'] = 'Ruby'
req.body = 'hello'
res = Net::HTTP.start(uri.hostname, uri.port) { |h|
h.request(req)
}
assert_equal(Net::HTTPCreated, res.class)
assert_equal('hello', res.body)
end | CWE-444 | 41 |
it "handles Symbol keys with underscore" do
cl = subject.build_command_line("true", :abc_def => "ghi")
expect(cl).to eq "true --abc-def ghi"
end | CWE-78 | 6 |
def read_lines(path, selector)
if selector
IO.foreach(path).select.with_index(1, &selector)
else
URI.open(path, &:read)
end
end | CWE-78 | 6 |
def update_auth
Log.add_info(request, params.inspect)
return unless request.post?
auth = nil
if params[:check_auth_all] == '1'
auth = User::AUTH_ALL
else
auth_selected = params[:auth_selected]
unless auth_selected.nil? or auth_selected.empty?
auth = '|' + auth_selected.join('|') + '|'
end
if auth_selected.nil? or !auth_selected.include?(User::AUTH_USER)
user_admin_err = false
user_admins = User.where("auth like '%|#{User::AUTH_USER}|%' or auth='#{User::AUTH_ALL}'").to_a
if user_admins.nil? or user_admins.empty?
user_admin_err = true
elsif user_admins.length == 1
if user_admins.first.id.to_s == params[:id]
user_admin_err = true
end
end
if user_admin_err
render(:text => t('user.no_user_auth'))
return
end
end
end
begin
user = User.find(params[:id])
rescue => evar
Log.add_error(request, evar)
end
if user.nil?
render(:text => t('msg.already_deleted', :name => User.model_name.human))
else
user.update_attribute(:auth, auth)
if user.id == @login_user.id
@login_user = user
end
render(:text => '')
end
end | CWE-89 | 0 |
def query
Log.add_info(request, '') # Not to show passwords.
unless @login_user.admin?(User::AUTH_ZEPTAIR)
render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
return
end
target_user = nil
user_id = params[:user_id]
zeptair_id = params[:zeptair_id]
group_id = params[:group_id]
SqlHelper.validate_token([user_id, zeptair_id, group_id])
unless user_id.blank?
target_user = User.find(user_id)
end
unless zeptair_id.blank?
target_user = User.where("zeptair_id=#{zeptair_id}").first
end
if target_user.nil?
if group_id.blank?
sql = 'select distinct Item.* from items Item, attachments Attachment'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << ' order by Item.user_id ASC'
else
group_ids = [group_id]
if params[:recursive] == 'true'
group_ids += Group.get_childs(group_id, true, false)
end
groups_con = []
group_ids.each do |grp_id|
groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{grp_id}|")
end
sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
sql << ' order by Item.user_id ASC'
end
@post_items = Item.find_by_sql(sql)
else
@post_item = ZeptairPostHelper.get_item_for(target_user)
end
rescue => evar
Log.add_error(request, evar)
render(:text => 'ERROR:' + t('msg.system_error'))
end | CWE-89 | 0 |
it "returns the group permissions for everyone group too" do
category.set_permissions(everyone: :readonly)
category.save!
json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json
expect(json[:group_permissions]).to eq([
{ permission_type: CategoryGroup.permission_types[:readonly], group_name: 'everyone' },
])
end | CWE-276 | 45 |
def actions
if params[:media_action] != 'crop_url'
authorize! :manage, :media
end
params[:folder] = params[:folder].gsub("//", "/") if params[:folder].present?
case params[:media_action]
when "new_folder"
params[:folder] = slugify_folder(params[:folder])
render partial: "render_file_item", locals: {files: [cama_uploader.add_folder(params[:folder])]}
when "del_folder"
cama_uploader.delete_folder(params[:folder])
render inline: ""
when "del_file"
cama_uploader.delete_file(params[:folder].gsub("//", "/"))
render inline: ""
when 'crop_url'
unless params[:url].start_with?('data:')
params[:url] = (params[:url].start_with?('http') ? '' : current_site.the_url(locale: nil)) + params[:url]
end
r = cama_tmp_upload( params[:url], formats: params[:formats], name: params[:name])
unless r[:error].present?
params[:file_upload] = r[:file_path]
sett = {remove_source: true}
sett[:same_name] = true if params[:same_name].present?
sett[:name] = params[:name] if params[:name].present?
upload(sett)
else
render inline: r[:error]
end
end | CWE-918 | 16 |
def build_gem_lines(conservative_versioning)
@deps.map do |d|
name = d.name.dump
requirement = if conservative_versioning
", \"#{conservative_version(@definition.specs[d.name][0])}\""
else
", #{d.requirement.as_list.map(&:dump).join(", ")}"
end
if d.groups != Array(:default)
group = d.groups.size == 1 ? ", :group => #{d.groups.first.inspect}" : ", :groups => #{d.groups.inspect}"
end
source = ", :source => \"#{d.source}\"" unless d.source.nil?
git = ", :git => \"#{d.git}\"" unless d.git.nil?
branch = ", :branch => \"#{d.branch}\"" unless d.branch.nil?
%(gem #{name}#{requirement}#{group}#{source}#{git}#{branch})
end.join("\n") | CWE-88 | 3 |
it "downloads a file" do
expect(subject.download(uri).file.read).to eq file
end | CWE-918 | 16 |
def read_lines(filename, selector)
if selector
IO.foreach(filename).select.with_index(1, &selector)
else
URI.open(filename, &:read)
end
end | CWE-78 | 6 |
def RelaxNG string_or_io
RelaxNG.new(string_or_io)
end | CWE-611 | 13 |
def edit_page
# Saved contents of Login User
begin
@research = Research.where("user_id=#{@login_user.id}").first
rescue
end
if @research.nil?
@research = Research.new
else
# Already accepted?
if [email protected]? and @research.status != 0
render(:action => 'show_receipt')
return
end
end
# Specifying page
@page = '01'
unless params[:page].nil? or params[:page].empty?
@page = params[:page]
end
end | CWE-89 | 0 |
def empty
Log.add_info(request, params.inspect)
@folder_id = params[:id]
mail_account_id = params[:mail_account_id]
SqlHelper.validate_token([mail_account_id])
trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)
mail_folder = MailFolder.find(@folder_id)
emails = MailFolder.get_mails(mail_folder.id, @login_user) || []
if mail_folder.id == trash_folder.id \
or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
emails.each do |email|
email.destroy
end
flash[:notice] = t('msg.delete_success')
else
emails.each do |email|
email.update_attribute(:mail_folder_id, trash_folder.id)
end
flash[:notice] = t('msg.moved_to_trash')
end
get_mails
end | CWE-89 | 0 |
def self.get_for_group(group_id, incl_img_content=false)
SqlHelper.validate_token([group_id])
if group_id.nil?
office_map = nil
else
if incl_img_content
office_map = OfficeMap.where("group_id=#{group_id}").first
else
sql = 'select id, group_id, img_enabled, img_name, img_size, img_content_type, created_at, updated_at from office_maps'
sql << " where group_id=#{group_id}"
begin
office_map = OfficeMap.find_by_sql(sql).first
rescue
end
end
end
if office_map.nil?
office_map = OfficeMap.new
office_map.group_id = group_id.to_i unless group_id.nil?
office_map.img_enabled = false
end
return office_map
end | CWE-89 | 0 |
def destroy
Log.add_info(request, params.inspect)
begin
OfficialTitle.destroy(params[:id])
rescue => evar
Log.add_error(nil, evar)
end
@group_id = params[:group_id]
if @group_id.nil? or @group_id.empty?
@group_id = '0' # '0' for ROOT
end
render(:partial => 'groups/ajax_group_official_titles', :layout => false)
end | CWE-89 | 0 |
def self.get_for(mail_account_id, enabled=nil, trigger=nil)
return [] if mail_account_id.nil?
SqlHelper.validate_token([mail_account_id, trigger])
con = []
con << "(mail_account_id=#{mail_account_id})"
con << "(enabled=#{(enabled)?(1):(0)})" unless enabled.nil?
con << SqlHelper.get_sql_like([:triggers], "|#{trigger}|") unless trigger.nil?
return MailFilter.where(con.join(' and ')).order('(xorder is null) ASC, xorder ASC, id ASC').to_a
end | CWE-89 | 0 |
def get_mail_attachments
Log.add_info(request, params.inspect)
email_id = params[:id]
email = Email.find_by_id(email_id)
if email.nil? or email.user_id != @login_user.id
render(:text => '')
return
end
download_name = "mail_attachments#{email.id}.zip"
zip_file = email.zip_attachments(params[:enc])
if zip_file.nil?
send_data('', :type => 'application/octet-stream;', :disposition => 'attachment;filename="'+download_name+'"')
else
filepath = zip_file.path
send_file(filepath, :filename => download_name, :stream => true, :disposition => 'attachment')
end
end | CWE-89 | 0 |
def new
Log.add_info(request, params.inspect)
mail_account_id = params[:mail_account_id]
if mail_account_id.nil? or mail_account_id.empty?
account_xtype = params[:mail_account_xtype]
@mail_account = MailAccount.get_default_for(@login_user.id, account_xtype)
else
@mail_account = MailAccount.find(mail_account_id)
if @mail_account.user_id != @login_user.id
flash[:notice] = 'ERROR:' + t('msg.need_to_be_owner')
render(:partial => 'common/flash_notice', :layout => false)
return
end
end
if $thetis_config[:menu]['disp_user_list'] == '1'
unless params[:to_user_ids].blank?
@email = Email.new
to_addrs = []
@user_obj_cache ||= {}
params[:to_user_ids].each do |user_id|
user = User.find_with_cache(user_id, @user_obj_cache)
user_emails = user.get_emails_by_type(nil)
user_emails.each do |user_email|
disp = EmailsHelper.format_address_exp(user.get_name, user_email, false)
entry_val = "#{disp}" # "#{disp}#{Email::ADDR_ORDER_SEPARATOR}#{user.get_xorder(@group_id)}"
to_addrs << entry_val
end
end
@email.to_addresses = to_addrs.join(Email::ADDRESS_SEPARATOR)
end
end
render(:action => 'edit', :layout => (!request.xhr?))
end | CWE-89 | 0 |
def attachments_without_content
return [] if self.id.nil?
sql = 'select id, title, memo, name, size, content_type, comment_id, xorder, location from attachments'
sql << ' where comment_id=' + self.id.to_s
sql << ' order by xorder ASC'
begin
attachments = Attachment.find_by_sql(sql)
rescue => evar
Log.add_error(nil, evar)
end
attachments = [] if attachments.nil?
return attachments
end | CWE-89 | 0 |
def install_location filename, destination_dir # :nodoc:
raise Gem::Package::PathError.new(filename, destination_dir) if
filename.start_with? '/'
destination_dir = File.realpath destination_dir if
File.respond_to? :realpath
destination_dir = File.expand_path destination_dir
destination = File.join destination_dir, filename
destination = File.expand_path destination
raise Gem::Package::PathError.new(destination, destination_dir) unless
destination.start_with? destination_dir
destination.untaint
destination
end | CWE-22 | 2 |
def redirect_url
return "/" unless member_login_node
member_login_node.redirect_url || "/"
end | CWE-601 | 11 |
def self.validate_token(tokens, extra_chars=nil)
extra_chars ||= []
regexp = Regexp.new("^\s*[a-zA-Z0-9_.#{extra_chars.join()}]+\s*$")
[tokens].flatten.each do |token|
next if token.blank?
if token.to_s.match(regexp).nil?
raise("[ERROR] SqlHelper.validate_token failed: #{token}")
end
end
end | CWE-89 | 0 |
def team_organize
Log.add_info(request, params.inspect)
team_id = params[:team_id]
unless team_id.nil? or team_id.empty?
begin
@team = Team.find(team_id)
rescue
@team = nil
ensure
if @team.nil?
flash[:notice] = t('msg.already_deleted', :name => Team.model_name.human)
return
end
end
users = @team.get_users_a
end
team_members = params[:team_members]
created = false
modified = false
if team_members.nil? or team_members.empty?
unless team_id.nil? or team_id.empty?
# @team must not be nil.
@team.save if modified = @team.clear_users
end
else
if team_members != users
if team_id.nil? or team_id.empty?
item = Item.find(params[:id])
created = true
@team = Team.new
@team.name = item.title
@team.item_id = params[:id]
@team.status = Team::STATUS_STANDBY
else
@team.clear_users
end
@team.add_users team_members
@team.save
@team.remove_application team_members
modified = true
end
end
if created
@team.create_team_folder
end
@item = @team.item
if modified
flash[:notice] = t('msg.register_success')
end
render(:partial => 'ajax_team_info', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_team_info', :layout => false)
end | CWE-89 | 0 |
def check_owner
return if params[:id].nil? or params[:id].empty? or @login_user.nil?
begin
owner_id = Location.find(params[:id]).user_id
rescue
owner_id = -1
end
if !@login_user.admin?(User::AUTH_LOCATION) and owner_id != @login_user.id
Log.add_check(request, '[check_owner]'+request.to_s)
flash[:notice] = t('msg.need_to_be_owner')
redirect_to(:controller => 'desktop', :action => 'show')
end
end | CWE-89 | 0 |
it "should not display completed tasks" do
task_1 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Your first task", :bucket => "due_asap", :assigned_to => current_user.id)
task_2 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Completed task", :bucket => "due_asap", :completed_at => 1.days.ago, :completed_by => current_user.id, :assigned_to => current_user.id)
get :index
assigns[:my_tasks].should == [task_1]
end | CWE-89 | 0 |
def self.parse_csv_row(row, book, idxs, user)
imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)
SqlHelper.validate_token([imp_id])
unless imp_id.blank?
org_address = Address.find_by_id(imp_id)
end
if org_address.nil?
address = Address.new
else
address = org_address
end
address.id = imp_id
attr_names = [
:name,
:name_ruby,
:nickname,
:screenname,
:email1,
:email2,
:email3,
:postalcode,
:address,
:tel1_note,
:tel1,
:tel2_note,
:tel2,
:tel3_note,
:tel3,
:fax,
:url,
:organization,
:title,
:memo,
:xorder,
:groups,
:teams
]
attr_names.each_with_index do |attr_name, idx|
row_idx = idxs[idx+1]
break if row_idx.nil?
val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)
address.send(attr_name.to_s + '=', val)
end
if (address.groups == Address::EXP_IMP_FOR_ALL) \
or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)
address.groups = nil
address.teams = nil
address.owner_id = 0
elsif !address.groups.blank? or !address.teams.blank?
address.owner_id = 0
else
address.owner_id = user.id
end
return address
end | CWE-89 | 0 |
def self.get_tmpl_folder
tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first
if tmpl_folder.nil?
ary = self.setup_tmpl_folder
unless ary.nil? or ary.empty?
tmpl_folder = ary[0]
tmpl_system_folder = ary[1]
tmpl_workflows_folder = ary[2]
tmpl_local_folder = ary[3]
tmpl_q_folder = ary[4]
end
else
folders = Folder.where("parent_id=#{tmpl_folder.id}").to_a
unless folders.nil?
folders.each do |child|
case child.name
when TMPL_SYSTEM
tmpl_system_folder = child
when TMPL_WORKFLOWS
tmpl_workflows_folder = child
when TMPL_LOCAL
tmpl_local_folder = child
when TMPL_RESEARCH
tmpl_q_folder = child
end
end
end
end | CWE-89 | 0 |
def week
Log.add_info(request, params.inspect)
date_s = params[:date]
if date_s.nil? or date_s.empty?
@date = Date.today
else
@date = Date.parse(date_s)
end
params[:display] = 'week'
end | CWE-89 | 0 |
def send_password
Log.add_info(request, params.inspect)
mail_addr = params[:thetisBoxEdit]
SqlHelper.validate_token([mail_addr])
begin
users = User.where("email='#{mail_addr}'").to_a
rescue => evar
end
if users.nil? or users.empty?
Log.add_error(request, evar)
flash[:notice] = 'ERROR:' + t('email.address_not_found')
else
user_passwords_h = {}
users.each do |user|
newpass = UsersHelper.generate_password
user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))
user_passwords_h[user] = newpass
end
NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
flash[:notice] = t('email.sent')
end
render(:controller => 'login', :action => 'index')
end | CWE-89 | 0 |
def call(env)
return @app.call(env) unless env['PATH_INFO'].start_with? "#{@bus.base_route}message-bus/_diagnostics"
route = env['PATH_INFO'].split("#{@bus.base_route}message-bus/_diagnostics")[1]
if @bus.is_admin_lookup.nil? || [email protected]_admin_lookup.call(env)
return [403, {}, ['not allowed']]
end
return index unless route
if route == '/discover'
user_id = @bus.user_id_lookup.call(env)
@bus.publish('/_diagnostics/discover', user_id: user_id)
return [200, {}, ['ok']]
end
if route =~ /^\/hup\//
hostname, pid = route.split('/hup/')[1].split('/')
@bus.publish('/_diagnostics/hup', hostname: hostname, pid: pid.to_i)
return [200, {}, ['ok']]
end
asset = route.split('/assets/')[1]
if asset && !asset !~ /\//
content = asset_contents(asset)
return [200, { 'Content-Type' => 'application/javascript;charset=UTF-8' }, [content]]
end
[404, {}, ['not found']]
end | CWE-22 | 2 |
it "should find a user by first name and last name" do
@cur_user.stub(:pref).and_return(:activity_user => 'Billy Elliot')
controller.instance_variable_set(:@current_user, @cur_user)
User.should_receive(:where).with("(upper(first_name) LIKE upper('%Billy%') AND upper(last_name) LIKE upper('%Elliot%')) OR (upper(first_name) LIKE upper('%Elliot%') AND upper(last_name) LIKE upper('%Billy%'))").and_return([@user])
controller.send(:activity_user).should == 1
end | CWE-89 | 0 |
def ajax_delete_mails
Log.add_info(request, params.inspect)
folder_id = params[:id]
mail_account_id = params[:mail_account_id]
unless params[:check_mail].blank?
mail_folder = MailFolder.find(folder_id)
trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)
count = 0
params[:check_mail].each do |email_id, value|
next if value != '1'
email = Email.find_by_id(email_id)
next if email.nil? or (email.user_id != @login_user.id)
if trash_folder.nil? \
or folder_id == trash_folder.id.to_s \
or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
email.destroy
flash[:notice] ||= t('msg.delete_success')
else
begin
email.update_attribute(:mail_folder_id, trash_folder.id)
flash[:notice] ||= t('msg.moved_to_trash')
rescue => evar
Log.add_error(request, evar)
email.destroy
flash[:notice] ||= t('msg.delete_success')
end
end
count += 1
end
end
get_mails
end | CWE-89 | 0 |
it "allows/disable marshalling" do
store = Redis::Store::Factory.create :marshalling => false
store.instance_variable_get(:@marshalling).must_equal(false)
store.instance_variable_get(:@options)[:raw].must_equal(true)
end | CWE-502 | 15 |
def self.get_tmpl_subfolder(name)
SqlHelper.validate_token([name])
tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first
unless tmpl_folder.nil?
con = "(parent_id=#{tmpl_folder.id}) and (name='#{name}')"
begin
child = Folder.where(con).first
rescue => evar
Log.add_error(nil, evar)
end
end
return [tmpl_folder, child]
end | CWE-89 | 0 |
def apply(operations)
operations.inject(self) do |builder, (name, argument)|
if argument == true || argument == nil
builder.send(name)
elsif argument.is_a?(Array)
builder.send(name, *argument)
elsif argument.is_a?(Hash)
builder.send(name, **argument)
else
builder.send(name, argument)
end
end
end | CWE-78 | 6 |
def check_owner
return if (params[:id].nil? or params[:id].empty? or @login_user.nil?)
mail_filter = MailFilter.find(params[:id])
if !@login_user.admin?(User::AUTH_MAIL) and mail_filter.mail_account.user_id != @login_user.id
Log.add_check(request, '[check_owner]'+request.to_s)
flash[:notice] = t('msg.need_to_be_owner')
redirect_to(:controller => 'desktop', :action => 'show')
end
end | CWE-89 | 0 |
def login
Log.add_info(request, '') # Not to show passwords.
user = User.authenticate(params[:user])
if user.nil?
flash[:notice] = '<span class=\'font_msg_bold\'>'+t('user.u_name')+'</span>'+t('msg.or')+'<span class=\'font_msg_bold\'>'+t('password.name')+'</span>'+t('msg.is_invalid')
if params[:fwd_controller].nil? or params[:fwd_controller].empty?
redirect_to(:controller => 'login', :action => 'index')
else
url_h = {:controller => 'login', :action => 'index', :fwd_controller => params[:fwd_controller], :fwd_action => params[:fwd_action]}
unless params[:fwd_params].nil?
params[:fwd_params].each do |key, val|
url_h["fwd_params[#{key}]"] = val
end
end
redirect_to(url_h)
end
else
@login_user = LoginHelper.on_login(user, session)
if params[:fwd_controller].nil? or params[:fwd_controller].empty?
prms = ApplicationHelper.get_fwd_params(params)
prms.delete('user')
prms[:controller] = 'desktop'
prms[:action] = 'show'
redirect_to(prms)
else
url_h = {:controller => params[:fwd_controller], :action => params[:fwd_action]}
url_h = url_h.update(params[:fwd_params]) unless params[:fwd_params].nil?
redirect_to(url_h)
end
end
end | CWE-89 | 0 |
def destroy_workflow
Log.add_info(request, params.inspect)
Item.find(params[:id]).destroy
@tmpl_folder, @tmpl_workflows_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_WORKFLOWS)
@group_id = params[:group_id]
if @group_id.nil? or @group_id.empty?
@group_id = '0' # '0' for ROOT
end
render(:partial => 'groups/ajax_group_workflows', :layout => false)
end | CWE-89 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.