C++

1 program Added 2025-10-22T17:02:34Z Model: x-ai/grok-4-fastTemp: 0.4 Evidence Report issue View issues
Aliases: CPP
Provenance: commit 9dae8d38f7 · authored 2025-10-22T19:02:35+02:00 · model x-ai/grok-4-fast

Sources mentioning this language

8 sources · pl_id: pl/cpp
LLM (this repo) · 1LinguistPygmentsWikipediaEsolangHyperpolyglotRosettacodeWikidata · Q2407

Wikipedia infobox

Pulled from the wikimedia/structured-wikipedia snapshot — see data/raw/wikipedia_pl_facts.*.jsonl and pl_fact.csv for the long-table provenance.

Paradigmsmulti-paradigm: procedural · imperative · functional · object-oriented · generic · modular · reflective · design by contract
Typingstatic, strong, nominative, partially inferred
Designed byISO/IEC JTC 1 (Joint Technical Committee 1) / SC 22 (Subcommittee 22) / WG 21 (Working Group 21) · Bjarne Stroustrup
First appeared1985
Influenced byAda · ALGOL 68 · BCPL · C · CLU · F# · ML · Mesa · Modula-2 · Simula · Smalltalk
Homepagehttps://isocpp.org/

Extensions claimed by this language

44 claims. Each row is one upstream assertion with its strength. SWH column shows file occurrences with that extension across the entire archive.
ExtensionSourceStrengthSWH
.cwikidataprimary157.9M files
.c++wikidataprimary
.ccwikidataprimary30.8M files
.cpplinguistprimary215.9M files
.cpppygmentsprimary215.9M files
.cppwikidataprimary215.9M files
.cxxwikidataprimary6.9M files
.hwikidataprimary215.7M files
.h++wikidataprimary
.hhwikidataprimary3.9M files
.hppwikidataprimary32.3M files
.hxxwikidataprimary2.0M files
.cpygmentssecondary157.9M files
.c++linguistsecondary
.c++pygmentssecondary
.cclinguistsecondary30.8M files
.ccpygmentssecondary30.8M files
.cplinguistsecondary84.2K files
.cppygmentssecondary84.2K files
.cppmlinguistsecondary8.9K files
.cxxlinguistsecondary6.9M files
.cxxpygmentssecondary6.9M files
.hlinguistsecondary215.7M files
.hpygmentssecondary215.7M files
.h++linguistsecondary
.h++pygmentssecondary
.hhlinguistsecondary3.9M files
.hhpygmentssecondary3.9M files
.hpplinguistsecondary32.3M files
.hpppygmentssecondary32.3M files
.hxxlinguistsecondary2.0M files
.hxxpygmentssecondary2.0M files
.inclinguistsecondary6.3M files
.inllinguistsecondary742.4K files
.inolinguistsecondary4.4M files
.ipplinguistsecondary163.4K files
.ixxlinguistsecondary72.1K files
.relinguistsecondary545.7K files
.tcclinguistsecondary139.2K files
.tpplinguistsecondary141.7K files
.tpppygmentssecondary141.7K files
.txxlinguistsecondary97.0K files
.hmanual_review:achermproposed215.7M files
.ixxwikipediaproposed72.1K files

Related languages

C++/CLI (0.37)CUDA C++ (0.33)Cpp2 (0.21)CC++ (0.19)Compositional C++ (0.19)

LLM-contributed programs

Hello World Program

Provenance: commit 9dae8d38f7 · authored 2025-10-22T19:02:35+02:00 · model x-ai/grok-4-fast · Temp 0.4
code.cpp · added: 2025-10-22T17:02:34Z
// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}

Real programs from Software Heritage

10 samples mined from derived_datasets/<date>/contents/*.parquet, byte-verified against the SWH archive. Citation-grade qualified SWHIDs preserved.
memory_details_linux.cc · 4401 B · ext .cc · seen 51041× in SWH
via fallback
swh:1:cnt:7f699d1e71269071805d76fe3048e84ad696cd30;origin=https://github.com/kiwibrowser/src.next;anchor=swh:1:rev:b2a61e552c940b89d2ae504de720832780f4e7ea;path=/chrome/browser/memory_details_linux.cc
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/memory_details.h"

#include <stddef.h>
#include <sys/types.h>
#include <unistd.h>

#include <map>
#include <memory>
#include <set>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/process/process_iterator.h"
#include "base/process/process_metrics.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/scoped_blocking_call.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/process_type.h"
#include "ui/base/l10n/l10n_util.h"

using base::ProcessEntry;
namespace {

struct Process {
  pid_t pid;
  pid_t parent;
};

typedef std::map<pid_t, Process> ProcessMap;

// Get information on all the processes running on the system.
ProcessMap GetProcesses() {
  ProcessMap map;

  base::ProcessIterator process_iter(NULL);
  while (const ProcessEntry* process_entry = process_iter.NextProcessEntry()) {
    Process process;
    process.pid = process_entry->pid();
    process.parent = process_entry->parent_pid();
    map.insert(std::make_pair(process.pid, process));
  }
  return map;
}

// For each of a list of pids, collect memory information about that process.
ProcessData GetProcessDataMemoryInformation(
    const std::vector<pid_t>& pids) {
  ProcessData process_data;
  for (pid_t pid : pids) {
    ProcessMemoryInformation pmi;

    pmi.pid = pid;
    pmi.num_processes = 1;

    if (pmi.pid == base::GetCurrentProcId())
      pmi.process_type = content::PROCESS_TYPE_BROWSER;
    else
      pmi.process_type = content::PROCESS_TYPE_UNKNOWN;

    std::unique_ptr<base::ProcessMetrics> metrics(
        base::ProcessMetrics::CreateProcessMetrics(pid));
    pmi.num_open_fds = metrics->GetOpenFdCount();
    pmi.open_fds_soft_limit = metrics->GetOpenFdSoftLimit();

    process_data.processes.push_back(pmi);
  }
  return process_data;
}

// Find all children of the given process with pid |root|.
std::vector<pid_t> GetAllChildren(const ProcessMap& processes, pid_t root) {
  std::vector<pid_t> children;
  children.push_back(root);

  std::set<pid_t> wavefront, next_wavefront;
  wavefront.insert(root);

  while (wavefront.size()) {
    for (const auto& entry : processes) {
      const Process& process = entry.second;
      if (wavefront.count(process.parent)) {
        children.push_back(process.pid);
        next_wavefront.insert(process.pid);
      }
    }

    wavefront.clear();
    wavefront.swap(next_wavefront);
  }
  return children;
}

}  // namespace

MemoryDetails::MemoryDetails() {
}

ProcessData* MemoryDetails::ChromeBrowser() {
  return &process_data_[0];
}

void MemoryDetails::CollectProcessData(
    const std::vector<ProcessMemoryInformation>& child_info) {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  ProcessMap process_map = GetProcesses();
  std::set<pid_t> browsers_found;

  ProcessData current_browser =
      GetProcessDataMemoryInformation(GetAllChildren(process_map, getpid()));
  current_browser.name = l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME);
  current_browser.process_name = u"chrome";

  for (auto i = current_browser.processes.begin();
       i != current_browser.processes.end(); ++i) {
    // Check if this is one of the child processes whose data we collected
    // on the IO thread, and if so copy over that data.
    for (size_t child = 0; child < child_info.size(); child++) {
      if (child_info[child].pid != i->pid)
        continue;
      i->titles = child_info[child].titles;
      i->process_type = child_info[child].process_type;
      break;
    }
  }

  process_data_.push_back(current_browser);

#if BUILDFLAG(IS_CHROMEOS_ASH)
  base::GetSwapInfo(&swap_info_);
#endif

  // Finally return to the browser thread.
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&MemoryDetails::CollectChildInfoOnUIThread, this));
}
cache_stats_recorder.h · 964 B · ext .h · seen 34543× in SWH
via heuristicrule h/linguist/.h/1
swh:1:cnt:87a75d5d2567f8644a4ef41724c6f02105904f7e;origin=https://github.com/kiwibrowser/src.next;anchor=swh:1:rev:b2a61e552c940b89d2ae504de720832780f4e7ea;path=/chrome/browser/cache_stats_recorder.h
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_CACHE_STATS_RECORDER_H_
#define CHROME_BROWSER_CACHE_STATS_RECORDER_H_

#include "chrome/common/cache_stats_recorder.mojom.h"

class CacheStatsRecorder : public chrome::mojom::CacheStatsRecorder {
 public:
  explicit CacheStatsRecorder(int render_process_id);

  CacheStatsRecorder(const CacheStatsRecorder&) = delete;
  CacheStatsRecorder& operator=(const CacheStatsRecorder&) = delete;

  ~CacheStatsRecorder() override;

  static void Create(
      int render_process_id,
      mojo::PendingAssociatedReceiver<chrome::mojom::CacheStatsRecorder>
          receiver);

 private:
  // chrome::mojom::CacheStatsRecorder:
  void RecordCacheStats(uint64_t capacity, uint64_t size) override;

  const int render_process_id_;
};

#endif  // CHROME_BROWSER_CACHE_STATS_RECORDER_H_
chrome_origin_trials_browsertest.cc · 6466 B · ext .cc · seen 24045× in SWH
via fallback
swh:1:cnt:32302aa8ac24ac5d0253b02054597f70a5aaa8ff;origin=https://github.com/kiwibrowser/src.next;anchor=swh:1:rev:b2a61e552c940b89d2ae504de720832780f4e7ea;path=/chrome/browser/chrome_origin_trials_browsertest.cc
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "components/embedder_support/origin_trials/pref_names.h"
#include "components/embedder_support/switches.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

struct DisabledItemsTestData {
  const std::vector<std::string> input_list;
  const std::string expected_switch;
};

static const char kNewPublicKey[] = "new public key";

const DisabledItemsTestData kDisabledFeaturesTests[] = {
    // One feature
    {{"A"}, "A"},
    // Two features
    {{"A", "B"}, "A|B"},
    // Three features
    {{"A", "B", "C"}, "A|B|C"},
    // Spaces in feature name
    {{"A", "B C"}, "A|B C"},
};

const DisabledItemsTestData kDisabledTokensTests[] = {
    // One token
    {{"t1"}, "t1"},
    // Two tokens
    {{"t1", "t2"}, "t1|t2"},
    // Three tokens
    {{"t1", "t2", "t3"}, "t1|t2|t3"},
};

class ChromeOriginTrialsTest : public InProcessBrowserTest {
 public:
  ChromeOriginTrialsTest(const ChromeOriginTrialsTest&) = delete;
  ChromeOriginTrialsTest& operator=(const ChromeOriginTrialsTest&) = delete;

 protected:
  ChromeOriginTrialsTest() {}

  std::string GetCommandLineSwitch(const base::StringPiece& switch_name) {
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    EXPECT_TRUE(command_line->HasSwitch(switch_name));
    return command_line->GetSwitchValueASCII(switch_name);
  }

  void AddDisabledFeaturesToPrefs(const std::vector<std::string>& features) {
    base::Value disabled_feature_list(base::Value::Type::LIST);
    for (const std::string& feature : features) {
      disabled_feature_list.Append(feature);
    }
    ListPrefUpdate update(
        local_state(), embedder_support::prefs::kOriginTrialDisabledFeatures);
    *update = std::move(disabled_feature_list);
  }

  void AddDisabledTokensToPrefs(const std::vector<std::string>& tokens) {
    base::Value disabled_token_list(base::Value::Type::LIST);
    for (const std::string& token : tokens) {
      disabled_token_list.Append(token);
    }
    ListPrefUpdate update(local_state(),
                          embedder_support::prefs::kOriginTrialDisabledTokens);
    *update = std::move(disabled_token_list);
  }

  PrefService* local_state() { return g_browser_process->local_state(); }
};

// Tests to verify that the command line is not set, when no prefs exist for
// the various updates.

IN_PROC_BROWSER_TEST_F(ChromeOriginTrialsTest, NoPublicKeySet) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  EXPECT_FALSE(
      command_line->HasSwitch(embedder_support::kOriginTrialPublicKey));
}

IN_PROC_BROWSER_TEST_F(ChromeOriginTrialsTest, NoDisabledFeatures) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  EXPECT_FALSE(
      command_line->HasSwitch(embedder_support::kOriginTrialDisabledFeatures));
}

IN_PROC_BROWSER_TEST_F(ChromeOriginTrialsTest, NoDisabledTokens) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  EXPECT_FALSE(
      command_line->HasSwitch(embedder_support::kOriginTrialDisabledTokens));
}

// Tests to verify that the public key is correctly read from prefs and
// added to the command line
IN_PROC_BROWSER_TEST_F(ChromeOriginTrialsTest, PRE_PublicKeySetOnCommandLine) {
  local_state()->Set(embedder_support::prefs::kOriginTrialPublicKey,
                     base::Value(kNewPublicKey));
  ASSERT_EQ(kNewPublicKey, local_state()->GetString(
                               embedder_support::prefs::kOriginTrialPublicKey));
}

IN_PROC_BROWSER_TEST_F(ChromeOriginTrialsTest, PublicKeySetOnCommandLine) {
  ASSERT_EQ(kNewPublicKey, local_state()->GetString(
                               embedder_support::prefs::kOriginTrialPublicKey));
  std::string actual =
      GetCommandLineSwitch(embedder_support::kOriginTrialPublicKey);
  EXPECT_EQ(kNewPublicKey, actual);
}

// Tests to verify that disabled features are correctly read from prefs and
// added to the command line
class ChromeOriginTrialsDisabledFeaturesTest
    : public ChromeOriginTrialsTest,
      public ::testing::WithParamInterface<DisabledItemsTestData> {};

IN_PROC_BROWSER_TEST_P(ChromeOriginTrialsDisabledFeaturesTest,
                       PRE_DisabledFeaturesSetOnCommandLine) {
  AddDisabledFeaturesToPrefs(GetParam().input_list);
  ASSERT_TRUE(local_state()->HasPrefPath(
      embedder_support::prefs::kOriginTrialDisabledFeatures));
}

IN_PROC_BROWSER_TEST_P(ChromeOriginTrialsDisabledFeaturesTest,
                       DisabledFeaturesSetOnCommandLine) {
  ASSERT_TRUE(local_state()->HasPrefPath(
      embedder_support::prefs::kOriginTrialDisabledFeatures));
  std::string actual =
      GetCommandLineSwitch(embedder_support::kOriginTrialDisabledFeatures);
  EXPECT_EQ(GetParam().expected_switch, actual);
}

INSTANTIATE_TEST_SUITE_P(All,
                         ChromeOriginTrialsDisabledFeaturesTest,
                         ::testing::ValuesIn(kDisabledFeaturesTests));

// Tests to verify that disabled tokens are correctly read from prefs and
// added to the command line
class ChromeOriginTrialsDisabledTokensTest
    : public ChromeOriginTrialsTest,
      public ::testing::WithParamInterface<DisabledItemsTestData> {};

IN_PROC_BROWSER_TEST_P(ChromeOriginTrialsDisabledTokensTest,
                       PRE_DisabledTokensSetOnCommandLine) {
  AddDisabledTokensToPrefs(GetParam().input_list);
  ASSERT_TRUE(local_state()->HasPrefPath(
      embedder_support::prefs::kOriginTrialDisabledTokens));
}

IN_PROC_BROWSER_TEST_P(ChromeOriginTrialsDisabledTokensTest,
                       DisabledTokensSetOnCommandLine) {
  ASSERT_TRUE(local_state()->HasPrefPath(
      embedder_support::prefs::kOriginTrialDisabledTokens));
  std::string actual =
      GetCommandLineSwitch(embedder_support::kOriginTrialDisabledTokens);
  EXPECT_EQ(GetParam().expected_switch, actual);
}

INSTANTIATE_TEST_SUITE_P(All,
                         ChromeOriginTrialsDisabledTokensTest,
                         ::testing::ValuesIn(kDisabledTokensTests));

}  // namespace
gcWhen.hpp · 1552 B · ext .hpp · seen 3353× in SWH
via fallback
swh:1:cnt:22d6f76b54fb9956f86bd81e60d2faf0d69932f2;origin=https://github.com/openjdk/jdk;anchor=swh:1:rev:1428db798c8b983c23b31001ce2964f174139fea;path=/src/hotspot/share/gc/shared/gcWhen.hpp
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/*
 * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

#ifndef SHARE_GC_SHARED_GCWHEN_HPP
#define SHARE_GC_SHARED_GCWHEN_HPP

#include "memory/allStatic.hpp"
#include "utilities/debug.hpp"

class GCWhen : AllStatic {
 public:
  enum Type {
    BeforeGC,
    AfterGC,
    GCWhenEndSentinel
  };

  static const char* to_string(GCWhen::Type when) {
    switch (when) {
    case BeforeGC: return "Before GC";
    case AfterGC:  return "After GC";
    default: ShouldNotReachHere(); return nullptr;
    }
  }
};

#endif // SHARE_GC_SHARED_GCWHEN_HPP
rtkXRadImageIO.cxx · 5883 B · ext .cxx · seen 1781× in SWH
via fallback
swh:1:cnt:fb02952016ed37ce421de70ea8dd312694974167;origin=https://github.com/vfonov/vv;anchor=swh:1:rev:942db0e6f00e876ac6fbea41076db2ff703010a5;path=/common/rtkXRadImageIO.cxx
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "rtkXRadImageIO.h"

#include <itkRawImageIO.h>
#include <itkMetaDataObject.h>

//--------------------------------------------------------------------
// Read Image Information
void rtk::XRadImageIO::ReadImageInformation()
{
  std::ifstream is;
  is.open(m_FileName.c_str());

  if(!is.is_open())
    itkExceptionMacro(<<"Could not open file " << m_FileName);

  SetNumberOfDimensions(3);
  std::string section="";
  while(!is.eof())
    {
    std::string line;
    std::getline(is, line);
    if(line.find('[') != std::string::npos)
      {
      unsigned int pos1 = line.find('[');
      unsigned int pos2 = line.find(']');
      section = line.substr(pos1+1, pos2-pos1-1);
      }
    if(line.find('=') != std::string::npos)
      {
      unsigned int pos       = line.find('=');
      std::string paramName  = line.substr(0,pos);
      std::string paramValue = line.substr(pos+1, line.length()-pos-1);

      if(paramName == std::string("CBCT.DimensionalAttributes.IDim"))
        SetDimensions(0, atoi(paramValue.c_str()));
      else if(paramName == std::string("CBCT.DimensionalAttributes.JDim"))
        SetDimensions(1, atoi(paramValue.c_str()));
      else if(paramName == std::string("CBCT.DimensionalAttributes.KDim"))
        SetDimensions(2, atoi(paramValue.c_str()));
      else if(paramName == std::string("CBCT.DimensionalAttributes.DataSize"))
        {
        if(atoi(paramValue.c_str()) == 3)
          SetComponentType(itk::ImageIOBase::FLOAT);
        if(atoi(paramValue.c_str()) == 6)
          SetComponentType(itk::ImageIOBase::USHORT);
        }
      else if(paramName == std::string("CBCT.DimensionalAttributes.PixelDimension_I_cm"))
        {
        double spacing = 10*atof(paramValue.c_str());
        SetSpacing(0, (spacing==0.)?1.:spacing);
        }
      else if(paramName == std::string("CBCT.DimensionalAttributes.PixelDimension_J_cm"))
        {
        double spacing = 10*atof(paramValue.c_str());
        SetSpacing(1, (spacing==0.)?1.:spacing);
        }
      else if(paramName == std::string("CBCT.DimensionalAttributes.PixelDimension_K_cm"))
        {
        double spacing = 10*atof(paramValue.c_str());
        SetSpacing(2, (spacing==0.)?1.:spacing);
        }
      else
        {
        paramName = section + std::string("_") + paramName;
        itk::EncapsulateMetaData<std::string>(this->GetMetaDataDictionary(),
                                              paramName.c_str(),
                                              paramValue);
        }
      }

    }
} ////

//--------------------------------------------------------------------
// Read Image Information
bool rtk::XRadImageIO::CanReadFile(const char* FileNameToRead)
{
  std::string                  filename(FileNameToRead);
  const std::string::size_type it = filename.find_last_of( "." );
  std::string                  fileExt( filename, it+1, filename.length() );

  if (fileExt != std::string("header") ) return false;
  return true;
} ////

//--------------------------------------------------------------------
// Read Image Content
void rtk::XRadImageIO::Read(void * buffer)
{
  // Adapted from itkRawImageIO
  std::string rawFileName( m_FileName, 0, m_FileName.size()-6);
  rawFileName += "img";

  std::ifstream is(rawFileName.c_str(), std::ios::binary);
  if(!is.is_open() )
    itkExceptionMacro(<<"Could not open file " << rawFileName);

  unsigned long numberOfBytesToBeRead = GetComponentSize();
  for(unsigned int i=0; i<GetNumberOfDimensions(); i++) numberOfBytesToBeRead *= GetDimensions(i);

  if(!this->ReadBufferAsBinary(is, buffer, numberOfBytesToBeRead) ) {
    itkExceptionMacro(<<"Read failed: Wanted "
                      << numberOfBytesToBeRead
                      << " bytes, but read "
                      << is.gcount() << " bytes.");
    }
  itkDebugMacro(<< "Reading Done");

  // Adapted from itkRawImageIO
    {
    using namespace itk;
    // Swap bytes if necessary
    if itkReadRawBytesAfterSwappingMacro( unsigned short, USHORT )
    else if itkReadRawBytesAfterSwappingMacro( short, SHORT )
    else if itkReadRawBytesAfterSwappingMacro( char, CHAR )
    else if itkReadRawBytesAfterSwappingMacro( unsigned char, UCHAR )
    else if itkReadRawBytesAfterSwappingMacro( unsigned int, UINT )
    else if itkReadRawBytesAfterSwappingMacro( int, INT )
    else if itkReadRawBytesAfterSwappingMacro( unsigned int, ULONG )
    else if itkReadRawBytesAfterSwappingMacro( int, LONG )
    else if itkReadRawBytesAfterSwappingMacro( float, FLOAT )
    else if itkReadRawBytesAfterSwappingMacro( double, DOUBLE );
    }
}

//--------------------------------------------------------------------
// Write Image Information
void rtk::XRadImageIO::WriteImageInformation(bool itkNotUsed(keepOfStream))
{
}

//--------------------------------------------------------------------
// Write Image Information
bool rtk::XRadImageIO::CanWriteFile(const char* itkNotUsed(FileNameToWrite))
{
  return false;
}

//--------------------------------------------------------------------
// Write Image
void rtk::XRadImageIO::Write(const void * itkNotUsed(buffer))
{
} ////
BKE_node_runtime.hh · 25636 B · ext .hh · seen 510× in SWH
via fallback
swh:1:cnt:afebe5c63ec2e72fd4fbd9f8efc14026ae3afa3d;origin=https://github.com/asd158/blender3.5.1;anchor=swh:1:rev:d25f4f71c312a5de61486349ae02551988266aed;path=/src/source/blender/blenkernel/BKE_node_runtime.hh
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/* SPDX-License-Identifier: GPL-2.0-or-later */

#pragma once

#include <memory>
#include <mutex>

#include "BLI_cache_mutex.hh"
#include "BLI_math_vector_types.hh"
#include "BLI_multi_value_map.hh"
#include "BLI_resource_scope.hh"
#include "BLI_utility_mixins.hh"
#include "BLI_vector.hh"
#include "BLI_vector_set.hh"

#include "DNA_node_types.h"

#include "BKE_node.hh"

struct bNode;
struct bNodeSocket;
struct bNodeTree;
struct bNodeType;

namespace blender::nodes {
struct FieldInferencingInterface;
class NodeDeclaration;
struct GeometryNodesLazyFunctionGraphInfo;
namespace anonymous_attribute_lifetime {
struct RelationsInNode;
}
namespace aal = anonymous_attribute_lifetime;
}  // namespace blender::nodes
namespace blender::bke::node_tree_zones {
class TreeZones;
}

namespace blender {

struct NodeIDHash {
  uint64_t operator()(const bNode *node) const
  {
    return node->identifier;
  }
  uint64_t operator()(const int32_t id) const
  {
    return id;
  }
};

struct NodeIDEquality {
  bool operator()(const bNode *a, const bNode *b) const
  {
    return a->identifier == b->identifier;
  }
  bool operator()(const bNode *a, const int32_t b) const
  {
    return a->identifier == b;
  }
  bool operator()(const int32_t a, const bNode *b) const
  {
    return this->operator()(b, a);
  }
};

}  // namespace blender

namespace blender::bke {

using NodeIDVectorSet = VectorSet<bNode *, DefaultProbingStrategy, NodeIDHash, NodeIDEquality>;

class bNodeTreeRuntime : NonCopyable, NonMovable {
 public:
  /**
   * Keeps track of what changed in the node tree until the next update.
   * Should not be changed directly, instead use the functions in `BKE_node_tree_update.h`.
   * #eNodeTreeChangedFlag.
   */
  uint32_t changed_flag = 0;
  /**
   * A hash of the topology of the node tree leading up to the outputs. This is used to determine
   * of the node tree changed in a way that requires updating geometry nodes or shaders.
   */
  uint32_t output_topology_hash = 0;

  /**
   * Used to cache run-time information of the node tree.
   * #eNodeTreeRuntimeFlag.
   */
  uint8_t runtime_flag = 0;

  /**
   * Storage of nodes based on their identifier. Also used as a contiguous array of nodes to
   * allow simpler and more cache friendly iteration. Supports lookup by integer or by node.
   * Unlike other caches, this is maintained eagerly while changing the tree.
   */
  NodeIDVectorSet nodes_by_id;

  /** Execution data.
   *
   * XXX It would be preferable to completely move this data out of the underlying node tree,
   * so node tree execution could finally run independent of the tree itself.
   * This would allow node trees to be merely linked by other data (materials, textures, etc.),
   * as ID data is supposed to.
   * Execution data is generated from the tree once at execution start and can then be used
   * as long as necessary, even while the tree is being modified.
   */
  struct bNodeTreeExec *execdata = nullptr;

  /* Callbacks. */
  void (*progress)(void *, float progress) = nullptr;
  /** \warning may be called by different threads */
  void (*stats_draw)(void *, const char *str) = nullptr;
  bool (*test_break)(void *) = nullptr;
  void (*update_draw)(void *) = nullptr;
  void *tbh = nullptr, *prh = nullptr, *sdh = nullptr, *udh = nullptr;

  /** Information about how inputs and outputs of the node group interact with fields. */
  std::unique_ptr<nodes::FieldInferencingInterface> field_inferencing_interface;
  /** Information about usage of anonymous attributes within the group. */
  std::unique_ptr<nodes::aal::RelationsInNode> anonymous_attribute_relations;

  /**
   * For geometry nodes, a lazy function graph with some additional info is cached. This is used to
   * evaluate the node group. Caching it here allows us to reuse the preprocessed node tree in case
   * its used multiple times.
   */
  std::mutex geometry_nodes_lazy_function_graph_info_mutex;
  std::unique_ptr<nodes::GeometryNodesLazyFunctionGraphInfo>
      geometry_nodes_lazy_function_graph_info;

  /**
   * Protects access to all topology cache variables below. This is necessary so that the cache can
   * be updated on a const #bNodeTree.
   */
  CacheMutex topology_cache_mutex;
  std::atomic<bool> topology_cache_exists = false;
  /**
   * Under some circumstances, it can be useful to use the cached data while editing the
   * #bNodeTree. By default, this is protected against using an assert.
   */
  mutable std::atomic<int> allow_use_dirty_topology_cache = 0;

  CacheMutex tree_zones_cache_mutex;
  std::unique_ptr<node_tree_zones::TreeZones> tree_zones;

  /** Only valid when #topology_cache_is_dirty is false. */
  Vector<bNodeLink *> links;
  Vector<bNodeSocket *> sockets;
  Vector<bNodeSocket *> input_sockets;
  Vector<bNodeSocket *> output_sockets;
  MultiValueMap<const bNodeType *, bNode *> nodes_by_type;
  Vector<bNode *> toposort_left_to_right;
  Vector<bNode *> toposort_right_to_left;
  Vector<bNode *> group_nodes;
  bool has_available_link_cycle = false;
  bool has_undefined_nodes_or_sockets = false;
  bNode *group_output_node = nullptr;
  Vector<bNode *> root_frames;
  Vector<bNodeSocket *> interface_inputs;
  Vector<bNodeSocket *> interface_outputs;
};

/**
 * Run-time data for every socket. This should only contain data that is somewhat persistent (i.e.
 * data that lives longer than a single depsgraph evaluation + redraw). Data that's only used in
 * smaller scopes should generally be stored in separate arrays and/or maps.
 */
class bNodeSocketRuntime : NonCopyable, NonMovable {
 public:
  /**
   * References a socket declaration that is owned by `node->declaration`. This is only runtime
   * data. It has to be updated when the node declaration changes. Access can be allowed by using
   * #AllowUsingOutdatedInfo.
   */
  const SocketDeclarationHandle *declaration = nullptr;

  /** #eNodeTreeChangedFlag. */
  uint32_t changed_flag = 0;

  /**
   * Runtime-only cache of the number of input links, for multi-input sockets,
   * including dragged node links that aren't actually in the tree.
   */
  short total_inputs = 0;

  /**
   * The location of the socket in the tree, calculated while drawing the nodes and invalid if the
   * node tree hasn't been drawn yet. In the node tree's "world space" (the same as
   * #bNode::runtime::totr).
   */
  float2 location;

  /** Only valid when #topology_cache_is_dirty is false. */
  Vector<bNodeLink *> directly_linked_links;
  Vector<bNodeSocket *> directly_linked_sockets;
  Vector<bNodeSocket *> logically_linked_sockets;
  Vector<bNodeSocket *> logically_linked_skipped_sockets;
  bNode *owner_node = nullptr;
  bNodeSocket *internal_link_input = nullptr;
  int index_in_node = -1;
  int index_in_all_sockets = -1;
  int index_in_inout_sockets = -1;
};

/**
 * Run-time data for every node. This should only contain data that is somewhat persistent (i.e.
 * data that lives longer than a single depsgraph evaluation + redraw). Data that's only used in
 * smaller scopes should generally be stored in separate arrays and/or maps.
 */
class bNodeRuntime : NonCopyable, NonMovable {
 public:
  /**
   * Describes the desired interface of the node. This is run-time data only.
   * The actual interface of the node may deviate from the declaration temporarily.
   * It's possible to sync the actual state of the node to the desired state. Currently, this is
   * only done when a node is created or loaded.
   *
   * In the future, we may want to keep more data only in the declaration, so that it does not have
   * to be synced to other places that are stored in files. That especially applies to data that
   * can't be edited by users directly (e.g. min/max values of sockets, tooltips, ...).
   *
   * The declaration of a node can be recreated at any time when it is used. Caching it here is
   * just a bit more efficient when it is used a lot. To make sure that the cache is up-to-date,
   * call #nodeDeclarationEnsure before using it.
   *
   * Currently, the declaration is the same for every node of the same type. Going forward, that is
   * intended to change though. Especially when nodes become more dynamic with respect to how many
   * sockets they have.
   */
  NodeDeclarationHandle *declaration = nullptr;

  /** #eNodeTreeChangedFlag. */
  uint32_t changed_flag = 0;

  /** Used as a boolean for execution. */
  uint8_t need_exec = 0;

  /** The original node in the tree (for localized tree). */
  struct bNode *original = nullptr;

  /**
   * XXX TODO
   * Node totr size depends on the prvr size, which in turn is determined from preview size.
   * In earlier versions bNodePreview was stored directly in nodes, but since now there can be
   * multiple instances using different preview images it is possible that required node size
   * varies between instances. preview_xsize, preview_ysize defines a common reserved size for
   * preview rect for now, could be replaced by more accurate node instance drawing,
   * but that requires removing totr from DNA and replacing all uses with per-instance data.
   */
  /** Reserved size of the preview rect. */
  short preview_xsize, preview_ysize = 0;
  /** Entire bound-box (world-space). */
  rctf totr{};
  /** Optional preview area. */
  rctf prvr{};

  /** Used at runtime when going through the tree. Initialize before use. */
  short tmp_flag = 0;

  /** Used at runtime when iterating over node branches. */
  char iter_flag = 0;

  /** Update flags. */
  int update = 0;

  /** Initial locx for insert offset animation. */
  float anim_init_locx;
  /** Offset that will be added to locx for insert offset animation. */
  float anim_ofsx;

  /** List of cached internal links (input to output), for muted nodes and operators. */
  Vector<bNodeLink> internal_links;

  /** Eagerly maintained cache of the node's index in the tree. */
  int index_in_tree = -1;

  /** Only valid if #topology_cache_is_dirty is false. */
  Vector<bNodeSocket *> inputs;
  Vector<bNodeSocket *> outputs;
  Map<StringRefNull, bNodeSocket *> inputs_by_identifier;
  Map<StringRefNull, bNodeSocket *> outputs_by_identifier;
  bool has_available_linked_inputs = false;
  bool has_available_linked_outputs = false;
  Vector<bNode *> direct_children_in_frame;
  bNodeTree *owner_tree = nullptr;
};

namespace node_tree_runtime {

/**
 * Is executed when the node tree changed in the depsgraph.
 */
void preprocess_geometry_node_tree_for_evaluation(bNodeTree &tree_cow);

class AllowUsingOutdatedInfo : NonCopyable, NonMovable {
 private:
  const bNodeTree &tree_;

 public:
  AllowUsingOutdatedInfo(const bNodeTree &tree) : tree_(tree)
  {
    tree_.runtime->allow_use_dirty_topology_cache.fetch_add(1);
  }

  ~AllowUsingOutdatedInfo()
  {
    tree_.runtime->allow_use_dirty_topology_cache.fetch_sub(1);
  }
};

inline bool topology_cache_is_available(const bNodeTree &tree)
{
  if (!tree.runtime->topology_cache_exists) {
    return false;
  }
  if (tree.runtime->allow_use_dirty_topology_cache.load() > 0) {
    return true;
  }
  if (tree.runtime->topology_cache_mutex.is_dirty()) {
    return false;
  }
  return true;
}

inline bool topology_cache_is_available(const bNode &node)
{
  const bNodeTree *ntree = node.runtime->owner_tree;
  if (ntree == nullptr) {
    return false;
  }
  return topology_cache_is_available(*ntree);
}

inline bool topology_cache_is_available(const bNodeSocket &socket)
{
  const bNode *node = socket.runtime->owner_node;
  if (node == nullptr) {
    return false;
  }
  return topology_cache_is_available(*node);
}

}  // namespace node_tree_runtime

namespace node_field_inferencing {
bool update_field_inferencing(const bNodeTree &tree);
}
namespace anonymous_attribute_inferencing {
Array<const nodes::aal::RelationsInNode *> get_relations_by_node(const bNodeTree &tree,
                                                                 ResourceScope &scope);
bool update_anonymous_attribute_relations(bNodeTree &tree);
}  // namespace anonymous_attribute_inferencing
}  // namespace blender::bke

/* -------------------------------------------------------------------- */
/** \name #bNodeTree Inline Methods
 * \{ */

inline blender::Span<const bNode *> bNodeTree::all_nodes() const
{
  return this->runtime->nodes_by_id.as_span();
}

inline blender::Span<bNode *> bNodeTree::all_nodes()
{
  return this->runtime->nodes_by_id;
}

inline bNode *bNodeTree::node_by_id(const int32_t identifier)
{
  BLI_assert(identifier >= 0);
  bNode *const *node = this->runtime->nodes_by_id.lookup_key_ptr_as(identifier);
  return node ? *node : nullptr;
}

inline const bNode *bNodeTree::node_by_id(const int32_t identifier) const
{
  BLI_assert(identifier >= 0);
  const bNode *const *node = this->runtime->nodes_by_id.lookup_key_ptr_as(identifier);
  return node ? *node : nullptr;
}

inline blender::Span<bNode *> bNodeTree::nodes_by_type(const blender::StringRefNull type_idname)
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->nodes_by_type.lookup(nodeTypeFind(type_idname.c_str()));
}

inline blender::Span<const bNode *> bNodeTree::nodes_by_type(
    const blender::StringRefNull type_idname) const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->nodes_by_type.lookup(nodeTypeFind(type_idname.c_str()));
}

inline blender::Span<const bNode *> bNodeTree::toposort_left_to_right() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->toposort_left_to_right;
}

inline blender::Span<const bNode *> bNodeTree::toposort_right_to_left() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->toposort_right_to_left;
}

inline blender::Span<bNode *> bNodeTree::toposort_left_to_right()
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->toposort_left_to_right;
}

inline blender::Span<bNode *> bNodeTree::toposort_right_to_left()
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->toposort_right_to_left;
}

inline blender::Span<const bNode *> bNodeTree::group_nodes() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->group_nodes;
}

inline blender::Span<bNode *> bNodeTree::group_nodes()
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->group_nodes;
}

inline bool bNodeTree::has_available_link_cycle() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->has_available_link_cycle;
}

inline bool bNodeTree::has_undefined_nodes_or_sockets() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->has_undefined_nodes_or_sockets;
}

inline bNode *bNodeTree::group_output_node()
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->group_output_node;
}

inline const bNode *bNodeTree::group_output_node() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->group_output_node;
}

inline blender::Span<const bNode *> bNodeTree::group_input_nodes() const
{
  return this->nodes_by_type("NodeGroupInput");
}

inline blender::Span<const bNodeSocket *> bNodeTree::interface_inputs() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->interface_inputs;
}

inline blender::Span<const bNodeSocket *> bNodeTree::interface_outputs() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_available(*this));
  return this->runtime->interface_outputs;
}

inline blender::Span<const bNodeSocket *> bNodeTree::all_input_sockets() const
{
  BLI_assert(blender::bke::node_tree_runtime::topology_cache_is_avail
…(truncated)…
BKE_node.hh · 12259 B · ext .hh · seen 464× in SWH
via fallback
swh:1:cnt:d6c8353da42015c26f04840a392fdad083dd3905;origin=https://github.com/dshawshank/Blender-android_arm64;anchor=swh:1:rev:c8b5b17d40c4e969fada2e89873edaf0dda5cd30;path=/source/blender/blenkernel/BKE_node.hh
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/* SPDX-License-Identifier: GPL-2.0-or-later
 * Copyright 2005 Blender Foundation */

#pragma once

/** \file
 * \ingroup bke
 */

#include "BLI_compiler_compat.h"
#include "BLI_ghash.h"

#include "DNA_listBase.h"

#include "BKE_node.h"

/* for FOREACH_NODETREE_BEGIN */
#include "DNA_node_types.h"

#include "RNA_types.h"

#include "BLI_map.hh"
#include "BLI_string_ref.hh"

namespace blender::bke {

bNodeTree *ntreeAddTreeEmbedded(Main *bmain, ID *owner_id, const char *name, const char *idname);

/* Copy/free functions, need to manage ID users. */

/**
 * Free (or release) any data used by this node-tree.
 * Does not free the node-tree itself and does no ID user counting.
 */
void ntreeFreeTree(bNodeTree *ntree);

bNodeTree *ntreeCopyTree_ex(const bNodeTree *ntree, Main *bmain, bool do_id_user);
bNodeTree *ntreeCopyTree(Main *bmain, const bNodeTree *ntree);

void ntreeFreeLocalNode(bNodeTree *ntree, bNode *node);

void ntreeUpdateAllNew(Main *main);

void ntreeNodeFlagSet(const bNodeTree *ntree, int flag, bool enable);

/**
 * Merge local tree results back, and free local tree.
 *
 * We have to assume the editor already changed completely.
 */
void ntreeLocalMerge(Main *bmain, bNodeTree *localtree, bNodeTree *ntree);

/**
 * \note `ntree` itself has been read!
 */
void ntreeBlendReadData(BlendDataReader *reader, ID *owner_id, bNodeTree *ntree);
void ntreeBlendReadLib(BlendLibReader *reader, bNodeTree *ntree);

void ntreeBlendReadExpand(BlendExpander *expander, bNodeTree *ntree);

/* -------------------------------------------------------------------- */
/** \name Node Tree Interface
 * \{ */

bNodeSocket *ntreeFindSocketInterface(bNodeTree *ntree,
                                      eNodeSocketInOut in_out,
                                      const char *identifier);

bNodeSocket *ntreeInsertSocketInterface(bNodeTree *ntree,
                                        eNodeSocketInOut in_out,
                                        const char *idname,
                                        bNodeSocket *next_sock,
                                        const char *name);

bNodeSocket *ntreeAddSocketInterfaceFromSocket(bNodeTree *ntree,
                                               const bNode *from_node,
                                               const bNodeSocket *from_sock);

bNodeSocket *ntreeAddSocketInterfaceFromSocketWithName(bNodeTree *ntree,
                                                       const bNode *from_node,
                                                       const bNodeSocket *from_sock,
                                                       const char *idname,
                                                       const char *name);

bNodeSocket *ntreeInsertSocketInterfaceFromSocket(bNodeTree *ntree,
                                                  bNodeSocket *next_sock,
                                                  const bNode *from_node,
                                                  const bNodeSocket *from_sock);

/** \} */

bool node_type_is_undefined(const bNode *node);

bool nodeIsStaticSocketType(const bNodeSocketType *stype);

const char *nodeSocketSubTypeLabel(int subtype);

void nodeRemoveSocketEx(bNodeTree *ntree, bNode *node, bNodeSocket *sock, bool do_id_user);

void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node);

void nodeModifySocketType(bNodeTree *ntree, bNode *node, bNodeSocket *sock, const char *idname);

/**
 * \note Goes over entire tree.
 */
void nodeUnlinkNode(bNodeTree *ntree, bNode *node);

/**
 * Rebuild the `node_by_id` runtime vector set. Call after removing a node if not handled
 * separately. This is important instead of just using `nodes_by_id.remove()` since it maintains
 * the node order.
 */
void nodeRebuildIDVector(bNodeTree *node_tree);

/**
 * \note keeps socket list order identical, for copying links.
 * \param use_unique: If true, make sure the node's identifier and name are unique in the new
 * tree. Must be *true* if the \a dst_tree had nodes that weren't in the source node's tree.
 * Must be *false* when simply copying a node tree, so that identifiers don't change.
 */
bNode *node_copy_with_mapping(bNodeTree *dst_tree,
                              const bNode &node_src,
                              int flag,
                              bool use_unique,
                              Map<const bNodeSocket *, bNodeSocket *> &new_socket_map);

bNode *node_copy(bNodeTree *dst_tree, const bNode &src_node, int flag, bool use_unique);

/**
 * Move socket default from \a src (input socket) to locations specified by \a dst (output socket).
 * Result value moved in specific location. (potentially multiple group nodes socket values, if \a
 * dst is a group input node).
 * \note Conceptually, the effect should be such that the evaluation of
 * this graph again returns the value in src.
 */
void node_socket_move_default_value(Main &bmain,
                                    bNodeTree &tree,
                                    bNodeSocket &src,
                                    bNodeSocket &dst);

/**
 * Free the node itself.
 *
 * \note ID user reference-counting and changing the `nodes_by_id` vector are up to the caller.
 */
void node_free_node(bNodeTree *tree, bNode *node);

/**
 * Set the mute status of a single link.
 */
void nodeLinkSetMute(bNodeTree *ntree, bNodeLink *link, const bool muted);

bool nodeLinkIsSelected(const bNodeLink *link);

void nodeInternalRelink(bNodeTree *ntree, bNode *node);

void nodeToView(const bNode *node, float x, float y, float *rx, float *ry);

void nodeFromView(const bNode *node, float x, float y, float *rx, float *ry);

void nodePositionRelative(bNode *from_node,
                          const bNode *to_node,
                          const bNodeSocket *from_sock,
                          const bNodeSocket *to_sock);

void nodePositionPropagate(bNode *node);

/**
 * \note Recursive.
 */
bNode *nodeFindRootParent(bNode *node);

/**
 * Iterate over a chain of nodes, starting with \a node_start, executing
 * \a callback for each node (which can return false to end iterator).
 *
 * \param reversed: for backwards iteration
 * \note Recursive
 */
void nodeChainIter(const bNodeTree *ntree,
                   const bNode *node_start,
                   bool (*callback)(bNode *, bNode *, void *, const bool),
                   void *userdata,
                   bool reversed);

/**
 * Iterate over a chain of nodes, starting with \a node_start, executing
 * \a callback for each node (which can return false to end iterator).
 *
 * Faster than nodeChainIter. Iter only once per node.
 * Can be called recursively (using another nodeChainIterBackwards) by
 * setting the recursion_lvl accordingly.
 *
 * \note Needs updated socket links (ntreeUpdateTree).
 * \note Recursive
 */
void nodeChainIterBackwards(const bNodeTree *ntree,
                            const bNode *node_start,
                            bool (*callback)(bNode *, bNode *, void *),
                            void *userdata,
                            int recursion_lvl);

/**
 * Iterate over all parents of \a node, executing \a callback for each parent
 * (which can return false to end iterator)
 *
 * \note Recursive
 */
void nodeParentsIter(bNode *node, bool (*callback)(bNode *, void *), void *userdata);

/**
 * A dangling reroute node is a reroute node that does *not* have a "data source", i.e. no
 * non-reroute node is connected to its input.
 */
bool nodeIsDanglingReroute(const bNodeTree *ntree, const bNode *node);

bNode *nodeGetActivePaintCanvas(bNodeTree *ntree);

/**
 * \brief Does the given node supports the sub active flag.
 *
 * \param sub_active: The active flag to check. #NODE_ACTIVE_TEXTURE / #NODE_ACTIVE_PAINT_CANVAS.
 */
bool nodeSupportsActiveFlag(const bNode *node, int sub_active);

void nodeSetSocketAvailability(bNodeTree *ntree, bNodeSocket *sock, bool is_available);

/**
 * If the node implements a `declare` function, this function makes sure that `node->declaration`
 * is up to date. It is expected that the sockets of the node are up to date already.
 */
bool nodeDeclarationEnsure(bNodeTree *ntree, bNode *node);

/**
 * Just update `node->declaration` if necessary. This can also be called on nodes that may not be
 * up to date (e.g. because the need versioning or are dynamic).
 */
bool nodeDeclarationEnsureOnOutdatedNode(bNodeTree *ntree, bNode *node);

/**
 * Update `socket->declaration` for all sockets in the node. This assumes that the node declaration
 * and sockets are up to date already.
 */
void nodeSocketDeclarationsUpdate(bNode *node);

using bNodeInstanceHashIterator = GHashIterator;

BLI_INLINE bNodeInstanceHashIterator *node_instance_hash_iterator_new(bNodeInstanceHash *hash)
{
  return BLI_ghashIterator_new(hash->ghash);
}

BLI_INLINE void node_instance_hash_iterator_init(bNodeInstanceHashIterator *iter,
                                                 bNodeInstanceHash *hash)
{
  BLI_ghashIterator_init(iter, hash->ghash);
}

BLI_INLINE void node_instance_hash_iterator_free(bNodeInstanceHashIterator *iter)
{
  BLI_ghashIterator_free(iter);
}

BLI_INLINE bNodeInstanceKey node_instance_hash_iterator_get_key(bNodeInstanceHashIterator *iter)
{
  return *(bNodeInstanceKey *)BLI_ghashIterator_getKey(iter);
}

BLI_INLINE void *node_instance_hash_iterator_get_value(bNodeInstanceHashIterator *iter)
{
  return BLI_ghashIterator_getValue(iter);
}

BLI_INLINE void node_instance_hash_iterator_step(bNodeInstanceHashIterator *iter)
{
  BLI_ghashIterator_step(iter);
}

BLI_INLINE bool node_instance_hash_iterator_done(bNodeInstanceHashIterator *iter)
{
  return BLI_ghashIterator_done(iter);
}

#define NODE_INSTANCE_HASH_ITER(iter_, hash_) \
  for (blender::bke::node_instance_hash_iterator_init(&iter_, hash_); \
       blender::bke::node_instance_hash_iterator_done(&iter_) == false; \
       blender::bke::node_instance_hash_iterator_step(&iter_))

/* Node Previews */
bool node_preview_used(const bNode *node);

bNodePreview *node_preview_verify(
    bNodeInstanceHash *previews, bNodeInstanceKey key, int xsize, int ysize, bool create);

bNodePreview *node_preview_copy(bNodePreview *preview);

void node_preview_free(bNodePreview *preview);

void node_preview_init_tree(bNodeTree *ntree, int xsize, int ysize);

void node_preview_remove_unused(bNodeTree *ntree);

void node_preview_clear(bNodePreview *preview);

void node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, bool remove_old);

/* -------------------------------------------------------------------- */
/** \name Node Type Access
 * \{ */

void nodeLabel(const bNodeTree *ntree, const bNode *node, char *label, int maxlen);

/**
 * Get node socket label if it is set.
 */
const char *nodeSocketLabel(const bNodeSocket *sock);

/**
 * Initialize a new node type struct with default values and callbacks.
 */
void node_type_base(bNodeType *ntype, int type, const char *name, short nclass);

void node_type_socket_templates(bNodeType *ntype,
                                bNodeSocketTemplate *inputs,
                                bNodeSocketTemplate *outputs);

void node_type_size(bNodeType *ntype, int width, int minwidth, int maxwidth);

enum class eNodeSizePreset : int8_t {
  DEFAULT,
  SMALL,
  MIDDLE,
  LARGE,
};

void node_type_size_preset(bNodeType *ntype, eNodeSizePreset size);

/* -------------------------------------------------------------------- */
/** \name Node Generic Functions
 * \{ */

bool node_is_connected_to_output(const bNodeTree *ntree, const bNode *node);

bNodeSocket *node_find_enabled_socket(bNode &node, eNodeSocketInOut in_out, StringRef name);

bNodeSocket *node_find_enabled_input_socket(bNode &node, StringRef name);

bNodeSocket *node_find_enabled_output_socket(bNode &node, StringRef name);

extern bNodeTreeType NodeTreeTypeUndefined;
extern bNodeType NodeTypeUndefined;
extern bNodeSocketType NodeSocketTypeUndefined;

}  // namespace blender::bke

#define NODE_STORAGE_FUNCS(StorageT) \
  [[maybe_unused]] static StorageT &node_storage(bNode &node) \
  { \
    return *static_cast<StorageT *>(node.storage); \
  } \
  [[maybe_unused]] static const StorageT &node_storage(const bNode &node) \
  { \
    return *static_cast<const StorageT *>(node.storage); \
  }
GHOST_SystemSDL.hh · 2527 B · ext .hh · seen 183× in SWH
via fallback
swh:1:cnt:67e093f3ddd12d5059fc29462e5b64848d601fc1;origin=https://github.com/dshawshank/Blender-android_arm64;anchor=swh:1:rev:b626f1fd18e98b18a8ea1ac90fbf659cd23ee361;path=/intern/ghost/intern/GHOST_SystemSDL.hh
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/* SPDX-License-Identifier: GPL-2.0-or-later */

/** \file
 * \ingroup GHOST
 * Declaration of GHOST_SystemSDL class.
 */

#pragma once

#include "../GHOST_Types.h"
#include "GHOST_DisplayManagerSDL.hh"
#include "GHOST_Event.hh"
#include "GHOST_System.hh"
#include "GHOST_TimerManager.hh"
#include "GHOST_WindowSDL.hh"

extern "C" {
#include "SDL.h"
}

#if !SDL_VERSION_ATLEAST(2, 0, 0)
#  error "SDL 2.0 or newer is needed to build with Ghost"
#endif

class GHOST_WindowSDL;

class GHOST_SystemSDL : public GHOST_System {
 public:
  void addDirtyWindow(GHOST_WindowSDL *bad_wind);

  GHOST_SystemSDL();
  ~GHOST_SystemSDL();

  bool processEvents(bool waitForEvent) override;

  bool setConsoleWindowState(GHOST_TConsoleWindowState /*action*/) override
  {
    return false;
  }

  GHOST_TSuccess getModifierKeys(GHOST_ModifierKeys &keys) const override;

  GHOST_TSuccess getButtons(GHOST_Buttons &buttons) const override;

  GHOST_TCapabilityFlag getCapabilities() const override;

  char *getClipboard(bool selection) const override;

  void putClipboard(const char *buffer, bool selection) const override;

  uint64_t getMilliSeconds() const override;

  uint8_t getNumDisplays() const override;

  GHOST_TSuccess getCursorPosition(int32_t &x, int32_t &y) const override;

  GHOST_TSuccess setCursorPosition(int32_t x, int32_t y) override;

  void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override;

  void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override;

  GHOST_IContext *createOffscreenContext(GHOST_GLSettings glSettings) override;

  GHOST_TSuccess disposeContext(GHOST_IContext *context) override;

 private:
  GHOST_TSuccess init() override;

  GHOST_IWindow *createWindow(const char *title,
                              int32_t left,
                              int32_t top,
                              uint32_t width,
                              uint32_t height,
                              GHOST_TWindowState state,
                              GHOST_GLSettings glSettings,
                              const bool exclusive = false,
                              const bool is_dialog = false,
                              const GHOST_IWindow *parentWindow = nullptr) override;

  /* SDL specific */
  GHOST_WindowSDL *findGhostWindow(SDL_Window *sdl_win);

  bool generateWindowExposeEvents();

  void processEvent(SDL_Event *sdl_event);

  /** The vector of windows that need to be updated. */
  std::vector<GHOST_WindowSDL *> m_dirty_windows;
};
modifiedmemberclass.c++ · 5554 B · ext .c++ · seen 38× in SWH
via fallback
swh:1:cnt:289a641d46e3028aeeefaa053dab4c23700f2afe;origin=https://github.com/DevarshVasani/DA-Club-Manager;anchor=swh:1:rev:95826b52d49772d3c4d3c7393d105683ff4ee007;path=/CPP/modifiedmemberclass.c++
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <unordered_map>
#include <limits>
using namespace std;

class Member {
public:
    string name;
    string id;
    string club;
    

    // Default constructor
    Member() : name(""), id(""), club("") {}

    // Parameterized constructor
    Member(const string& name, const string& id, const string& club)
        : name(name), id(id), club(club) {}

unordered_map<string, Member> buildHashTable(const string& myfile, const string& key) {
    ifstream file(myfile);
    unordered_map<string, Member> hashtable;

    if (!file.is_open()) {
        cout << "File doesn't exist" << endl;
        return hashtable;
    }

    string line;
    while (getline(file, line)) {
        istringstream iss(line);
        string name, id, club;

        getline(iss, name, ',');
        getline(iss, id, ',');
        getline(iss, club);

        Member student{name, id, club};
        string k = (key == "id") ? id : (key == "club") ? club : name;

        hashtable[k] = student;
    }

    file.close();
    return hashtable;
}
void printHashTable(const unordered_map<string, Member>& hashtable) {
    for (const auto& pair : hashtable) {
        cout << "Key: " << pair.first 
             << " | Name: " << pair.second.name 
             << ", ID: " << pair.second.id 
             << ", Club: " << pair.second.club << endl;
    }
}

    unordered_map<string,Member>nametable=buildHashTable("C:\\Users\\DELL\\Desktop\\C++_files\\Records.csv","name");
    unordered_map<string,Member>idtable=buildHashTable("C:\\Users\\DELL\\Desktop\\C++_files\\Records.csv","id");
   void searchbyName() {
    //input buffer ko clear karne kelie and press enter to input
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string key;
    cout << "Enter name of the member: ";
    getline(cin, key); //getline so that spaces in the name can be ignored
   
    auto it = nametable.find(key);
    if (it != nametable.end()) {
        cout << "Member found!" << endl;
        cout << "Name: " << it->second.name << endl;
        cout << "ID: " << it->second.id << endl;
        cout << "Club: " << it->second.club << endl;
    } else {
        cout << "Member not found :(" << endl;
    }
}
void searchbyID() {
   
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string key;
    cout << "Enter id of the member: ";
    getline(cin, key); 
    
    auto it = idtable.find(key);
    if (it != idtable.end()) {
        cout << "Member found!" << endl;
        cout << "Name: " << it->second.name << endl;
        cout << "ID: " << it->second.id << endl;
        cout << "Club: " << it->second.club << endl;
    } else {
        cout << "Member not found :(" << endl;
    }
}

    // Delete member function
    void deleteMemberByName() {
        string password;
        cout << "Enter password (consists of six digits): ";
        cin >> password;
        if (password != "123456") {
            cout << "Incorrect password. Access denied." << endl;
            return;
        }

        ifstream inFile("Records.csv");
        ofstream tempFile("temp.csv");
        string memberName;
        cout << "Enter the name of the member to be deleted: ";
        cin >> memberName;
        if (inFile.is_open() && tempFile.is_open()) {
            string line;
            while (getline(inFile, line)) {
                istringstream iss(line);
                string n, i, c;
                getline(iss, n, ',');
                getline(iss, i, ',');
                getline(iss, c);
                // Check if the name contains the memberName as a substring
                if (n.find(memberName) == string::npos) {
                    tempFile << line << endl;
                }
            }
            inFile.close();
            tempFile.close();
            remove("Records.csv");
            rename("temp.csv", "Records.csv");
            cout << "Member deleted successfully." << endl;
        } else {
            cerr << "Failed to open CSV file." << endl;
        }
        cout<<"Member deleted successfully"<<endl;
        return;
    }

    // Insert member function
   void insert() {
        
        string password;
        cout << "Enter password (consists of 6 digits): ";
        cin >> password;


        if (password != "123456") {
            cout << "Incorrect password. Access denied." << endl;
            return;
        }

        
        cout << "Enter name of the member: ";
        cin.ignore(); 
        getline(cin, name);
        cout << "Enter ID of the member: ";
        getline(cin, id);
        cout << "Enter club of the member: ";
        getline(cin, club);

        
       ofstream file("Records.csv",ios::app);
        if (!file.is_open()) {
            cerr << "Failed to open CSV file." << endl;
            return;
        }

       
        file << name << "," << id <<","<<club<<endl;
        file.close();

        cout << "Member added successfully." <<endl;
    }

    friend void printHashTable(const unordered_map<string, Member>& hashtable);

};

vector<string> returnKey(unordered_map<string,Member>&hashtable){
    vector<string> v;
    for(const auto& pair: hashtable){
        v.push_back(pair.first);
    }
    return v;
}

int main()
{
    Member M1;
    

    printHashTable(M1.nametable);
}
oscillation.ipp · 6599 B · ext .ipp · seen 31× in SWH
via fallback
swh:1:cnt:d0efe66e4f5aa53c2e4f93aa26476ec57522fb2d;origin=https://github.com/WhitmanOptiLab/DENSE;anchor=swh:1:rev:26aad9018f593bc958dd848dca92f8c0cc8fda15;path=/source/measurement/oscillation.ipp
Open in SWH · Raw bytes (SWH) · GitHub raw
Show source
/*
 * FINALIZE
 * finds peaks and troughs in final half-window of simulation data
 * precondition: the simulation has finished
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::finalize() {
    int timeTemp = this->samples;
    for (std::size_t s = 0; s < this->observed_species_.size(); ++s)
    {
        for (Natural c = 0; c < this->max - this->min; ++c){
            this->samples = timeTemp;
            while (windows[s][c].getSize()>=(range_steps/2)&&bst[s][c].size()>0){
                Real removed = windows[s][c].dequeue();
                bst[s][c].erase(bst[s][c].find(removed));
                //std::cout<<"bst size="<<bst[s][c].size()<<'\n';
                checkCritPoint(s, c);
                ++this->samples;
            }
            calcAmpsAndPers(s, c);
        }
    }
		if(!finalized){
		finalized = true;
		}
}

#include <numeric>

template <typename Simulation>
void OscillationAnalysis<Simulation>::show (csvw * csv_out) {
  Analysis<>::show(csv_out);
  if (csv_out)
  {
      for (Natural c = this->min; c < this->max; ++c) {
        std::vector<Real> avg_peak(this->observed_species_.size());
        for (std::size_t s = 0; s < this->observed_species_.size(); ++s) {
              dense::Natural peak_count = 0;
              auto& x = peaksAndTroughs[s][c];
              avg_peak[s] = std::accumulate(x.begin(), x.end(), 0.0, [&](Real total, crit_point cp) {
                if (cp.is_peak) {
                  peak_count = peak_count + 1;
                  return total + cp.conc;
                }
                return total;
              });
/*
              for (std::size_t pt = 0; pt < peaksAndTroughs[s][c].size(); ++pt)
              {
                  crit_point cp = peaksAndTroughs[s][c][pt];
                  if (cp.is_peak) {
                      avg_peak[s] += cp.conc;
                      ++peak_count;
                  }
              }*/

              if (peak_count != 0) avg_peak[s] /= Real(peak_count);
          }

          *csv_out << "\n# Showing cell " << c << "\nSpecies";
          for (specie_id const& lcfID : this->observed_species_)
              *csv_out << ',' << specie_str[lcfID];

          csv_out->add_div("\navg peak,");
          for (std::size_t s = 0; s < this->observed_species_.size(); ++s)
              csv_out->add_data(avg_peak[s]);

          csv_out->add_div("\navg amp,");
          for (std::size_t s = 0; s < this->observed_species_.size(); ++s)
              csv_out->add_data(amplitudes[s][c]);

          csv_out->add_div("\navg per,");
          for (std::size_t s = 0; s < this->observed_species_.size(); ++s)
              csv_out->add_data(periods[s][c]);
      }
  }
}


/*
 * GET_PEAKS_AND_TROUGHS
 * advances the local range window and identifies critical points
 * arg "start": context iterator to access conc levels with
 * arg "c": the cell the context inhabits
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::get_peaks_and_troughs (Simulation const& simulation, int c) {

    for (std::size_t i = 0; i < this->observed_species_.size(); ++i)
    {
        Real added = simulation.get_concentration(c + this->min, this->observed_species_[i]);
        windows[i][c].enqueue(added);
        bst[i][c].insert(added);
        if ( windows[i][c].getSize() == range_steps + 1) {
            Real removed = windows[i][c].dequeue();
            bst[i][c].erase(bst[i][c].find(removed));
        }
        if ( windows[i][c].getSize() < range_steps/2) {
            return;
        }
	    checkCritPoint(i, c);
    }
}

/*
 * CHECKCRITPOINT
 * determines if a particular specie conc level in a particular cell is a peak, trough, or neither
 * arg "c": the cell this concentration level is found in
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::checkCritPoint (int s, int c) {
	Real mid_conc = windows[s][c].getVal(windows[s][c].getCurrent());
	if (mid_conc == *bst[s][c].rbegin() && mid_conc != *bst[s][c].begin()) {
		addCritPoint(s,c, crit_point{ std::max<Real>(0.0,(this->samples - range_steps/2)*analysis_interval + this->start_time),mid_conc, true });
	}
	else if (mid_conc == *bst[s][c].begin()) {
		addCritPoint(s,c, crit_point{ std::max<Real>(0.0,(this->samples - (range_steps/2))*analysis_interval + this->start_time),mid_conc, false });
	}
}

/*
 * ADDCRITPOINT
 * adds the peak or trough to the "crit_point" vector if it is an oscillating feature (no two peaks or two troughs in a row)
 * arg "context": context iterator to access conc levels with
 * arg "isPeak": bool is true if the conc level is a peak and false if it is a trough
 * arg "minute": time, in minutes, that the critical point occurs
 * arg "concentration": the concentration level of the critical point
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::addCritPoint (int s, int context, crit_point crit) {
	if (peaksAndTroughs[s][context].size() > 0){
		crit_point prev_crit = peaksAndTroughs[s][context].back();
		if (prev_crit.is_peak == crit.is_peak){
			if (crit.is_peak ? (crit.conc >= prev_crit.conc) : (crit.conc <= prev_crit.conc)){
				peaksAndTroughs[s][context].back() = crit;
			}
		}
		else {
			peaksAndTroughs[s][context].push_back(crit);
		}
	} else {
		peaksAndTroughs[s][context].push_back(crit);
	}
}

/*
 * UPDATE
 * called by attached observables in "notify" function
 * main analysis function
 * arg "start": context iterator to access con levels with
 * precondition: "start" inhabits cell 0
 * postcondtion: "start" inhabits an invalid cell
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::update (Simulation& simulation, std::ostream&) {
	for (Natural c = this->min; c < this->max; ++c) {
		get_peaks_and_troughs(simulation, c - this->min);
	}
	++this->samples;
}

/*
 * CALCAMPSANDPERS
 * calculates amplitudes and periods off of current analysis data
 * arg "c": the cell to analysis amplitudes and periods from
*/
template <typename Simulation>
void OscillationAnalysis<Simulation>::calcAmpsAndPers (int s, int c) {
	std::vector<crit_point> crits = peaksAndTroughs[s][c];
    Real peakSum = 0.0, troughSum = 0.0, cycleSum = 0.0;
    int numPeaks = 0, numTroughs = 0, cycles = 0;
	for (std::size_t i = 0; i < crits.size(); ++i) {
    auto& sum = crits[i].is_peak ? peakSum : troughSum;
    auto& count = crits[i].is_peak ? numPeaks : numTroughs;
		sum += crits[i].conc;
		++count;
		if (i < 2){
			continue;
		}
		++cycles;
		cycleSum+=(crits[i].time-crits[i-2].time);
	}
	amplitudes[s][c] = ((peakSum/numPeaks)-(troughSum/numTroughs))/2;
	periods[s][c] = cycleSum/cycles;
}

Disambiguation rules

Linguist heuristic rules that predict this language when one of its claimed extensions is shared with another.
RuleExtKindPredicates (truncated)
h/linguist/.h/1.hpredicates[{"kind": "any", "regexes": ["^\\s*#\\s*include <(cstdint|string|vector|map|list|array|bitset|queue|stack|forward_list|unordered_map|unordered_set|(i|o|io)stream)>", "^\\s*template\\s*<", "^[ \\t]*(tr
h/linguist/.re/1.repredicates[{"kind": "any", "regexes": ["^\\s*#(?:(?:if|ifdef|define|pragma)\\s+\\w|\\s*include\\s+<[^>]+>)", "^\\s*template\\s*<"]}]

Contribute — propose a file extension

Tell us where to find evidence about C++ (mapped to pl/cpp). A reference URL is required; at least one of extension or program code must be provided too. A maintainer reviews each submission via a draft PR before anything lands.
Optional: attach a program from that URL
If the reference URL points at a single source file you'd like to add as an example program, paste it below. The workflow will write it under languages/C++/programs/<sha>/. Keep under ~200 lines.
(or open the pre-filled issue directly)
← C* C+++ →