question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
I would like to create a vector in which each element is the i+6th element of another vector.
For example, in a vector of length 120 I want to create another vector of length 20 in which each element is value i, i+6, i+12, i+18... of the initial vector, i.e. I want to extract every 6th element of the original.
| a <- 1:120
b <- a[seq(1, length(a), 6)]
| Vector | 5,237,557 | 162 |
I want to create a vector out of a row of a data frame. But I don't want to have to row and column names. I tried several things... but had no luck.
This is my data frame:
> df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3))
> df
a b c
1 1 2 2.6
2 2 6 8.2
3 4 2 7.5
4 2 1 3.0
I tried:
> newV <- as.vecto... | When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:
as.numeric(df[1,])
As @Roland suggests, unlist(df[1,]) will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,])) is another, slightly more explic... | Vector | 14,484,728 | 162 |
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a std::vector. I don't want to have... | There have been many answers here and just about all of them will get the job done.
However there is some misleading advice!
Here are the options:
vector<int> dataVec;
int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
unsigned dataArraySize = sizeof(dataArray) / sizeof(int);
// Method 1: Copy the array to the vect... | Vector | 259,297 | 159 |
I can not find within the documentation of Vec<T> how to retrieve a slice from a specified range.
Is there something like this in the standard library:
let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];
| The documentation for Vec covers this in the section titled "slicing".
You can create a slice of a Vec or array by indexing it with a Range (or RangeInclusive, RangeFrom, RangeTo, RangeToInclusive, or RangeFull), for example:
fn main() {
let a = vec![1, 2, 3, 4, 5];
// With a start and an end
println!("{:?... | Vector | 39,785,597 | 157 |
My question is simple: are std::vector elements guaranteed to be contiguous? In other words, can I use the pointer to the first element of a std::vector as a C-array?
If my memory serves me well, the C++ standard did not make such guarantee. However, the std::vector requirements were such that it was virtually imposs... | This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.
From n2798 (draft of C++0x):
23.2.6 Class template vector [vector]
1 A vector is a sequence container that supports random access iterators. In addition, it supports ... | Vector | 849,168 | 142 |
I'm coding in C++. If I have some function void foo(vector<int> test) and I call it in my program, will the vector be passed by value or reference? I'm unsure because I know vectors and arrays are similar and that a function like void bar(int test[]) would pass test in by reference (pointer?) instead of by value. My gu... | In C++, things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by referenc... | Vector | 26,647,152 | 141 |
What are the differences between an array and a vector in C++? An example of the differences might be included libraries, symbolism, abilities, etc.
Array
Arrays contain a specific number of elements of a particular type. So that the compiler can reserve the required amount of space when the program is compiled, you m... | arrays:
are a builtin language construct;
come almost unmodified from C89;
provide just a contiguous, indexable sequence of elements; no bells and whistles;
are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
their size must be a compile-time constant unles... | Vector | 15,079,057 | 140 |
The goal is to access the "nth" element of a vector of strings instead of the [] operator or the "at" method. From what I understand, iterators can be used to navigate through containers, but I've never used iterators before, and what I'm reading is confusing.
If anyone could give me some information on how to achieve ... | You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively.
using namespace std;
vector<string> myvector; // a vector of stings.
// push some strings in the vector.
myvector.push_back("a");
myvector.push_back("b");
myvec... | Vector | 2,395,275 | 137 |
vector<int> v;
v.push_back(1);
v.push_back(v[0]);
If the second push_back causes a reallocation, the reference to the first integer in the vector will no longer be valid. So this isn't safe?
vector<int> v;
v.push_back(1);
v.reserve(v.size() + 1);
v.push_back(v[0]);
This makes it safe?
| It looks like http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#526 addressed this problem (or something very similar to it) as a potential defect in the standard:
1) Parameters taken by const reference can be changed during execution
of the function
Examples:
Given std::vector v:
v.insert(v.begin(), v[2])... | Vector | 18,788,780 | 137 |
I have two vectors u and v. Is there a way of finding a quaternion representing the rotation from u to v?
| Quaternion q;
vector a = crossproduct(v1, v2);
q.xyz = a;
q.w = sqrt((v1.Length ^ 2) * (v2.Length ^ 2)) + dotproduct(v1, v2);
Don't forget to normalize q.
Richard is right about there not being a unique rotation, but the above should give the "shortest arc," which is probably what you need.
| Vector | 1,171,849 | 136 |
I'm trying to test whether all elements of a vector are equal to one another. The solutions I have come up with seem somewhat roundabout, both involving checking length().
x <- c(1, 2, 3, 4, 5, 6, 1) # FALSE
y <- rep(2, times = 7) # TRUE
With unique():
length(unique(x)) == 1
length(unique(y)) == 1
With rle():
... | Why not simply using the variance:
var(x) == 0
If all the elements of x are equal, you will get a variance of 0.
This works only for double and integers though.
Edit based on the comments below:
A more generic option would be to check for the length of unique elements in the vector which must be 1 in this case. This h... | Vector | 4,752,275 | 130 |
What is a good clean way to convert a std::vector<int> intVec to std::vector<double> doubleVec. Or, more generally, to convert two vectors of convertible types?
| Use std::vector's range constructor:
std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());
| Vector | 6,399,090 | 125 |
I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
s... | Since C++20, there are freestanding std::erase and std::erase_if functions that work on containers and simplify things considerably:
std::erase(myNumbers, number_in);
// or
std::erase_if(myNumbers, [&](int x) { return x == number_in; });
Prior to C++20, use the erase-remove idiom:
std::vector<int>& vec = myNumbers; //... | Vector | 347,441 | 124 |
I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: [1,2,3,4] and [6,7,8,9].
| Note: all of the other answers here will fail if the two vectors have either the same direction (ex, (1, 0, 0), (1, 0, 0)) or opposite directions (ex, (-1, 0, 0), (1, 0, 0)).
Here is a function which will correctly handle these cases:
import numpy as np
def unit_vector(vector):
""" Returns the unit vector of the v... | Vector | 2,827,393 | 124 |
I have a vector of IInventory*, and I am looping through the list using C++11 range for, to do stuff with each one.
After doing some stuff with one, I may want to remove it from the list and delete the object. I know I can call delete on the pointer any time to clean it up, but what is the proper way to remove it from ... | No, you can't. Range-based for is for when you need to access each element of a container once.
You should use the normal for loop or one of its cousins if you need to modify the container as you go along, access an element more than once, or otherwise iterate in a non-linear fashion through the container.
For example:... | Vector | 10,360,461 | 123 |
What is the difference between std::array and std::vector? When do you use one over other?
I have always used and considered std:vector as an C++ way of using C arrays, so what is the difference?
| std::array is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.
std::vector ... | Vector | 6,632,971 | 121 |
How can I list the distinct values in a vector where the values are replicative? I mean, similarly to the following SQL statement:
SELECT DISTINCT product_code
FROM data
| Do you mean unique:
R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4
| Vector | 7,755,240 | 121 |
What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state that a default constructed vector does not call heap memory allocation?
This way it would be possible to create an array with an arbitrary reserve using a single allocation, like std::vec... | The standard doesn't specify what the initial capacity of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345); so stick with it... | Vector | 12,271,017 | 120 |
Goal: from a list of vectors of equal length, create a matrix where each vector becomes a row.
Example:
> a <- list()
> for (i in 1:10) a[[i]] <- c(i,1:5)
> a
[[1]]
[1] 1 1 2 3 4 5
[[2]]
[1] 2 1 2 3 4 5
[[3]]
[1] 3 1 2 3 4 5
[[4]]
[1] 4 1 2 3 4 5
[[5]]
[1] 5 1 2 3 4 5
[[6]]
[1] 6 1 2 3 4 5
[[7]]
[1] 7 1 2 3 4 5
... | One option is to use do.call():
> do.call(rbind, a)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 ... | Vector | 1,329,940 | 119 |
I am looking for just the value of the B1(newx) linear model coefficient, not the name. I just want the 0.5 value. I do not want the name "newx".
newx <- c(0.5,1.5,2.5)
newy <- c(2,3,4)
out <- lm(newy ~ newx)
out looks like:
Call:
lm(formula = newy ~ newx)
Coefficients:
(Intercept) newx
1.5 ... | For a single element like this, use [[ rather than [. Compare:
coefficients(out)["newx"]
# newx
# 1
coefficients(out)[["newx"]]
# [1] 1
More generally, use unname():
unname(coefficients(out)[c("newx", "(Intercept)")])
# [1] 1.0 1.5
head(unname(mtcars))
# NA NA NA NA NA NA NA NA NA ... | Vector | 15,736,719 | 119 |
From wikipedia:
the cross product is a binary operation on two vectors in a three-dimensional Euclidean space that results in another vector which is perpendicular to the plane containing the two input vectors.
Given that the definition is only defined in three (or seven, one and zero) dimensions, how does one calcu... | Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus th... | Vector | 243,945 | 117 |
I am attempting to use vector drawables in my Android app. From http://developer.android.com/training/material/drawables.html (emphasis mine):
In Android 5.0 (API Level 21) and above, you can define vector drawables, which scale without losing definition.
Using this drawable:
<vector xmlns:android="http://schemas.an... | There is new info about this issue here:
https://code.google.com/p/android/issues/detail?id=202019
It looks like using
android:scaleType="fitXY" will make it scale correctly on Lollipop.
From a Google engineer:
Hi, Let me know if scaleType='fitXY' can be a workaround for you , in
order to get the image look sharp.... | Vector | 34,936,590 | 117 |
C++ has std::vector and Java has ArrayList, and many other languages have their own form of dynamically allocated array. When a dynamic array runs out of space, it gets reallocated into a larger area and the old values are copied into the new array. A question central to the performance of such an array is how fast the... | I remember reading many years ago why 1.5 is preferred over two, at least as applied to C++ (this probably doesn't apply to managed languages, where the runtime system can relocate objects at will).
The reasoning is this:
Say you start with a 16-byte allocation.
When you need more, you allocate 32 bytes, then free up ... | Vector | 1,100,311 | 115 |
I have a named character vector returned from xmlAttrs like this:
testVect <- structure(c("11.2.0.3.0", "12.89", "12.71"), .Names = c("db_version",
"elapsed_time", "cpu_time"))
I would like to convert it to a data frame that looks like this:
testDF <- data.frame("db_version"="11.2.0.3.0","elapsed_time"=1... | It's as simple as data.frame(as.list(testVect)). Or if you want sensible data types for your columns, data.frame(lapply(testVect, type.convert), stringsAsFactors=FALSE).
| Vector | 16,816,032 | 115 |
Please consider this code. I have seen this type of code several times. words is a local vector. How is it possible to return it from a function?
Can we guarantee it will not die?
std::vector<std::string> read_file(const std::string& path)
{
std::ifstream file("E:\\names.txt");
if (!file.is_open())
{
... | Pre C++11:
The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.
See this question & answer for further details.
C++11:
The function will move the value. See this answer for further details.
| Vector | 22,655,059 | 115 |
Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like
[2,2,2] - [1,1,1] = [1,1,1]
Should I use tuples?
If none of them defines these operands on these types, can I define it instead?
If not, should I create a new vector3 class?
| If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.
Otherwise, look for list comprehensions used with the zip builtin function:
[a_i - b_i for a_i, b_i in zip(a, b)]
| Vector | 534,855 | 114 |
I have a vector<int> container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form
"1,2,3,4"
What is the cleanest way to do that in C++?
In Python this is how I would do it:
>>> array = [1,2,3,4]
>>> ",".join(map(str,array))
'1,2,3,4'
| Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++.
You could use a stringstream ...
#include <sstream>
//...
std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
{
if(i != 0)
ss << ",";
ss << v[i];
}
std::string s = ss.str();
You could also make use of std::for_each i... | Vector | 1,430,757 | 112 |
What is the simplest way to convert array to vector?
void test(vector<int> _array)
{
...
}
int x[3]={1, 2, 3};
test(x); // Syntax error.
I want to convert x from int array to vector in simplest way.
| Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:
int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);
or
test(std::vector<int>(x, x + sizeof x / sizeof x[0]));
where sizeof x / sizeof x[0]... | Vector | 8,777,603 | 111 |
Is there a good way of differentiating between row and column vectors in numpy? If I was to give one a vector, say:
from numpy import *
v = array([1,2,3])
they wouldn't be able to say weather I mean a row or a column vector. Moreover:
>>> array([1,2,3]) == array([1,2,3]).transpose()
array([ True, True, True])
Which... | You can make the distinction explicit by adding another dimension to the array.
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14
Now force it to be a column vector:
>>> a.shape = (3,1)
>>> a
array([[1],
[2],
[3]])
>>> a.transpose()
array([[... | Vector | 17,428,621 | 111 |
Is there any built in function which tells me that my vector contains a certain element or not
e.g.
std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");
if (v.contains("abc")) // I am looking for one such feature, is there any
// such function or i need to loop through whole vector?
| You can use std::find as follows:
if (std::find(v.begin(), v.end(), "abc") != v.end())
{
// Element in vector.
}
To be able to use std::find: include <algorithm>.
| Vector | 6,277,646 | 110 |
As (hopefully) we all know, vector<bool> is totally broken and can't be treated as a C array. What is the best way to get this functionality?
So far, the ideas I have thought of are:
Use a vector<char> instead, or
Use a wrapper class and have vector<bool_wrapper>
How do you guys handle this problem? I need the c_arra... | Use std::deque if you don't need the array, yes.
Otherwise use an alternative vector that doesn't specialize on bool, such as the one in Boost Container.
| Vector | 670,308 | 107 |
Lately I've been asked to write a function that reads the binary file into the std::vector<BYTE> where BYTE is an unsigned char. Quite quickly I came with something like this:
#include <fstream>
#include <vector>
typedef unsigned char BYTE;
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
s... | When testing for performance, I would include a test case for:
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
std::ifstream file(filename, std::ios::binary);
// Stop eating new lines in binary mode!!!
file.unsetf(std::ios::skipws);
// get its size:
std::streampos fileSize... | Vector | 15,138,353 | 107 |
Container requirements have changed from C++03 to C++11. While C++03 had blanket requirements (e.g. copy constructibility and assignability for vector), C++11 defines fine-grained requirements on each container operation (section 23.2).
As a result, you can e.g. store a type that is copy-constructible but not assignabl... | No, I believe the allocator requirements say that T can be a "non-const, non-reference object type".
You wouldn't be able to do much with a vector of constant objects. And a const vector<T> would be almost the same anyway.
Many years later this quick-and-dirty answer still seems to be attracting comments and votes. No... | Vector | 6,954,906 | 105 |
There is a thread in the comments section in this post about using std::vector::reserve() vs. std::vector::resize().
Here is the original code:
void MyClass::my_method()
{
my_member.reserve(n_dim);
for(int k = 0 ; k < n_dim ; k++ )
my_member[k] = k ;
}
I believe that to write elements in the vector, t... | There are two different methods for a reason:
std::vector::reserve will allocate the memory but will not resize your vector, which will have a logical size the same as it was before.
std::vector::resize will actually modify the size of your vector and will fill any space with objects in their default state. If they are... | Vector | 13,029,299 | 103 |
Currently when I have to use vector.push_back() multiple times.
The code I'm currently using is
std::vector<int> TestVector;
TestVector.push_back(2);
TestVector.push_back(5);
TestVector.push_back(8);
TestVector.push_back(11);
TestVector.push_back(14);
Is there a way to only use vector.push_back() once and just pass mu... | You can do it with initializer list:
std::vector<unsigned int> array;
// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });
| Vector | 14,561,941 | 103 |
I would like to randomly reorganize the order of the numbers in a vector, in a simple one-line command?
My particular vector V has 150 entries for each value from 1 to 10:
V <- rep(1:10, each=150)
| Yes.
sample(V)
From ?sample:
For ‘sample’ the default for ‘size’ is the number of items
inferred from the first argument, so that ‘sample(x)’ generates a
random permutation of the elements of ‘x’ (or ‘1:x’).
| Vector | 13,765,972 | 102 |
I need to convert a multi-row two-column data.frame to a named character vector.
My data.frame would be something like:
dd = data.frame(crit = c("a","b","c","d"),
name = c("Alpha", "Beta", "Caesar", "Doris")
)
and what I actually need would be:
whatiwant = c("a" = "Alpha",
... | Use the names function:
whatyouwant <- as.character(dd$name)
names(whatyouwant) <- dd$crit
as.character is necessary, because data.frame and read.table turn characters into factors with default settings.
If you want a one-liner:
whatyouwant <- setNames(as.character(dd$name), dd$crit)
| Vector | 19,265,172 | 102 |
I'm using a external library which at some point gives me a raw pointer to an array of integers and a size.
Now I'd like to use std::vector to access and modify these values in place, rather than accessing them with raw pointers.
Here is an articifial example that explains the point:
size_t size = 0;
int * data = get_d... | C++20's std::span
If you are able to use C++20, you could use std::span which is a pointer - length pair that gives the user a view into a contiguous sequence of elements. It is some sort of a std::string_view, and while both std::span and std::string_view are non-owning views, std::string_view is a read-only view.
Fro... | Vector | 60,151,514 | 102 |
In matlab there is a way to find the values in one vector but not in the other.
for example:
x <- c(1,2,3,4)
y <- c(2,3,4)
is there any function that would tell me that the value in x that's not in y is 1?
| you can use the setdiff() (set difference) function:
> setdiff(x, y)
[1] 1
| Vector | 1,837,968 | 101 |
What's the C# equivalent of C++ vector?
I am searching for this feature:
To have a dynamic array of contiguously stored memory that has no performance penalty for access vs. standard arrays.
I was searching and they say .NET equivalent to the vector in C++ is the ArrayList, so:
Do ArrayList have that contiguous memory... | You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
| Vector | 6,943,229 | 101 |
In C++ one can create an array of predefined size, such as 20, with int myarray[20]. However, the online documentation on vectors doesn't show an alike way of initialising vectors: Instead, a vector should be initialised with, for example, std::vector<int> myvector (4, 100);. This gives a vector of size 4 with all elem... | With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
| Vector | 10,559,283 | 101 |
I was trying to create a vector of lambda, but failed:
auto ignore = [&]() { return 10; }; //1
std::vector<decltype(ignore)> v; //2
v.push_back([&]() { return 100; }); //3
Up to line #2, it compiles fine. But the line#3 gives compilation error:
error: no matching function for call to 'std::vector<main()::<lamb... | Every lambda has a different type—even if they have the same signature. You must use a run-time encapsulating container such as std::function if you want to do something like that.
e.g.:
std::vector<std::function<int()>> functors;
functors.push_back([&] { return 100; });
functors.push_back([&] { return 10; });
| Vector | 7,477,310 | 100 |
I want know how I can add values to my vector of structs using the push_back method
struct subject
{
string name;
int marks;
int credits;
};
vector<subject> sub;
So now how can I add elements to it?
I have function that initializes string name(subject name to it)
void setName(string s1, string s2, ...... strin... | Create vector, push_back element, then modify it as so:
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
s... | Vector | 8,067,338 | 99 |
How can I move some elements from first vector to second, and the elements will remove from the first?
if I am using std::move, the elements not removed from first vector.
this is the code I wrote:
move(xSpaces1.begin() + 7, xSpaces1.end(), back_inserter(xSpaces2));
| Resurrecting an old thread, but I am surprised that nobody mentioned std::make_move_iterator combined with insert. It has the important performance benefit of preallocating space in the target vector:
v2.insert(v2.end(), std::make_move_iterator(v1.begin() + 7),
std::make_move_iterator(v1.end()));
... | Vector | 15,004,517 | 97 |
I am trying to do a foreach on a vector of attacks, each attack has a unique ID say, 1-3.
The class method takes the keyboard input of 1-3.
I am trying to use a foreach to run through my elements in m_attack to see if the number matches, if it does... do something.
The problem I'm seeing is this:
a'for each' statement ... | For next examples assumed that you use C++11.
Example with ranged-based for loops:
for (auto &attack : m_attack) // access by reference to avoid copying
{
if (attack.m_num == input)
{
attack.makeDamage();
}
}
You should use const auto &attack depending on the behavior of makeDamage().
You can us... | Vector | 15,027,282 | 97 |
Is there a way to extend a vector by making it repeat itself?
>v = [1 2];
>v10 = v x 5; %x represents some function. Something like "1 2" x 5 in perl
Then v10 would be:
>v10
1 2 1 2 1 2 1 2 1 2
This should work for the general case, not just for [1 2]
| The function you're looking for is repmat().
v10 = repmat(v, 1, 5)
| Vector | 2,459,851 | 96 |
Since
they are both contiguous memory containers;
feature wise, deque has almost everything vector has but more, since it is more efficient to insert in the front.
Why whould anyone prefer std::vector to std::deque?
| Elements in a deque are not contiguous in memory; vector elements are guaranteed to be. So if you need to interact with a plain C library that needs contiguous arrays, or if you care (a lot) about spatial locality, then you might prefer vector. In addition, since there is some extra bookkeeping, other ops are probably ... | Vector | 5,345,152 | 96 |
The member begin has two overloadings one of them is const_iterator begin() const;. There's also the cbegin const_iterator cbegin() const noexcept;. Both of them returns const_iterator to the begin of a list. What's the difference?
| begin will return an iterator or a const_iterator depending on the const-qualification of the object it is called on.
cbegin will return a const_iterator unconditionally.
std::vector<int> vec;
const std::vector<int> const_vec;
vec.begin(); //iterator
vec.cbegin(); //const_iterator
const_vec.begin(); //const_iterator
... | Vector | 31,208,640 | 96 |
I'm using vector drawables in android prior to Lollipop and these are of some of my libraries and tool versions:
Android Studio : 2.0
Android Gradle Plugin : 2.0.0
Build Tools : 23.0.2
Android Support Library : 23.3.0
I added this property in my app level Build.Gradle
android {
defaultConfig {
vectorDraw... | LATEST UPDATE - Jun/2019
Support Library has changed a bit since the original answer. Now, even the Android plugin for Gradle is able to automatically generate the PNG at build time. So, below are two new approaches that should work these days. You can find more info here:
PNG Generation
Gradle can automatically create... | Vector | 36,867,298 | 96 |
I'm trying to send a vector as an argument to a function and i can't figure out how to make it work. Tried a bunch of different ways but they all give different error messages.
I only include part of the code, since it's only this part that doesn't work.
(the vector "random" is filled with random, but sorted, values be... | It depends on if you want to pass the vector as a reference or as a pointer (I am disregarding the option of passing it by value as clearly undesirable).
As a reference:
int binarySearch(int first, int last, int search4, vector<int>& random);
vector<int> random(100);
// ...
found = binarySearch(first, last, search4, r... | Vector | 5,333,113 | 95 |
I have a vector, in which I save objects. I need to convert it to set. I have been reading about sets, but I still have a couple of questions:
How to correctly initialize it? Honestly, some tutorials say it is fine to initialize it like set<ObjectName> something. Others say that you need an iterator there too, like se... | Suppose you have a vector of strings, to convert it to a set you can:
std::vector<std::string> v;
std::set<std::string> s(v.begin(), v.end());
For other types, you must have operator< defined.
| Vector | 20,052,674 | 95 |
How do I extract a column from a data.table as a vector by its position? Below are some code snippets I have tried:
DT<-data.table(x=c(1,2),y=c(3,4),z=c(5,6))
DT
# x y z
#1: 1 3 5
#2: 2 4 6
I want to get this output using column position
DT$y
#[1] 3 4
is.vector(DT$y)
#[1] TRUE
Other way to get this output using co... | A data.table inherits from class data.frame. Therefore it is a list (of column vectors) internally and can be treated as such.
is.list(DT)
#[1] TRUE
Fortunately, extracting a vector from a list, i.e. [[, is very fast and, in contrast to [, package data.table doesn't define a method for it. Thus, you can simply use [[ ... | Vector | 20,043,313 | 93 |
I want to build a HashSet<u8> from a Vec<u8>. I'd like to do this
in one line of code,
copying the data only once,
using only 2n memory,
but the only thing I can get to compile is this piece of .. junk, which I think copies the data twice and uses 3n memory.
fn vec_to_set(vec: Vec<u8>) -> HashSet<u8> {
let mut v... | Because the operation does not need to consume the vector¹, I think it should not consume it. That only leads to extra copying somewhere else in the program:
use std::collections::HashSet;
use std::iter::FromIterator;
fn hashset(data: &[u8]) -> HashSet<u8> {
HashSet::from_iter(data.iter().cloned())
}
Call it like... | Vector | 39,803,237 | 93 |
Section 23.3.7 Class vector<bool> [vector.bool], paragraph 1 states:
template <class Allocator> class vector<bool, Allocator> {
public:
// types:
typedef bool const_reference;
...
However this program fails to compile when using libc++:
#include <vector>
#include <type_traits>
int
main()
{
... | The motivation for this extension, which is detectable by a conforming program, and thus non-conforming, is to make vector<bool> behave more like vector<char> with respect to references (const and otherwise).
Introduction
Since 1998, vector<bool> has been derided as "not quite a container." LWG 96, one of the very fir... | Vector | 31,974,237 | 92 |
What is the most efficient way of obtaining lists (as a vector) of the keys and values from an unordered_map?
For concreteness, suppose the map in question is a unordered_map<string, double>.
I'd then like to obtain the keys as a vector<string>, and the values as a vector<double>.
unordered_map<string, double> um;
ve... | Okay, here you go:
std::vector<Key> keys;
keys.reserve(map.size());
std::vector<Val> vals;
vals.reserve(map.size());
for(auto kv : map) {
keys.push_back(kv.first);
vals.push_back(kv.second);
}
Efficiency can probably be improved, but there it is. You're operating on two containers though, so there's not re... | Vector | 8,483,985 | 90 |
I know the size of a vector, which is the best way to initialize it?
Option 1:
vector<int> vec(3); //in .h
vec.at(0)=var1; //in .cpp
vec.at(1)=var2; //in .cpp
vec.at(2)=var3; //in .cpp
Option 2:
vector<int> vec; //in .h
vec.reserve(3); //in .cpp
vec.push_back(var1); //in .cpp
vec.push_back(var2); ... | Somehow, a non-answer answer that is completely wrong has remained accepted and most upvoted for ~7 years. This is not an apples and oranges question. This is not a question to be answered with vague cliches.
For a simple rule to follow:
Option #1 is faster...
...but this probably shouldn't be your biggest concern.... | Vector | 8,928,547 | 90 |
Is there an equivalent of list slicing [1:] from Python in C++ with vectors? I simply want to get all but the first element from a vector.
Python's list slicing operator:
list1 = [1, 2, 3]
list2 = list1[1:]
print(list2) # [2, 3]
C++ Desired result:
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2;
v2 = v1[1:];
... | This can easily be done using std::vector's copy constructor:
v2 = std::vector<int>(v1.begin() + 1, v1.end());
| Vector | 50,549,611 | 90 |
I have a vector vec of structures. Such a structure has elements int a, int b, int c. I would like to assign to some int var the element c, from the last structure in a vector. Please can you provide me with this simple solution? I'm going circle in line like this:
var = vec.end().c;
| The immediate answer to your question as to fetching access to the last element in a vector can be accomplished using the back() member. Such as:
int var = vec.back().c;
Note: If there is a possibility your vector is empty, such a call to back() causes undefined behavior. In such cases you can check your vector's empt... | Vector | 14,275,291 | 89 |
I have two vectors as Python lists and an angle. E.g.:
v = [3, 5, 0]
axis = [4, 4, 1]
theta = 1.2 # In radians.
What is the best/easiest way to get the resulting vector when rotating the v vector around the axis?
The rotation should appear to be counter clockwise for an observer to whom the axis vector is pointing. T... | Using the Euler-Rodrigues formula:
import numpy as np
import math
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = mat... | Vector | 6,802,577 | 88 |
Can/should prometheus be used as a log aggregator? We are deploying apps into a kubernetes cluster. All containers already log to stdout/err and we want all devs to instrument their code with logs to stdout/err. Fluentd will then collate all logs across the whole cluster and send to an aggregator. We have thought about... | Prometheus is a metrics system rather than a logs system. There's the mtail and grok exporters to process logs, but really that's only for cases where instrumenting your code with metrics is not possible.
For logs something like Elasticsearch is far more appropriate.
| Prometheus | 41,596,104 | 12 |
docker-compose.yml:
This is the docker-compose to run the prometheus, node-exporter and alert-manager service. All the services are running great. Even the health status in target menu of prometheus shows ok.
version: '2'
services:
prometheus:
image: prom/prometheus
privileged: true
vol... | Your ./alertmanager/alert.rules file is not included in your docker config, so it is not available in the container. You need to add it to the prometheus service:
prometheus:
image: prom/prometheus
privileged: true
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- ./alertmanager/a... | Prometheus | 48,556,768 | 12 |
I recently upgraded a spring boot application from 1.5 to 2.0.1. I also migrated the prometheus integration to the new actuator approach using micrometer. Most things work now - including some custom counters and gauges.
I noted the new prometheus endpoint /actuator/prometheus does no longer publish the spring cache me... | As you've answered my question, I can provide an answer for this.
my caches get created through scheduled tasks later on
Then this section of the doc applies to you:
Only caches that are available on startup are bound to the registry. For caches created on-the-fly or programmatically after the startup phase, an expl... | Prometheus | 49,697,063 | 12 |
There's an article "Tracking Every Release" which tells about displaying a vertical line on graphs for every code deployment. They are using Graphite. I would like to do something similar with Prometheus 2.2 and Grafana 5.1. More specifically I want to get an "application start" event displayed on a graph.
Grafana anno... | The simplest way to do this is via the same basic approach as in the article, by having your deployment tool tell Grafana when it performs a deployment.
Grafan has a built-in system for storing annotations, which are displayed on graphs as vertical lines and can have text associated with them. It would be as simple as ... | Prometheus | 50,415,659 | 12 |
I am trying to load prometheus with docker using the following custom conf file: danilo@machine:/prometheus-data/prometheus.yml:
global:
scrape_interval: 15s # By default, scrape targets every 15 seconds.
# Attach these labels to any time series or alerts when communicating with
# external systems (federatio... | By “the file already exists”, do you mean that the file is on your host at /prometheus-data/prometheus.yml? If so, then you need to bind mount it into your container for it to be accessible to Prometheus.
sudo docker run -p 9090:9090 -v /prometheus-data/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus
It'... | Prometheus | 52,523,610 | 12 |
I have one query where I am trying to join two metrics on a label.
K_Status_Value == 5 and ON(macAddr) state_details{live="True"}
The label macAddr is present in both the metrics. The value of the label appears in 'K_Status_Value' sometimes in upper case (78:32:5A:29:2F:0D) and sometimes in lower case (78:72:5d:39:2f:0... | I can think of two options
Using regex "i" match modifier:
To quote Ben Kochie on Prometheus user mailing list:
The regexp matching in Prometheus is based on RE2
I think you can set flags within a match by using (?i(matchstring))
It works indeed: this metric up{instance="localhost:9090",job="prometheus"} is matched b... | Prometheus | 53,312,007 | 12 |
I want to deploy Prometheus from the official helm chart on the stable repo.
Also, I want to add my own scrape config.
I can successfully add extra configs directly from the values.yml file of the chart, after downloading and altering it, but when I try to pass it as argument with --set nothing happens.
This works [in ... | When we are going to inject a multi-line text into values we need to deal with indentation in YAML.
For your particular case it is:
sudo helm upgrade --install prometheus \
--set rbac.create=true \
--set server.persistentVolume.enabled=false \
--set alertmanager.persistentVolume.enabled=false \
--set alertmanager.enabl... | Prometheus | 55,360,726 | 12 |
I've upgraded my Spring Boot application to the latest 2.2.2 Boot version. Since then, I only have a metrics endpoint but no Prometheus.
My build.gradle.kts file has org.springframework.boot:spring-boot-starter-actuator as dependency, I also added io.micrometer:micrometer-registry-prometheus as the reference suggests (... | I followed your setup, I created a project from this project loaded Spring Boot 2.2.2.RELEASE, I added the following dependency for Prometheus
implementation("io.micrometer:micrometer-registry-prometheus")
Also I added the following configuration in application.yml
management:
server:
port: 9000
endpoints:
... | Prometheus | 59,392,548 | 12 |
I am using this chart : https://github.com/helm/charts/tree/master/stable/prometheus-mongodb-exporter
This chart requires MONGODB_URI environment variable or mongodb.uri populated in values.yaml file,
Since this is a connection string I don't want to check-in that into git.
I was thinking of kubernetes secrets and prov... | Solution 1: Create custom chart
Delete the secret.yaml from chart's template directory.
Create the k8s secret on your own, maybe named cumstom-secret
Edit the deployment.yaml: here
- name: MONGODB_URI
valueFrom:
secretKeyRef:
name: custom-secret ## {{ include "prometheus-mongo... | Prometheus | 60,051,056 | 12 |
I'm trying to show system uptime as DD-HH-MM-SS format, doing it using common code wouldn't be an issue but I'm doing it using Prometheus (PromQL) and Grafana only, here's the PromQL query:
time()-process_start_time_seconds{instance="INSTANCE",job="JOB"}
I achieved the basic output I wanted, it shows me the process lif... | You can achieve this using "Unit" drop-down in the visualization section and select your unit as duration with the hh:mm:ss format, as you can see in the screenshot.
| Prometheus | 60,757,793 | 12 |
Here's my query, which is supposed to show the delta for each counter of the form taskcnt.*:
delta(label_replace({__name__=~"taskcnt.*"}, "old_name", "$1", "__name__", "(.+)")[1w])
I'm getting:
Error executing query: 1:83: parse error: ranges only allowed for
vector selectors
Basically, without the label_replace I... | The Subquery is what you need indeed (credit to commenter above M. Doubez). This should work for you - it calculates the weekly delta by calculating the subquery each day (see [1w:1d])
delta(label_replace({__name__=~"desired_metric_prefix_.+_suffix"}, "metric_name", "$1", "__name__", "desired_metric_prefix_(.+)_suffix"... | Prometheus | 61,169,517 | 12 |
I went through the PromQL docs and found rate little bit confusing. Then I tried one query from Prometheus query dashboard and found below given results
Time Count increase rate(count[1m])
15s 4381 0 0
30s 4381 0 0
45s 4381 0 0
1m 4381 0 0
15s 4381 0 0
30s 4402... | The "increase" function calculates how much some counter has grown and the "rate" function calculates the amount per second the measure grows.
Analyzing your data I think you used [30s] for the "increase" and [1m] for the "rate" (the correct used values are important to the result).
Basically, for example, in time 2m w... | Prometheus | 66,674,880 | 12 |
I want to exclude mulitple app groups from my query... Not sure how to go about it.. My thoughts are like this
count(master_build_state{app_group~! "oss-data-repair", "pts-plan-tech-solution", kubernets_namespace = "etc"} ==0)
I do not want to include those two app_groups, but am not sure how to implement in PromQL. ... | count(master_build_state{app_group !~ "(oss-data-repair|pts-plan-tech-solution)", kubernets_namespace="etc"} ==0)
| Prometheus | 68,681,720 | 12 |
I tried to obtains these measurements from prometheus:
increase(http_server_requests_seconds_count{uri="myURI"}[10s])
increase(http_server_requests_seconds_count{uri="myURI"}[30s])
rate(http_server_requests_seconds_count{uri="myURI"}[10s])
rate(http_server_requests_seconds_count{uri="myURI"}[30s])
Then I run a python... | Prometheus calculates increase(m[d]) at timestamp t in the following way:
It fetches raw samples stored in the database for time series matching m on a time range (t-d .. t]. Note that samples at timestamp t-d aren't included in the time range, while samples at t are included. It is expected that every selected time s... | Prometheus | 70,835,778 | 12 |
I've got an alert configured like this:
ALERT InstanceDown
IF up == 0
FOR 30s
ANNOTATIONS {
summary = "Server {{ $labels.Server }} is down.",
description = "{{ $labels.Server }} ({{ $labels.job }}) is down for more than 30 seconds."
}
The slack receiver looks like this:
receivers:
- name: general_receiver
sl... | You need to define your own template (I just hat to walk that path). For a brief example see: https://prometheus.io/blog/2016/03/03/custom-alertmanager-templates/
All alerts here have at least a summary and a runbook annotation. runbook contains an Wiki URL. I've defined the following template (as described in the blog... | Prometheus | 39,389,463 | 11 |
I use the Prometheus Java Client to export session information of my application. We want to show how long sessions have been idle.
The problem is that we have a maximum of 1000 sessions and sessions are removed after a certain period. Unfortunately they do not disappear from Prometheus:
My code looks like this:
stati... | The Gauge class has a remove method which has the same signature as the labels method. For your specific example, removing the metrics associated with that gauge would look like this
sessionInactivity.remove(internalKey, externalKey, browser);
The client library documentation states:
Metrics with labels SHOULD suppor... | Prometheus | 45,172,765 | 11 |
Calculating the maximum quantile over all dataseries is a problem for me:
query
http_response_time{job=~"^(x|y)$", quantile="0.95",...}
result
http_response_time{job="x",...} 0.26
http_response_time{job="y",...} NaN
This is how I would try to calculate the maximum:
avg(http_response_time{job=~"^(x|y)$",...})
Now the... | I didn't try this one with NaN, but you can simply filter by values with binary operators. Since NaN mathematically doesn't equal NaN you could try this trick (since a response time should be always positive):
avg(http_response_time{job=~"^(x|y)$",...} >= 0)
| Prometheus | 47,887,142 | 11 |
I am trying to solve a problem of making a sum and group by query in Prometheus on a metric where the labels assigned to the metric values to unique to my sum and group by requirements.
I have a metric sampling sizes of ElasticSearch indices, where the index names are labelled on the metric. The indices are named like ... | It is possible to use label_replace() function in order to extract the needed parts of the label into a separate label and then group by this label when summing the results. For example, the following query extracts the project.sample-y from project.sample-y.jksdjkfs-2f16-11e7-3454-005056bf2fbf.2018.03.11 value stored ... | Prometheus | 49,334,224 | 11 |
When i make a table panel and go to "Options" tab, columns parameter set to Auto: Columns and their order are determined by the data query.
Is there a doc on how write prometheus queries for grafana tables?
My prometheus data is a metric with 2 labels my_col and my_row:
my_metric{instance="lh",job="job",my_col="1",my_... | After some experimentations in Grafana 9.1.1, I have obtained a way to construct a table like you have described with prometheus metric like that. Here are Grafana transform functions you will need:
Labels to fields
This function separate the labels in the metric to columns.
Set Mode to Columns
Set Labels to be only... | Prometheus | 52,163,689 | 11 |
I have used a variable in grafana which looks like this:
label_values(some_metric, service)
If the metric is not emitted by the data source at the current time the variable values are not available for the charts. The variable in my case is the release name and all the charts of grafana are dependent on this variable... | I'd suggest query_result(count by (somelabel)(count_over_time(some_metric[$__range]))) and then use regular expressions to extract out the label value you want.
That I'm using count here isn't too important, it's more that I'm using an over_time function and then aggregating.
| Prometheus | 52,778,031 | 11 |
Using this [https://github.com/prometheus/pushgateway][1] we are trying to push one metric to prometheus. It seems to require the data in a very specific format.
It works fine when doing their example curl of
echo "some_metric 3.14" | curl --data-binary @- http://pushgateway.example.org:9091/metrics/job/some_job
Yet... | From curl man page:
--data-ascii
(HTTP) This is just an alias for -d, --data.
--data-binary
(HTTP) This posts data exactly as specified with no extra processing whatsoever.
If you start the data with the letter @, the rest should be a filename. Data is posted > in a similar manner as -d, --data does, except that newli... | Prometheus | 53,318,936 | 11 |
I have a Kubernetes Cluster and want to know how much disk space my containers use. I am not talking about mounted Volumes.
I can get this information by using docker commands like docker system df -v or docker ps -s, but I don't want to connect to every single worker node.
Is there a way to get a container's disk usag... | Yes, but currently not with kubectl, you can get metrics from the kubelet, either through the kube-apiserver (proxied) or directly calling the kubelet HTTP(s) server endpoint (default port 10250). Disk metrics are generally available on the /stats/summary endpoint and you can also find some cAdvisor metrics on the /met... | Prometheus | 53,328,104 | 11 |
I am using Prometheus to query metrics from Apache Flink. I want to measure the number of records In and Out per second of a Map function. When I query two different metrics in Prometheus, the chart only shows one of them.
flink_taskmanager_job_task_operator_numRecordsInPerSecond{operator_name="Map"}
or flink_taskmana... | First of all, for more complex graphing you should definitely investigate Grafana.
The built-in Prometheus graphs are useful eg. for debugging, but definitely more limited. In particular one graph will only display the results of one query.
Now for a hack that I definitely do not recommend:
flink_taskmanager_job_task_o... | Prometheus | 55,490,701 | 11 |
I have several metrics with the label "service". I want to get a list of all the "service" levels that begin with "abc" and end with "xyz". These will be the values of a grafana template variable.
This is that I have tried:
label_values(service) =~ "abc.*xyz"
However this produces a error Template variables could not b... | This should work (replacing up with the metric you mention):
label_values(up{service=~"abc.*xyz"}, service)
Or, in case you actually need to look across multiple metrics (assuming that for some reason some metrics have some service label values and other metrics have other values):
label_values({__name__=~"metric1|met... | Prometheus | 55,958,636 | 11 |
I'm looking for a query to get the average uptime of the server on which prometheus runs over the last week. It should be about 15h/week, so about 8-10 %.
I'm using Prometheus 2.5.0 with node_exporter on CentOS 7.6.1810.
My most promising experiments would be:
1 - avg_over_time(up{job="prometheus"}[7d])
This is what ... | Here you go. Don't ask. (o:
avg_over_time(
(
sum without() (up{job="prometheus"})
or
(0 * sum_over_time(up{job="prometheus"}[7d]))
)[7d:5m]
)
To explain that bit by bit:
sum without() (up{job="prometheus"}): take the up metric (the sum without() part is there to get rid of the metric name while keep... | Prometheus | 58,080,200 | 11 |
In Prometheus I've got 14 seconds for http_server_requests_seconds_max.
http_server_requests_seconds_max{exception="None",method="GET",outcome="SUCCESS",status="200",uri="/v1/**",} 14.3
Does this mean the total time for the request from the server to the client or does it only measure the time in the Spring container... | From the copy of Spring documentation at Archive.org (or current Micrometer.io page), when @Timed attribute is used on a function or a Controller, it produces the metrics http_server_requests.
which by default contains dimensions for the HTTP status of the
response, HTTP method, exception type if the request fails, an... | Prometheus | 60,206,507 | 11 |
In the prometheus configuration I have a job with these specs:
- job_name: name_of_my_job
scrape_interval: 5m
scrape_timeout: 30s
metrics_path: /metrics
scheme: http
The script that creates the metrics takes 3 minutes to finish, but from prometheus I don't see the metrics. What is the operation of ... | Every 5 minutes (scrape_interval) Prometheus will get the metrics from the given URL. It will try 30 seconds (scrape_timeout) to get the metrics if it can't scrape in this time it will time out.
| Prometheus | 60,989,807 | 11 |
We have been struggling to create a good memory monitoring for our nodes running Docker components. We use Prometheus in combination with cadvisor and node_exporter.
What is the best way to determine the used memory per node?
Method 1: gives in our example around 42%
(1-(node_memory_MemAvailable_bytes/node_memory_Me... | This documentation tells in detail what are those numbers mean:
https://github.com/torvalds/linux/blob/master/Documentation/filesystems/proc.rst#meminfo
MemAvailable:
An estimate of how much memory is available for starting new applications, without swapping. Calculated from MemFree, SReclaimable, the size of the file... | Prometheus | 61,751,232 | 11 |
I am considering to use Prometheus as a time-series database to store data for long periods of time (months or maybe even over a year).
However, I read in few places that Prometheus is not suitable for long-term storage and other TSDB would be a better solution in that case. But why exactly is it not suitable and what'... | It is a design decision and it has mainly to do with the scope of a project/tool. The original authors, in the context of their use case at SoundCloud, decided not to build a distributed data storage layer but keep things simple.
In other words: Prometheus will fill up a disk but doesn't shard or replicate the data for... | Prometheus | 68,891,824 | 11 |
I'm new to monitoring the k8s cluster with prometheus, node exporter and so on.
I want to know that what the metrics exactly mean for though the name of metrics are self descriptive.
I already checked the github of node exporter, but I got not useful information.
Where can I get the descriptions of node exporter metric... | There is a short description along with each of the metrics. You can see them if you open node exporter in browser or just curl http://my-node-exporter:9100/metrics. You will see all the exported metrics and lines with # HELP are the description ones:
# HELP node_cpu_seconds_total Seconds the cpus spent in each mode.
#... | Prometheus | 70,300,286 | 11 |
I am using a NewGaugeVec to report my metrics:
elapsed := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "gogrinder_elapsed_ms",
Help: "Current time elapsed of gogrinder teststep",
}, []string{"teststep", "user", "iteration", "timestamp"})
prometheus.MustRegister(elapsed)
All works fine but I noticed that ... | Well the topic is rather old but in case others have to deal with it.
The following code works fine with current codebase v0.9.0-pre1
// [...] imports, metric initialization ...
func main() {
// go get rid of any additional metrics
// we have to expose our metrics with a custom registry
r := prometheus.NewRegis... | Prometheus | 35,117,993 | 10 |
I want to know why prometheus is not suitable for billing system.
the Prometheus overview page says
If you need 100% accuracy, such as for per-request billing, Prometheus is not a good choice as the collected data will likely not be detailed and complete enough.
I don't really understand 100% accuracy. Does it mean ... | Prometheus prefers reliability over 100% accuracy, so there are tradeoffs where a tiny amount of data may be lost rather than taking out the whole system. This is fine for monitoring, but rarely okay when money is involved.
See also https://www.robustperception.io/monitoring-without-consensus/
| Prometheus | 44,518,575 | 10 |
I have different metrices in prometheus counter_metrics a, couneter_metrices b and I want a singlestat for the count of all the different request metrics.
How am I able to fetch this?
(sum(couneter_metrics{instance="a,job="b"}))+
| For the singlestat panel, you can just sum the two metrics and then add them together. Here is an example with two different metrics:
sum(prometheus_local_storage_memory_series) + sum(counters_logins)
Recommended reading, just in case you are doing anything with rates as well: https://www.robustperception.io/rate-the... | Prometheus | 45,343,371 | 10 |
Counters and Gauges allow for labels to be added to them. When I try to add labels to a Summary, I get an "incorrect number of labels" error.
This is what I'm trying:
private static final Summary latencySummary = Summary.build()
.name("all_latencies")
.help("all latencies.")
.regist... | You need to provide the labelname in the metric:
private static final Summary latencySummary = Summary.build()
.name("latency_seconds")
.help("All latencies.")
.labelNames("api")
.register();
| Prometheus | 48,287,188 | 10 |
Use Helm installed Prometheus and Grafana in a kubernetes cluster:
helm install stable/prometheus
helm install stable/grafana
It has an alertmanage service.
But I saw a blog introduced how to setup alertmanager config with yaml files:
http://blog.wercker.com/how-to-setup-alerts-on-prometheus
Is it possible to use t... | The alerts and rules keys in the serverFiles group of the values.yaml file are mounted in the Prometheus container in the /etc/config folder. You can put in there the configuration you want (for example take inspiration by the blog post you linked) and it will be used by Prometheus to handle the alerts.
For example, a ... | Prometheus | 48,374,858 | 10 |
I run a small flask application with gunicorn and multiple worker processes on kubernetes. I would like to collect metrics from this application with prometheus, but the metrics should only be accessible cluster internally on a separate port (as this required in our current setting).
For one gunicorn worker process I ... | What you would want to do here is start up a separate process just to serve the metrics. Put the app function in https://github.com/prometheus/client_python#multiprocess-mode-gunicorn in an app of its own, and make sure that prometheus_multiproc_dir is the same for both it and the main application.
| Prometheus | 49,737,354 | 10 |
I am trying to drop all but a few whitelisted metrics in prometheus. I can persist them selectively with something like this:
metric_relabel_configs:
- source_labels: [__name__]
regex: (?i)(metric1|metric2|metric3)
action: keep
However I want to drop all of the other, non-matching metrics. Is there any str... | The keep action drops everything that doesn't match, so that single action is enough to do what you want.
| Prometheus | 50,108,835 | 10 |
I am using the following query to calculate the cost of nodes in our GKE cluster (new lines added for readability)
sum(
kube_node_status_capacity_cpu_cores * on(node) group_left(label_cloud_google_com_gke_nodepool)
kube_node_labels{
label_cloud_google_com_gke_preemptible = "true"
}
) * 5.10 +
sum(
k... | You can use or to insert a value if one is not present:
(
sum(
kube_node_status_capacity_cpu_cores
* on(node) group_left(label_cloud_google_com_gke_nodepool)
kube_node_labels{label_cloud_google_com_gke_preemptible = "true"}
) * 5.10
or
vector(0)
)
+
sum(
... | Prometheus | 50,420,467 | 10 |
Is there a way to round a decimal value in grafana? round() and ceil() functions gets an "instant-vector", not a numeric value, and for example, adding a query like ceil(1/15) will return 0.
| It depends what you're using to display the data, for example a single stat or gauge you'll find the 'Decimals' option in Grafana, for graphs it's in the 'Axes' options. You don't need to do this in the query for the metric.
| Prometheus | 50,634,445 | 10 |
I have an application that I have to monitor every 5 mins. However, that application does not have a /metrics port for Prometheus to directly scrape from and I don't have any control over that application.
As a workaround, I wrote a python program to manually scrape the data, and transforms those data to my own metric... | You can create the lambda and run it every 5 minutes with a cloudwatch rule. Inside the lambda, instead of calling push_to_gateway, you can just curl the pushgateway. see and example here.
Make sure that the gateway is accessible from the lambda - either behind a public ELB or have them both in the same vpc.
| Prometheus | 52,744,475 | 10 |
I have implemented a Java web service using Dropwizard. Now I want it to also expose Prometheus metrics.
I have followed this pretty straight-forward example. However, the endpoint at http://localhost:9090/metrics is still not exposed.
Here's the relevant code:
Dependencies in the pom.xml:
<dependency>
<gro... | Remember default dropwizard configuration has the admin app on a different port. That's where you'd find the metrics servlet.
| Prometheus | 52,931,289 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.