Exemple #1
0
/** Creates a new  output X array  according to specific boundary defnitions
 *
 *  @param params ::    rebin parameters input [x_1, delta_1,x_2, ...
 *,x_n-1,delta_n-1,x_n)
 *  @param xold ::      the current x array
 *  @param xnew ::      new output workspace x array
 *  @param xoldIndex :: indeces of new x in XValues_old
 *  @return The number of bin boundaries in the new X array
 **/
int Regroup::newAxis(const std::vector<double> &params,
                     const std::vector<double> &xold, std::vector<double> &xnew,
                     std::vector<int> &xoldIndex) {
  double xcurr, xs;
  int ibound(2), istep(1), inew(0);
  int ibounds = static_cast<int>(
      params.size()); // highest index in params array containing a bin boundary
  int isteps = ibounds - 1; // highest index in params array containing a step

  xcurr = params[0];
  auto iup = std::find_if(xold.cbegin(), xold.cend(),
                          std::bind2nd(std::greater_equal<double>(), xcurr));
  if (iup != xold.end()) {
    xcurr = *iup;
    xnew.push_back(xcurr);
    xoldIndex.push_back(inew);
    inew++;
  } else
    return 0;

  while ((ibound <= ibounds) && (istep <= isteps)) {
    // if step is negative then it is logarithmic step
    if (params[istep] >= 0.0)
      xs = params[istep];
    else
      xs = xcurr * fabs(params[istep]);

    // xcurr += xs;

    // find nearest x_i that is >= xcurr
    iup = std::find_if(xold.begin(), xold.end(),
                       std::bind2nd(std::greater_equal<double>(), xcurr + xs));
    if (iup != xold.end()) {
      if (*iup <= params[ibound]) {
        xcurr = *iup;
        xnew.push_back(xcurr);
        xoldIndex.push_back(inew);
        inew++;
      } else {
        ibound += 2;
        istep += 2;
      }
    } else
      return inew;
  }
  // returns length of new x array or -1 if failure
  return inew;
  // return( (ibound == ibounds) && (istep == isteps) ? inew : -1 );
}
Exemple #2
0
/// Assigns symmetry operations, throws std::invalid_argument if vector is
/// empty.
void Group::setSymmetryOperations(
    const std::vector<SymmetryOperation> &symmetryOperations) {
  if (symmetryOperations.empty()) {
    throw std::invalid_argument("Group needs at least one element.");
  }

  m_operationSet.clear();
  std::transform(symmetryOperations.cbegin(), symmetryOperations.cend(),
                 std::inserter(m_operationSet, m_operationSet.begin()),
                 &getUnitCellIntervalOperation);

  m_allOperations = std::vector<SymmetryOperation>(m_operationSet.begin(),
                                                   m_operationSet.end());
  m_axisSystem = getCoordinateSystemFromOperations(m_allOperations);
}
Exemple #3
0
double average_dbl(const std::vector<double> & v)
{
	double res = 0.0;
	#if 0
	for(auto it = v.cbegin(); it != v.cend(); ++it)
	{
		res += *it;
	}
	#endif
	
	for(double e : v)
		res += e;
	
	return res / v.size();
}
void QEvalTmpResultCore::addEdgeConstraint(size_t lArgId, size_t rArgId, const std::vector<std::pair<idx_t, idx_t>>& edges)
{
	assert(nodesLoaded[lArgId]);
	assert(nodesLoaded[rArgId]);

	assert(lArgId != rArgId);
	bool swap = lArgId > rArgId;

	std::vector<std::pair<idx_t, idx_t> > swappedEdge;
	if (swap) {
		swappedEdge.reserve(edges.size());
		std::vector<std::pair<idx_t, idx_t> >::const_iterator edgeIter;
		for (edgeIter = edges.cbegin(); edgeIter != edges.cend(); edgeIter++) {
			swappedEdge.push_back(std::make_pair((*edgeIter).second, (*edgeIter).first));
		}
	}
	else {
		swappedEdge = edges;
	}

	size_t smallNodeId, largeNodeId;
	if (swap) {
		smallNodeId = rArgId;
		largeNodeId = lArgId;
	}
	else {
		smallNodeId = lArgId;
		largeNodeId = rArgId;
	}

	size_t edgeId = matIdMapper.twoDToOneDNoBoundCheck(smallNodeId, largeNodeId);

	// sort, unique
	std::sort(swappedEdge.begin(), swappedEdge.end());
	auto last = std::unique(swappedEdge.begin(), swappedEdge.end());
	swappedEdge.erase(last, swappedEdge.end());

	// first filtered by node
	filterEdgeListByNodeSet(swappedEdge, true, nodeHashSets[smallNodeId]);
	filterEdgeListByNodeSet(swappedEdge, false, nodeHashSets[largeNodeId]);

	// second filtered by edge
	if (!edgeLists[edgeId].empty()) {
		filterSortedEdgeListBySortedUniqEdgeList(swappedEdge, edgeLists[edgeId]);
	}

	setEdgeInterTriggerUpdate(smallNodeId, largeNodeId, swappedEdge);
}
void GridGameListView::populateList(const std::vector<FileData*>& files)
{
	mGrid.clear();
	mHeaderText.setText(mRoot->getSystem()->getFullName());
	if (files.size() > 0)
	{
		for (auto it = files.cbegin(); it != files.cend(); it++)
		{
			mGrid.add((*it)->getName(), (*it)->getThumbnailPath(), *it);
		}
	}
	else
	{
		addPlaceholder();
	}
}
Exemple #6
0
  GraphType Create(const std::vector<VertexName>& names) {
    ContactGraph graph;
    auto name_iter=names.cbegin();
    for (; name_iter!=names.cend(); ++name_iter) {
      graph.add_vertex(name_iter);
    }

    auto left=boost::vertices(n);
    for ( ; left.first!=left.second; ++left.first) {
      auto right=left.first;
      for ( ++right; right!=left.second; ++right) {
        boost::add_edge(graph, left, right);
      }
    }
    return GraphType;
  }
bool CStakeInfo::IsShapePoint(const DCoord& coord, const std::vector<DCoord>& vecCoords, unsigned int& nPos)
{
	auto itCoords = vecCoords.cbegin();
	nPos = 0;
	for (itCoords; itCoords != vecCoords.cend(); ++itCoords)
	{
		if (Equal(coord, *itCoords))
		{
			return true;
		}
		++nPos;
	}

	nPos = -1;
	return false;
}
Exemple #8
0
 // Just checks whether style can be created without constructing actual style.
 void check(const std::vector<Tag>& tags, const FilterMap& filters)
 {
     FilterMap::const_iterator iter = filters.find(levelOfDetails_);
     if (iter != filters.end()) {
         for (const Filter& filter : iter->second) {
             bool isMatched = true;
             for (auto it = filter.conditions.cbegin(); it != filter.conditions.cend() && isMatched; ++it) {
                 isMatched &= match_tags(tags.cbegin(), tags.cend(), *it);
             }
             if (isMatched) {
                 canBuild_ = true;
                 return;
             }
         }
     }
 }
Exemple #9
0
void cnpy::npy_save_data(const std::string& fname,
                         const unsigned char* data, const Type dtype,
                         const size_t elemSize, const std::vector<size_t>& shape,
                         const char mode)
{
    FILE* fp = NULL;

    if(mode == 'a')
        fp = fopen(fname.c_str(),"r+b");

    if(fp)
    {
        //file exists. we need to append to it. read the header, modify the array size
        size_t word_size;
        std::vector<size_t> tmp_shape;
        bool fortran_order;
        parse_npy_header(fp, word_size, tmp_shape, fortran_order);
        assert(!fortran_order);

        if(word_size != elemSize)
            throw std::runtime_error("Attempting to append misdimensioned data to "+fname);
        if(tmp_shape.size() != shape.size())
            throw std::runtime_error("Attempting to append misdimensioned data to "+fname);

        for(int i=1; i<shape.size(); ++i)
        {
            if(shape[i] != tmp_shape[i])
                throw std::runtime_error("Attempting to append misshaped data to "+fname);
        }
        tmp_shape[0] += shape[0];

        fseek(fp, 0, SEEK_SET);
        std::vector<char> header = create_npy_header(dtype, elemSize, tmp_shape);
        fwrite(header.data(), sizeof(char), header.size(), fp);
        fseek(fp, 0, SEEK_END);
    }
    else
    {
        fp = fopen(fname.c_str(),"wb");
        std::vector<char> header = create_npy_header(dtype, elemSize, shape);
        fwrite(header.data(), sizeof(char), header.size(), fp);
    }

    size_t nels = std::accumulate(shape.cbegin(), shape.cend(), 1U, std::multiplies<size_t>());
    std::fwrite(data, elemSize, nels, fp);
    fclose(fp);
}
Exemple #10
0
/**
 * LeetCode 26  Remove Duplicates from Sorted Array 31.5% Easy
 * Given a sorted array, remove the duplicates in place such that each element
 *appear only once
 * and return the new length.
 * Do not allocate extra space for another array, you must do this in place with
 *constant memory.
 * For example,
 * Given input array A = [1,1,2],
 *
 * Your function should return length = 2, and A is now [1,2].
 */
int ArrayQuiz::removeDuplicates(std::vector<int> &A) {
    int n = A.size();
    if (n == 0) return 0;
    int index = 0;
    for (int i = 0; i < n; i++) {

        if (A[index] == A[i]) { continue; }
        index++;
        A[index] = A[i];
        for_each(A.cbegin(), A.cend(), [&](int i) { cout << i << ", "; });
        cout << endl;
    }
    // remove element from index+1 to end
    A.erase(A.begin() + index + 1, A.end());
    return index + 1;
    //	return length;
}
Exemple #11
0
GLuint prepareProgram(const std::vector<GLuint>& shaders, bool *errorFlagPtr) {
    *errorFlagPtr = false;

    GLuint programId = glCreateProgram();
    for(auto it = shaders.cbegin(); it != shaders.cend(); ++it) {
        glAttachShader(programId, *it);
    }
    glLinkProgram(programId);

    *errorFlagPtr = checkProgramLinkStatus(programId);
    if(*errorFlagPtr) {
        glDeleteProgram(programId);
        return 0;
    }

    return programId;
}
Exemple #12
0
boost::optional<ValidatorToken>
ValidatorToken::make_ValidatorToken(std::vector<std::string> const& tokenBlob)
{
    try
    {
        std::string tokenStr;
        tokenStr.reserve (
            std::accumulate (tokenBlob.cbegin(), tokenBlob.cend(), std::size_t(0),
                [] (std::size_t init, std::string const& s)
                {
                    return init + s.size();
                }));

        for (auto const& line : tokenBlob)
            tokenStr += beast::rfc2616::trim(line);

        tokenStr = beast::detail::base64_decode(tokenStr);

        Json::Reader r;
        Json::Value token;
        if (! r.parse (tokenStr, token))
            return boost::none;

        if (token.isMember("manifest") && token["manifest"].isString() &&
            token.isMember("validation_secret_key") &&
            token["validation_secret_key"].isString())
        {
            auto const ret = strUnHex (token["validation_secret_key"].asString());
            if (! ret.second || ! ret.first.size ())
                return boost::none;

            return ValidatorToken(
                token["manifest"].asString(),
                SecretKey(Slice{ret.first.data(), ret.first.size()}));
        }
        else
        {
            return boost::none;
        }
    }
    catch (std::exception const&)
    {
        return boost::none;
    }
}
Exemple #13
0
std::vector<uint8_t>
Node::get_parameter_types(
  const std::vector<std::string> & names) const
{
  std::lock_guard<std::mutex> lock(mutex_);
  std::vector<uint8_t> results;
  for (auto & kv : parameters_) {
    if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
      return name == kv.first;
    }))
    {
      results.push_back(kv.second.get_type());
    } else {
      results.push_back(rcl_interfaces::msg::ParameterType::PARAMETER_NOT_SET);
    }
  }
  return results;
}
Exemple #14
0
TaskSolveTravelled::TaskSolveTravelled(const std::vector<OrderedTaskPoint *> &tps,
                                       const unsigned activeTaskPoint,
                                       const AircraftState &_aircraft,
                                       const GlideSettings &settings,
                                       const GlidePolar &gp,
                                       const fixed _xmin,
                                       const fixed _xmax)
  :ZeroFinder(_xmin, _xmax, fixed(TOLERANCE_CRUISE_EFFICIENCY)),
   aircraft(_aircraft),
   tm(tps.cbegin(), activeTaskPoint, settings, gp)
{
  dt = aircraft.time-tps[0]->GetEnteredState().time;
  if (positive(dt)) {
    inv_dt = fixed(1)/dt;
  } else {
    inv_dt = fixed(0); // error!
  }
}
Exemple #15
0
TaskMinTarget::TaskMinTarget(const std::vector<OrderedTaskPoint*>& tps,
                             const unsigned activeTaskPoint,
                             const AircraftState &_aircraft,
                             const GlideSettings &settings,
                             const GlidePolar &_gp,
                             const fixed _t_remaining,
                             StartPoint *_ts)
  :ZeroFinder(fixed(0), fixed(1), fixed(TOLERANCE_MIN_TARGET)),
   tm(tps.cbegin(), tps.cend(), activeTaskPoint, settings, _gp,
      /* ignore the travel to the start point */
      false),
   aircraft(_aircraft),
   t_remaining(_t_remaining),
   tp_start(_ts),
   force_current(false)
{

}
void QEvalTmpResultCore::filterSortedEdgeListBySortedUniqEdgeList(std::vector<std::pair<idx_t, idx_t>>& edgeList, const std::vector<std::pair<idx_t, idx_t>>& refEdge)
{
	std::vector<std::pair<idx_t, idx_t> >::const_iterator edgeIter = edgeList.cbegin(), refEdgeIter = refEdge.cbegin();
	std::vector<std::pair<idx_t, idx_t> >::iterator edgewIter = edgeList.begin();
	while (edgeIter != edgeList.cend() && refEdgeIter != refEdge.cend()) {
		if (*edgeIter < *refEdgeIter) {
			edgeIter++;
		}
		else if (*edgeIter == *refEdgeIter) {
			*edgewIter = *edgeIter;
			edgewIter++, edgeIter++;
		}
		else {
			refEdgeIter++;
		}
	}
	edgeList.erase(edgewIter, edgeList.end());
}
Exemple #17
0
TaskOptTarget::TaskOptTarget(const std::vector<OrderedTaskPoint*>& tps,
                             const unsigned activeTaskPoint,
                             const AircraftState &_aircraft,
                             const GlideSettings &settings,
                             const GlidePolar &_gp,
                             AATPoint &_tp_current,
                             const TaskProjection &projection,
                             StartPoint *_ts)
  :ZeroFinder(fixed(0.02), fixed(0.98), fixed(TOLERANCE_OPT_TARGET)),
   tm(tps.cbegin(), tps.cend(), activeTaskPoint, settings, _gp,
      /* ignore the travel to the start point */
      false),
   aircraft(_aircraft),
   tp_start(_ts),
   tp_current(_tp_current),
   iso(_tp_current, projection)
{
}
Exemple #18
0
typename std::vector<T>::const_iterator
  binSearch(const std::vector<T>& large, T val) {
  auto it = large.cbegin();
  int64_t beg = 0;
  int64_t end = large.size()-1;
  while(beg<=end)
  {
    auto mid = (beg+end)/2;
    if (large[mid] < val) {
      beg = mid+1;
    } else if (large[mid] == val) {
      return it+mid;
    } else {
      end = mid-1;
    }
  }
  return large.cend();
}
Exemple #19
0
CLWContext CLWContext::Create(std::vector<CLWDevice> const& devices, cl_context_properties* props)
{
    std::vector<cl_device_id> deviceIds;
    std::for_each(devices.cbegin(), devices.cend(),
                  [&deviceIds](CLWDevice const& device)
                  {
                      deviceIds.push_back(device);
                  });
    cl_int status = CL_SUCCESS;
    cl_context ctx = clCreateContext(props, static_cast<cl_int>(deviceIds.size()), &deviceIds[0], nullptr, nullptr, &status);
    ThrowIf(status != CL_SUCCESS, status, "clCreateContext failed");
    
    CLWContext context(ctx, devices);
    
    clReleaseContext(ctx);
    
    return context;
}
Exemple #20
0
    void MinTorqueError::calculate(const std::vector<Result>& results) {
        //reset f
        f_ = 0;

        using TrialDataIt = std::vector<TrialData>::const_iterator;
        using ResultIt = std::vector<Result>::const_iterator;

        class TrialCost {
        public:
            vector<double> torqueError;
            double penalty;
            TrialCost(size_t nDofs) :
                torqueError(nDofs, 0.),
                penalty(0.) {}
            ;
        };

        std::vector<TrialCost> trialCosts;
        auto tIt(trials_.cbegin());
        auto rIt(results.cbegin());
        for (tIt; tIt != trials_.cend(); ++tIt, ++rIt) {
            auto trialIndex(std::distance(trials_.cbegin(), tIt));
            auto diff(tIt->torqueData - rIt->torques);
            auto squaredDiff(diff*diff);

            TrialCost trialCost(tIt->noDoF);
            for (size_t r(0); r < squaredDiff.getNRows(); ++r)
                for (auto& c : dofsToCalibrateIdx_.at(trialIndex))
                    trialCost.torqueError.at(c) += squaredDiff.at(r, c);

            for (size_t r(0); r < rIt->penalties.getNRows(); ++r)
                for (size_t c(0); c < rIt->penalties.getNColumns(); ++c)
                    trialCost.penalty += rIt->penalties.at(r, c);

            trialCosts.emplace_back(trialCost);
        }


        for (size_t trialIndex(0); trialIndex < trials_.size(); ++trialIndex) {
            for (auto& dofIdx : dofsToCalibrateIdx_.at(trialIndex))
                f_ += (trialCosts.at(trialIndex).torqueError.at(dofIdx) / torqueVariance_.at(trialIndex).at(dofIdx) +
                trialCosts.at(trialIndex).penalty) / results.at(trialIndex).torques.getNRows();
        }
    }
Exemple #21
0
void pcnn::fast_linking(const std::vector<double> & feeding, std::vector<double> & linking, std::vector<double> & output) {
	std::vector<double> previous_outputs(output.cbegin(), output.cend());
	
	bool previous_output_change = true;
	bool current_output_change = false;
	
	while (previous_output_change) {
		for (unsigned int index = 0; index < size(); index++) {
			pcnn_oscillator & current_oscillator = m_oscillators[index];

			std::vector<unsigned int> neighbors;
			get_neighbors(index, neighbors);

			double linking_influence = 0.0;

			for (std::vector<unsigned int>::const_iterator iter = neighbors.begin(); iter != neighbors.end(); iter++) {
				linking_influence += previous_outputs[(*iter)] * m_params.W;
			}

			linking_influence *= m_params.VL;
			linking[index] = linking_influence;

			double internal_activity = feeding[index] * (1.0 + m_params.B * linking[index]);
			if (internal_activity > current_oscillator.threshold) {
				output[index] = OUTPUT_ACTIVE_STATE;
			}
			else {
				output[index] = OUTPUT_INACTIVE_STATE;
			}

			if (output[index] != previous_outputs[index]) {
				current_output_change = true;
			}
		}

		/* check for changes for avoiding useless operation copy */
		if (current_output_change) {
			std::copy(output.begin(), output.end(), previous_outputs.begin());
		}

		previous_output_change = current_output_change;
		current_output_change = false;
	}
}
Exemple #22
0
void QTreeValidator::determineArgIdxType(idx_t & idx, ArgType & type, const std::string & input, const std::vector<std::string>& decSynList, const std::vector<std::string>& implList)
{
	if (!implList.empty() && std::find(implList.cbegin(), implList.cend(), input) != implList.cend()) {
		idx = ARG_IDX_NOT_SPECIFIED;
		type = ArgType::IMPLICIT;
	}
	else {
		idx_t tmpIdx;
		tmpIdx = getVarArgIdx(decSynList, input);
		if (tmpIdx != ARG_IDX_NOT_FOUND) {
			idx = tmpIdx;
			type = ArgType::DECVAR;
		}
		else {
			idx = ARG_IDX_NOT_SPECIFIED;
			type = ArgType::NOT_SPECIFIED;
		}
	}
}
Exemple #23
0
std::vector<rcl_interfaces::msg::ParameterDescriptor>
Node::describe_parameters(
  const std::vector<std::string> & names) const
{
  std::lock_guard<std::mutex> lock(mutex_);
  std::vector<rcl_interfaces::msg::ParameterDescriptor> results;
  for (auto & kv : parameters_) {
    if (std::any_of(names.cbegin(), names.cend(), [&kv](const std::string & name) {
      return name == kv.first;
    }))
    {
      rcl_interfaces::msg::ParameterDescriptor parameter_descriptor;
      parameter_descriptor.name = kv.first;
      parameter_descriptor.type = kv.second.get_type();
      results.push_back(parameter_descriptor);
    }
  }
  return results;
}
void CGitBlameLogList::GetParentNumbers(GitRevLoglist* pRev, const std::vector<CTGitPath>& paths, std::set<int>& parentNos)
{
	if (pRev->m_ParentHash.empty())
	{
		if (pRev->GetParentFromHash(pRev->m_CommitHash))
			MessageBox(pRev->GetLastErr(), _T("TortoiseGit"), MB_ICONERROR);
	}

	GIT_REV_LIST allParentHash;
	CGitLogListBase::GetParentHashes(pRev, allParentHash);

	try
	{
		const CTGitPathList& files = pRev->GetFiles(nullptr);
		for (int j=0, j_size = files.GetCount(); j < j_size; ++j)
		{
			const CTGitPath &file =  files[j];
			for (auto it=paths.cbegin(); it != paths.cend(); ++it)
			{
				const CTGitPath& path = *it;
				if (file.IsEquivalentTo(path))
				{
					if (!(file.m_ParentNo & MERGE_MASK))
					{
						int action = file.m_Action;
						// ignore (action & CTGitPath::LOGACTIONS_ADDED), as then there is nothing to blame/diff
						// ignore (action & CTGitPath::LOGACTIONS_DELETED), should never happen as the file must exist
						if (action & (CTGitPath::LOGACTIONS_MODIFIED | CTGitPath::LOGACTIONS_REPLACED))
						{
							int parentNo = file.m_ParentNo & PARENT_MASK;
							if (parentNo >= 0 && (size_t)parentNo < pRev->m_ParentHash.size())
								parentNos.insert(parentNo);
						}
					}
				}
			}
		}
	}
	catch (const char* msg)
	{
		MessageBox(_T("Could not get files of parents.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_ICONERROR);
	}
}
Exemple #25
0
std::string String_from_vector(const std::vector<uint8_t>& vec)
{
    std::string str;

    for(auto iter = vec.cbegin(); iter != vec.cend(); ++iter)
    {
        if((*iter != 0) && (*iter < 128))
        {
            str.push_back(*iter);
        }
        else
        {
            break;
        }
    }

    return str;

}
Exemple #26
0
std::string FormattedMessageLoader::GetFormattedMessage(
    IErrorReporter& reporter,
    DWORD messageId,
    std::vector<std::wstring> const& arguments)
{
    this->RequireValid();
    std::vector<DWORD_PTR> argumentPtrs;
    argumentPtrs.reserve(arguments.size());
    std::transform(arguments.cbegin(), arguments.cend(), std::back_inserter(argumentPtrs),
        [](std::wstring const& str) { return reinterpret_cast<DWORD_PTR>(str.c_str()); });

    auto argPtr = reinterpret_cast<va_list*>(argumentPtrs.data());
    if (arguments.empty())
    {
        argPtr = nullptr;
    }

    return FormatMessageU(reporter, this->hModule, messageId, argPtr);
}
LocalToGlobalIndexMap::LocalToGlobalIndexMap(
    std::vector<MeshLib::MeshSubsets*> const& mesh_subsets,
    std::vector<MeshLib::Element const*> const& elements,
    AssemblerLib::MeshComponentMap&& mesh_component_map,
    AssemblerLib::ComponentOrder const order)
    : _mesh_subsets(mesh_subsets), _mesh_component_map(std::move(mesh_component_map))
{
    // For all MeshSubsets and each of their MeshSubset's and each element
    // of that MeshSubset save a line of global indices.
    for (MeshLib::MeshSubsets const* const mss : _mesh_subsets)
    {
        for (MeshLib::MeshSubset const* const ms : *mss)
        {
            std::size_t const mesh_id = ms->getMeshID();

            findGlobalIndices(elements.cbegin(), elements.cend(), mesh_id, order);
        }
    }
}
Exemple #28
0
void cnpy::npz_save_data(const std::string& zipname, const std::string& name,
                         const unsigned char* data, const cnpy::Type dtype,
                         const size_t elemSize, const std::vector<size_t>& shape,
                         const char mode)
{
    //first, append a .npy to the fname
    std::string fname(name);
    fname += ".npy";

    if(mode=='w' && std::ifstream(zipname).is_open())
    {
        // Remove the old file if present
        if(std::remove(zipname.c_str())!=0)
            throw std::runtime_error("Unable to overwrite "+zipname);
    }

    Handler<struct zip> zip = zip_open(zipname.c_str(), ZIP_CREATE, nullptr);
    if(zip.handle()==nullptr)
        throw std::runtime_error("Error opening npz file "+zipname);

    // Remove the old array if present
    int nameLookup = zip_name_locate(zip.handle(), fname.c_str(), 0);
    if(nameLookup>=0 && zip_delete(zip.handle(), nameLookup)!=0)
        throw std::runtime_error("Unable to overwrite "+name+" array");

    std::vector<char> header = create_npy_header(dtype, elemSize, shape);

    const int dataSize = std::accumulate(shape.cbegin(), shape.cend(), elemSize, std::multiplies<size_t>());
    ZipSourceCallbackData cbData(header, data, dataSize);

    Handler<struct zip_source> zipSource = zip_source_function(zip.handle(), zipSourceCallback, &cbData);
    if(zipSource.handle()==nullptr)
        throw std::runtime_error("Error creating "+name+" array");

    zip_int64_t fid = zip_add(zip.handle(), fname.c_str(), zipSource.handle());
    if(fid<0)
    {
        zip_source_free(zipSource.handle());
        throw std::runtime_error("Error creating "+name+" array");
    }

    zip.close();
}
void vappend(std::vector<std::string> &v, const std::string &s, char sep = ' ')
{
    if (s.empty())
        return;

    std::istringstream stream(s);
    std::string substr;

    while (std::getline(stream, substr, sep))
    {
        if (substr.empty())
            continue;

        if (std::find(v.cbegin(), v.cend(), substr) != v.cend())
            continue;

        v.push_back(substr);
    }
}
Exemple #30
0
 // Builds style object. More expensive to call than check.
 void build(const std::vector<Tag>& tags, const FilterMap& filters)
 {
     FilterMap::const_iterator iter = filters.find(levelOfDetails_);
     if (iter != filters.end()) {
         for (const Filter &filter : iter->second) {
             bool isMatched = true;
             for (auto it = filter.conditions.cbegin(); it != filter.conditions.cend() && isMatched; ++it) {
                 isMatched &= match_tags(tags.cbegin(), tags.cend(), *it);
             }
             // merge declarations to style
             if (isMatched) {
                 canBuild_ = true;
                 for (const auto &d : filter.declarations) {
                     style_.put(d.second);
                 }
             }
         }
     }
 }