本文整理汇总了C++中std::vector类的典型用法代码示例。如果您正苦于以下问题:C++ vector类的具体用法?C++ vector怎么用?C++ vector使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了vector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: save
inline void save(
Archive & ar,
const STD::vector<bool, Allocator> &t,
const unsigned int /* file_version */
){
// record number of elements
unsigned int count = t.size();
ar << BOOST_SERIALIZATION_NVP(count);
STD::vector<bool>::const_iterator it = t.begin();
while(count-- > 0){
bool tb = *it++;
ar << boost::serialization::make_nvp("item", tb);
}
}
示例2: load
inline void load(
Archive & ar,
STD::vector<bool, Allocator> &t,
const unsigned int /* file_version */
){
// retrieve number of elements
unsigned int count;
ar >> BOOST_SERIALIZATION_NVP(count);
t.clear();
while(count-- > 0){
bool i;
ar >> boost::serialization::make_nvp("item", i);
t.push_back(i);
}
}
示例3: debug
/* Export a graph (triangle navmesh graph) to a file
* Requires:
* @nodes The list of all the nodes
* @fname the filename to export the graph
*/
bool TriNavMeshBuilder::exportGraph(const std::vector<GNode *> &nodes,
const std::vector<GEdge *> &edges,
const Ogre::String &fname)
{
std::ofstream out;
out.open(fname.c_str());
if(!out.is_open()){
debug("Error trying to open the file %s\n", fname.c_str());
return false;
}
// get all the vertexs
std::map<const sm::Vertex *, int> vertexs;
int vertexCount = 0;
std::vector<const sm::Vertex *> vertexList;
for(int i = nodes.size()-1; i >= 0; --i){
ASSERT(nodes[i]->getTriangle());
const sm::Vertex *v1 = nodes[i]->getTriangle()->v1;
const sm::Vertex *v2 = nodes[i]->getTriangle()->v2;
const sm::Vertex *v3 = nodes[i]->getTriangle()->v3;
if(vertexs.find(v1) == vertexs.end())
{vertexs[v1] = vertexCount++; vertexList.push_back(v1);}
if(vertexs.find(v2) == vertexs.end())
{vertexs[v2] = vertexCount++; vertexList.push_back(v2);}
if(vertexs.find(v3) == vertexs.end())
{vertexs[v3] = vertexCount++; vertexList.push_back(v3);}
}
ASSERT(vertexCount == vertexList.size());
// save the number of vertexs and save the vertexs
out << vertexCount << "\n";
for(int i = 0; i < vertexCount; ++i){
out << vertexList[i]->x << "\t" << vertexList[i]->y << "\n";
}
// save the number of nodes and the nodes and the nodeMap
std::map<const GNode *, int> nodesMap;
int nodesCount = 0;
out << nodes.size() << "\n";
for(int i = 0; i < nodes.size(); ++i){
if(nodesMap.find(nodes[i]) == nodesMap.end()){nodesMap[nodes[i]] = nodesCount++;}
const Triangle *t = nodes[i]->getTriangle();
ASSERT(t);
// we will save the vertexs index of the triangle of the node
out << vertexs[t->v1] << "\t" << vertexs[t->v2] << "\t" <<
vertexs[t->v3] << "\n";
}
// save the number of edges and the edges
out << edges.size() << "\n";
for(int i = 0; i < edges.size(); ++i){
const GNode *n1 = edges[i]->getNode1();
const GNode *n2 = edges[i]->getNode2();
ASSERT(n1 && n2);
// we will save the nodes index and the distance
out << nodesMap[n1] << "\t" << nodesMap[n2] << "\t" <<
edges[i]->getWeight() << "\n";
}
out.close();
return true;
}
示例4: assert
template <typename PointT, typename FlannDistance> void
pcl::search::FlannSearch<PointT, FlannDistance>::radiusSearch (
const PointCloud& cloud, const std::vector<int>& indices, double radius, std::vector< std::vector<int> >& k_indices,
std::vector< std::vector<float> >& k_sqr_distances, unsigned int max_nn) const
{
if (indices.empty ()) // full point cloud + trivial copy operation = no need to do any conversion/copying to the flann matrix!
{
k_indices.resize (cloud.size ());
k_sqr_distances.resize (cloud.size ());
if (! cloud.is_dense) // remove this check as soon as FLANN does NaN checks internally
{
for (size_t i = 0; i < cloud.size(); i++)
{
assert (point_representation_->isValid (cloud[i]) && "Invalid (NaN, Inf) point coordinates given to radiusSearch!");
}
}
bool can_cast = point_representation_->isTrivial ();
float* data = 0;
if (!can_cast)
{
data = new float[dim_*cloud.size ()];
for (size_t i = 0; i < cloud.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[i],out);
}
}
float* cdata = can_cast ? const_cast<float*> (reinterpret_cast<const float*> (&cloud[0])) : data;
const flann::Matrix<float> m (cdata ,cloud.size (), dim_, can_cast ? sizeof (PointT) : dim_ * sizeof (float));
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.checks = checks_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn != 0 ? max_nn : -1;
index_->radiusSearch (m,k_indices,k_sqr_distances,static_cast<float> (radius * radius), p);
delete [] data;
}
else // if indices are present, the cloud has to be copied anyway. Only copy the relevant parts of the points here.
{
k_indices.resize (indices.size ());
k_sqr_distances.resize (indices.size ());
if (! cloud.is_dense) // remove this check as soon as FLANN does NaN checks internally
{
for (size_t i = 0; i < indices.size(); i++)
{
assert (point_representation_->isValid (cloud [indices[i]]) && "Invalid (NaN, Inf) point coordinates given to radiusSearch!");
}
}
float* data = new float [dim_ * indices.size ()];
for (size_t i = 0; i < indices.size (); ++i)
{
float* out = data+i*dim_;
point_representation_->vectorize (cloud[indices[i]], out);
}
const flann::Matrix<float> m (data, cloud.size (), point_representation_->getNumberOfDimensions ());
flann::SearchParams p;
p.sorted = sorted_results_;
p.eps = eps_;
p.checks = checks_;
// here: max_nn==0: take all neighbors. flann: max_nn==0: return no neighbors, only count them. max_nn==-1: return all neighbors
p.max_neighbors = max_nn != 0 ? max_nn : -1;
index_->radiusSearch (m, k_indices, k_sqr_distances, static_cast<float> (radius * radius), p);
delete[] data;
}
if (!identity_mapping_)
{
for (size_t j = 0; j < k_indices.size (); ++j )
{
for (size_t i = 0; i < k_indices[j].size (); ++i)
{
int& neighbor_index = k_indices[j][i];
neighbor_index = index_mapping_[neighbor_index];
}
}
}
}
示例5: IsValidSignatureEncoding
/**
* A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
* Where R and S are not negative (their first byte has its highest bit not set), and not
* excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
* in which case a single 0 byte is necessary and even required).
*
* See https://cryptomailcointalk.org/index.php?topic=8392.msg127623#msg127623
*
* This function is consensus-critical since BIP66.
*/
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
// * total-length: 1-byte length descriptor of everything that follows,
// excluding the sighash byte.
// * R-length: 1-byte length descriptor of the R value that follows.
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
// possible encoding for a positive integers (which means no null bytes at
// the start, except a single one when the next byte has its highest bit set).
// * S-length: 1-byte length descriptor of the S value that follows.
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
// signature)
// Minimum and maximum size constraints.
if (sig.size() < 9) return false;
if (sig.size() > 73) return false;
// A signature is of type 0x30 (compound).
if (sig[0] != 0x30) return false;
// Make sure the length covers the entire signature.
if (sig[1] != sig.size() - 3) return false;
// Extract the length of the R element.
unsigned int lenR = sig[3];
// Make sure the length of the S element is still inside the signature.
if (5 + lenR >= sig.size()) return false;
// Extract the length of the S element.
unsigned int lenS = sig[5 + lenR];
// Verify that the length of the signature matches the sum of the length
// of the elements.
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
// Check whether the R element is an integer.
if (sig[2] != 0x02) return false;
// Zero-length integers are not allowed for R.
if (lenR == 0) return false;
// Negative numbers are not allowed for R.
if (sig[4] & 0x80) return false;
// Null bytes at the start of R are not allowed, unless R would
// otherwise be interpreted as a negative number.
if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
// Check whether the S element is an integer.
if (sig[lenR + 4] != 0x02) return false;
// Zero-length integers are not allowed for S.
if (lenS == 0) return false;
// Negative numbers are not allowed for S.
if (sig[lenR + 6] & 0x80) return false;
// Null bytes at the start of S are not allowed, unless S would otherwise be
// interpreted as a negative number.
if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
return true;
}
示例6: loadOBJ
bool loadOBJ(const char* path, std::vector<glm::vec3> &out_vertices, std::vector<glm::vec2> &out_uvs, std::vector<glm::vec3> &out_normals)
{
std::vector<unsigned int> vertex_indices;
std::vector<unsigned int> uv_indices;
std::vector<unsigned int> normal_indices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_uvs;
std::vector<glm::vec3> temp_normals;
// Opens file
FILE* file = fopen(path, "r");
if (file == NULL)
{
std::cout << "Couldn't open " << path << std::endl;
return false;
}
// Reads file and changes it's shape
while(true)
{
// Reads until End Of File
char line_header[128];
int line = fscanf(file, "%s", line_header);
if (line == EOF)
break;
if (strcmp(line_header, "v") == 0)
{
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex);
} else if (strcmp(line_header, "vt") == 0)
{
glm::vec2 uv;
fscanf(file, "%f %f", &uv.x, &uv.y);
temp_uvs.push_back(uv);
} else if (strcmp(line_header, "vn") == 0)
{
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.push_back(normal);
} else if (strcmp(line_header, "f") == 0)
{
std::string vertex1, vertex2, vertex3;
unsigned int vertex_index[3], uv_index[3], normal_index[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertex_index[0], &uv_index[0], &normal_index[0], &vertex_index[1], &uv_index[1], &normal_index[1], &vertex_index[2], &uv_index[2], &normal_index[2]);
if (matches != 9)
{
std::cout << "File wasn't standard" << std::endl;
return false;
}
vertex_indices.push_back(vertex_index[0]);
vertex_indices.push_back(vertex_index[1]);
vertex_indices.push_back(vertex_index[2]);
uv_indices.push_back(uv_index[0]);
uv_indices.push_back(uv_index[1]);
uv_indices.push_back(uv_index[2]);
normal_indices.push_back(normal_index[0]);
normal_indices.push_back(normal_index[1]);
normal_indices.push_back(normal_index[2]);
}
}
for(unsigned int i = 0; i < vertex_indices.size(); i++)
{
unsigned int vertex_index = vertex_indices[i];
glm::vec3 vertex = temp_vertices[vertex_index - 1];
out_vertices.push_back(vertex);
unsigned int uv_index = uv_indices[i];
glm::vec2 uv = temp_uvs[uv_index - 1];
out_uvs.push_back(uv);
unsigned int normal_index = normal_indices[i];
glm::vec3 normal = temp_normals[normal_index - 1];
out_normals.push_back(normal);
}
return true;
}
示例7: sizeof
unsigned long
StaticRangeCoder::decodeStreamToCharVector (std::istream& inputByteStream_arg,
std::vector<char>& outputByteVector_arg)
{
uint8_t ch;
DWord freq[257];
unsigned int i;
// define range limits
const DWord top = (DWord)1 << 24;
const DWord bottom = (DWord)1 << 16;
DWord low, range;
DWord code;
unsigned int outputBufPos;
unsigned int output_size;
unsigned long streamByteCount;
streamByteCount = 0;
output_size = outputByteVector_arg.size ();
outputBufPos = 0;
// read cumulative frequency table
inputByteStream_arg.read ((char*)&freq[0], sizeof(freq));
streamByteCount += sizeof(freq);
code = 0;
low = 0;
range = (DWord)-1;
// init code
for (i = 0; i < 4; i++)
{
inputByteStream_arg.read ((char*)&ch, sizeof(char));
streamByteCount += sizeof(char);
code = (code << 8) | ch;
}
// decoding
for (i = 0; i < output_size; i++)
{
// symbol lookup in cumulative frequency table
uint8_t symbol = 0;
uint8_t sSize = 256 / 2;
DWord count = (code - low) / (range /= freq[256]);
while (sSize > 0)
{
if (freq[symbol + sSize] <= count)
{
symbol += sSize;
}
sSize /= 2;
}
// write symbol to output stream
outputByteVector_arg[outputBufPos++] = symbol;
low += freq[symbol] * range;
range *= freq[symbol + 1] - freq[symbol];
// check range limits
while ((low ^ (low + range)) < top || ((range < bottom) && ((range = -low & (bottom - 1)), 1)))
{
inputByteStream_arg.read ((char*)&ch, sizeof(char));
streamByteCount += sizeof(char);
code = code << 8 | ch;
range <<= 8;
low <<= 8;
}
}
return streamByteCount;
}
示例8: memset
unsigned long
StaticRangeCoder::encodeCharVectorToStream (const std::vector<char>& inputByteVector_arg,
std::ostream& outputByteStream_arg)
{
DWord freq[257];
uint8_t ch;
int i, f;
char out;
// define numerical limits
const DWord top = (DWord)1 << 24;
const DWord bottom = (DWord)1 << 16;
const DWord maxRange = (DWord)1 << 16;
DWord low, range;
unsigned int input_size;
input_size = inputByteVector_arg.size ();
unsigned int readPos;
unsigned long streamByteCount;
streamByteCount = 0;
// init output vector
outputCharVector_.clear();
outputCharVector_.reserve(sizeof(char) * input_size);
uint64_t FreqHist[257];
// calculate frequency table
memset (FreqHist, 0, sizeof(FreqHist));
readPos = 0;
while (readPos < input_size)
{
uint8_t symbol = (uint8_t)inputByteVector_arg[readPos++];
FreqHist[symbol + 1]++;
}
// convert to cumulative frequency table
freq[0] = 0;
for (f = 1; f <= 256; f++)
{
freq[f] = freq[f - 1] + (DWord)FreqHist[f];
if (freq[f] <= freq[f - 1])
freq[f] = freq[f - 1] + 1;
}
// rescale if numerical limits are reached
while (freq[256] >= maxRange)
{
for (f = 1; f <= 256; f++)
{
freq[f] /= 2;
;
if (freq[f] <= freq[f - 1])
freq[f] = freq[f - 1] + 1;
}
}
// write cumulative frequency table to output stream
outputByteStream_arg.write ((const char *)&freq[0], sizeof(freq));
streamByteCount += sizeof(freq);
readPos = 0;
low = 0;
range = (DWord)-1;
// start encoding
while (readPos < input_size)
{
// read symol
ch = inputByteVector_arg[readPos++];
// map to range
low += freq[ch] * (range /= freq[256]);
range *= freq[ch + 1] - freq[ch];
// check range limits
while ((low ^ (low + range)) < top || ((range < bottom) && ((range = -low & (bottom - 1)), 1)))
{
out = low >> 24;
range <<= 8;
low <<= 8;
outputCharVector_.push_back(out);
}
}
// flush remaining data
for (i = 0; i < 4; i++)
{
out = low >> 24;
outputCharVector_.push_back(out);
low <<= 8;
}
//.........这里部分代码省略.........
示例9: while
unsigned long
StaticRangeCoder::encodeIntVectorToStream (std::vector<unsigned int>& inputIntVector_arg,
std::ostream& outputByteStream_arg)
{
unsigned int inputsymbol;
unsigned int i, f;
char out;
uint64_t frequencyTableSize;
uint8_t frequencyTableByteSize;
// define numerical limits
const uint64_t top = (uint64_t)1 << 56;
const uint64_t bottom = (uint64_t)1 << 48;
const uint64_t maxRange = (uint64_t)1 << 48;
unsigned long input_size = (unsigned) inputIntVector_arg.size ();
uint64_t low, range;
unsigned int inputSymbol;
unsigned int readPos;
unsigned long streamByteCount;
streamByteCount = 0;
// init output vector
outputCharVector_.clear();
outputCharVector_.reserve(sizeof(char) * input_size * 2);
frequencyTableSize = 1;
readPos = 0;
// calculate frequency table
cFreqTable_[0] = cFreqTable_[1] = 0;
while (readPos < input_size)
{
inputSymbol = inputIntVector_arg[readPos++];
if (inputSymbol + 1 >= frequencyTableSize)
{
// frequency table is to small -> adaptively extend it
uint64_t oldfrequencyTableSize;
oldfrequencyTableSize = frequencyTableSize;
do
{
// increase frequency table size by factor 2
frequencyTableSize <<= 1;
} while (inputSymbol + 1 > frequencyTableSize);
if (cFreqTable_.size () < frequencyTableSize + 1)
{
// resize frequency vector
cFreqTable_.resize (frequencyTableSize + 1);
}
// init new frequency range with zero
memset (&cFreqTable_[oldfrequencyTableSize + 1], 0,
sizeof(uint64_t) * (frequencyTableSize - oldfrequencyTableSize));
}
cFreqTable_[inputSymbol + 1]++;
}
frequencyTableSize++;
// convert to cumulative frequency table
for (f = 1; f < frequencyTableSize; f++)
{
cFreqTable_[f] = cFreqTable_[f - 1] + cFreqTable_[f];
if (cFreqTable_[f] <= cFreqTable_[f - 1])
cFreqTable_[f] = cFreqTable_[f - 1] + 1;
}
// rescale if numerical limits are reached
while (cFreqTable_[frequencyTableSize - 1] >= maxRange)
{
for (f = 1; f < cFreqTable_.size (); f++)
{
cFreqTable_[f] /= 2;
;
if (cFreqTable_[f] <= cFreqTable_[f - 1])
cFreqTable_[f] = cFreqTable_[f - 1] + 1;
}
}
// calculate amount of bytes per frequency table entry
frequencyTableByteSize = (uint8_t)ceil (Log2 ((double) cFreqTable_[frequencyTableSize - 1]) / 8.0);
// write size of frequency table to output stream
outputByteStream_arg.write ((const char *)&frequencyTableSize, sizeof(frequencyTableSize));
outputByteStream_arg.write ((const char *)&frequencyTableByteSize, sizeof(frequencyTableByteSize));
streamByteCount += sizeof(frequencyTableSize)+sizeof(frequencyTableByteSize);
// write cumulative frequency table to output stream
for (f = 1; f < frequencyTableSize; f++)
{
//.........这里部分代码省略.........
示例10: setup_one_l3_interface
//L3 Interface Initialization
static bool setup_one_l3_interface(sai_vlan_id_t vlanid,
int port_count,
const sai_object_id_t *port_list,
const MacAddress mac,
const IpAddress ipaddr,
const IpAddress ipmask,
sai_object_id_t &rif_id)
{
LOGG(TEST_INFO, SETL3, "sai_vlan_api->create_vlan, create vlan %hu.\n", vlanid);
sai_status_t status = sai_vlan_api->create_vlan(vlanid);
if (status != SAI_STATUS_SUCCESS && status != SAI_STATUS_ITEM_ALREADY_EXISTS)
{
LOGG(TEST_ERR, SETL3, "fail to create vlan %hu. status=0x%x\n", vlanid, -status);
return false;
}
std::vector<sai_attribute_t> member_attrs;
sai_attribute_t member_attr;
sai_object_id_t vlan_member_id;
for (int i = 0; i < port_count; ++i)
{
member_attr.id = SAI_VLAN_MEMBER_ATTR_VLAN_ID;
member_attr.value.u16 = vlanid;
member_attrs.push_back(member_attr);
member_attr.id = SAI_VLAN_MEMBER_ATTR_PORT_ID;
member_attr.value.oid = port_list[i];
member_attrs.push_back(member_attr);
member_attr.id = SAI_VLAN_MEMBER_ATTR_TAGGING_MODE;
member_attr.value.s32 = SAI_VLAN_PORT_UNTAGGED;
member_attrs.push_back(member_attr);
LOGG(TEST_INFO, SETL3, "sai_vlan_api->create_vlan_member, with vlan %d.\n", vlanid);
status = sai_vlan_api->create_vlan_member(&vlan_member_id, member_attrs.size(), member_attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
LOGG(TEST_ERR, SETL3, "fail to create member vlan %hu. status=0x%x\n", vlanid, -status);
return false;
}
vlan_member_list.push_back(vlan_member_id);
}
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_PORT_VLAN_ID;
attr.value.u16 = vlanid;
for (int i = 0; i < port_count; ++i)
{
LOGG(TEST_INFO, SETL3, "sai_port_api->set_port_attribute SAI_PORT_ATTR_PORT_VLAN_ID %hu to port 0x%lx\n",
vlanid, port_list[i]);
status = sai_port_api->set_port_attribute(port_list[i], &attr);
if (status != SAI_STATUS_SUCCESS)
{
LOGG(TEST_ERR, SETL3, "fail to set port %lu untagged vlan %hu. status=0x%x\n", port_list[i], vlanid, -status);
return false;
}
}
// create router interface
std::vector<sai_attribute_t> rif_attrs;
sai_attribute_t rif_attr;
rif_attr.id = SAI_ROUTER_INTERFACE_ATTR_VIRTUAL_ROUTER_ID;
rif_attr.value.oid = g_vr_id;
rif_attrs.push_back(rif_attr);
rif_attr.id = SAI_ROUTER_INTERFACE_ATTR_TYPE;
rif_attr.value.s32 = SAI_ROUTER_INTERFACE_TYPE_VLAN;
rif_attrs.push_back(rif_attr);
rif_attr.id = SAI_ROUTER_INTERFACE_ATTR_SRC_MAC_ADDRESS;
memcpy(rif_attr.value.mac, mac.to_bytes(), sizeof(sai_mac_t));
rif_attrs.push_back(rif_attr);
rif_attr.id = SAI_ROUTER_INTERFACE_ATTR_VLAN_ID;
rif_attr.value.u16 = vlanid;
rif_attrs.push_back(rif_attr);
LOGG(TEST_INFO, SETL3, "sai_rif_api->create_router_interface\n");
status = sai_rif_api->create_router_interface(&rif_id, rif_attrs.size(), rif_attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
LOGG(TEST_ERR, SETL3, "fail to create router interface. status=0x%x\n", -status);
return false;
}
if (!SAI_OID_TYPE_CHECK(rif_id, SAI_OBJECT_TYPE_ROUTER_INTERFACE))
{
LOGG(TEST_ERR, SETL3, "router interface oid generated is not the right type\n");
return false;
}
LOGG(TEST_DEBUG, SETL3, "router_interface created, rif_id 0x%lx\n", rif_id);
//.........这里部分代码省略.........
示例11: basic_router_setup
//.........这里部分代码省略.........
LOGG(TEST_ERR, SETL3, "fail to set port 0x%lx admin state to UP: %d\n", port_list[i], -status);
return false;
}
attr.id = SAI_PORT_ATTR_FDB_LEARNING;
attr.value.s32 = SAI_PORT_LEARN_MODE_HW;
status = sai_port_api->set_port_attribute(port_list[i], &attr);
if (status != SAI_STATUS_SUCCESS)
{
LOGG(TEST_ERR, SETL3, "fail to set port 0x%lx learning mode to hw: %d\n", port_list[i], -status);
return false;
}
}
//one interface for each port
for (i = 0; i < g_testcount; i++)
{
g_intfAlias[i] = "et0_" + to_string(i + 1);
g_ipAddr[i] = IpAddress("10.10." + to_string(140 + i + 1) + "." + to_string(130));
g_ipMask[i] = IpAddress("255.255.255.252");
g_macAddr[i] = MacAddress("00:11:11:11:11:" + to_string(i + 1));
}
for (i = 0; i < g_testcount; i++)
{
LOGG(TEST_DEBUG, SETL3, "--- interface %s %s/%s %s ---\n",
g_intfAlias[i].c_str(),
g_ipAddr[i].to_string().c_str(),
g_ipMask[i].to_string().c_str(),
g_macAddr[i].to_string().c_str()
);
std::vector<sai_object_id_t> port_objlist;
long unsigned int vlanid;
sai_attribute_t attr;
std::vector<sai_attribute_t> attr_list;
//assuming interface is of PANEL_INTF
vlanid = PANEL_PORT_VLAN_START + i + 1;
port_objlist.push_back(port_list[i]);
if (!setup_one_l3_interface(vlanid, port_objlist.size(), port_objlist.data(),
g_macAddr[i], g_ipAddr[i], g_ipMask[i], g_rif_id[i]))
{
LOGG(TEST_ERR, SETL3, "fail to setup l3 interface for %s\n", g_intfAlias[i].c_str());
return false;
}
LOGG(TEST_DEBUG, SETL3, "setup_l3_interface for %s successfully\n",
g_intfAlias[i].c_str());
attr.id = SAI_HOSTIF_ATTR_TYPE;
attr.value.s32 = SAI_HOSTIF_TYPE_NETDEV;
attr_list.push_back(attr);
attr.id = SAI_HOSTIF_ATTR_RIF_OR_PORT_ID;
attr.value.oid = port_list[i];
attr_list.push_back(attr);
attr.id = SAI_HOSTIF_ATTR_NAME;
strncpy((char *)&attr.value.chardata, g_intfAlias[i].c_str(), HOSTIF_NAME_SIZE);
attr_list.push_back(attr);
LOGG(TEST_INFO, SETL3, "sai_hif_api->create_hostif name %s\n", g_intfAlias[i].c_str());
示例12: write
//cached call
bool DCDTrajectoryWriter::write(const std::vector<Vector3DBlock> &cachedCoords) {
//push out if sufficient
if( cachedCoords.size() > 0 ){
report << debug(1) <<"Writing DCD, multiple frames." << endr;
//original code modified for caching, index 0 must exist here
const unsigned int setcount = cachedCoords.size();
const unsigned int count = cachedCoords[0].size();//ccoords.size();
if (!reopen(count, setcount)) return false;
//loop over each set of coordinates
for( int i=0; i<setcount; i++){
Vector3DBlock ccoords = cachedCoords[i];
//original code
//const unsigned int count = ccoords.size();
//if (!reopen(count)) return false;
myX.resize(count);
myY.resize(count);
myZ.resize(count);
for (unsigned int i = 0; i < count; ++i) {
myX[i] = static_cast<float>(ccoords[i].c[0]);
myY[i] = static_cast<float>(ccoords[i].c[1]);
myZ[i] = static_cast<float>(ccoords[i].c[2]);
if (myIsLittleEndian != ISLITTLEENDIAN) {
swapBytes(myX[i]);
swapBytes(myY[i]);
swapBytes(myZ[i]);
}
}
int32 nAtoms = static_cast<int32>(count * 4);
if (myIsLittleEndian != ISLITTLEENDIAN) swapBytes(nAtoms);
file.write((char *)&nAtoms, sizeof(int32));
file.write((char *)&(myX[0]), count * sizeof(float4));
file.write((char *)&nAtoms, sizeof(int32));
file.write((char *)&nAtoms, sizeof(int32));
file.write((char *)&(myY[0]), count * sizeof(float4));
file.write((char *)&nAtoms, sizeof(int32));
file.write((char *)&nAtoms, sizeof(int32));
file.write((char *)&(myZ[0]), count * sizeof(float4));
file.write((char *)&nAtoms, sizeof(int32));
//close();
if( file.fail() ){
close();
return false;
}//end of coordinate save
}//end of loop
//close file once strored
close();
return true;//!file.fail();
}
}
示例13: trendCubeNames
CravaTrend::CravaTrend(Simbox * timeSimbox,
Simbox * timeCutSimbox,
ModelSettings * modelSettings,
bool & failed,
std::string & errTxt,
const InputFiles * inputFiles)
{
n_samples_ = 1000;
const std::vector<std::string> trend_cube_parameters = modelSettings->getTrendCubeParameters();
const std::vector<int> trend_cube_type = modelSettings->getTrendCubeType();
n_trend_cubes_ = static_cast<int>(trend_cube_parameters.size());
std::vector<std::string> trendCubeNames(n_trend_cubes_);
if(n_trend_cubes_ > 0) {
std::string errorText = "";
const int nx = timeSimbox->getnx();
const int ny = timeSimbox->getny();
const int nz = timeSimbox->getnz();
const int nxp = nx;
const int nyp = ny;
const int nzp = nz;
const int rnxp = 2*(nxp/2 + 1);
for(int grid_number=0; grid_number<n_trend_cubes_; grid_number++) {
FFTGrid * trend_cube = NULL;
const std::string log_name = "trend cube '"+trend_cube_parameters[grid_number]+"'";
if(trend_cube_type[grid_number] == ModelSettings::CUBE_FROM_FILE) {
trendCubeNames[grid_number] = inputFiles->getTrendCube(grid_number);
const SegyGeometry * dummy1 = NULL;
const TraceHeaderFormat * dummy2 = NULL;
const float offset = modelSettings->getSegyOffset(0); //Facies estimation only allowed for one time lapse
ModelGeneral::readGridFromFile(trendCubeNames[grid_number],
log_name,
offset,
trend_cube,
dummy1,
dummy2,
FFTGrid::PARAMETER,
timeSimbox,
timeCutSimbox,
modelSettings,
errorText,
true);
if(errorText != "") {
errorText += "Reading of file \'"+trendCubeNames[grid_number]+"\' failed\n";
errTxt += errorText;
failed = true;
}
}
else if(trend_cube_type[grid_number] == ModelSettings::STRATIGRAPHIC_DEPTH) {
LogKit::LogFormatted(LogKit::Low,"\nGenerating trend grid \'"+trend_cube_parameters[grid_number]+"\'\n");
trend_cube = ModelGeneral::createFFTGrid(nx, ny, nz, nxp, nyp, nzp, false);
trend_cube->createRealGrid();
trend_cube->setAccessMode(FFTGrid::WRITE);
for(int k=0; k<nzp; k++) {
for(int j=0; j<nyp; j++) {
for(int i=0; i<rnxp; i++) {
if(i < nx)
trend_cube->setRealValue(i, j, k, static_cast<float>(k));
else
trend_cube->setRealValue(i, j, k, 0);
}
}
}
trend_cube->endAccess();
}
else if(trend_cube_type[grid_number] == ModelSettings::TWT) {
LogKit::LogFormatted(LogKit::Low,"\nGenerating trend grid \'"+trend_cube_parameters[grid_number]+"\'\n");
trend_cube = ModelGeneral::createFFTGrid(nx, ny, nz, nxp, nyp, nzp, false);
trend_cube->createRealGrid();
trend_cube->setAccessMode(FFTGrid::WRITE);
for(int k=0; k<nzp; k++) {
for(int j=0; j<nyp; j++) {
for(int i=0; i<rnxp; i++) {
if(i < nx) {
float value = static_cast<float>(timeSimbox->getTop(i,j) + timeSimbox->getdz(i,j)*k);
trend_cube->setRealValue(i, j, k, value);
}
else
//.........这里部分代码省略.........
示例14: FuzzerDriver
int FuzzerDriver(const std::vector<std::string> &Args,
UserSuppliedFuzzer &USF) {
using namespace fuzzer;
assert(!Args.empty());
ProgName = new std::string(Args[0]);
ParseFlags(Args);
if (Flags.help) {
PrintHelp();
return 0;
}
if (Flags.jobs > 0 && Flags.workers == 0) {
Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
if (Flags.workers > 1)
Printf("Running %d workers\n", Flags.workers);
}
if (Flags.workers > 0 && Flags.jobs > 0)
return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
Fuzzer::FuzzingOptions Options;
Options.Verbosity = Flags.verbosity;
Options.MaxLen = Flags.max_len;
Options.UnitTimeoutSec = Flags.timeout;
Options.MaxTotalTimeSec = Flags.max_total_time;
Options.DoCrossOver = Flags.cross_over;
Options.MutateDepth = Flags.mutate_depth;
Options.ExitOnFirst = Flags.exit_on_first;
Options.UseCounters = Flags.use_counters;
Options.UseIndirCalls = Flags.use_indir_calls;
Options.UseTraces = Flags.use_traces;
Options.ShuffleAtStartUp = Flags.shuffle;
Options.PreferSmallDuringInitialShuffle =
Flags.prefer_small_during_initial_shuffle;
Options.Reload = Flags.reload;
Options.OnlyASCII = Flags.only_ascii;
Options.TBMDepth = Flags.tbm_depth;
Options.TBMWidth = Flags.tbm_width;
if (Flags.runs >= 0)
Options.MaxNumberOfRuns = Flags.runs;
if (!Inputs->empty())
Options.OutputCorpus = (*Inputs)[0];
if (Flags.sync_command)
Options.SyncCommand = Flags.sync_command;
Options.SyncTimeout = Flags.sync_timeout;
Options.ReportSlowUnits = Flags.report_slow_units;
if (Flags.artifact_prefix)
Options.ArtifactPrefix = Flags.artifact_prefix;
if (Flags.dict)
if (!ParseDictionaryFile(FileToString(Flags.dict), &Options.Dictionary))
return 1;
if (Flags.verbosity > 0 && !Options.Dictionary.empty())
Printf("Dictionary: %zd entries\n", Options.Dictionary.size());
Options.SaveArtifacts = !Flags.test_single_input;
Fuzzer F(USF, Options);
// Timer
if (Flags.timeout > 0)
SetTimer(Flags.timeout / 2 + 1);
if (Flags.test_single_input)
return RunOneTest(&F, Flags.test_single_input);
if (Flags.merge) {
F.Merge(*Inputs);
exit(0);
}
unsigned Seed = Flags.seed;
// Initialize Seed.
if (Seed == 0)
Seed = time(0) * 10000 + getpid();
if (Flags.verbosity)
Printf("Seed: %u\n", Seed);
USF.GetRand().ResetSeed(Seed);
F.RereadOutputCorpus();
for (auto &inp : *Inputs)
if (inp != Options.OutputCorpus)
F.ReadDir(inp, nullptr);
if (F.CorpusSize() == 0)
F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
F.ShuffleAndMinimize();
if (Flags.save_minimized_corpus)
F.SaveCorpus();
F.Loop();
if (Flags.verbosity)
Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
F.secondsSinceProcessStartUp());
exit(0); // Don't let F destroy itself.
}
示例15: termcrit
/// Perform tracking
std::vector<cv::DMatch> MatcherOpenCV::performTracking(cv::Mat prevImg,
cv::Mat img, std::vector<cv::Point2f> &prevFeatures,
std::vector<cv::Point2f> &features,
std::vector<cv::KeyPoint>& prevKeyPoints,
std::vector<cv::KeyPoint>& keyPoints,
std::vector<double>& prevDetDists,
std::vector<double>& detDists) {
// Some needed variables
std::vector<uchar> status;
std::vector<float> err;
cv::TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS,
matcherParameters.OpenCVParams.maxIter,
matcherParameters.OpenCVParams.eps);
// Setting OpenCV flags based on our parameters
int trackingFlags = 0;
if (matcherParameters.OpenCVParams.useInitialFlow > 0)
trackingFlags = cv::OPTFLOW_USE_INITIAL_FLOW;
if (matcherParameters.OpenCVParams.trackingErrorType > 0)
trackingFlags |= cv::OPTFLOW_LK_GET_MIN_EIGENVALS;
// Calculating the movement of features
cv::calcOpticalFlowPyrLK(prevImg, img, prevFeatures, features, status,
err,
cv::Size(matcherParameters.OpenCVParams.winSize,
matcherParameters.OpenCVParams.winSize),
matcherParameters.OpenCVParams.maxLevels, termcrit,
trackingFlags,
matcherParameters.OpenCVParams.trackingMinEigThreshold);
keyPoints = prevKeyPoints;
//copy new positions to keyPoints
for(std::vector<cv::Point2f>::size_type i = 0; i < features.size(); ++i){
keyPoints[i].pt = features[i];
}
detDists = prevDetDists;
// This parts removes additional features for which we observed an error above preset threshold
int errSize = (int)err.size();
for (int i = 0; i < errSize; i++) {
if (err[i] > matcherParameters.OpenCVParams.trackingErrorThreshold)
status[i] = 0;
}
// Removing features if they are too close to each other - the feature to remove is based on an error from tracking
std::set<int> featuresToRemove;
for (std::vector<cv::Point2f>::size_type i = 0; i < features.size(); i++) {
for (std::vector<cv::Point2f>::size_type j = i + 1; j < features.size(); j++) {
if (cv::norm(features[i] - features[j]) < matcherParameters.OpenCVParams.minimalReprojDistanceNewTrackingFeatures) {
if ( err[i] > err[j])
featuresToRemove.insert((int)i);
else
featuresToRemove.insert((int)j);
}
}
}
// Returning result in matching-compatible format
int i = 0, j = 0;
std::vector<cv::DMatch> matches;
std::vector<cv::Point2f>::iterator itFeatures = features.begin();
std::vector<cv::KeyPoint>::iterator itKeyPoints = keyPoints.begin();
std::vector<double>::iterator itDetDists = detDists.begin();
std::vector<uchar>::iterator it = status.begin();
for (; it != status.end(); ++it, i++) {
// Tracking succeed and the feature is not too close to feature with more precise tracking
if (*it != 0 && featuresToRemove.find(i) == featuresToRemove.end()) {
matches.push_back(cv::DMatch(i, j, 0));
j++;
++itFeatures;
++itKeyPoints;
++itDetDists;
}
// Tracking failed -- we remove those features
else {
itFeatures = features.erase(itFeatures);
itKeyPoints = keyPoints.erase(itKeyPoints);
itDetDists = detDists.erase(itDetDists);
}
}
if (matcherParameters.verbose > 0)
std::cout << "MatcherOpenCV::performTracking -- features tracked "
<< matches.size() << " ("
<< (float)matches.size() * 100.0 / (float)prevFeatures.size() << "%)"
<< std::endl;
// Return result
return matches;
}