blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
b01517202050413f04a8ae5dec1b957ba5955ade
704624668674a343b50e3edb5f5b2cbba8107875
/ortools/sat/samples/solve_all_solutions.cc
db711550e4ad3f567bd23b35d4287aee92ddf338
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athiselvam/or-tools
c53a1ff5a77a5ead8892bf0f33674984391d7a08
8738c076566fd844e145abc8805f0b374170254a
refs/heads/master
2020-04-05T11:59:33.645307
2018-11-08T18:18:15
2018-11-08T18:18:15
156,853,679
1
0
Apache-2.0
2018-11-09T11:34:06
2018-11-09T11:34:06
null
UTF-8
C++
false
false
1,855
cc
// Copyright 2010-2017 Google // 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 // // 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 "ortools/sat/cp_model.h" #include "ortools/sat/model.h" #include "ortools/sat/sat_parameters.pb.h" namespace operations_research { namespace sat { void SearchAllSolutions() { CpModelBuilder cp_model; const Domain domain(0, 2); const IntVar x = cp_model.NewIntVar(domain).WithName("x"); const IntVar y = cp_model.NewIntVar(domain).WithName("y"); const IntVar z = cp_model.NewIntVar(domain).WithName("z"); cp_model.AddNotEqual(x, y); Model model; // Tell the solver to enumerate all solutions. SatParameters parameters; parameters.set_enumerate_all_solutions(true); model.Add(NewSatParameters(parameters)); int num_solutions = 0; model.Add(NewFeasibleSolutionObserver([&](const CpSolverResponse& r) { LOG(INFO) << "Solution " << num_solutions; LOG(INFO) << " x = " << SolutionIntegerValue(r, x); LOG(INFO) << " y = " << SolutionIntegerValue(r, y); LOG(INFO) << " z = " << SolutionIntegerValue(r, z); num_solutions++; })); const CpSolverResponse response = SolveWithModel(cp_model, &model); LOG(INFO) << "Number of solutions found: " << num_solutions; } } // namespace sat } // namespace operations_research int main() { operations_research::sat::SearchAllSolutions(); return EXIT_SUCCESS; }
[ "lperron@google.com" ]
lperron@google.com
01d1176295d28fbc4ff6eb9ede99895d963483bc
039622ed6bdcdd1a00aec0bc419db4e8f4135424
/fuseentity.h
9ff15c3c1d1888365959cfe07a8b9c0f46c45706
[]
no_license
lookup69/fuseUtil
60d5155d85313bff358825364537639b654fb39c
b2297993e0cf318b1b347d923b9a0100a15168ab
refs/heads/master
2021-01-10T08:17:32.342876
2016-03-28T09:28:23
2016-03-28T09:28:23
54,880,469
0
0
null
null
null
null
UTF-8
C++
false
false
8,554
h
#ifndef _FUSEENTITY_H_ #define _FUSEENTITY_H_ #include "fuseoper.h" #include <assert.h> #include <memory> #include <stdio.h> class FuseEntity { private: struct fuse_operations m_fuseOper; static std::shared_ptr<FuseOper> m_operHook; public: FuseEntity(); FuseEntity(FuseOper *oper); ~FuseEntity(); void attachFuseOper(FuseOper *oper) { std::shared_ptr<FuseOper> tmpOperPtr(oper); m_operHook = tmpOperPtr; } int fuseMain(int argc, char *argv[]) { assert(m_operHook.get() != nullptr); return fuse_main(argc, argv, &m_fuseOper, NULL); } static int Getattr(const char *path, struct stat *stbuf) { assert(m_operHook.get() != nullptr); return m_operHook->Getattr(path, stbuf); } static int Fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Fgetattr(path, stbuf, fi); } static int Access(const char *path, int mask) { assert(m_operHook.get() != nullptr); return m_operHook->Access(path, mask); } static int Create(const char *path, mode_t mode, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Create(path, mode, fi); } static int Opendir(const char *path, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Opendir(path, fi); } static int Releasedir(const char *path, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Opendir(path, fi); } static int Readlink(const char *path, char *buf, size_t size) { assert(m_operHook.get() != nullptr); return m_operHook->Readlink(path, buf, size); } static int Readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Readdir(path, buf, filler, offset, fi); } static int Mknod(const char *path, mode_t mode, dev_t rdev) { assert(m_operHook.get() != nullptr); return m_operHook->Mknod(path, mode, rdev); } static int Mkdir(const char *path, mode_t mode) { assert(m_operHook.get() != nullptr); return m_operHook->Mkdir(path, mode); } static int Unlink(const char *path) { assert(m_operHook.get() != nullptr); return m_operHook->Unlink(path); } static int Rmdir(const char *path) { assert(m_operHook.get() != nullptr); return m_operHook->Rmdir(path); } static int Symlink(const char *from, const char *to) { assert(m_operHook.get() != nullptr); return m_operHook->Symlink(from, to); } static int Rename(const char *from, const char *to) { assert(m_operHook.get() != nullptr); return m_operHook->Rename(from, to); } static int Link(const char *from, const char *to) { assert(m_operHook.get() != nullptr); return m_operHook->Link(from, to); } static int Chmod(const char *path, mode_t mode) { assert(m_operHook.get() != nullptr); return m_operHook->Chmod(path, mode); } static int Chown(const char *path, uid_t uid, gid_t gid) { assert(m_operHook.get() != nullptr); return m_operHook->Chown(path, uid, gid); } static int Truncate(const char *path, off_t size) { assert(m_operHook.get() != nullptr); return m_operHook->Truncate(path, size); } static int Ftruncate(const char *path, off_t size, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Ftruncate(path, size, fi); } static int Open(const char *path, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Open(path, fi); } static int Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Read(path, buf, size, offset, fi); } static int Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Write(path, buf, size, offset, fi); } static int ReadBuf(const char *path, struct fuse_bufvec **bufp, size_t size, off_t offset, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->ReadBuf(path, bufp, size, offset, fi); } static int WriteBuf(const char *path, struct fuse_bufvec *buf, off_t offset, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->WriteBuf(path, buf, offset, fi); } static int Statfs(const char *path, struct statvfs *stbuf) { assert(m_operHook.get() != nullptr); return m_operHook->Statfs(path, stbuf); } static int Fsync(const char *path, int isdatasync, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Fsync(path, isdatasync, fi); } static int Flush(const char *path, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Flush(path, fi); } static int Release(const char *path, struct fuse_file_info *fi) { assert(m_operHook.get() != nullptr); return m_operHook->Release(path, fi); } static int Setxattr(const char *path, const char *name, const char *value, size_t size, int flags) { assert(m_operHook.get() != nullptr); return m_operHook->Setxattr(path, name, value, size, flags); } static int Getxattr(const char *path, const char *name, char *value, size_t size) { assert(m_operHook.get() != nullptr); return m_operHook->Getxattr(path, name, value, size); } static int Listxattr(const char *path, char *list, size_t size) { assert(m_operHook.get() != nullptr); return m_operHook->Listxattr(path, list, size); } static int Removexattr(const char *path, const char *name) { assert(m_operHook.get() != nullptr); return m_operHook->Removexattr(path, name); } static int Ioctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi, unsigned int flags, void *data) { assert(m_operHook.get() != nullptr); return m_operHook->Ioctl(path, cmd, arg, fi, flags, data); } static int Lock(const char *path, struct fuse_file_info *fi, int cmd, struct flock *lock) { assert(m_operHook.get() != nullptr); return m_operHook->Lock(path, fi, cmd, lock); } static int Flock(const char *path, struct fuse_file_info *fi, int op) { assert(m_operHook.get() != nullptr); return m_operHook->Flock(path, fi, op); } static int Utimens(const char *path, const struct timespec ts[2]) { assert(m_operHook.get() != nullptr); return m_operHook->Utimens(path, ts); } }; #endif
[ "archerchang@qnap.com" ]
archerchang@qnap.com
573398db25e974293490de008c0d4d2cfa732a49
6999cadecfcaeac4ab5d33e4645395c9e34c43cc
/framework/src/Primitives.h
a47b0351df8b87c46cb587d50fac5c6eb8245128
[]
no_license
fgan/cs184
f18d341ef263ae4b7567d5e26f9f2b0f4af2a192
3b4bc93c49a8d3efdff94839c8f2aa60f8c69130
refs/heads/master
2020-06-06T12:02:33.086406
2011-05-10T23:02:41
2011-05-10T23:02:41
1,726,534
0
1
null
null
null
null
UTF-8
C++
false
false
1,610
h
/* * Primitive.h * * Created on: Feb 19, 2009 * Author: njoubert * (edited by jima) */ #ifndef PRIMITIVE_H_ #define PRIMITIVE_H_ #include "global.h" #include "UCB/SceneInfo.h" struct Light { Light() {} Light(vec3 pos, vec3 dir, LightInfo l) : _l(l), _pos(pos), _dir(dir) {} inline const LightInfo& getLightInfo() { return _l; } inline const vec3& getPosition() { return _pos; } inline const vec3& getDirection() { return _dir; } private: LightInfo _l; vec3 _pos, _dir; }; class Sphere { public: Sphere(vec4 center, double radius, MaterialInfo m, mat4 sphereToWorldMatrix); double intersect(Ray & ray); vec4 calculateNormal(vec4 & position); inline MaterialInfo& getMaterial() { return _m; } double getRefractiveIndex() {return _m.k[MAT_KTN];} vec4 getCenter(); double getRadius(); void getAxisAlignedBounds(vec3 & upperBound, vec3 & lowerBound); private: vec4 _p; double _r; MaterialInfo _m; mat4 _worldToSphere; mat4 _sphereToWorld; mat4 _sphereNormToWorldNorm; vec3 _upperAxisAlignedBound; vec3 _lowerAxisAlignedBound; // these won't be needed until you want to stretch the spheres: // mat4 _modelToWorld; // mat4 _worldToModel; }; class Cube { public: Cube(vec4 center, double sideLength, MaterialInfo m, string filename = "texture.bmp"); double intersect(Ray & ray); vec4 calculateNormal(vec4 & position); vec3 calculateColor(vec4 & position); inline MaterialInfo& getMaterial() { return _m; } private: vec3 _upperCorner; vec3 _lowerCorner; double _sideLength; MaterialInfo _m; FIBITMAP *_bitmap; }; #endif /* PRIMITIVE_H_ */
[ "frank.yugan@gmail.com" ]
frank.yugan@gmail.com
763ab38809800991f664bb62c38ad193bff10185
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-proton/include/aws/proton/model/ListEnvironmentProvisionedResourcesRequest.h
4fafb0e55a04328fa8da97b57c3b05d40f17d2ce
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
5,708
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/proton/Proton_EXPORTS.h> #include <aws/proton/ProtonRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Proton { namespace Model { /** */ class AWS_PROTON_API ListEnvironmentProvisionedResourcesRequest : public ProtonRequest { public: ListEnvironmentProvisionedResourcesRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListEnvironmentProvisionedResources"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The environment name.</p> */ inline const Aws::String& GetEnvironmentName() const{ return m_environmentName; } /** * <p>The environment name.</p> */ inline bool EnvironmentNameHasBeenSet() const { return m_environmentNameHasBeenSet; } /** * <p>The environment name.</p> */ inline void SetEnvironmentName(const Aws::String& value) { m_environmentNameHasBeenSet = true; m_environmentName = value; } /** * <p>The environment name.</p> */ inline void SetEnvironmentName(Aws::String&& value) { m_environmentNameHasBeenSet = true; m_environmentName = std::move(value); } /** * <p>The environment name.</p> */ inline void SetEnvironmentName(const char* value) { m_environmentNameHasBeenSet = true; m_environmentName.assign(value); } /** * <p>The environment name.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithEnvironmentName(const Aws::String& value) { SetEnvironmentName(value); return *this;} /** * <p>The environment name.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithEnvironmentName(Aws::String&& value) { SetEnvironmentName(std::move(value)); return *this;} /** * <p>The environment name.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithEnvironmentName(const char* value) { SetEnvironmentName(value); return *this;} /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>A token that indicates the location of the next environment provisioned * resource in the array of environment provisioned resources, after the list of * environment provisioned resources that was previously requested.</p> */ inline ListEnvironmentProvisionedResourcesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::String m_environmentName; bool m_environmentNameHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; }; } // namespace Model } // namespace Proton } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
08418986f6399ee34c7445a25a5692409799e97a
9b7d378b24b1bdab54ad2c6055e4855e118ee62c
/tool/ebcutil.cpp
26b315393ed308c5f7dafc8523b39e83412e8128
[ "Apache-2.0" ]
permissive
jetming/LibEBC
6402d2898beaeda78d6eaee5ae250fc0f9583455
de19754245088754244d53f0e60ca655379196d0
refs/heads/master
2022-12-07T22:51:18.546338
2020-09-03T02:58:00
2020-09-03T02:58:00
292,451,047
0
0
null
2020-09-03T02:58:52
2020-09-03T02:58:51
null
UTF-8
C++
false
false
6,062
cpp
#include "ebc/BitcodeArchive.h" #include "ebc/BitcodeContainer.h" #include "ebc/BitcodeMetadata.h" #include "ebc/BitcodeRetriever.h" #include "ebc/EmbeddedBitcode.h" #include "ebc/EmbeddedFile.h" #include <tclap/CmdLine.h> #include <rang/rang.hpp> #include <iomanip> #include <iostream> using namespace ebc; static constexpr auto VERSION = "@VERSION_MAJOR@.@VERSION_MINOR@ (@GIT_COMMIT_HASH@)"; static constexpr int WIDTH = 12; static constexpr int WIDTH_NESTED = 14; static std::string filePrefix(const EmbeddedFile& file) { switch (file.GetType()) { case EmbeddedFile::Type::Bitcode: { auto bitcodeFile = static_cast<const EmbeddedBitcode&>(file); switch (bitcodeFile.GetBitcodeType()) { case BitcodeType::BitcodeWrapper: return "Wrapper:"; case BitcodeType::IR: return "IR:"; case BitcodeType::LTO: return "LTO:"; default: return "Bitcode:"; } } case EmbeddedFile::Type::Xar: return "Xar:"; case EmbeddedFile::Type::LTO: return "LTO:"; case EmbeddedFile::Type::Object: return "Object:"; case EmbeddedFile::Type::File: return "File:"; case EmbeddedFile::Type::Exports: return "Exports:"; } } static void printContainerInfo(const BitcodeContainer& bitcodeContainer) { std::cout << rang::style::bold << bitcodeContainer.GetBinaryMetadata().GetFileFormatName() << rang::style::reset << std::endl; std::cout << std::setw(WIDTH) << "File name:" << " " << bitcodeContainer.GetBinaryMetadata().GetFileName() << std::endl; std::cout << std::setw(WIDTH) << "Arch:" << " " << bitcodeContainer.GetBinaryMetadata().GetArch() << std::endl; std::cout << std::setw(WIDTH) << "UUID:" << " " << bitcodeContainer.GetBinaryMetadata().GetUUID() << std::endl; } static void printArchiveInfo(const BitcodeArchive& bitcodeArchive) { std::cout << std::setw(WIDTH) << "Dylibs:"; bool indent = false; for (const auto& dylib : bitcodeArchive.GetMetadata().GetDylibs()) { if (indent) { std::cout << std::setw(WIDTH) << " "; } else { indent = true; } std::cout << " " << dylib << std::endl; } std::cout << std::setw(WIDTH) << "Link opts:"; for (const auto& option : bitcodeArchive.GetMetadata().GetLinkOptions()) { std::cout << " " << option; } std::cout << std::endl; } static void printEmbeddedFiles(const BitcodeContainer& bitcodeContainer, bool extract) { auto embeddedFiles = bitcodeContainer.GetEmbeddedFiles(); if (embeddedFiles.empty()) { std::cout << std::setw(WIDTH) << "Bitcode:" << " marker only" << std::endl; return; } for (auto& embeddedFile : embeddedFiles) { std::cout << std::setw(WIDTH) << filePrefix(*embeddedFile) << " " << embeddedFile->GetName() << std::endl; if (!extract) { embeddedFile->Remove(); } auto commands = embeddedFile->GetCommands(); if (!commands.empty()) { std::cout << std::setw(WIDTH_NESTED) << "Clang:"; for (auto& command : commands) { std::cout << " " << command; } std::cout << std::endl; } } } static void printDetailled(const BitcodeContainer& bitcodeContainer, bool extract) { printContainerInfo(bitcodeContainer); if (bitcodeContainer.IsArchive()) { const auto& bitcodeArchive = static_cast<const BitcodeArchive&>(bitcodeContainer); printArchiveInfo(bitcodeArchive); } printEmbeddedFiles(bitcodeContainer, extract); } static void printSimple(const BitcodeContainer& bitcodeContainer, bool extract) { std::cout << bitcodeContainer.GetBinaryMetadata().GetFileName() << " (" << bitcodeContainer.GetBinaryMetadata().GetArch() << "): "; auto embeddedFiles = bitcodeContainer.GetEmbeddedFiles(); if (embeddedFiles.empty()) { std::cout << "Bitcode marker only" << std::endl; return; } for (auto& embeddedFile : embeddedFiles) { std::cout << embeddedFile->GetName() << " "; if (!extract) { embeddedFile->Remove(); } } std::cout << std::endl; } int main(int argc, char* argv[]) { try { // Command line arguments TCLAP::CmdLine cmd("Embedded Bitcode Tool", ' ', VERSION, true); TCLAP::SwitchArg extractArg("e", "extract", "Extract bitcode files", cmd, false); TCLAP::SwitchArg simpleArg("s", "simple", "Simple output, no details", cmd, false); TCLAP::ValueArg<std::string> archArg("a", "arch", "Limit to a single architecture", false, "", "string"); cmd.add(archArg); TCLAP::ValueArg<std::string> prefixArg("p", "prefix", "Prefix the files extracted by ebcutil", false, "", "string"); cmd.add(prefixArg); TCLAP::UnlabeledValueArg<std::string> fileArg("File", "Binary file", true, "", "file"); cmd.add(fileArg); cmd.parse(argc, argv); const bool extract = extractArg.getValue(); BitcodeRetriever bitcodeRetriever(fileArg.getValue()); for (auto& bitcodeInfo : bitcodeRetriever.GetBitcodeInfo()) { if (archArg.isSet() && archArg.getValue() != bitcodeInfo.arch) { continue; } if (!bitcodeInfo.bitcodeContainer) { std::cout << "No bitcode for architecture '" << bitcodeInfo.arch << "'" << std::endl; continue; } if (prefixArg.isSet()) { bitcodeInfo.bitcodeContainer->SetPrefix(prefixArg.getValue()); } if (simpleArg.getValue()) { printSimple(*bitcodeInfo.bitcodeContainer, extract); } else { printDetailled(*bitcodeInfo.bitcodeContainer, extract); } } } catch (TCLAP::ArgException& e) { std::cerr << rang::fg::red << "Error: " << rang::fg::reset << e.error() << " for arg " << e.argId() << std::endl; return EXIT_FAILURE; } catch (std::exception& e) { std::cerr << rang::fg::red << "Error: " << rang::fg::reset << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << rang::fg::red << "Error: " << rang::fg::reset << "exiting" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
[ "jonas@devlieghere.com" ]
jonas@devlieghere.com
3f26dec6c2482a92c3aa433008579608de3960de
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/Handle_StepShape_FacetedBrep.hxx
08d6d896af568e55dae9cadd2b73780208a5c3dc
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
865
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_StepShape_FacetedBrep_HeaderFile #define _Handle_StepShape_FacetedBrep_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_StepShape_ManifoldSolidBrep_HeaderFile #include <Handle_StepShape_ManifoldSolidBrep.hxx> #endif class Standard_Transient; class Handle(Standard_Type); class Handle(StepShape_ManifoldSolidBrep); class StepShape_FacetedBrep; DEFINE_STANDARD_HANDLE(StepShape_FacetedBrep,StepShape_ManifoldSolidBrep) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
da01544e5f08ca26c6f8d5c4e9cc68d93b48c4a5
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Source/Runtime/Core/Public/Misc/LocalTimestampDirectoryVisitor.h
d19721d89caa22b75ba78ed4a9fd6561b1e335e2
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
1,427
h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once /** * Visitor to gather local files with their timestamps. */ class CORE_API FLocalTimestampDirectoryVisitor : public IPlatformFile::FDirectoryVisitor { public: /** Relative paths to local files and their timestamps. */ TMap<FString, FDateTime> FileTimes; /** * Creates and initializes a new instance. * * @param InFileInterface - The platform file interface to use. * @param InDirectoriesToIgnore - The list of directories to ignore. * @param InDirectoriesToNotRecurse - The list of directories to not visit recursively. * @param bInCacheDirectories - Whether to cache the directories. */ FLocalTimestampDirectoryVisitor( IPlatformFile& InFileInterface, const TArray<FString>& InDirectoriesToIgnore, const TArray<FString>& InDirectoriesToNotRecurse, bool bInCacheDirectories = false ); public: // IPlatformFile::FDirectoryVisitor interface virtual bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory); private: // true if we want directories in this list. */ bool bCacheDirectories; // Holds a list of directories that we should not traverse into. */ TArray<FString> DirectoriesToIgnore; // Holds a list of directories that we should only go one level into. */ TArray<FString> DirectoriesToNotRecurse; // Holds the file interface to use for any file operations. */ IPlatformFile& FileInterface; };
[ "dkroell@acm.org" ]
dkroell@acm.org
6a69302b488c474c24c49ba186bedb86b382fb19
b06713320cd3f78218d28fcaeba3fb0784e557da
/code.cpp
a1f68708bb73fa8de18f276f86e1af5c0604235a
[]
no_license
ChristopherOwenFPV/ChristopherOwenFPV.github.io
f9fba91f57dfc4da1a48d8d4177e04b98b9178e4
3c92efe8e180ead9d7506ce8396522512899955c
refs/heads/main
2021-12-03T00:23:00.905027
2021-11-03T02:45:00
2021-11-03T02:45:00
157,265,340
0
0
null
null
null
null
UTF-8
C++
false
false
84
cpp
#include<iostream> using namespace std; int main() { cout << "test" << endl; }
[ "christopherowen125@gmail.com" ]
christopherowen125@gmail.com
a0e193530403d227bf8ccbd1e9b8375a3de7645f
06b1959aa801e35c972febbfd7b84bf76833d13a
/Lab3/Practice3_2/Practice3_2/Header.h
57fdf2472db63eda19cbe6708f4f0116233e415b
[]
no_license
blakexdd/labs_cpp
89e7493d8518f487b20ab703f525bc960a1771f2
fff4d2e50b1a060b4b51857f6cafcbaa5007d0ef
refs/heads/master
2020-09-10T16:48:42.590836
2019-12-19T03:50:14
2019-12-19T03:50:14
221,760,966
0
0
null
null
null
null
UTF-8
C++
false
false
1,825
h
/* FILE NAME: Header.h * PROGRAMMER: VG6 * DATE: 28.09.2019 * PURPOSE: header for Practice3_2.cpp */ #include <iostream> #include <math.h> /* Ititialize float as FLT*/ typedef float FLT; /* Ititialize int as INT*/ typedef int INT; /* make 3d vector type */ typedef struct tagVEC { FLT X, Y, Z; } VEC; /* make 2d vector type */ typedef struct tagVEC2 { FLT X, Y; /* Vector components */ } VEC2; /* setting 2d vectors. * ARGUMENTS: * - vector coordinates: * FLT X, FLT Y; * RETURNS: * -vector * VEC2. */ VEC2 VecSet2(FLT X, FLT Y) { VEC2 v = { X, Y }; return v; } /* setting 3d vectors. * ARGUMENTS: * - vector coordinates: * FLT X, FLT Y, FLT Z; * RETURNS: * -vector * VEC. */ VEC VecSet3(FLT X, FLT Y, FLT Z) { VEC v = { X, Y, Z }; return v; } /* making vector from two points. * ARGUMENTS: * - points: * FLT X1, FLT Y1, FLT X2, FLT Y2; * RETURNS: * -vector * VEC2. */ VEC2 MakeVec2(FLT X1, FLT Y1, FLT X2, FLT Y2) { VEC2 v = { X2 - X1, Y2 - Y1 }; return v; } /* cross operation. * ARGUMENTS: * - two vectors: * VEC2 V1, VEC2 V2; * RETURNS: * -vector * VEC. */ VEC VecCrossVec(VEC2 V1, VEC2 V2) { return VecSet3(0, 0, V1.X * V2.Y + V1.Y * V2.X); } /* finding square of figure. * ARGUMENTS: * - vector: * VEC V; * RETURNS: * -square * FLT. */ FLT Square(VEC V) { return V.Z; } /* finding square of triangle. * ARGUMENTS: * - lenght of one side: * FLT a; * RETURNS: * -square * FLT. */ FLT Square(FLT a) { return a * a * sqrt(3) / 4; } /* finding side length. * ARGUMENTS: * - two triangle coordinates: * FLT X1, FLT Y1, FLT X2, FLT Y2; * RETURNS: * -square * FLT. */ FLT SideLength(FLT X1, FLT Y1, FLT X2, FLT Y2) { VEC2 a = MakeVec2(X1, Y1, X2, Y2); return sqrt(a.X * a.X + a.Y * a.Y); }
[ "39838109+blakexdd@users.noreply.github.com" ]
39838109+blakexdd@users.noreply.github.com
f1367bc831b7abfea25851b7062189e41767b9c3
c475cd8531a94ffae69cc92371d41531dbbddb6c
/Projects/bullet3-2.89/examples/ThirdPartyLibs/Gwen/Controls/VerticalSlider.h
7b19cd2bae62d36a7c22f2e729278a78b0218b51
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "Zlib" ]
permissive
WolfireGames/overgrowth
72d3dd29cbd7254337265c29f8de3e5c32400114
594a2a4f9da0855304ee8cd5335d042f8e954ce1
refs/heads/main
2023-08-15T19:36:56.156578
2023-05-17T08:17:53
2023-05-17T08:20:36
467,448,492
2,264
245
Apache-2.0
2023-05-09T07:29:58
2022-03-08T09:38:54
C++
UTF-8
C++
false
false
741
h
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #pragma once #ifndef GWEN_CONTROLS_VERTICALSLIDER_H #define GWEN_CONTROLS_VERTICALSLIDER_H #include "Gwen/Controls/Base.h" #include "Gwen/Controls/Button.h" #include "Gwen/Controls/Dragger.h" #include "Gwen/Gwen.h" #include "Gwen/Skin.h" #include "Gwen/Controls/Slider.h" namespace Gwen { namespace Controls { class GWEN_EXPORT VerticalSlider : public Slider { GWEN_CONTROL(VerticalSlider, Slider); virtual void Layout(Skin::Base* skin); virtual void Render(Skin::Base* skin); virtual float CalculateValue(); virtual void UpdateBarFromValue(); virtual void OnMouseClickLeft(int x, int y, bool bDown); }; } // namespace Controls } // namespace Gwen #endif
[ "max@autious.net" ]
max@autious.net
116b7aec9714ee1b5153656f29e4e46191f2a567
3f713aed2756c7b6dc090dc0a69b9d1fd592da12
/src/net.h
544f4fa3130c1618fc52315ba0e8974422d94092
[ "MIT" ]
permissive
anyagixx/xorx
ba1a64fdf799c2b74a4b35aefa57ab630e8a0e6b
974709b63c6233a37d08f914b723e513e0ef5e44
refs/heads/master
2020-03-27T00:55:44.889288
2019-05-15T09:51:43
2019-05-15T09:51:43
145,667,570
0
0
null
null
null
null
UTF-8
C++
false
false
21,093
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NET_H #define BITCOIN_NET_H #include "bloom.h" #include "compat.h" #include "hash.h" #include "limitedmap.h" #include "mruset.h" #include "netbase.h" #include "protocol.h" #include "random.h" #include "streams.h" #include "sync.h" #include "uint256.h" #include "utilstrencodings.h" #include <deque> #include <stdint.h> #ifndef WIN32 #include <arpa/inet.h> #endif #include <boost/filesystem/path.hpp> #include <boost/foreach.hpp> #include <boost/signals2/signal.hpp> class CAddrMan; class CBlockIndex; class CNode; namespace boost { class thread_group; } // namespace boost /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */ static const int PING_INTERVAL = 2 * 60; /** Time after which to disconnect, after waiting for a ping response (or inactivity). */ static const int TIMEOUT_INTERVAL = 20 * 60; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024; /** -listen default */ static const bool DEFAULT_LISTEN = true; /** -upnp default */ #ifdef USE_UPNP static const bool DEFAULT_UPNP = USE_UPNP; #else static const bool DEFAULT_UPNP = false; #endif /** The maximum number of entries in mapAskFor */ static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ; unsigned int ReceiveFloodSize(); unsigned int SendBufferSize(); void AddOneShot(std::string strDest); bool RecvLine(SOCKET hSocket, std::string& strLine); void AddressCurrentlyConnected(const CService& addr); CNode* FindNode(const CNetAddr& ip); CNode* FindNode(const std::string& addrName); CNode* FindNode(const CService& ip); CNode* ConnectNode(CAddress addrConnect, const char* pszDest = NULL, bool obfuScationMaster = false); bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound = NULL, const char* strDest = NULL, bool fOneShot = false); void MapPort(bool fUseUPnP); unsigned short GetListenPort(); bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false); void StartNode(boost::thread_group& threadGroup); bool StopNode(); void SocketSendData(CNode* pnode); typedef int NodeId; // Signals for message handling struct CNodeSignals { boost::signals2::signal<int()> GetHeight; boost::signals2::signal<bool(CNode*)> ProcessMessages; boost::signals2::signal<bool(CNode*, bool)> SendMessages; boost::signals2::signal<void(NodeId, const CNode*)> InitializeNode; boost::signals2::signal<void(NodeId)> FinalizeNode; }; CNodeSignals& GetNodeSignals(); enum { LOCAL_NONE, // unknown LOCAL_IF, // address a local interface listens on LOCAL_BIND, // address explicit bound to LOCAL_UPNP, // address reported by UPnP LOCAL_MANUAL, // address explicitly specified (-externalip=) LOCAL_MAX }; bool IsPeerAddrLocalGood(CNode* pnode); void AdvertizeLocal(CNode* pnode); void SetLimited(enum Network net, bool fLimited = true); bool IsLimited(enum Network net); bool IsLimited(const CNetAddr& addr); bool AddLocal(const CService& addr, int nScore = LOCAL_NONE); bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE); bool RemoveLocal(const CService& addr); bool SeenLocal(const CService& addr); bool IsLocal(const CService& addr); bool GetLocal(CService& addr, const CNetAddr* paddrPeer = NULL); bool IsReachable(enum Network net); bool IsReachable(const CNetAddr& addr); void SetReachable(enum Network net, bool fFlag = true); CAddress GetLocalAddress(const CNetAddr* paddrPeer = NULL); extern bool fDiscover; extern bool fListen; extern uint64_t nLocalServices; extern uint64_t nLocalHostNonce; extern CAddrMan addrman; extern int nMaxConnections; extern std::vector<CNode*> vNodes; extern CCriticalSection cs_vNodes; extern std::map<CInv, CDataStream> mapRelay; extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration; extern CCriticalSection cs_mapRelay; extern limitedmap<CInv, int64_t> mapAlreadyAskedFor; extern std::vector<std::string> vAddedNodes; extern CCriticalSection cs_vAddedNodes; extern NodeId nLastNodeId; extern CCriticalSection cs_nLastNodeId; struct LocalServiceInfo { int nScore; int nPort; }; extern CCriticalSection cs_mapLocalHost; extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost; class CNodeStats { public: NodeId nodeid; uint64_t nServices; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; std::string addrName; int nVersion; std::string cleanSubVer; bool fInbound; int nStartingHeight; uint64_t nSendBytes; uint64_t nRecvBytes; bool fWhitelisted; double dPingTime; double dPingWait; std::string addrLocal; }; class CNetMessage { public: bool in_data; // parsing header (false) or data (true) CDataStream hdrbuf; // partially received header CMessageHeader hdr; // complete header unsigned int nHdrPos; CDataStream vRecv; // received message data unsigned int nDataPos; int64_t nTime; // time (in microseconds) of message receipt. CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) { hdrbuf.resize(24); in_data = false; nHdrPos = 0; nDataPos = 0; nTime = 0; } bool complete() const { if (!in_data) return false; return (hdr.nMessageSize == nDataPos); } void SetVersion(int nVersionIn) { hdrbuf.SetVersion(nVersionIn); vRecv.SetVersion(nVersionIn); } int readHeader(const char* pch, unsigned int nBytes); int readData(const char* pch, unsigned int nBytes); }; /** Information about a peer */ class CNode { public: // socket uint64_t nServices; SOCKET hSocket; CDataStream ssSend; size_t nSendSize; // total size of all vSendMsg entries size_t nSendOffset; // offset inside the first vSendMsg already sent uint64_t nSendBytes; std::deque<CSerializeData> vSendMsg; CCriticalSection cs_vSend; std::deque<CInv> vRecvGetData; std::deque<CNetMessage> vRecvMsg; CCriticalSection cs_vRecvMsg; uint64_t nRecvBytes; int nRecvVersion; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; CAddress addr; std::string addrName; CService addrLocal; int nVersion; // strSubVer is whatever byte array we read from the xorx. However, this field is intended // to be printed out, displayed to humans in various forms and so on. So we sanitize it and // store the sanitized version in cleanSubVer. The original should be used when dealing with // the network or xorx types and the cleaned string used when displayed or logged. std::string strSubVer, cleanSubVer; bool fWhitelisted; // This peer can bypass DoS banning. bool fOneShot; bool fClient; bool fInbound; bool fNetworkNode; bool fSuccessfullyConnected; bool fDisconnect; // We use fRelayTxes for two purposes - // a) it allows us to not relay tx invs before receiving the peer's version message // b) the peer may tell us in their version message that we should not relay tx invs // until they have initialized their bloom filter. bool fRelayTxes; // Should be 'true' only if we connected to this node to actually mix funds. // In this case node will be released automatically via CMasternodeMan::ProcessMasternodeConnections(). // Connecting to verify connectability/status or connecting for sending/relaying single message // (even if it's relative to mixing e.g. for blinding) should NOT set this to 'true'. // For such cases node should be released manually (preferably right after corresponding code). bool fObfuScationMaster; CSemaphoreGrant grantOutbound; CCriticalSection cs_filter; CBloomFilter* pfilter; int nRefCount; NodeId id; protected: // Denial-of-service detection/prevention // Key is IP address, value is banned-until-time static std::map<CNetAddr, int64_t> setBanned; static CCriticalSection cs_setBanned; std::vector<std::string> vecRequestsFulfilled; //keep track of what client has asked for // Whitelisted ranges. Any node connecting from these is automatically // whitelisted (as well as those connecting to whitelisted binds). static std::vector<CSubNet> vWhitelistedRange; static CCriticalSection cs_vWhitelistedRange; // Basic fuzz-testing void Fuzz(int nChance); // modifies ssSend public: uint256 hashContinue; int nStartingHeight; // flood relay std::vector<CAddress> vAddrToSend; mruset<CAddress> setAddrKnown; bool fGetAddr; std::set<uint256> setKnown; // inventory based relay mruset<CInv> setInventoryKnown; std::vector<CInv> vInventoryToSend; CCriticalSection cs_inventory; std::multimap<int64_t, CInv> mapAskFor; std::vector<uint256> vBlockRequested; // Ping time measurement: // The pong reply we're expecting, or 0 if no pong expected. uint64_t nPingNonceSent; // Time (in usec) the last ping was sent, or 0 if no ping was ever sent. int64_t nPingUsecStart; // Last measured round-trip time. int64_t nPingUsecTime; // Whether a ping is requested. bool fPingQueued; CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn = false); ~CNode(); private: // Network usage totals static CCriticalSection cs_totalBytesRecv; static CCriticalSection cs_totalBytesSent; static uint64_t nTotalBytesRecv; static uint64_t nTotalBytesSent; CNode(const CNode&); void operator=(const CNode&); public: NodeId GetId() const { return id; } int GetRefCount() { assert(nRefCount >= 0); return nRefCount; } // requires LOCK(cs_vRecvMsg) unsigned int GetTotalRecvSize() { unsigned int total = 0; BOOST_FOREACH (const CNetMessage& msg, vRecvMsg) total += msg.vRecv.size() + 24; return total; } // requires LOCK(cs_vRecvMsg) bool ReceiveMsgBytes(const char* pch, unsigned int nBytes); // requires LOCK(cs_vRecvMsg) void SetRecvVersion(int nVersionIn) { nRecvVersion = nVersionIn; BOOST_FOREACH (CNetMessage& msg, vRecvMsg) msg.SetVersion(nVersionIn); } CNode* AddRef() { nRefCount++; return this; } void Release() { nRefCount--; } void AddAddressKnown(const CAddress& addr) { setAddrKnown.insert(addr); } void PushAddress(const CAddress& addr) { // Known checking here is only to save space from duplicates. // SendMessages will filter it again for knowns that were added // after addresses were pushed. if (addr.IsValid() && !setAddrKnown.count(addr)) { if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) { vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr; } else { vAddrToSend.push_back(addr); } } } void AddInventoryKnown(const CInv& inv) { { LOCK(cs_inventory); setInventoryKnown.insert(inv); } } void PushInventory(const CInv& inv) { { LOCK(cs_inventory); if (!setInventoryKnown.count(inv)) vInventoryToSend.push_back(inv); } } void AskFor(const CInv& inv); // TODO: Document the postcondition of this function. Is cs_vSend locked? void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void AbortMessage() UNLOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void EndMessage() UNLOCK_FUNCTION(cs_vSend); void PushVersion(); void PushMessage(const char* pszCommand) { try { BeginMessage(pszCommand); EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1> void PushMessage(const char* pszCommand, const T1& a1) { try { BeginMessage(pszCommand); ssSend << a1; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2) { try { BeginMessage(pszCommand); ssSend << a1 << a2; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11, const T12& a12) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11 << a12; EndMessage(); } catch (...) { AbortMessage(); throw; } } bool HasFulfilledRequest(std::string strRequest) { BOOST_FOREACH (std::string& type, vecRequestsFulfilled) { if (type == strRequest) return true; } return false; } void ClearFulfilledRequest(std::string strRequest) { std::vector<std::string>::iterator it = vecRequestsFulfilled.begin(); while (it != vecRequestsFulfilled.end()) { if ((*it) == strRequest) { vecRequestsFulfilled.erase(it); return; } ++it; } } void FulfilledRequest(std::string strRequest) { if (HasFulfilledRequest(strRequest)) return; vecRequestsFulfilled.push_back(strRequest); } bool IsSubscribed(unsigned int nChannel); void Subscribe(unsigned int nChannel, unsigned int nHops = 0); void CancelSubscribe(unsigned int nChannel); void CloseSocketDisconnect(); bool DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand = ""); // Denial-of-service detection/prevention // The idea is to detect peers that are behaving // badly and disconnect/ban them, but do it in a // one-coding-mistake-won't-shatter-the-entire-network // way. // IMPORTANT: There should be nothing I can give a // node that it will forward on that will make that // node's peers drop it. If there is, an attacker // can isolate a node and/or try to split the network. // Dropping a node for sending stuff that is invalid // now but might be valid in a later version is also // dangerous, because it can cause a network split // between nodes running old code and nodes running // new code. static void ClearBanned(); // needed for unit testing static bool IsBanned(CNetAddr ip); static bool Ban(const CNetAddr& ip); void copyStats(CNodeStats& stats); static bool IsWhitelistedRange(const CNetAddr& ip); static void AddWhitelistedRange(const CSubNet& subnet); // Network stats static void RecordBytesRecv(uint64_t bytes); static void RecordBytesSent(uint64_t bytes); static uint64_t GetTotalBytesRecv(); static uint64_t GetTotalBytesSent(); }; class CExplicitNetCleanup { public: static void callCleanup(); }; class CTransaction; void RelayTransaction(const CTransaction& tx); void RelayTransaction(const CTransaction& tx, const CDataStream& ss); void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll = false); void RelayInv(CInv& inv); /** Access to the (IP) address database (peers.dat) */ class CAddrDB { private: boost::filesystem::path pathAddr; public: CAddrDB(); bool Write(const CAddrMan& addr); bool Read(CAddrMan& addr); }; #endif // BITCOIN_NET_H
[ "anyagixx@yandex.ru" ]
anyagixx@yandex.ru
f741efaa6d137ed246a19dfce59b268c5eb88b4c
f15a0236a88c02e44933ebc7aa133fba72c1db55
/src/geometry.hpp
016a4dbccd23d9529608f9025b42143438247fbd
[ "BSD-2-Clause" ]
permissive
YTomTJ/edge4d
ffbe34cad8b5c785b784b4d223ee2f149f57e92f
e21a308d619c03db83ef68cf63b1637685bd2139
refs/heads/master
2023-03-16T08:37:22.507256
2017-05-08T20:51:24
2017-05-08T20:51:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,398
hpp
#ifndef __GEOMETRY_HPP__ #define __GEOMETRY_HPP__ #include <vector> #include <algorithm> #include <iostream> #include <limits> #include <math.h> // Moller code in tribox3.cpp TODO: Get rid of this and use a simpler // (but slower) approach to triangle-AABB intersections. int triBoxOverlap(float boxcenter[3],float boxhalfsize[3],float triverts[3][3]); namespace geom { using namespace std; // Return determinant of 2x2 matrix inline float det2(float a, float b, float c, float d) { return (a * d - b * c); } // Return determinant of 3x3 matrix. inline float det3(float a, float b, float c, float d, float e, float f, float g, float h, float i) { return (a * (e * i - h * f) - b * (d * i - g * f) + c * (d * h - g * e)); } // A simple 3x3 matrix. struct matrix3 { float data[3][3]; float &v(int i, int j) { return data[i][j]; } float v(int i, int j) const { return data[i][j]; } matrix3() { v(0,0) = 0; v(0,1) = 0; v(0,2) = 0; v(1,0) = 0; v(1,1) = 0; v(1,2) = 0; v(2,0) = 0; v(2,1) = 0; v(2,2) = 0; } float &operator () (int i, int j) { return v(i,j); } float operator () (int i, int j) const { return v(i,j); } float trace() { return v(0,0) + v(1,1) + v(2,2); } // Compute the determinant. float det() const { return det3(v(0,0), v(0,1), v(0,2), v(1,0), v(1,1), v(1,2), v(2,0), v(2,1), v(2,2)); } // Multiply two 3x3 matricies. matrix3 operator * (const matrix3 &p) { matrix3 R; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) R(i,j) = v(i,0) * p(0,j) + v(i,1) * p(1,j) + v(i,2) * p(2,j); return R; } // Matrix subtract. matrix3 operator - (const matrix3 &p) { matrix3 R; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) R(i,j) = v(i,j) - p(i,j); return R; } }; // Left-multiply a 3x3 matrix by a scalar. inline matrix3 operator * (float s, const matrix3 &A) { matrix3 R; R(0,0) = s * A(0,0); R(0,1) = s * A(0,1); R(0,2) = s * A(0,2); R(1,0) = s * A(1,0); R(1,1) = s * A(1,1); R(1,2) = s * A(1,2); R(2,0) = s * A(2,0); R(2,1) = s * A(2,1); R(2,2) = s * A(2,2); return R; } // Return a 3x3 identity matrix. inline matrix3 eye3() { matrix3 A; A(0,0) = 1; A(0,1) = 0; A(0,2) = 0; A(1,0) = 0; A(1,1) = 1; A(1,2) = 0; A(2,0) = 0; A(2,1) = 0; A(2,2) = 1; return A; } // Compute an inverse 3x3 matrix. matrix3 inv(const matrix3 &A); // A simple 3-d vector class. struct vec3 { float v[3]; vec3() { v[0] = v[1] = v[2] = 0; } vec3(float v0, float v1, float v2) { v[0] = v0; v[1] = v1; v[2] = v2; } vec3(float v2[3]) { v[0] = v2[0]; v[1] = v2[1]; v[2] = v2[2]; } vec3(const vec3 &z) { v[0] = z[0]; v[1] = z[1]; v[2] = z[2]; } vec3(float x) { v[0] = v[1] = v[2] = x; } void zero() { v[0] = v[1] = v[2] = 0; } void operator = (float x) { v[0] = x; v[1] = x; v[2] = x; } float &operator[] (int dim) { return v[dim]; } float operator[] (int dim) const { return v[dim]; } vec3 operator-() { return vec3(-v[0],-v[1],-v[2]); } float &x() { return v[0]; } float &y() { return v[1]; } float &z() { return v[2]; } vec3 operator * (float a) { return vec3(v[0] * a, v[1] * a, v[2] * a); } vec3 operator * (const vec3 &z) { return vec3(v[0] * z[0], v[1] * z[1], v[2] * z[2]); } vec3 operator + (const vec3 &z) { return vec3(v[0] + z[0], v[1] + z[1], v[2] + z[2]); } vec3 operator - (const vec3 &z) { return vec3(v[0] - z[0], v[1] - z[1], v[2] - z[2]); } void operator += (const vec3 &z) { v[0] += z[0]; v[1] += z[1]; v[2] += z[2]; } void operator *= (const vec3 &z) { v[0] *= z[0]; v[1] *= z[1]; v[2] *= z[2]; } void operator += (float a) { v[0] += a; v[1] += a; v[2] += a; } void operator -= (float a) { v[0] -= a; v[1] -= a; v[2] -= a; } void operator *= (float a) { v[0] *= a; v[1] *= a; v[2] *= a; } void operator /= (float a) { v[0] /= a; v[1] /= a; v[2] /= a; } void operator -= (const vec3 &z) { v[0] -= z[0]; v[1] -= z[1]; v[2] -= z[2]; } vec3 operator / (float a) { return vec3(v[0] / a, v[1] / a, v[2] / a); } vec3 operator % (const vec3 &z) { // Cross product vec3 x; x[0] = (v[1]*z[2]) - (v[2]*z[1]); x[1] = (v[2]*z[0]) - (v[0]*z[2]); x[2] = (v[0]*z[1]) - (v[1]*z[0]); return x; } float l2normsq() { return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; } float length() { return sqrt(l2normsq()); } float l2norm() { return length(); } void normalize() { float Z = length(); v[0] /= Z; v[1] /= Z; v[2] /= Z; } float dot(const vec3 &z) { return v[0] * z[0] + v[1] * z[1] + v[2] * z[2]; } float angle(const vec3 &b) { float dotprod = dot(b); if(dotprod > 1 || dotprod < -1) return 0; // Addresses numeric problems. else return acosf(dotprod); } float abs_angle(const vec3 &b) { float dotprod = fabs(dot(b)); if(dotprod > 1) return 0; // Addresses numeric problems. else return acosf(dotprod); } // Magnitude of b in the direction of this vector. float scalar_proj(const vec3 &b) { return dot(b) / l2norm(); } // Vector projection of b onto this vector. vec3 proj(const vec3 &b) { return vec3(v[0], v[1], v[2]) * (dot(b) / l2normsq()); } vec3 max_mag_project(vector<vec3> &vs) { if(vs.size() == 0) return vec3(0,0,0); float max_scalar = fabsf(scalar_proj(vs[0])); vec3 maxv = vs[0]; for(size_t i = 1; i < vs.size(); i++) { float scalar = fabsf(scalar_proj(vs[i])); if(scalar > max_scalar) { max_scalar = scalar; maxv = vs[i];} } return proj(maxv); } vec3 max_project(vector<vec3> &vs, int *max_idx_ref = NULL) { if(vs.size() == 0) return vec3(0,0,0); int max_idx = 0; float max_scalar = scalar_proj(vs[0]); vec3 maxv = vs[0]; for(size_t i = 1; i < vs.size(); i++) { float scalar = scalar_proj(vs[i]); if(scalar > max_scalar) { max_scalar = scalar; maxv = vs[i]; max_idx = i; } } if(max_idx_ref != NULL) *max_idx_ref = max_idx; return proj(maxv); } }; inline float rad2deg(float rad) { return rad * (180.0 / M_PI); } // Integer 3d vector class. TODO: Maybe make vec3 template typed // <T> to minimize code repeated. struct ivec3 { ivec3() { v[0] = v[1] = v[2] = 0; } ivec3(int x, int y, int z) { v[0] = x; v[1] = y; v[2] = z; } ivec3(const ivec3 &z) { v[0] = z[0]; v[1] = z[1]; v[2] = z[2]; } int v[3]; int &x() { return v[0]; } int &y() { return v[1]; } int &z() { return v[2]; } int &operator[] (int dim) { return v[dim]; } int operator[] (int dim) const { return v[dim]; } bool operator == (const ivec3 &z) const { return v[0] == z[0] && v[1] == z[1] && v[2] == z[2]; } bool operator != (const ivec3 &z) const { return v[0] != z[0] || v[1] != z[1] || v[2] != z[2]; } ivec3 operator + (const ivec3 &z) { return ivec3(v[0] + z[0], v[1] + z[1], v[2] + z[2]); } ivec3 operator - (const ivec3 &z) { return ivec3(v[0] - z[0], v[1] - z[1], v[2] - z[2]); } ivec3 operator + (int s) { return ivec3(v[0] + s, v[1] + s, v[2] + s); } ivec3 operator - (int s) { return ivec3(v[0] - s, v[1] - s, v[2] - s); } void operator += (int s) { v[0] += s; v[1] += s; v[2] += s; } void operator -= (int s) { v[0] -= s; v[1] -= s; v[2] -= s; } void operator += (const ivec3 &z) { v[0] += z[0]; v[1] += z[1]; v[2] += z[2]; } void operator -= (const ivec3 &z) { v[0] -= z[0]; v[1] -= z[1]; v[2] -= z[2]; } void operator = (int x) { v[0] = x; v[1] = x; v[2] = x; } vec3 to_vec3() { vec3 p; p[0] = v[0]; p[1] = v[1]; p[2] = v[2]; return p; } int l2normsq() { return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; } }; inline void bounding_box(ivec3 &mn, ivec3 &mx, const vector<ivec3> &vs) { mn = numeric_limits<int>::max(); mx = -(numeric_limits<int>::max()); for(size_t i = 0; i < vs.size(); i++) { for(int d = 0; d < 3; d++) mn[d] = min(vs[i][d], mn[d]); for(int d = 0; d < 3; d++) mx[d] = max(vs[i][d], mx[d]); } } inline void bounding_box(vec3 &mn, vec3 &mx, const vector<ivec3> &vs) { ivec3 mn_i, mx_i; bounding_box(mn_i, mx_i, vs); mn = mn_i.to_vec3(); mx = mx_i.to_vec3(); } inline float l2norm(vec3 v) { return v.l2norm(); } // Compute a 3x3 matrix as an outer product of two vectors. inline matrix3 outer3(vec3 &a, vec3 &b); // Left-multiply a vector by a scalar. inline vec3 operator * (float a, const vec3 &v) { return vec3(a * v[0] , a * v[1], a * v[2]); } inline vec3 operator * (const matrix3 &A, const vec3 &v) { vec3 r; r[0] = A(0,0) * v[0] + A(0,1) * v[1] + A(0,2) * v[2]; r[1] = A(1,0) * v[0] + A(1,1) * v[1] + A(1,2) * v[2]; r[2] = A(2,0) * v[0] + A(2,1) * v[1] + A(2,2) * v[2]; return r; } // An axis with an origin and 3 directions. struct axis { vec3 origin, d[3]; }; // Compute PCA of a a set of points. x has the eigenvalues from // smallest to largest. vec3 Centroid3(vector<vec3> &points); vec3 Centroid3(vector<ivec3> &points); bool PCA3(vector<vec3> &v, vector<float> &x, vector<vec3> &points); // Clears largest component. If there are multiple components with the max size, all are cleared. void ClearLargest(vector< vector<ivec3> > &comps); // Compute the distance between two vectors. inline float distance3sq(vec3 s, vec3 t) { float dx = s[0] - t[0], dy = s[1] - t[1], dz = s[2] - t[2]; return dx * dx + dy * dy + dz * dz; } inline float distance3sq(ivec3 s, ivec3 t) { float dx = s[0] - t[0], dy = s[1] - t[1], dz = s[2] - t[2]; return dx * dx + dy * dy + dz * dz; } inline float distancesq_xy(vec3 s, vec3 t) { float dx = s[0] - t[0], dy = s[1] - t[1]; return dx * dx + dy * dy; } inline float distance3(vec3 s, vec3 t) { return sqrtf( distance3sq(s,t) ); } // Rodrigues' rotation formula inline vec3 rotate(vec3 &v, vec3& a, float theta) { return v * cosf (theta) + a * (v.dot(a)) * (1 - cosf (theta)) - (v % a) * sinf(theta); } // Compute triangle area in 3-d. float area(vec3 &a, vec3 &b, vec3 &c); inline vec3 ComputeNormal(vec3 &p0, vec3 &p1, vec3 &p2) { vec3 v1 = p1 - p0, v2 = p2 - p0; vec3 normal = v1 % v2; normal.normalize(); return normal; } // An independent 3-d triangle with an intersection test. struct triangle { vec3 v[3], normal; //triangle() { color[1] = 1.0; } // Green is the default. void as_plane(vec3 &n, float &d) { n = normal; d = -n.dot(v[0]); } float area() { return geom::area(v[0], v[1], v[2]); } vec3 centroid() { return v[0] / 3.0 + v[1] / 3.0 + v[2] / 3.0; } // Triangle centroid. float x() const { return (1.0/3.0) * (v[0][0] + v[1][0] + v[2][0]); } float y() const { return (1.0/3.0) * (v[0][1] + v[1][1] + v[2][1]); } float z() const { return (1.0/3.0) * (v[0][2] + v[1][2] + v[2][2]); } float minf(const float a, const float b) const { return a < b ? a : b; } float maxf(const float a, const float b) const { return a > b ? a : b; } // Accessors are used by BVH. float max_x() const { return maxf(v[0][0], maxf(v[1][0], v[2][0])); } float max_y() const { return maxf(v[0][1], maxf(v[1][1], v[2][1])); } float max_z() const { return maxf(v[0][2], maxf(v[1][2], v[2][2])); } float min_x() const { return minf(v[0][0], minf(v[1][0], v[2][0])); } float min_y() const { return minf(v[0][1], minf(v[1][1], v[2][1])); } float min_z() const { return minf(v[0][2], minf(v[1][2], v[2][2])); } void ComputeNormal() { vec3 v1 = v[1] - v[0], v2 = v[2] - v[0]; normal = v1 % v2; normal.normalize(); } vec3 &operator[] (int tex) { return v[tex]; } // "Fast, minimum storage ray-triangle intersection". Tomas // Moller and Ben Trumbore. Journal of Graphics Tools, // 2(1):21--28, 1997. Adapted from // http://www.mathworks.com.au/matlabcentral/fileexchange/25058-raytriangle-intersection // by Jesus P. Mena-Chalco bool ray_intersect(vec3 &i, vec3 &o, vec3 &d) { vec3 e1 = v[1] - v[0], e2 = v[2] - v[0]; vec3 q = d % e2; float a = e1.dot(q); if(a > -1e-6f && a < 1e-6f) return false; float f = 1.0f/a; vec3 s = o - v[0]; float u = f * s.dot(q); // u,v barycentric coordinates of intersection if(u < 0.0f) return false; vec3 r = s % e1; float v = f * d.dot(r); // u,v barycentric coordinates of intersection if( v < 0.0f || u + v > 1.0f) return false; float t = f * e2.dot(r); // t distance from the ray origin i = o + t * d; return t > 0.0f; // NOTE: i = o + t * d, intersection = origin + t*direction } // TODO: Add triangle triangle intersection. bool tri_intersect(triangle &) { // TODO: Use ray_intersect above // ray 1 = v[0], d = v[1] - v[0], t = distance from ray origin < l2normsq(d) // ray 2 = v[1], d = v[2] - v[1], // ray 3 = v[2], d = v[3] - v[2], cout << "not implemented yet" << endl; return false; } }; // A face stores indices of given vertices in a vector<vec3> array. struct face { int vert[3]; }; struct plane3 { vec3 v; float d; // Construct plane from point and normal vector void from_pnorm(vec3 p, vec3 n) { n.normalize(); v = n; d = -p.dot(n); } float pdist(const vec3 &p) { return v.dot(p) + d; } bool neg_side(const vec3 &p) { return pdist(p) < 0; } bool pos_side(const vec3 &p) { return pdist(p) > 0; } }; // perspective camera geometry struct camera3 { vec3 eye; // position vec3 towards, right, up; // direction float xfov, yfov; // field of view float neardist, fardist; // distance of near clipping plane and far plane // ix and iy are integer image positions. void create_ray(vec3 &o, vec3 &p, int ix, int iy, int width, int height) { float px = ix, py = iy; // Place image points in -1 < x < 1 and -1 < y < 1. float x = 2.0 * (px + 0.5) / float(width) - 1.0; float y = -(2.0 * (py + 0.5) / float(height) - 1.0); // TODO: Check if flipped!!!!! vec3 &T = towards, &U = up, &R = right; // Compute direction based on camera geometry. /*p = T + U * y * tanf(yfov/2) + R * x * tanf(xfov/2); p.normalize();*/ T.normalize(); U.normalize(); R.normalize(); float D = 1.0 / tanf(yfov/2); // distance to projection plane float ar = float(width) / float(height); // aspect ratio p = D * T + U * y + R * ar * x; // ray direction p.normalize(); o = eye + neardist * p; // Move ray origin to the near plane. } // For all the calls below dx and dy define a delta position in // the movement of the mouse. center is the center of the scene. void rotate_scene(int dx, int dy, int width, int height, vec3 &center) { float vx = (float) dx / (float) width, vy = (float) dy / (float) height; float theta = 4.0 * (fabsf(vx) + fabsf(vy)); vec3 vector = (right * vx) + (up * vy); vec3 rotation_axis = towards % vector; rotation_axis.normalize(); eye -= center; // Don't forget to translate back from center. eye = rotate(eye, rotation_axis, theta) + center; towards = rotate(towards, rotation_axis, theta); up = rotate(up, rotation_axis, theta); right = towards % up; up = right % towards; towards.normalize(); up.normalize(); right.normalize(); } void scale_scene(int dx, int dy, int width, int height, vec3 &center) { float factor = (float) dx / (float) width + (float) dy / (float) height; factor = exp(2.0 * factor); factor = (factor - 1.0) / factor; vec3 translation = (center - eye) * factor; eye += translation; } void translate_scene(int dx, int dy, int width, int height, vec3 &center) { float length = distance3(center, eye) * tanf(yfov); float vx = length * (float) dx / (float) width; float vy = length * (float) dy / (float) height; vec3 translation = -((right * vx) + (up * vy)); eye += translation; } }; // Axis aligned bounding box (AABB) with a ray intersection function. struct AABB { float x_min, x_max, y_min, y_max, z_min, z_max; // Simplest constructor. It just assigns max and min elements as specified. AABB(float x_min_, float x_max_, float y_min_, float y_max_, float z_min_, float z_max_){ x_min = x_min_; x_max = x_max_; y_min = y_min_; y_max = y_max_; z_min = z_min_; z_max = z_max_; } // If no ranges are specified, the region spans the entire (x, y, z) space. AABB() { x_min = -(numeric_limits<float>::max()); x_max = numeric_limits<float>::max(); y_min = -(numeric_limits<float>::max()); y_max = numeric_limits<float>::max(); z_min = -(numeric_limits<float>::max()); z_max = numeric_limits<float>::max(); } // Adapted from http://ompf.org/ray/ray_box.html Branchless // Ray/Box intersections by Mueller/Geimer Also has numeric fixes // (for possible NaNs) described on // http://www.flipcode.com/archives/SSE_RayBox_Intersection_Test.shtml float minf(const float a, const float b) { return a < b ? a : b; } float maxf(const float a, const float b) { return a > b ? a : b; } // The paramters [ idx, idy, idz ] = [ 1 / dx, 1 / dy , 1 / dz], the inverse of the direction vector. // o = [x,y,z] and d = [dx,dy,dz] // o + lmin * d = first intersection point // o + lmax * d = second intersection point bool ray_intersect(float &lmin, float &lmax, float x, float y, float z, float idx, float idy, float idz) { float l1, l2, fl1a, fl1b, fl2a, fl2b; l1 = (x_min - x) * idx; l2 = (x_max - x) * idx; fl1a = minf(l1, numeric_limits<float>::infinity()); fl2a = minf(l2, numeric_limits<float>::infinity()); fl1b = maxf(l1, -numeric_limits<float>::infinity()); fl2b = maxf(l2, -numeric_limits<float>::infinity()); float lmin_x = min(fl1b,fl2b); float lmax_x = max(fl1a,fl2a); l1 = (y_min - y) * idy; l2 = (y_max - y) * idy; fl1a = minf(l1, numeric_limits<float>::infinity()); fl2a = minf(l2, numeric_limits<float>::infinity()); fl1b = maxf(l1, -numeric_limits<float>::infinity()); fl2b = maxf(l2, -numeric_limits<float>::infinity()); float lmin_y = minf(fl1b,fl2b); float lmax_y = maxf(fl1a,fl2a); l1 = (z_min - z) * idz; l2 = (z_max - z) * idz; fl1a = minf(l1, numeric_limits<float>::infinity()); fl2a = minf(l2, numeric_limits<float>::infinity()); fl1b = maxf(l1, -numeric_limits<float>::infinity()); fl2b = maxf(l2, -numeric_limits<float>::infinity()); float lmin_z = minf(fl1b,fl2b); float lmax_z = maxf(fl1a,fl2a); lmin = maxf(lmin_z,maxf(lmin_y, lmin_x)); lmax = minf(lmax_z,minf(lmax_y, lmax_x)); //return ((lmax > 0.f) && (lmax >= lmin)); //return ((lmax > 0.f) && (lmax > lmin)); //return ((lmax >= 0.f) && (lmax >= lmin)); return ((lmax >= 0.f) && (lmax >= lmin)); } bool ray_intersect(float x, float y, float z, float idx, float idy, float idz) { float lmin, lmax; return ray_intersect(lmin, lmax, x,y,z, idx,idy,idz); } bool contains(float x, float y, float z) { return ( x_min <= x && x <= x_max ) && ( y_min <= y && y <= y_max ) && ( z_min <= z && z <= z_max ); } // Arvo's algorithm from "A Simple Method for Box-Sphere // Intersection Testing", by Jim Arvo, in "Graphics Gems", // Academic Press, 1990. bool sphere_intersect(AABB &bbox, float r, float cx, float cy, float cz) { if(intersect_AABB(bbox) == false) return false; // No bbox intersect, skip. float s, d = 0; if( cx < x_min ) { s = cx - x_min; d += s * s; } else if( cx > x_max ) { s = cx - x_max; d += s * s; } if( cy < y_min ) { s = cy - y_min; d += s * s; } else if( cy > y_max ) { s = cy - y_max; d += s * s; } if( cz < z_min ) { s = cz - z_min; d += s * s; } else if( cz > z_max ) { s = cz - z_max; d += s * s; } return d <= r * r; } bool sphere_intersect(float r, float cx, float cy, float cz) { AABB bbox(cx - r, cx + r, cy - r, cy + r, cz - r, cz + r); return sphere_intersect(bbox, r, cx, cy, cz); } // Intersect two AABB. bool intersect_AABB(AABB &R) { // Negation of (not intersection). return !( R.x_max < x_min || R.x_min > x_max ) && !( R.y_max < y_min || R.y_min > y_max ) && !( R.z_max < z_min || R.z_min > z_max ); } // Returns true if the current region encloses the passed region R. bool encloses_AABB(AABB &R ){ return ( (R.x_max <= x_max) && (R.x_min >= x_min) ) && ( (R.y_max <= y_max) && (R.y_min >= y_min) ) && ( (R.z_max <= z_max) && (R.z_min >= z_min) ); } // Assumes caller computed a minimum AABB around the triangle as // follows: AABB tribox(tri.min_x(), tri.max_x(), tri.min_y(), // tri.max_y(), tri.min_z(), tri.max_z()); bool tri_intersect(triangle &tri, AABB &tribox) { // 1. Does the AABB enclose the minimum AABB triangle box. if(encloses_AABB(tribox)) return true; // 2. Test overlap of minimum AABB of the triangle. if(intersect_AABB(tribox) == false) return false; // No overlap, no intersection. // 3. Apply full Moller intersection testing float boxcenter[3], boxhalfsize[3], triverts[3][3]; boxhalfsize[0] = (x_max - x_min) / 2.0; boxhalfsize[1] = (y_max - y_min) / 2.0; boxhalfsize[2] = (z_max - z_min) / 2.0; boxcenter[0] = x_min + boxhalfsize[0]; boxcenter[1] = y_min + boxhalfsize[1]; boxcenter[2] = z_min + boxhalfsize[2]; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) triverts[i][j] = tri[i][j]; // TODO: We can get rid of triBoxOverlap and tribox3.cpp using // this alternative algorithm. This is *SIMPLER* probably 2x // slower. Create a small triangle mesh of the AABB. This will // have 2 x 6 = 12 triangles. Cast a ray from the 3 edges of // the intersecting triangle. If the edge ray intersects the // triangle with distance < the edge length. Then there is an // intersection. We can also ask if the minimum box of those // triangles intersects the min box of the intersecting triangle // TODO: Can also replace with a 6 x 2 triangle/triangle // intersections. // TODO: Find a simple triangle/triangle intersection algorithm. return triBoxOverlap(boxcenter, boxhalfsize, triverts) > 0; } }; // T must support x(), y(), z(), min/max_x(), min/max_y(), min/max_z(). template <typename T> struct BVH { // Comparitors for partitioning data x,y, or z axes. struct x_cmp { bool operator () (T a, T b) const { return a.x() < b.x(); } }; struct y_cmp { bool operator () (T a, T b) const { return a.y() < b.y(); } }; struct z_cmp { bool operator () (T a, T b) const { return a.z() < b.z(); } }; typedef typename vector<T>::iterator it_t; vector<T> &data; // Lmis, Rmids, Lbv, and Rbv all implement a linear probing hash // table. Given a midpoint the hash table returns an axis aligned // bounding box. vector<it_t> Lmids, Rmids; vector< AABB > Lbv, Rbv; size_t leftN, rightN; void insert(vector<it_t> &mids, vector<AABB> &bv, it_t mid, AABB &aabb) { // Get the distance of th enew midpoint from the start of the data array. size_t i = distance(data.begin(), mid) % mids.size(); // Find an open slot. size_t istart = i; while(mids[i] != data.end()) { i = (i+1) % mids.size(); if(i == istart) { cerr << "BVH: split table is full!" << endl; exit(1); } } // Save midpoint and bounding box. mids[i] = mid; bv[i] = aabb; } // Look for AABB for a given mid point in hash table. AABB find(vector<it_t> &mids, vector<AABB> &bv, it_t mid) { size_t i = distance(data.begin(), mid) % mids.size(); size_t istart = i; while(mids[i] != data.end()) { if(mids[i] == mid) return bv[i]; else i = (i + 1) % mids.size(); if(i == istart) { cerr << "BVH: Did not find mid. Problem!!!" << endl; exit(1);} } return AABB(); } void build(it_t first, it_t last, int dim) { if (last - first <= 7) return; // Since 3 dimensions are partitioned. it_t mid = first + ( last - first + 1 ) / 2; // NOTE: nth_elment calls the destructor if it exists. This // sometimes creates issues. switch(dim) { // Cycle through x, y, z axes. case 0: nth_element(first, mid, last, x_cmp()); dim++; break; case 1: nth_element(first, mid, last, y_cmp()); dim++; break; case 2: nth_element(first, mid, last, z_cmp()); dim = 0; break; } // For a given split point mid, save in a hash table the right and left AABBs. AABB left; BV(left, first, mid); insert(Lmids, Lbv, mid, left); leftN++; AABB right; BV(right, mid, last); insert(Rmids, Rbv, mid, right); rightN++; build(first, mid, dim); build(mid, last, dim); } // Determine bounding volume, AABB given in iterator range. void BV(AABB &bv, it_t first, it_t last) { // Maximum bounding range. bv.x_max = -(numeric_limits<float>::max()); bv.x_min = numeric_limits<float>::max(); bv.y_max = -(numeric_limits<float>::max()); bv.y_min = numeric_limits<float>::max(); bv.z_max = -(numeric_limits<float>::max()); bv.z_min = numeric_limits<float>::max(); // Scan data to determine dimensions of AABB. for(it_t it = first; it != last; it++) { T &obj = *it; float min_x = obj.min_x(), min_y = obj.min_y(), min_z = obj.min_z(); if(min_x < bv.x_min) bv.x_min = min_x; if(min_y < bv.y_min) bv.y_min = min_y; if(min_z < bv.z_min) bv.z_min = min_z; float max_x = obj.max_x(), max_y = obj.max_y(), max_z = obj.max_z(); if(max_x > bv.x_max) bv.x_max = max_x; if(max_y > bv.y_max) bv.y_max = max_y; if(max_z > bv.z_max) bv.z_max = max_z; } } BVH(vector<T> &data_) : data(data_) { leftN = rightN = 0; Lbv.resize(data.size()/2); Lmids.resize(data.size()/2, data.end()); Rbv.resize(data.size()/2); Rmids.resize(data.size()/2, data.end()); build(data.begin(), data.end(), 0); } // Recursively intersect a ray with members of the BVH. void query(it_t first, it_t last, float x, float y, float z, // origin float idx, float idy, float idz, // direction with each dimensio inverted. vector<T*> &res) { if( last - first <= 7 ) { for(it_t it = first; it != last; it++) { AABB test(it->min_x(), it->max_x(), it->min_y(), it->max_y(), it->min_z(), it->max_z()); if(test.ray_intersect(x,y,z,idx,idy,idz)) res.push_back(&*it); } return; } it_t mid = first + ( last - first + 1 ) / 2; // Given a mid point "mid" find an axis aligned bounding box for the "left" side. AABB left = find(Lmids, Lbv, mid); if(left.ray_intersect(x,y,z,idx,idy,idz)) query(first, mid, x,y,z, idx,idy,idz, res); // Given a mid point "mid" find an axis aligned bounding box for the "right" side. AABB right = find(Rmids, Rbv, mid); if(right.ray_intersect(x,y,z,idx,idy,idz)) query(mid, last, x,y,z, idx,idy,idz, res); } // Recursively intersect a sphere with BVH members. void query(it_t first, it_t last, float r, float cx, float cy, float cz, vector<T*> &res) { if( last - first <= 7 ) { for(it_t it = first; it != last; it++) { T &v = *it; AABB vbox(v.min_x(), v.max_x(), v.min_y(), v.max_y(), v.min_z(), v.max_z()); if(vbox.sphere_intersect(r,cx,cy,cz)) res.push_back(&v); } return; } it_t mid = first + ( last - first + 1 ) / 2; AABB left = find(Lmids, Lbv, mid); if(left.sphere_intersect(r,cx,cy,cz)) query(first, mid, r, cx,cy,cz , res); AABB right = find(Rmids, Rbv, mid); if(right.sphere_intersect(r,cx,cy,cz)) query(mid, last, r, cx,cy,cz , res); } // Cast a ray through bounding volume with origin [x,y,z]' and direction [dx,dy,dz]'. void Query(vector<T*> &res, float x, float y, float z, // origin float dx, float dy, float dz) { // direction query(data.begin(), data.end(), x,y,z, 1.0f/dx, 1.0f/dy, 1.0f/dz, res); } // Intersects sphere with AABBs of the BVH. void Query(vector<T*> &res, float r, // radius of sphere float cx, float cy, float cz) { // center of sphere query(data.begin(), data.end(), r, cx,cy,cz, res); } }; // Pointer based interface for a BVH. template <typename T> struct BVHptr { T *ptr; // Accessors for BVH<> float x() { return ptr->x(); } float y() { return ptr->y(); } float z() { return ptr->z(); } float min_x() { return ptr->min_x(); } float max_x() { return ptr->max_x(); } float min_y() { return ptr->min_y(); } float max_y() { return ptr->max_y(); } float min_z() { return ptr->min_z(); } float max_z() { return ptr->max_z(); } }; // BVH2 allows pointers to be used for a BVH. This is accomplished // by "wrapping" th epointer in the BVHptr class above. template <typename T> struct BVH2 { vector< BVHptr<T> > ptrs; BVH< BVHptr<T> > *bvh; BVH2(vector <T> &data) { ptrs.resize(data.size()); for(size_t i = 0; i < ptrs.size(); i++) ptrs[i].ptr = &data[i]; bvh = new BVH< BVHptr<T> > (ptrs); } BVH2(vector <T *> &data) { ptrs.resize(data.size()); for(size_t i = 0; i < ptrs.size(); i++) ptrs[i].ptr = data[i]; bvh = new BVH< BVHptr<T> > (ptrs); } ~BVH2() { delete bvh; } void Query(vector<T*> &res, float x, float y, float z, // origin float dx, float dy, float dz) { // direction vector< BVHptr<T> * > res_q; bvh->Query(res_q, x, y, z, dx, dy, dz); for(size_t i = 0; i < res_q.size(); i++) res.push_back(res_q[i]->ptr); } void Query(vector<T*> &res, float r, // radius of sphere float cx, float cy, float cz) { // center of sphere vector< BVHptr<T> * > res_q; bvh->Query(res_q, r, cx, cy, cz); for(size_t i = 0; i < res_q.size(); i++) res.push_back(res_q[i]->ptr); } }; } #endif
[ "zia@Zias-MBP.home" ]
zia@Zias-MBP.home
fddf89d31b3cea7378ec80f4c60b5976d55767b3
926be6cac667168db041b1820adc6437f8fc58d3
/src/LayerBody.h
15c5e2f1f92633da14cc192f41cdf9ebbdac64ee
[ "Apache-2.0" ]
permissive
idealab-isu/de-la-mo
951b3dc7d0533ff6bf5267d9a3a6a5c19ff98606
ddd2293a8d6ecca1b92386dbecfa0b2631dff1df
refs/heads/master
2020-03-29T17:55:59.136921
2019-07-18T05:26:22
2019-07-18T05:26:22
150,186,180
5
0
null
null
null
null
UTF-8
C++
false
false
3,898
h
#ifndef LAYERBODY_H #define LAYERBODY_H #include "APIConfig.h" #include "MBBody.h" #include "LayerSurface.h" #include "LayerMold.h" // Export file is generated by CMake's GenerateExportHeader module #include "modelbuilder_export.h" // Defines the structure of the body class MODELBUILDER_EXPORT LayerBody : public MBBody { public: unsigned int next_ls_id; /**< Internal counter for LayerSurface numbering */ /** * \brief Default constructor. */ LayerBody(); /** * \brief Copy constructor. * \param rhs object to be copied into */ LayerBody(const LayerBody& rhs); /** * \brief Default destructor. */ ~LayerBody(); /** * \brief Copy assignment operator. * \param rhs object to be copied into * \return updated object */ LayerBody& operator=(const LayerBody& rhs); /** * \brief Copies the layer body to lhs. * \param lhs new object */ void copy(LayerBody& lhs); /** * \brief Gets the LayerBody name. * \return name of the LayerBody */ char* name(); /** * \brief Sets the LayerBody name. * \param name new name of the LayerBody */ void name(const char* name); /** * \brief Gets the BODY object. * \return body object as defined by the solid modeling kernel */ DLM_BODYP body(); /** * \brief Sets the BODY object. * \param body body object as defined by the solid modeling kernel */ void body(DLM_BODYP body); /** * \brief Add a new layer surface to the layer. * \param[in] elem LayerSurface element to be contained in this LayerBody */ void add_surface(LayerSurface *elem); /** * \brief LayerSurface iterator structure. * \return the first iterator object */ LayerSurface** begin(); /** * \brief LayerSurface iterator structure. * \return the last iterator object (nullptr) */ LayerSurface** end(); /** * \brief Gets the layer surface elements from the layer. * \param idx the array index * \return stored LayerSurface object described by the array index */ LayerSurface* at(int idx); /** * \brief Number of layer surfaces contained in the layer. * \return list of layer surfaces */ LayerSurface** list(); /** * \brief Gets the number of layer surfaces contained in the layer. * \return number of LayerSurface elements contained in this layer */ int size(); /** * \brief Clear the layer surface elements contained in the layer. */ void clear(); /** * \brief Sets the owner of the LayerBody object. * \param[in] owner new owner as a pointer to a Layer object */ void owner(Layer* owner); /** * \brief Gets ownerof the LayerBody object. * \return owner as a pointer to a Layer object */ Layer* owner(); /** * \brief Sets mold which generated this LayerBody. * \param[in] new_mold LayerMold object as a pointer */ void mold(LayerMold* new_mold); /** * \brief Sets mold which generated this LayerBody. * \return LayerMold object as a pointer */ LayerMold* mold(); /** * \brief Checks whether the input face is contained in this layer body or not. * \param[in] face_query the face object (a solid modeler object) to be queried * \return id of the LayerSurface object (LayerSurface::_mId) contained in this LayerBody */ int face_id(DLM_FACEP face_query); protected: /** * \brief Error handler */ void error_handler(int errnum); private: LayerSurface** _pSurfList; /**< List of LayerSurface objects contained in this LayerBody */ int _mSurfListSize; /**< Size of the LayerSurface objects list */ Layer* _pOwner; /**< Owner as a pointer to a Layer object */ LayerMold _mMold; /**< Mold to generate this LayerBody */ // DLM_BODYP and name defined in base class //DLM_BODYP _pBody; /**< BODY object defined by the solid modeling kernel */ //char* _pName; /**< LayerBody name */ void init_vars(); void delete_vars(); void copy_vars(const LayerBody& rhs, LayerBody& lhs); }; #endif // !LAYERBODY_H
[ "sdh4@iastate.edu" ]
sdh4@iastate.edu
d81c1e52070b872951e1c8e90218c95e5615d7c1
d5f579b89b9743e949ee9901780e9c3982fe3f98
/jet_playground/test/fastjet_test.cc
3121cce076eee081f3faff2dffb7b9a67681f41d
[]
no_license
nickelsey/jet_playground
03f1e8c5e1eee0addec2c53d352a36184934b87e
5384149f8b3b18e6d6c403fd8c1951cdaa59b729
refs/heads/master
2021-01-02T08:42:38.375765
2017-09-26T05:17:23
2017-09-26T05:17:23
99,049,091
0
0
null
null
null
null
UTF-8
C++
false
false
297
cc
#include <iostream> #include "fastjet/PseudoJet.hh" int main() { fastjet::PseudoJet a( 1, 2, 3, 4 ); std::cout << "vector a: { "; for ( int i = 0; i < 4; ++i ) { std::cout << a[i]; if ( i != 3 ) std::cout << ","; std::cout << " "; } std::cout <<" }" << std::endl; return 0; }
[ "nicholas.elsey@gmail.com" ]
nicholas.elsey@gmail.com
a240987bbbcb28d77506e9fac6ced45593ca88e1
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_6530.cpp
93a0aec609b5506f03f31ee8fb8879adc1b15528
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
26
cpp
f(!ctx) return result;
[ "993273596@qq.com" ]
993273596@qq.com
b8dd948445c6613a55e97d8f16a3ad27d5a2cce3
5bc6bd4ff4ad98e9df7741b9abdf61b6f7f0e4f3
/LinkedList/LinkedList.cc
ee6d414755677d163f387e04826066253da16bc2
[]
no_license
lpejakovic/PracticeCpp
04386d6f415917a17a901966b294e37597ae77fc
fbb99cec5fdaaa8ae4c12deda7aa11dd2a9fba7f
refs/heads/main
2023-02-22T05:30:12.680746
2021-01-27T19:17:58
2021-01-27T19:17:58
308,114,404
0
0
null
null
null
null
UTF-8
C++
false
false
3,902
cc
#include "LinkedList.h" #include <iostream> using namespace std; namespace practicecpp { template<class T> int LinkedList<T>::GetSize(){ int size = 0; LLNode<T> *node = head; while (node) { node = node->GetNext(); size++; } return size; } template <class T> bool LinkedList<T>::IsEmpty() { return head == nullptr; } template <class T> T LinkedList<T>::GetValueByIndex(int index) { int currentIndex = 0; LLNode<T> *node = head; while(node) { if (currentIndex == index) { return node->GetData(); } node = node->GetNext(); currentIndex++; } cout << "Index out of bounds" << endl; exit(EXIT_FAILURE); } template <class T> void LinkedList<T>::PushFront(T value) { LLNode<T> *newHead = new LLNode<T>(value); newHead->SetNext(head); head = newHead; } template <class T> T LinkedList<T>::PopFront() { if(head == nullptr){ cout << "List empty" << endl; exit(EXIT_FAILURE); } LLNode<T> *delNode = head; T retVal = head->GetData(); head = head->GetNext(); delete delNode; return retVal; } template <class T> void LinkedList<T>::PushBack(T value) { LLNode<T> *newNode = new LLNode<T>(value); LLNode<T> *node = head; while(node->GetNext()) { node = node->GetNext(); } node->SetData(newNode); } template <class T> T LinkedList<T>::PopBack() { if(head == nullptr){ cout << "List empty" << endl; exit(EXIT_FAILURE); } LLNode<T> *node = head; while(node->GetNext()->GetNext()) { node = node->GetNext(); } T retVal = node->GetNext()->GetData(); node->SetNext(nullptr); return retVal; } template <class T> T LinkedList<T>::GetFirst() { if(head == nullptr){ cout << "List empty" << endl; exit(EXIT_FAILURE); } return head->GetData(); } template <class T> T LinkedList<T>::GetLast() { if(head == nullptr){ cout << "List empty" << endl; exit(EXIT_FAILURE); } LLNode<T> *node = head; while(node->GetNext()) { node = node->GetNext(); } return node->GetData(); } template <class T> void LinkedList<T>::InsertAtIndex(int index, T value) { LLNode<T> newNode = LinkedListNode<T>(value); LLNode<T> *node = head; int i = 0; while(i < index && node->GetNext()) { node = node->GetNext(); i++; } if(i != index){ cout << "Bad Index" << endl; exit(EXIT_FAILURE); } LLNode<T> *oldNext = node->GetNext(); node->SetNext(newNode); newNode->SetNext(oldNext); } template <class T> void LinkedList<T>::RemoveAtIndex(int index) { if(head == nullptr){ cout << "List empty" << endl; exit(EXIT_FAILURE); } LLNode<T> *node = head; int currentIndex = 0; while(node) { if (currentIndex == index - 1) { node->SetNext(node->GetNext()->GetNext()); break; } node = node->GetNext(); currentIndex++; } } template <class T> T LinkedList<T>::GetValueFromBack(int offset) { if(head == nullptr || n < ){ cout << "List empty" << endl; exit(EXIT_FAILURE); } LLNode<T> *node = head; int size = this->GetSize(); return this->GetValueByIndex(size - offset - 1); } template <class T> void LinkedList<T>::Reverse(){ LLNode<T> *previous = nullptr; LLNode<T> *current = head; LLNode<T> *next; while (current) { next = current->GetNext(); current->SetNext(previous); previous = current; current = next; } head = previous; } template <class T> void LinkedList<T>::RemoveValue(T value){ LLNode<T> *node = head; LLNode<T> *previous = nullptr; while (node) { if(node->GetData() == value){ if(previous == nullptr){ head = node->GetNext(); } else { previous->SetNext(node->GetNext()); } delete node; continue; } previous = node; node = node->GetNext(); } } }
[ "luka.pejakovic@gmail.com" ]
luka.pejakovic@gmail.com
1845b3d4cbd1f9fdbd38c265e0c227b8aa08a00d
573ab921dd30de38b7e37d7157fa05201b1bb8d9
/src/boost/boost-memory-mapped-file.cpp
1af3bb3ea5f200e39590cdc743004e363b22be72
[]
no_license
ilovelibai/C-Cpp-Notes
4cab2320e34fc9991d2e16c0eb4bdc10fad35231
cea44f898b06215e127f63375282905568feda14
refs/heads/master
2022-11-30T23:55:48.541167
2020-08-18T17:50:26
2020-08-18T17:50:26
289,960,881
1
0
null
2020-08-24T15:06:38
2020-08-24T15:06:38
null
UTF-8
C++
false
false
2,905
cpp
#include <iostream> #include <functional> #include <string> #include <fstream> #include <vector> #include <boost/interprocess/managed_mapped_file.hpp> #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/mapped_region.hpp> namespace bi = boost::interprocess; /** @brief Returns true if exists. */ bool fileExists(std::string const& fileName) { auto fs = std::ifstream(fileName); return fs.good(); } /** Generic Memory-mapped file allocator */ template<typename T> using MMFAllocator = bi::allocator<T, bi::managed_mapped_file::segment_manager> ; /** Generic STL vector allocated in memory-mapped file */ template<typename T> using MMFVector = std::vector<T, MMFAllocator<T>> ; int main() { constexpr const char* fileName = "memory-dump.dat"; constexpr size_t fileSize = 4096; // 4 kbytes bool flagFileExists = fileExists(fileName); // Manged file mapping object => Creates the file if it does not exists auto mf = bi::managed_mapped_file{bi::open_or_create, fileName, fileSize}; if(!flagFileExists){ // Executed when the file did not exist std::cout << " [INFO] Setting file data" << std::endl; mf.construct<int>("NumberOfNodes")(100); mf.construct<double>("Speed")(200.0); mf.construct<const char*>("Text")("'Allocated text in memory mapped file'"); // Allocate std::vector<double> MMFAllocator<double> aloc1(mf.get_segment_manager()); MMFVector<double>* pVector = mf.construct<MMFVector<double>>("AVector")(aloc1); pVector->reserve(20); pVector->push_back(40.5); pVector->push_back(98.10); pVector->push_back(-50.45); pVector->push_back(10); return EXIT_SUCCESS; } // ======= Executed when file already exists =========// std::cout << " [INFO] Retrieving objects from memory mapped file" << std::endl; // Retrieve variable NumberOfNodes with very explicitly and verbose notation std::pair<int*, size_t> pairResult1 = mf.find<int>("NumberOfNodes"); if(pairResult1.first == nullptr){ std::cerr << " [ERROR] I cannot find the object 'NumberOfNodes'" << std::endl; return EXIT_FAILURE; } std::cout << "Number of nodes = " << *pairResult1.first << "\n"; (*pairResult1.first)++; // Retrieve variable text auto [pText, _size1 ] = mf.find<const char*>("Text"); assert(pText != nullptr); std::cout << "Text = " << *pText << "\n"; // Retrieve variable speed auto [pSpeed, _size2 ] = mf.find<double>("Speed"); assert(pSpeed != nullptr); std::cout << "Speed = " << *pSpeed << "\n"; std::cout << " => Set new speed := "; std::cin >> *pSpeed; // Rerieve vector auto [pVector, _size3] = mf.find<MMFVector<double>>("AVector"); assert(pVector != nullptr); std::cout << "\n pVector->size() = " << pVector->size() << std::endl; size_t idx = 0; for(auto const& x: *pVector) std::cout << " pVector[" << idx++ << "] = " << x << std::endl ; pVector->push_back(*pSpeed); return 0; }
[ "caiorss.rodrigues@gmail.com" ]
caiorss.rodrigues@gmail.com
e1874d289380fa792790a64827b5a2103d99cef6
1c8e5a1fc7f9dfee4969194c1bd77918eea73095
/Source/AllProjects/Samples/XMLDemo1/XMLDemo1.Cpp
b4928f984815dde37dbeebba752aba0d39a14e72
[]
no_license
naushad-rahman/CIDLib
bcb579a6f9517d23d25ad17a152cc99b7508330e
577c343d33d01e0f064d76dfc0b3433d1686f488
refs/heads/master
2020-04-28T01:08:35.084154
2019-03-10T02:03:20
2019-03-10T02:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,938
cpp
// // FILE NAME: XMLDemo1.Cpp // // AUTHOR: Dean Roddey // // CREATED: 08/21/99 // // COPYRIGHT: $_CIDLib_CopyRight_$ // // $_CIDLib_CopyRight2_$ // // DESCRIPTION: // // This is the main module for the first of the XML demo programs. This one // shows how to use the core XML services at its lowest level. This does not // depend upon any publically defined XML APIs (such as SAX or DOM.) It just // uses the core services, which are very fast and which provide maximum // access to the XML data parsed. // // In most cases, you wouldn't use this API. You'd use one of the parser // classes, which does most of this work for you. You then just derive from // one of the parsers and override its methods to get the events you want. // But, if you want it fast and to get maximum XML info, then this is the way // to go. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Include our own header which will bring in what we need and define our // facility object. // --------------------------------------------------------------------------- #include "XMLDemo1.Hpp" // ---------------------------------------------------------------------------- // Global Data // // facXMLDemo1 // The facility object for this program. This object implements all of the // callback interfaces from that XML parser core that we need. So it will // be informed of all of the XML events and handle them. // ---------------------------------------------------------------------------- TFacXMLDemo1 facXMLDemo1; // ---------------------------------------------------------------------------- // Magic macros for the facility class // ---------------------------------------------------------------------------- RTTIDecls(TFacXMLDemo1,TFacility) // ---------------------------------------------------------------------------- // Include magic main module code // // Note that we make the main thread run a member of the facility object. // See the program notes above in the file header. The TMemberFunc<> // template class takes a pointer to the object and the name of a member // on that object to run. It has to match the required prototype. See // the TMemberFunc class for details. // ---------------------------------------------------------------------------- CIDLib_MainModule ( TThread ( L"XMLDemo1MainThread" , TMemberFunc<TFacXMLDemo1>(&facXMLDemo1, &TFacXMLDemo1::eMainThreadFunc) ) ) // --------------------------------------------------------------------------- // CLASS: TFacXMLDemo1 // PREFIX: fac // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TFacXMLDemo1: Constructors and Destructor // --------------------------------------------------------------------------- TFacXMLDemo1::TFacXMLDemo1() : TFacility ( L"XMLDemo1" , tCIDLib::EModTypes::Exe , kCIDLib::c4MajVersion , kCIDLib::c4MinVersion , kCIDLib::c4Revision , tCIDLib::EModFlags::None ) , m_bShowWarnings(kCIDLib::False) , m_bTimeIt(kCIDLib::False) , m_c4ElemDepth(0) , m_c4EntityNesting(0) , m_c4MaxErrs(1) , m_eDisplayMode(EDisplayModes::None) , m_eOpts(tCIDXML::EParseOpts::None) , m_pstrmErr(nullptr) , m_pstrmOut(nullptr) { // // Create our output streams. If they are not redirected, then they just // go to the console. Otherwise, we create file streams with UTF-8 // text converters. // if (TFileSys::bIsRedirected(tCIDLib::EStdFiles::StdOut)) { m_pstrmOut = new TTextFileOutStream ( tCIDLib::EStdFiles::StdOut , new TUTFConverter(TUTFConverter::EEncodings::UTF8) ); } else { m_pstrmOut = new TOutConsole; } if (TFileSys::bIsRedirected(tCIDLib::EStdFiles::StdErr)) { m_pstrmErr = new TTextFileOutStream ( tCIDLib::EStdFiles::StdErr , new TUTFConverter(TUTFConverter::EEncodings::UTF8) ); } else { if (!TFileSys::bIsRedirected(tCIDLib::EStdFiles::StdOut)) m_pstrmErr = m_pstrmOut; else m_pstrmErr = new TOutConsole; } } TFacXMLDemo1::~TFacXMLDemo1() { if (m_pstrmErr != m_pstrmOut) delete m_pstrmErr; delete m_pstrmOut; } // --------------------------------------------------------------------------- // TFacXMLDemo1: Public, non-virtual methods // --------------------------------------------------------------------------- // // This is the the thread function for the main thread. It is started by // the CIDLib_MainModule() macro above. // tCIDLib::EExitCodes TFacXMLDemo1::eMainThreadFunc(TThread& thrThis, tCIDLib::TVoid*) { // We have to let our calling thread go first thrThis.Sync(); try { // Get the command line parms if (TSysInfo::c4CmdLineParmCount() < 1) { ShowUsage(); return tCIDLib::EExitCodes::BadParameters; } TSysInfo::TCmdLineCursor cursParms = TSysInfo::cursCmdLineParms(); TString strFileParm = *cursParms++; // Check for option parameters tCIDLib::TCard4 c4MaxErrs = 1; TString strTmp; for (; cursParms; ++cursParms) { strTmp = *cursParms; if (strTmp.bCompareI(L"/Validate")) { m_eOpts = tCIDLib::eOREnumBits(m_eOpts, tCIDXML::EParseOpts::Validate); } else if (strTmp.bCompareI(L"/Canonical")) { m_eDisplayMode = EDisplayModes::Canonical; } else if (strTmp.bCompareI(L"/ErrLoc")) { m_eDisplayMode = EDisplayModes::ErrLoc; } else if (strTmp.bCompareI(L"/ErrLoc2")) { m_eDisplayMode = EDisplayModes::ErrLoc2; } else if (strTmp.bCompareI(L"/IgnoreDTD")) { m_eOpts = tCIDLib::eOREnumBits(m_eOpts, tCIDXML::EParseOpts::IgnoreDTD); } else if (strTmp.bCompareI(L"/Std")) { m_eDisplayMode = EDisplayModes::Standard; } else if (strTmp.bCompareI(L"/ShowWarnings")) { m_bShowWarnings = kCIDLib::True; } else if (strTmp.bCompareI(L"/Time")) { m_bTimeIt = kCIDLib::True; } else if (strTmp.bCompareNI(L"/MaxErr=", 8)) { strTmp.Cut(0,8); c4MaxErrs = strTmp.c4Val(); if (!c4MaxErrs) *m_pstrmOut << L"Invalid maximum error value\n" << kCIDLib::EndLn; } else if (strTmp.bStartsWithI(L"/Mapping:")) { // // Parse out this mapping and add it to our catalog, which // we'll use to do entity redirection. They look like: // // /Mapping:pubid=sysid // // so its a mapping of a public id to a system id // strTmp.Cut(0, 9); if (!bLoadMapping(strTmp)) return tCIDLib::EExitCodes::BadParameters; } else { *m_pstrmOut << L"Unknown option: " << strTmp << kCIDLib::EndLn; ShowUsage(); return tCIDLib::EExitCodes::BadParameters; } } // Do the parse operation TXMLParserCore xprsTest; DoParse(xprsTest, strFileParm); #if CID_DEBUG_ON #define DEBUG_LEAKS 0 #if DEBUG_LEAKS TKrnlMemCheck kmchkTest; kmchkTest.ReportToFile(L"MemDump.Txt"); xprsTest.Reset(); kmchkTest.TakeSnapshot(); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); DoParse(xprsTest, strFileParm); xprsTest.Reset(); kmchkTest.DumpSnapDiffs(); #endif #endif // Flush the output stream to force all output out m_pstrmOut->Flush(); } // Catch any CIDLib runtime errors catch(const TError& errToCatch) { *m_pstrmOut << L"A CIDLib runtime error occured during processing.\n" << L"Error: " << errToCatch.strErrText() << kCIDLib::NewLn << kCIDLib::EndLn; return tCIDLib::EExitCodes::RuntimeError; } // // Kernel errors should never propogate out of CIDLib, but I test // for them in my demo programs so I can catch them if they do // and fix them. // catch(const TKrnlError& kerrToCatch) { *m_pstrmOut << L"A kernel error occured during processing.\nError=" << kerrToCatch.errcId() << kCIDLib::NewLn << kCIDLib::EndLn; return tCIDLib::EExitCodes::FatalError; } // Catch a general exception catch(...) { *m_pstrmOut << L"A general exception occured during processing" << kCIDLib::NewLn << kCIDLib::EndLn; return tCIDLib::EExitCodes::SystemException; } return tCIDLib::EExitCodes::Normal; } // --------------------------------------------------------------------------- // TFacXMLDemo1: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TFacXMLDemo1::bLoadMapping(TString& strMapping) { // // There should be one and only one = sign and it must not be first // or last char. // tCIDLib::TCard4 c4Ofs; if (!strMapping.bFirstOccurrence(kCIDLib::chEquals, c4Ofs) || !c4Ofs || (c4Ofs == (strMapping.c4Length() - 1))) { TSysInfo::strmErr() << L"\nThe mapping '" << strMapping << L"' was not well formed" << kCIDLib::EndLn; return kCIDLib::False; } // // Break out the two parts into separate strings. The incoming string is // not const, so we can keep the base part there, and copy the other part // out to a second string. // TString strSysId; strMapping.CopyOutSubStr(strSysId, c4Ofs + 1); strMapping.CapAt(c4Ofs); // And add this new item to the catalog TFileEntitySrc* pxesNew = new TFileEntitySrc(strSysId); pxesNew->strPublicId(strMapping); m_xcatMappings.AddMapping(pxesNew); return kCIDLib::True; } // // We split out the actual work to aid with heap leak checks. We can invoke // it once from the main thread method and then invoke it more times to // watch for leaks. So this way we completely destroy everything again // after we are done, so subsequent invocations shouldn't really create // any more faulted in data. WE also take a parser to use, so that we // can check when using the same parser, or destroying one and creating // another, to see if there's any difference. // tCIDLib::TVoid TFacXMLDemo1::DoParse(TXMLParserCore& xprsTest, const TString& strToParse) { // // Create the validator, and give him a pointer to the parser. He has // to use this to do a number of things, e.g. reporting errors. He // adopts it bue we keep a pointer so we can directly access it if // needed. // m_pxvalTest = new TDTDValidator(&xprsTest); xprsTest.pxvalValidator(m_pxvalTest); // // We always install the entity event handler in this program. Its used // to maintain an entity nesting level counter. // xprsTest.pmxevEntityEvents(this); // Set up the max errors value we defaulted or were given xprsTest.c4MaxErrors(m_c4MaxErrs); // // We have to set the parse flags so that we get only what we are // interested in. If we are doing canonical format, we don't want // any stuff outside the content. // // If we are doing canonical, we also need to remove ourselves as // the DTD event handler on the validator because we don't want any // stuff from there (and the parse flags only control optional stuff // not the markup decl stuff.) // tCIDXML::EParseFlags eFlags = tCIDXML::EParseFlags::Standard; if (m_eDisplayMode == EDisplayModes::Canonical) { eFlags = tCIDLib::eOREnumBits ( tCIDXML::EParseFlags::JustContent , tCIDXML::EParseFlags::PIsAC , tCIDXML::EParseFlags::PIsBC ); // We only need to add the document events and errors xprsTest.pmxevDocEvents(this); xprsTest.pmxevErrorEvents(this); } else if ((m_eDisplayMode == EDisplayModes::ErrLoc) || (m_eDisplayMode == EDisplayModes::ErrLoc2)) { // We just need to add the error events xprsTest.pmxevErrorEvents(this); } else { // // Its just normal output mode, so we need all the event handlers xprsTest.pmxevDocEvents(this); xprsTest.pmxevErrorEvents(this); m_pxvalTest->pmxevDTDEventHandler(this); } // If we got any entity mappings, set us as the entity resolver if (!m_xcatMappings.c4MapCount()) xprsTest.pmxevEntityResolver(this); // Get the current time TTime tmStart(tCIDLib::ESpecialTimes::CurrentTime); // And now parse the file xprsTest.ParseRootEntity(strToParse, m_eOpts, eFlags); // Get the end time TTime tmEnd(tCIDLib::ESpecialTimes::CurrentTime); if (m_bTimeIt) { *m_pstrmOut << L"Elapsed MS: " << (tmEnd.enctMilliSeconds() - tmStart.enctMilliSeconds()) << kCIDLib::EndLn; } // // The parser adopts the validator, so we need to clear our pointer, // and force the parser to drop it as well, since we'll create a new // one next time. // m_pxvalTest = 0; xprsTest.pxvalValidator(0); } tCIDLib::TVoid TFacXMLDemo1::ShowUsage() { *m_pstrmOut << L"Usage: XMLDemo1 filepath [options]\n" L" Options:\n" L" /Validate\n" L" /IgnoreDTD\n" L" /Mapping:pubid=sysid\n" L" /[Canonical | ErrLoc | ErrLoc2 | Std]\n\n" L" * Using /Validate and /IgnoreDTD will not work of course\n" L" because you told it to ignore the DTD it needs in order\n" L" to validate\n" << kCIDLib::EndLn; }
[ "droddey@charmedquark.com" ]
droddey@charmedquark.com
bcda6bb65adda2f85a394f79d62dd3c939fc0a18
4df5fc8a4116c3a9273d68de182e8d2ff414ec2f
/KDIS/DataTypes/ArealObjectAppearance.cpp
438e1530fb3025f236ab167b0f41508e27022835
[ "BSD-2-Clause" ]
permissive
pelicanmapping/bda-kdis
71c696e73a65ed9895dc104496dbffb2134b2530
ae0d1da99e62a4424b6cd14cd963b5a87a80fb7b
refs/heads/master
2021-07-05T22:42:09.292023
2017-09-29T13:56:07
2017-09-29T13:56:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,036
cpp
/********************************************************************* Copyright 2013 KDIS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. For Further Information Please Contact me at Karljj1@yahoo.com http://p.sf.net/kdis/UserGuide *********************************************************************/ #include "./ArealObjectAppearance.h" using namespace KDIS; using namespace DATA_TYPE; using namespace ENUMS; using namespace std; ////////////////////////////////////////////////////////////////////////// // Public: ////////////////////////////////////////////////////////////////////////// ArealObjectAppearance::ArealObjectAppearance( void ) { m_SpecificAppearanceUnion.m_ui32SpecificAppearance = 0; } ////////////////////////////////////////////////////////////////////////// ArealObjectAppearance::ArealObjectAppearance( KDataStream & stream ) throw( KException ) { Decode( stream ); } ////////////////////////////////////////////////////////////////////////// ArealObjectAppearance::~ArealObjectAppearance( void ) { } ////////////////////////////////////////////////////////////////////////// void ArealObjectAppearance::SetBreach( Breach2bit B ) { m_SpecificAppearanceUnion.m_Minefield.m_ui32Breach = B; } ////////////////////////////////////////////////////////////////////////// Breach2bit ArealObjectAppearance::GetBreach() const { return ( Breach2bit )m_SpecificAppearanceUnion.m_Minefield.m_ui32Breach; } ////////////////////////////////////////////////////////////////////////////// void ArealObjectAppearance::SetMineCount( KUINT16 M ) { m_SpecificAppearanceUnion.m_Minefield.m_ui32Mines = M; } ////////////////////////////////////////////////////////////////////////////// KUINT16 ArealObjectAppearance::GetMineCount() const { return m_SpecificAppearanceUnion.m_Minefield.m_ui32Mines; } ////////////////////////////////////////////////////////////////////////// KString ArealObjectAppearance::GetAsString() const { KStringStream ss; ss << ObjectAppearance::GetAsString() << "\tSpecific Appearance: " << m_SpecificAppearanceUnion.m_ui32SpecificAppearance << "\n"; return ss.str(); } ////////////////////////////////////////////////////////////////////////// void ArealObjectAppearance::Decode( KDataStream & stream ) throw( KException ) { if( stream.GetBufferSize() < ArealObjectAppearance::AREAL_OBJECT_APPEARANCE_SIZE )throw KException( __FUNCTION__, NOT_ENOUGH_DATA_IN_BUFFER ); stream >> m_SpecificAppearanceUnion.m_ui32SpecificAppearance >> m_GeneralAppearanceUnion.m_ui16GeneralAppearance; } ////////////////////////////////////////////////////////////////////////// KDataStream ArealObjectAppearance::Encode() const { KDataStream stream; ArealObjectAppearance::Encode( stream ); return stream; } ////////////////////////////////////////////////////////////////////////// void ArealObjectAppearance::Encode( KDataStream & stream ) const { // First add the specific bytes and then the general. stream << m_SpecificAppearanceUnion.m_ui32SpecificAppearance << m_GeneralAppearanceUnion.m_ui16GeneralAppearance; } ////////////////////////////////////////////////////////////////////////// KBOOL ArealObjectAppearance::operator == ( const ArealObjectAppearance & Value ) const { if( ObjectAppearance::operator != ( Value ) ) return false; if( m_SpecificAppearanceUnion.m_ui32SpecificAppearance != Value.m_SpecificAppearanceUnion.m_ui32SpecificAppearance ) return false; return true; } ////////////////////////////////////////////////////////////////////////// KBOOL ArealObjectAppearance::operator != ( const ArealObjectAppearance & Value ) const { return !( *this == Value ); } //////////////////////////////////////////////////////////////////////////
[ "gwaldron@gmail.com" ]
gwaldron@gmail.com
07c5abd7ef795356c14777e01b897e99f14c63b7
1fa6da9738f44aa7f23d234dcdfba5579eb4a30a
/blamlib/source/math/euler_angles3d.inl
0b2bd7aa0a2f577076376d43fd3936f01a00ce43
[]
no_license
TheDudeMods/zeta
aaaacef5a70208d82d20ec950f1f6b6fac6c9e1a
2d5d032487887fce54681a15f3f8a636cf1cab99
refs/heads/master
2020-11-30T11:29:19.607407
2019-12-30T04:54:07
2019-12-30T04:54:07
230,387,353
0
0
null
2019-12-27T06:35:32
2019-12-27T06:35:31
null
UTF-8
C++
false
false
178
inl
#pragma once template <typename t_element> struct s_euler_angles3d { t_element yaw; t_element pitch; t_element roll; }; static_assert(sizeof(s_euler_angles3d<long>) == 0xC);
[ "camden.smallwood@gmail.com" ]
camden.smallwood@gmail.com
59f25297ca9f1cf8fd5ab3a7c3eed10ce6191f08
dc25f8a17c2930c420f99450f0432bb2846ab4e8
/ros-packages/src/super4pcs/super4pcs/accelerators/kdtree.h
e964c20ab2e83046dbfa1ad72c574b1b2a7cdb01
[ "Apache-2.0" ]
permissive
Pandinosaurus/PHYSIM_6DPose
5e3ba3c42208f7c39dd90819757dbd42b1fdc015
d369bfdfceb0f8dc491611ad528ed787db90af0b
refs/heads/master
2020-06-04T19:19:32.602540
2018-03-13T14:01:02
2018-03-13T14:01:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,613
h
// Copyright 2014 Gael Guennebaud, Nicolas Mellado // // 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 // // 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. // // -------------------------------------------------------------------------- // // // Authors: Gael Guennebaud, Nicolas Mellado // // Part of the implementation of the Super 4-points Congruent Sets (Super 4PCS) // algorithm presented in: // // Super 4PCS: Fast Global Pointcloud Registration via Smart Indexing // Nicolas Mellado, Dror Aiger, Niloy J. Mitra // Symposium on Geometry Processing 2014. // // Data acquisition in large-scale scenes regularly involves accumulating // information across multiple scans. A common approach is to locally align scan // pairs using Iterative Closest Point (ICP) algorithm (or its variants), but // requires static scenes and small motion between scan pairs. This prevents // accumulating data across multiple scan sessions and/or different acquisition // modalities (e.g., stereo, depth scans). Alternatively, one can use a global // registration algorithm allowing scans to be in arbitrary initial poses. The // state-of-the-art global registration algorithm, 4PCS, however has a quadratic // time complexity in the number of data points. This vastly limits its // applicability to acquisition of large environments. We present Super 4PCS for // global pointcloud registration that is optimal, i.e., runs in linear time (in // the number of data points) and is also output sensitive in the complexity of // the alignment problem based on the (unknown) overlap across scan pairs. // Technically, we map the algorithm as an ‘instance problem’ and solve it // efficiently using a smart indexing data organization. The algorithm is // simple, memory-efficient, and fast. We demonstrate that Super 4PCS results in // significant speedup over alternative approaches and allows unstructured // efficient acquisition of scenes at scales previously not possible. Complete // source code and datasets are available for research use at // http://geometry.cs.ucl.ac.uk/projects/2014/super4PCS/. #ifndef KDTREE_H #define KDTREE_H #include "bbox.h" #include "Eigen/Core" #include <limits> #include <iostream> #include <numeric> //iota // max depth of the tree #define KD_MAX_DEPTH 32 // number of neighbors #define KD_POINT_PER_CELL 64 namespace Super4PCS{ /*! <h3>Generation</h3> You can create the KdTree in two way : - Simple pass construction : easy to use, but use a full vertices memory copy : \code basic::TArray < KdTree<float>::VectorType > data(60); int i = 0; for ( ; i != 30; i++ ) { data << vec3 (rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1); // vertex to add } data << vec3(0.5,0.5,0.5); // we must find this vertex i++; for ( ; i != 60; i++ ) { data << vec3 (rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1); // vertex to add } KdTree<float> t ( data ); // Memory copy \endcode - Per-vertex pass construction : more code, but avoid copy : \code KdTree<float> t ( 60 ); int i = 0; for ( ; i != 30; i++ ) { vec3 v( rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1); // vertex to add t.set( i ,v ); } t.set(i, vec3(0.5,0.5,0.5)); // we must find this vertex i++; for ( ; i != 60; i++ ) { vec3 v( rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1); // vertex to add t.set( i ,v ); } t.finalize(); // the real creation of the KdTree \endcode This version is very usefull if data are computed on the fly. <h3>Closest-Point query</h3> It is important to note that in the case of multiple neighbors request, the result isn't sorted (see HeapMaxPriorityQueue for more explanations). So if you want to get the closest point, you must perform a single request. You must specify the size of the request using setMaxNofNeighbors. \code t.setMaxNofNeighbors(1); t.doQueryK( vec3(0,0,0) ); vec3 result = t.getNeighbor( 0 ).p; unsigned int resultId = t.getNeighborId( 0 ); cout << resultId << endl; cout << result(0) << " " << result(1) << " " << result(2) << endl; cout << t.getNeighborSquaredDistance( 0 ) << endl; \endcode \ingroup groupGeometry */ template<typename _Scalar, typename _Index = int > class KdTree { public: struct KdNode { union { struct { float splitValue; unsigned int firstChildId:24; unsigned int dim:2; unsigned int leaf:1; }; struct { unsigned int start; unsigned short size; }; }; }; typedef _Scalar Scalar; typedef _Index Index; static constexpr Index invalidIndex() { return -1; } typedef Eigen::Matrix<Scalar,3,1> VectorType; typedef AABB3D<Scalar> AxisAlignedBoxType; typedef std::vector<KdNode> NodeList; typedef std::vector<VectorType> PointList; typedef std::vector<Index> IndexList; inline const NodeList& _getNodes (void) { return mNodes; } inline const PointList& _getPoints (void) { return mPoints; } inline const PointList& _getIndices (void) { return mIndices; } public: //! Create the Kd-Tree using memory copy. KdTree(const PointList& points, unsigned int nofPointsPerCell = KD_POINT_PER_CELL, unsigned int maxDepth = KD_MAX_DEPTH ); //! Create a void KdTree KdTree( unsigned int size = 0, unsigned int nofPointsPerCell = KD_POINT_PER_CELL, unsigned int maxDepth = KD_MAX_DEPTH ); //! Add a new vertex in the KdTree template <class VectorDerived> inline void add( const VectorDerived &p ){ // this is ok since the memory has been reserved at construction time mPoints.push_back(p); mIndices.push_back(mIndices.size()); mAABB.extendTo(p); } inline void add(Scalar *position){ add(Eigen::Map< Eigen::Matrix<Scalar, 3, 1> >(position)); } //! Finalize the creation of the KdTree inline void finalize( ); inline const AxisAlignedBoxType& aabb() const {return mAABB; } ~KdTree(); inline void doQueryK(const VectorType& p); /*! * \brief Performs distance query and return vector coordinates */ template<typename Container = std::vector<VectorType> > inline void doQueryDist(const VectorType& queryPoint, Scalar sqdist, Container& result){ _doQueryDistIndicesWithFunctor(queryPoint, sqdist, [&result,this](unsigned int i){ result.push_back(typename Container::value_type(mPoints[i])); }); } /*! * \brief Performs distance query and return indices */ template<typename IndexContainer = std::vector<Index> > inline void doQueryDistIndices(const VectorType& queryPoint, float sqdist, IndexContainer& result){ _doQueryDistIndicesWithFunctor(queryPoint, sqdist, [&result,this](unsigned int i){ result.push_back(typename IndexContainer::value_type(mIndices[i])); }); } /*! * \brief Finds the closest element index within the range [0:sqrt(sqdist)] * \param currentId Index of the querypoint if it belongs to the tree */ inline Index doQueryRestrictedClosestIndex(const VectorType& queryPoint, Scalar sqdist, int currentId = -1); EIGEN_MAKE_ALIGNED_OPERATOR_NEW protected: //! element of the stack struct QueryNode { inline QueryNode() {} inline QueryNode(unsigned int id) : nodeId(id) {} //! id of the next node unsigned int nodeId; //! squared distance to the next node Scalar sq; }; /*! Used to build the tree: split the subset [start..end[ according to dim and splitValue, and returns the index of the first element of the second subset. */ inline unsigned int split(int start, int end, unsigned int dim, Scalar splitValue); void createTree(unsigned int nodeId, unsigned int start, unsigned int end, unsigned int level, unsigned int targetCellsize, unsigned int targetMaxDepth); /*! * \brief Performs distance query and pass the internal id to a functor */ template<typename Functor > inline void _doQueryDistIndicesWithFunctor(const VectorType& queryPoint, float sqdist, Functor f); protected: PointList mPoints; IndexList mIndices; AxisAlignedBoxType mAABB; NodeList mNodes; QueryNode mNodeStack[64]; unsigned int _nofPointsPerCell; unsigned int _maxDepth; }; /*! \see KdTree(unsigned int size, unsigned int nofPointsPerCell, unsigned int maxDepth) */ template<typename Scalar, typename Index> KdTree<Scalar, Index>::KdTree(const PointList& points, unsigned int nofPointsPerCell, unsigned int maxDepth) : mPoints(points), mIndices(points.size()), mAABB(points.cbegin(), points.cend()), _nofPointsPerCell(nofPointsPerCell), _maxDepth(maxDepth) { std::iota (mIndices.begin(), mIndices.end(), 0); // Fill with 0, 1, ..., 99. finalize(); } /*! Second way to create the KdTree, in two time. You must call finalize() before requesting for closest points. \see finalize() */ template<typename Scalar, typename Index> KdTree<Scalar, Index>::KdTree(unsigned int size, unsigned int nofPointsPerCell, unsigned int maxDepth) : _nofPointsPerCell(nofPointsPerCell), _maxDepth(maxDepth) { mPoints.reserve(size); mIndices.reserve(size); } template<typename Scalar, typename Index> void KdTree<Scalar, Index>::finalize() { mNodes.clear(); mNodes.reserve(4*mPoints.size()/_nofPointsPerCell); mNodes.push_back(KdNode()); mNodes.back().leaf = 0; std::cout << "create tree" << std::endl; createTree(0, 0, mPoints.size(), 1, _nofPointsPerCell, _maxDepth); std::cout << "create tree ... DONE (" << mPoints.size() << " points)" << std::endl; } template<typename Scalar, typename Index> KdTree<Scalar, Index>::~KdTree() { } /*! This algorithm uses the simple distance to the split plane to prune nodes. A more elaborated approach consists to track the closest corner of the cell relatively to the current query point. This strategy allows to save about 5% of the leaves. However, in practice the slight overhead due to this tracking reduces the overall performance. This algorithm also use a simple stack while a priority queue using the squared distances to the cells as a priority values allows to save about 10% of the leaves. But, again, priority queue insertions and deletions are quite involved, and therefore a simple stack is by far much faster. The optionnal parameter currentId is used when the query point is stored in the tree, and must thus be avoided during the query */ template<typename Scalar, typename Index> Index KdTree<Scalar, Index>::doQueryRestrictedClosestIndex( const VectorType& queryPoint, Scalar sqdist, int currentId) { Index cl_id = invalidIndex(); Scalar cl_dist = sqdist; mNodeStack[0].nodeId = 0; mNodeStack[0].sq = 0.f; unsigned int count = 1; //int nbLoop = 0; while (count) { //nbLoop++; QueryNode& qnode = mNodeStack[count-1]; KdNode & node = mNodes[qnode.nodeId]; if (qnode.sq < cl_dist) { if (node.leaf) { --count; // pop const int end = node.start+node.size; for (int i=node.start ; i<end ; ++i){ const Scalar sqdist = (queryPoint - mPoints[i]).squaredNorm(); if (sqdist <= cl_dist && mIndices[i] != currentId){ cl_dist = sqdist; cl_id = mIndices[i]; } } } else { // replace the stack top by the farthest and push the closest const Scalar new_off = queryPoint[node.dim] - node.splitValue; //std::cout << "new_off = " << new_off << std::endl; if (new_off < 0.) { mNodeStack[count].nodeId = node.firstChildId; // stack top the farthest qnode.nodeId = node.firstChildId+1; // push the closest } else { mNodeStack[count].nodeId = node.firstChildId+1; qnode.nodeId = node.firstChildId; } mNodeStack[count].sq = qnode.sq; qnode.sq = new_off*new_off; ++count; } } else { // pop --count; } } return cl_id; } /*! \see doQueryRestrictedClosest For more information about the algorithm. This function is an alternative to doQueryK(const VectorType& queryPoint) that allow to perform the query by requesting a maximum distance instead of neighborhood size. */ template<typename Scalar, typename Index> template<typename Functor > void KdTree<Scalar, Index>::_doQueryDistIndicesWithFunctor( const VectorType& queryPoint, float sqdist, Functor f) { mNodeStack[0].nodeId = 0; mNodeStack[0].sq = 0.f; unsigned int count = 1; while (count) { QueryNode& qnode = mNodeStack[count-1]; KdNode & node = mNodes[qnode.nodeId]; if (qnode.sq < sqdist) { if (node.leaf) { --count; // pop unsigned int end = node.start+node.size; for (unsigned int i=node.start ; i<end ; ++i) if ( (queryPoint - mPoints[i]).squaredNorm() < sqdist){ f(i); } } else { // replace the stack top by the farthest and push the closest Scalar new_off = queryPoint[node.dim] - node.splitValue; if (new_off < 0.) { mNodeStack[count].nodeId = node.firstChildId; qnode.nodeId = node.firstChildId+1; } else { mNodeStack[count].nodeId = node.firstChildId+1; qnode.nodeId = node.firstChildId; } mNodeStack[count].sq = qnode.sq; qnode.sq = new_off*new_off; ++count; } } else { // pop --count; } } } template<typename Scalar, typename Index> unsigned int KdTree<Scalar, Index>::split(int start, int end, unsigned int dim, Scalar splitValue) { int l(start), r(end-1); for ( ; l<r ; ++l, --r) { while (l < end && mPoints[l][dim] < splitValue) l++; while (r >= start && mPoints[r][dim] >= splitValue) r--; if (l > r) break; std::swap(mPoints[l],mPoints[r]); std::swap(mIndices[l],mIndices[r]); } return (mPoints[l][dim] < splitValue ? l+1 : l); } /*! Recursively builds the kdtree The heuristic is the following: - if the number of points in the node is lower than targetCellsize then make a leaf - else compute the AABB of the points of the node and split it at the middle of the largest AABB dimension. This strategy might look not optimal because it does not explicitly prune empty space, unlike more advanced SAH-like techniques used for RT. On the other hand it leads to a shorter tree, faster to traverse and our experience shown that in the special case of kNN queries, this strategy is indeed more efficient (and much faster to build). Moreover, for volume data (e.g., fluid simulation) pruning the empty space is useless. Actually, storing at each node the exact AABB (we therefore have a binary BVH) allows to prune only about 10% of the leaves, but the overhead of this pruning (ball/ABBB intersection) is more expensive than the gain it provides and the memory consumption is x4 higher ! */ template<typename Scalar, typename Index> void KdTree<Scalar, Index>::createTree(unsigned int nodeId, unsigned int start, unsigned int end, unsigned int level, unsigned int targetCellSize, unsigned int targetMaxDepth) { KdNode& node = mNodes[nodeId]; AxisAlignedBoxType aabb; //aabb.Set(mPoints[start]); for (unsigned int i=start ; i<end ; ++i) aabb.extendTo(mPoints[i]); VectorType diag = Scalar(0.5) * (aabb.max()- aabb.min()); typename VectorType::Index dim; #ifdef DEBUG // std::cout << "createTree(" // << nodeId << ", " // << start << ", " // << end << ", " // << level << ")" // << std::endl; if (std::isnan(diag.maxCoeff(&dim))){ std::cerr << "NaN values discovered in the tree, abort" << std::endl; return; } #else diag.maxCoeff(&dim); #endif #undef DEBUG node.dim = dim; node.splitValue = aabb.center()(dim); unsigned int midId = split(start, end, dim, node.splitValue); node.firstChildId = mNodes.size(); { KdNode n; n.size = 0; mNodes.push_back(n); mNodes.push_back(n); } //mNodes << Node() << Node(); //mNodes.resize(mNodes.size()+2); { // left child unsigned int childId = mNodes[nodeId].firstChildId; KdNode& child = mNodes[childId]; if (midId-start <= targetCellSize || level>=targetMaxDepth) { child.leaf = 1; child.start = start; child.size = midId-start; } else { child.leaf = 0; createTree(childId, start, midId, level+1, targetCellSize, targetMaxDepth); } } { // right child unsigned int childId = mNodes[nodeId].firstChildId+1; KdNode& child = mNodes[childId]; if (end-midId <= targetCellSize || level>=targetMaxDepth) { child.leaf = 1; child.start = midId; child.size = end-midId; } else { child.leaf = 0; createTree(childId, midId, end, level+1, targetCellSize, targetMaxDepth); } } } } //namespace Super4PCS #endif // KDTREE_H
[ "cm1074@cs.rutgers.edu" ]
cm1074@cs.rutgers.edu
42fa85759e861a98289878383e3ffcacf0dac5cb
95a23d5647b80b20b7e2e813ebd1f48629353282
/Application/include/Ocean.hpp
7559b6aabe026fd612cac93cbb17cf45850e21cc
[ "MIT" ]
permissive
inhibitor1217/cs380-lighting
0cdf028606a3a376c25437fdb160518ea044fcf8
7949a743d78a4151db807c17ef89c7999a2c5334
refs/heads/master
2020-05-21T21:18:47.636991
2019-06-24T17:47:21
2019-06-24T17:47:21
186,150,934
0
0
null
null
null
null
UTF-8
C++
false
false
684
hpp
#pragma once #include "RenderObject.hpp" #include "TerrainMaterial.hpp" constexpr int NUM_WAVES = 4; constexpr float WAVE_VECTOR_LENGTH_MIN = 0.7; constexpr float WAVE_VECTOR_LENGTH_MAX = 5.0; class Ocean { public: Ocean(float _CHUNK_SIZE, int _TERRAIN_SIZE, float _LOD, float center_z); ~Ocean(); void SetMaterial(Engine::Material *material); void Render(Engine::Camera *camera, float angle); private: float CHUNK_SIZE; int TERRAIN_SIZE; float LOD; std::vector<Engine::RenderObject *> __objects; TerrainMaterial *__material; void generateObjects(float center_z); Engine::RenderObject *Ocean::generateChunk(float center_x, float center_y, float center_z, int lod); };
[ "cytops1217@gmail.com" ]
cytops1217@gmail.com
4f8927de203e312abff9aac585e3d38c7470a165
57dd602af73fa1add24f39c8f5b67aef84bf63b6
/src/DecSensorRadiation.cpp
188a659121a45917fcbe93c1c17246ea88531a6c
[]
no_license
evster-coder/IndustrialRobotSystem
af6aead374d3ab8444f96b28825e8e6feddbd285
5c56dda58ecccbd6066b23abcae14805161fa488
refs/heads/main
2023-03-05T03:35:08.591476
2021-02-13T17:03:34
2021-02-13T17:03:34
331,383,141
2
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include "DecSensorRadiation.h" bool DecSensorRadiation::scanConditions() { item->setRadiation(double(rand() % 10)); return item->scanConditions(); }
[ "8961240@gmail.com" ]
8961240@gmail.com
43a0b7c0f59dc0aa826968fdf22b17d0f12a1a5d
22cfcbfee89e491971d855ba4ed7e3eb12c5c9f0
/Source/PayCenterServer/ProcWorldHandler.cpp
e3373d3e0243504f902e2eee3483659c0d6a741f
[]
no_license
huangzuduan/HMX-Server
dac6a9f7cc40fa169a64605a6a365b49a7bb084c
13a28e243dccb44dd06d45dbddd35541a994d713
refs/heads/master
2018-10-31T23:32:38.788380
2018-09-26T11:14:53
2018-09-26T11:14:53
79,187,627
29
26
null
null
null
null
GB18030
C++
false
false
7,850
cpp
#include "ProcWorldHandler.h" #include "GameService.h" #include "MysqlProtobufHelper.h" #include "base/hmx_data.pb.h" #include "curl.h" #include "Poco/JSON/Parser.h" #include "Poco/JSON/ParseHandler.h" #include "Poco/JSON/JSONException.h" #include "Poco/StreamCopier.h" #include "Poco/Dynamic/Var.h" #include "Poco/JSON/Query.h" #include "Poco/JSON/PrintHandler.h" #include "Poco/Net/HTTPClientSession.h" #include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPResponse.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Path.h" #include "Poco/URI.h" #include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPServerParams.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerParams.h" #include "Poco/Net/HTMLForm.h" #include "Poco/Net/PartHandler.h" #include "Poco/Net/MessageHeader.h" #include "Poco/Net/ServerSocket.h" #include "Poco/CountingStream.h" #include "Poco/NullStream.h" #include "Poco/StreamCopier.h" #include "Poco/Exception.h" #include "Poco/Util/ServerApplication.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionSet.h" #include "Poco/Util/HelpFormatter.h" #include <iostream> using Poco::Net::HTTPClientSession; using Poco::Net::HTTPRequest; using Poco::Net::HTTPResponse; using Poco::Net::HTTPMessage; using Poco::StreamCopier; using Poco::Path; using Poco::URI; using Poco::Exception; using namespace Poco::Dynamic; using namespace Poco; #define SKIP_PEER_VERIFICATION #define SKIP_HOSTNAME_VERFICATION ProcWorldHandler::ProcWorldHandler() { } ProcWorldHandler::~ProcWorldHandler() { } void ProcWorldHandler::reqWxPayOrderInfo(zSession* pSession, const PbMsgWebSS* pMsg, int32_t nSize) { // CurlParm* parm = new CurlParm(); // // std::stringstream ss; // ss << "appid=wxd678efh567hg6787"; // ss << "&mch_id=1230000109"; // ss << "&nonce_str=no_" << time(NULL); // ss << "&sign=" << ""; // ss << "&body=" << "购买8张房卡"; // ss << "&out_trade_no=t_" << time(NULL); // ss << "&total_fee=" << "6.00"; // ss << "&spbill_create_ip=" << "192.168.16.100"; // ss << "&notify_url=" << ""; // ss << "&trade_type=APP"; // // std::string platUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; // // const string postParams; // // CURL *curl; // CURLcode res; // curl_global_init(CURL_GLOBAL_ALL); // curl = curl_easy_init(); // 初始化 // if (curl) // { // // curl_easy_setopt(curl, CURLOPT_POST, 1); // post req // curl_easy_setopt(curl, CURLOPT_URL, platUrl.c_str()); // curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ss.str().c_str()); // params // curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0"); // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6); // // //https 访问专用:start //#ifdef SKIP_PEER_VERIFICATION // //跳过服务器SSL验证,不使用CA证书 // curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // //如果不跳过SSL验证,则可指定一个CA证书目录 // //curl_easy_setopt(curl, CURLOPT_CAPATH, "this is ca ceat"); //#endif // //#ifdef SKIP_HOSTNAME_VERFICATION // //验证服务器端发送的证书,默认是 2(高),1(中),0(禁用) // curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //#endif // //https 访问专用:end // // curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &onPayResp); // curl_easy_setopt(curl, CURLOPT_WRITEDATA, parm); // res = curl_easy_perform(curl); // 执行 // curl_easy_cleanup(curl); // if (res == CURLE_OPERATION_TIMEDOUT) // { // fprintf(stderr, "%s\n", curl_easy_strerror(res)); // ::msg_maj::SDKTokenResp proRep; // proRep.set_result(::msg_maj::PLAT_REQ_TIMEOUT); // pSession->sendMsgProto(::comdef::msg_login, ::msg_maj::sdk_token_resp, proRep); // } // else if(res != CURLE_OK) // { // ASSERT(0); // } // else // { // // } // } // curl_global_cleanup(); // std::stringstream ss; // ss << "appid=wxd678efh567hg6787"; // ss << "&mch_id=1230000109"; // ss << "&nonce_str=no_" << time(NULL); // ss << "&sign=" << ""; // ss << "&body=" << "购买8张房卡"; // ss << "&out_trade_no=t_" << time(NULL); // ss << "&total_fee=" << "6.00"; // ss << "&spbill_create_ip=" << "192.168.16.100"; // ss << "&notify_url=" << ""; // ss << "&trade_type=APP"; // // std::string platUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; Poco::URI url("http://api.mch.weixin.qq.com/pay/unifiedorder"); HTTPClientSession session(url.getHost(), url.getPort()); HTTPRequest request(HTTPRequest::HTTP_POST, url.getPath(), HTTPRequest::HTTP_1_1); HTMLForm form; form.add("appid", "wxd678efh567hg6787"); form.add("mch_id", "1230000109"); form.add("nonce_str", "5555"); form.add("sign", "1230000109"); form.add("body", "wxd678efh567hg6787"); form.add("out_trade_no", "wxd678efh567hg6787"); form.add("total_fee", "1230000109"); form.add("spbill_create_ip", "192.168.16.100"); form.add("notify_url", "http://www.queyiyouxi.com/pay"); form.add("trade_type", "APP"); form.prepareSubmit(request); form.write(session.sendRequest(request)); Poco::Net::HTTPResponse res; std::istream & is = session.receiveResponse(res); StreamCopier::copyStream(is, std::cout); } size_t onPayResp(void *buffer, size_t size, size_t nmemb, void *parm) { CurlParm* pParm = (CurlParm*)parm; if (NULL == pParm) { ASSERT(0); return 0; } int16_t dataLength = (size * nmemb); pParm->buff_times++; memcpy(&pParm->buffer[pParm->buff_length], (char*)buffer, dataLength); pParm->buff_length += dataLength; std::string jsonStrSrc((char*)pParm->buffer, pParm->buff_length); zSession* pSession = pParm->conn; std::string token = pParm->token; delete pParm; pParm = NULL; JSON::Parser parser; Dynamic::Var result; parser.reset(); result = parser.parse(jsonStrSrc); JSON::Object::Ptr pObj = result.extract<JSON::Object::Ptr>(); int status = atoi(pObj->get("status").toString().c_str()); ::msg_maj::SDKTokenResp proRep; if (status == 1) // 根据参数判断,是否给于通过 { proRep.set_result(::msg_maj::TOKEN_ERROR); pSession->sendMsgProto(::comdef::msg_login, ::msg_maj::sdk_token_resp, proRep); return dataLength; } std::string gateIP = pObj->get("gateway_ip").toString(); std::string gatePort = pObj->get("gateway_port").toString(); std::string account = pObj->get("account").toString(); std::string icon_add = pObj->get("icon_add").toString(); if (strncmp(gateIP.c_str(), "0.0.0.0", 7) == 0) { zSession* pFep = GameService::getMe().SessionMgr()->getFep(); if (pFep == NULL) { proRep.set_result(::msg_maj::DATA_EXCEPTION); pSession->sendMsgProto(::comdef::msg_login, ::msg_maj::sdk_token_resp, proRep); return 0; } zServerReg* pFegReg = GameService::getMe().ServerRegMgr()->get(pFep->GetRemoteDataProto().serverid()); if (pFegReg == NULL) { proRep.set_result(::msg_maj::DATA_EXCEPTION); pSession->sendMsgProto(::comdef::msg_login, ::msg_maj::sdk_token_resp, proRep); return 0; } const std::vector< ::config::SerivceInfo>& serivceInfos = pFegReg->GetBroadSerivces(); for (std::vector< ::config::SerivceInfo>::const_iterator it = serivceInfos.begin(); it != serivceInfos.end(); ++it) { if (STRNICMP(it->serivcename().c_str(), "server", 6) == 0) { if (STRNICMP(it->serivcefun().c_str(), "foruser", 7) == 0) { proRep.set_result(::msg_maj::SUCCESS); proRep.set_ip(it->serivceip()); proRep.set_port(it->serivceport() + 1); break; } } } } else { proRep.set_result(::msg_maj::SUCCESS); proRep.set_ip(gateIP); proRep.set_port(atoi(gatePort.c_str())); } proRep.set_account(account); proRep.set_icon_add(icon_add); if (proRep.result() != ::msg_maj::SUCCESS) { pSession->sendMsgProto(::comdef::msg_login, ::msg_maj::sdk_token_resp, proRep); return dataLength; } return dataLength; }
[ "huangzuduan@qq.com" ]
huangzuduan@qq.com
43f25074268af4bf6ea7ea95565d63d4065e7918
7de76bab07db2da918f2392f349ca13c25dd5f8f
/Flight/MADLADS_receiver.ino
c3c4dee49a3e7531f609290eaa1449efb2df0aaf
[]
no_license
abust005/CS179J-Sp2019-Group-10
786e9333360c6016261fc8d95ba8ad456cca10cf
f9f5a76ab6962e4b562469f0d4047218489cf146
refs/heads/master
2023-01-03T16:51:03.337070
2019-06-10T18:16:25
2019-06-10T18:16:25
180,256,179
0
0
null
2022-12-08T05:13:06
2019-04-09T00:51:10
C#
UTF-8
C++
false
false
4,371
ino
/* * MADLADS_receiver.ino * Authors : Jonathan Woolf * Joshua Riley * Colton Vosburg * Adriel Bustamante * * Library: TMRh20/RF24, https://github.com/tmrh20/RF24/ */ #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> // ---------------------------------------- // === Inputs and Variables === // ---------------------------------------- const byte address[6] = "00001"; unsigned char isClose = 0; // This is a boolean to show if the drone is close to the ground unsigned char isValid = 0; // This is a boolean to show if the signal received is valid with the parity bit unsigned char droneSignal = 0; // This is the received signal from either the controller or navigation system unsigned short hover_cnt = 0; // This is a count in milliseconds of the time the drone has been hovering RF24 radio( 7, 8 ); // CE, CSN // ---------------------------------------- // === Functions === // ---------------------------------------- int GetBit( unsigned char var, unsigned char bit ) { return ( var & ( 0x01 << bit ) ); } void RadioServantInit() { radio.begin(); radio.openReadingPipe( 0, address ); radio.setPALevel( RF24_PA_MIN ); // radio.setPALevel( RF24_PA_MAX ); radio.startListening(); return; } /* LEFT JOYSTICK BITS - ***X XX** 000 - standby 001 - right 010 - forward 011 - forward/right 100 - left 101 - reverse 110 - forward/left 111 - N/A RIGHT JOYSTICK BITS - **** **XX 00 - standby 01 - down 10 - up 11 - N/A BUTTON BITS - *XX* **** 00 - claw is disengaged 10 - claw is engaged X1 - emergency shut off */ void MotorActuator( unsigned char value ) { // FIXME if( GetBit( value, 5) ) { // Kill motors } else { if( GetBit( value, 0 ) && !GetBit( value, 1) ) { // Drone is moving down along z-axis } else if( !GetBit( value, 0 ) && GetBit( value, 1)) { // Drone is moving up along z-axis } else { // Drone not moving along z-axis } } return; } int IsCloseToGround() { // FIXME // Input: LIDAR // Output: Boolean // if input < distance, return 1 return 0; } int IsSignalValid( unsigned char signal ){ unsigned char temp = 0; for ( unsigned i = 0; i < 8; i++ ) { temp ^= ( ( signal >> i ) & 0x01 ); } return (temp & 0x01); } // ---------------------------------------- // === Tick Function State Declarations === // ---------------------------------------- enum flightSM {Flight_Arm, Flight_Read, Flight_Standby, Flight_Process, Flight_Descend, Flight_Land} flight_states; // ---------------------------------------- // === Tick Functions === // ---------------------------------------- int TickFct_flight( int state ) { switch( state ) { // Transtions case Flight_Arm: state = Flight_Read; break; case Flight_Read: state = isValid ? Flight_Process : Flight_Standby; break; case Flight_Standby: if( hover_cnt > 300000 ) { state = Flight_Descend; } else { state = Flight_Read; } break; case Flight_Process: state = Flight_Read; break; case Flight_Descend: state = isClose ? Flight_Land : Flight_Descend; break; case Flight_Land: // Leave empty break; default: break; } switch( state ) { // Actions case Flight_Arm: hover_cnt = 0; RadioServantInit(); break; case Flight_Read: if( radio.available() ) { // Read signal from controller radio.read( &droneSignal, sizeof(droneSignal) ); } else { // FIXME: Read signal from navigation subsystem droneSignal = 0x00; } isValid = IsSignalValid(droneSignal); break; case Flight_Standby: hover_cnt++; break; case Flight_Process: hover_cnt = 0; MotorActuator( droneSignal ); break; case Flight_Descend: // Measure distance to ground with lidar isClose = IsCloseToGround(); break; case Flight_Land: // Kill motors and power off drone MotorActuator (0x40); break; } return state; } // ---------------------------------------- // === Main Code === // ---------------------------------------- void setup() { // Setup input and output pins // Setup tasks // Set timer } void loop() { // Leave empty }
[ "jrile002@ucr.edu" ]
jrile002@ucr.edu
0c7e118a22658682a689cef2553a0df1a28644de
bd753f1db4a3870f5b260d87e3165ef9ae03473d
/Linear_algebra/State.h
5ed5f7e8f3ddcecf3b144032a588ff2acb2be0b0
[]
no_license
vvaffl4/FinalAssignmentAAI
81e7377262e860d86275227e6528f792b20b3605
b6ef8d8ef4da19e7516b78530c1abae6dab62c59
refs/heads/master
2021-04-15T13:19:13.109242
2018-03-29T12:23:36
2018-03-29T12:23:36
126,816,927
0
0
null
2018-03-29T12:12:26
2018-03-26T11:12:17
C++
UTF-8
C++
false
false
340
h
#ifndef STATE_H #define STATE_H #pragma once class Guard; class StateMachine; class State { protected: StateMachine* _stateMachine = nullptr; public: State(StateMachine* stateMachine); virtual ~State(); virtual void enter(Guard* entity) = 0; virtual void execute(Guard* entity) = 0; virtual void exit(Guard* entity) = 0; }; #endif
[ "chris.coerdes@gmail.com" ]
chris.coerdes@gmail.com
68189a30641af73464762007115598f43aba3ad7
b02f404aa833b685997f8421a2c4bc31706da30b
/Leetcode/春招/双指针/1358.cpp
bc8af15a9d5ddb60172d375e2f600a463340147e
[]
no_license
Super-long/Leetcode
a596fda29cb0d210048957c9e6798586486316f1
d16d16a8e6076f37889c21f4c2c04ded7b915a85
refs/heads/master
2021-07-01T19:31:45.559894
2021-03-18T06:54:51
2021-03-18T06:54:51
226,631,026
4
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: int numberOfSubstrings(string s) { // 这题可以用二分解 int lhs = 0; unordered_map<char, int> vis; int res = 0; for (size_t i = 0; i < s.size(); i++){ vis[s[i]]++; if(vis.size() == 3){ while(lhs <= i && vis.size() == 3){ res += s.size() - i; vis[s[lhs]]--; if(vis[s[lhs]] == 0) vis.erase(s[lhs]); lhs++; } } } return res; } }; int main(){ Solution sol; std::cout << sol.numberOfSubstrings("abc") << endl; return 0; }
[ "2339824768@qq.com" ]
2339824768@qq.com
9c76c33153bd87462f86ec89684a6407171bb16b
6ec4087fb56ba7b33aada9b58a9aef80eb2de786
/gamesdk/src/Thread_Impl.h
5c77bc2fad555fb44513e77b0aec8027442be8f6
[]
no_license
wangscript007/xg-sdk
660d46fb8b66bb24676ea751630a5b2e461f74e3
e027f2382ea71c59d8d87552cd005fb3a589537c
refs/heads/master
2022-11-12T17:09:27.794713
2020-06-03T00:36:11
2020-06-03T00:36:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,100
h
/* $Id: Thread_Impl.h,v 1.1 2005/11/14 17:07:59 dmitry.vereshchagin Exp $ ** Game SDK ** */ // Thread_Impl.h: interface for the Thread_Impl class. // ////////////////////////////////////////////////////////////////////// #if !defined(HEADER_THREAD_IMPL_H_9505A529_5FA1_4CDD_8E75_1786B495BD98) #define HEADER_THREAD_IMPL_H_9505A529_5FA1_4CDD_8E75_1786B495BD98 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //#include <iostream> //using namespace std; #include "stdafx.h" #include "thread.h" #include "types.h" namespace GSDK { ////////////////////////////////////////////////////////////////////// /// ////////////////////////////////////////////////////////////////////// /** * */ class Thread_Impl { typedef unsigned int (__stdcall * PBEGIN_THREADEX_PROC ) ( void * ); public: ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// /// /// Thread_Impl() : m_handle(0) , m_tid(0) , m_stack_size(0) , m_security(0) , m_runnable(0) , m_delete_runnable(0) { } #ifdef _WIN32 Thread_Impl(LPSECURITY_ATTRIBUTES lpsa, ulong stack ) : m_handle(0) , m_tid(0) , m_stack_size(stack) , m_security(lpsa) , m_runnable(0) , m_delete_runnable(false) { } Thread_Impl(Runnable *runnable , bool delete_runnable = false , LPSECURITY_ATTRIBUTES lpsa = NULL , ulong stack = 0) : m_handle(0) , m_tid(0) , m_stack_size(0) , m_security(lpsa) , m_runnable(runnable) , m_delete_runnable(delete_runnable) { } #endif virtual ~Thread_Impl() { ::CloseHandle(m_handle); if(m_delete_runnable) delete m_runnable; }; ////////////////////////////////////////////////////////////////////// // Methods ////////////////////////////////////////////////////////////////////// bool start( int prio = THREAD_PRIORITY_NORMAL, bool suspended = false ); bool start( Thread::PTHREAD_PROC pfn, int prio = THREAD_PRIORITY_NORMAL, bool suspended = false ); ulong set_priority (int prio) { ::SetThreadPriority(m_handle,prio); }; ulong suspend() { return ::SuspendThread(m_handle); }; ulong resume() { return ::ResumeThread(m_handle); }; bool kill (int code) { return ::TerminateThread(m_handle,code) != 0; }; ulong wait ( time_t time = INFINITE ) { return ::WaitForSingleObject(m_handle,time); } HANDLE get_thread_handle() const { return m_handle; } ulong get_thread_id() const { return m_tid; } virtual int main (); protected: ////////////////////////////////////////////////////////////////////// // Private Members ////////////////////////////////////////////////////////////////////// static unsigned int __stdcall stdthread( Thread * thread ); HANDLE m_handle; u_int m_tid; ulong m_stack_size; Runnable *m_runnable; bool m_delete_runnable; #ifdef _WIN32 LPSECURITY_ATTRIBUTES m_security; #endif }; } // namespace GSDK #endif // !defined(HEADER_THREAD_IMPL_H_9505A529_5FA1_4CDD_8E75_1786B495BD98)
[ "dmver2@gmail.com" ]
dmver2@gmail.com
3dd3c24b6640856652071a3e39168f2082a19ebb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_patch_hunk_3178.cpp
efdefc5903ba2ae2a27cb2af7bad354b831453fa
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,776
cpp
if ((dc->nOptions & SSL_OPT_FAKEBASICAUTH) == 0 && dc->szUserName) { char *val = ssl_var_lookup(r->pool, r->server, r->connection, r, (char *)dc->szUserName); if (val && val[0]) r->user = val; else - ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(02227) "Failed to set r->user to '%s'", dc->szUserName); } /* * Check SSLRequire boolean expressions */ requires = dc->aRequirement; ssl_requires = (ssl_require_t *)requires->elts; for (i = 0; i < requires->nelts; i++) { ssl_require_t *req = &ssl_requires[i]; - ok = ssl_expr_exec(r, req->mpExpr); + const char *errstring; + ok = ap_expr_exec(r, req->mpExpr, &errstring); if (ok < 0) { - cp = apr_psprintf(r->pool, - "Failed to execute " - "SSL requirement expression: %s", - ssl_expr_get_error()); - - ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, - "access to %s failed, reason: %s", - r->filename, cp); + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02265) + "access to %s failed, reason: Failed to execute " + "SSL requirement expression: %s", + r->filename, errstring); /* remember forbidden access for strict require option */ apr_table_setn(r->notes, "ssl-access-forbidden", "1"); return HTTP_FORBIDDEN; } if (ok != 1) { - ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02266) "Access to %s denied for %s " "(requirement expression not fulfilled)", - r->filename, r->connection->remote_ip); + r->filename, r->useragent_ip); - ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02228) "Failed expression: %s", req->cpExpr); - ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02229) "access to %s failed, reason: %s", r->filename, "SSL requirement expression not fulfilled"); /* remember forbidden access for strict require option */ apr_table_setn(r->notes, "ssl-access-forbidden", "1");
[ "993273596@qq.com" ]
993273596@qq.com
29478e84fc46bf080c70afad581844c3c47fe814
5a68fa17bde90dfd71ceb2e6a82941af01529c56
/include/Ray.h
330b95dabeaf685d14387bf7a8b980e98c8c565e
[]
no_license
RepoBucket/Virtual-Pipe-Erosion
2cb6fb2633ffeff998173abc9b8a2fca1487989e
5b7e3bb38f19e20ab1c193326963ae2a9f0a9277
refs/heads/master
2021-01-23T08:38:42.037958
2013-06-06T15:21:56
2013-06-06T15:21:56
10,528,476
4
0
null
2013-06-06T15:21:57
2013-06-06T14:36:21
null
UTF-8
C++
false
false
1,217
h
#ifndef ALWAY_RAY_H #define ALWAY_RAY_H #include "AlwayMath.h" using namespace alway; class MatData; class Ray { public: ~Ray(); Ray(); Ray(const Ray&); Ray operator=(Ray& r); float FindRayPlaneIntersect(Vec3* normal, Vec3* point); void BlendInColor(float alpha, Vec3 color); void GetColor(float* out); bool IsSaturated(); void DiffuseReflection(Vec3 normal, int depth); //monte-carlo rejection sampled direction change void SpecularReflection(Vec3 normal); //reflect across given normal int PhotonReflection(MatData* matData, Vec3 normal, Vec3 position); int HeightmapIntersectionTest(int size, float* heightmap); float HeightmapIntersectionDistance(int size, float* heightmap); float HeightmapIntersectionDistance(int size, float* heightmap, float* lowRes1, float* lowRes2, float* lowRes3); Vec3 origin; Vec3 direction; Vec3 dirInv; Vec3 color; bool positive; protected: float saturation; int HeightmapIntersectionTestGetNextTileIndex(int size); int HeightmapIntersectionTestGetNextTileIndex(int size, int scale); int HeightmapIntersectionTestGetThisTile(int size, int scale); void HeightmapIntersectionTestGotoFirstCell(int size); }; #endif
[ "fluffyterran@gmail.com" ]
fluffyterran@gmail.com
8b93d4ab9438d26e15b2457616c7119ac6fe4d57
1edc2fe6e008e68f360a111f5650e498209205fc
/src/main_reconstruction.cxx
52ebde640b0f2ac757f55b54bb72c1ef65f3578f
[]
no_license
panmari/patchMatch
ede114d62a83da692db450dfa8ad5e13d655bc05
c7ce4be565ef8cff78559ca5da1b513cced8f5d1
refs/heads/master
2021-01-10T05:22:44.529426
2020-04-18T15:12:07
2020-04-18T15:12:07
43,545,058
11
3
null
null
null
null
UTF-8
C++
false
false
2,153
cxx
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "patch_match_provider/RandomizedPatchMatch.h" #include "TrivialReconstruction.h" #include "VotedReconstruction.h" #include "util.h" #include <iostream> using cv::addWeighted; using cv::Mat; using cv::Size; using cv::namedWindow; using cv::imread; using cv::Rect; using cv::Scalar; using cv::String; using cv::split; using pmutil::computeGradientX; using pmutil::computeGradientY; using pmutil::convert_for_computation; using pmutil::ssd; using std::cout; using std::endl; using std::shared_ptr; const float RESIZE_FACTOR = 0.5; const int PATCH_SIZE = 7; /** * Tries to reconstruct the second image with patches from the first images. */ int main( int argc, char** argv ) { // Load image and template Mat source = imread( argv[1], 1 ); Mat target = imread( argv[2], 1); if (!source.data || !target.data) { printf("Need two pictures as arguments.\n"); return -1; } // For later comparison. Mat original; resize(target, original, Size(), RESIZE_FACTOR, RESIZE_FACTOR); original.convertTo(original, CV_32FC3, 1 / 255.f); // For fast testing, make it tiny convert_for_computation(source, RESIZE_FACTOR); convert_for_computation(target, RESIZE_FACTOR); RandomizedPatchMatch rpm(source, target.size(), PATCH_SIZE); rpm.setTargetArea(target); shared_ptr<OffsetMap> offset_map = rpm.match(); TrivialReconstruction tr(offset_map, source, PATCH_SIZE); Mat reconstructed = tr.reconstruct(); cvtColor(reconstructed, reconstructed, CV_Lab2BGR); imwrite("reconstructed.exr", reconstructed); Mat empty_mask = Mat::zeros(source.size(), CV_8U); VotedReconstruction vr(offset_map, source, empty_mask, PATCH_SIZE); Mat reconstructed2; vr.reconstruct(reconstructed2, 3); cvtColor(reconstructed2, reconstructed2, CV_Lab2BGR); imwrite("reconstructed_voted.exr", reconstructed2); cout << "SSD trivial reconstruction: " << ssd(reconstructed, original) << endl; cout << "SSD voted reconstruction: " << ssd(reconstructed2, original) << endl; return 0; }
[ "smmuzi@gmail.com" ]
smmuzi@gmail.com
29a81d43976c956c8b5c104153f41f6200e84dcf
7b06bfd8addc6129218d35959b259293f719b1bd
/K1/14.cpp
1ec0fc6516d8d32fe582212b9c616bf0b4445a88
[]
no_license
Delemangi/OOP
8c35e25fcc0bfa584c316dc1bfc43b1404d68f7d
16181dd1bdac80ec03474a2a9028d03d7eaa0926
refs/heads/master
2023-07-19T04:10:15.502536
2021-08-29T18:58:44
2021-08-29T18:58:44
401,119,668
1
0
null
null
null
null
UTF-8
C++
false
false
9,499
cpp
/* Потребно е да се имплементираат класи File (датотека) и Folder (директориум) за работа со едноставен податочен систем. Во класата File треба да се чуваат следниве податоци: Име на датотеката (динамички алоцирана низа од знаци) Екстензија на датотеката (енумерација со можни вредности: txt, pdf, exe) Име на сопственикот на датотеката (динамички алоцирана низа од знаци) Големина на датотеката (цел број на мегабајти) Дополнително, во класата потребно е да се напишат и: Конструктор без параметри Конструктор со параметри Конструктор за копирање Деструктор Преоптоварување на операторот = Метод за печатење на информациите за една датотека (видете го излезот од тест примерите за структурата на печатење) - print() Метод за проверка на еднаквост помеѓу две датотеки со потпис bool equals(const File & that) кој ќе враќа true ако датотеките имаат исто име, екстензија и сопственик Метод за споредба на типот помеѓу две датотеки со потпис bool equalsType(const File & that) кој ќе враќа true ако датотеките се од ист тип, т.е. имаат исто име и екстензија Во класата Folder треба да се чуваат следниве податоци: Име на директориумот (динамички алоцирана низа од знаци) Број на датотеки во него (на почеток директориумот е празен) Динамички алоцирана низа од датотеки, објекти од класата File Дополнително, во класата потребно е да се напишат и: Конструктор со потпис Folder(const char* name) Деструктор Метод за печатење на информациите за еден директориум (видете го излезот од тест примерите за структурата на печатење) - print() Метод за бришење на датотека од директориумот со потпис void remove(const File & file) кој ќе ја избрише првата датотека од директориумот која е еднаква според equals методот Метод за додавање на датотека во директориумот со потпис void add(const File & file) кој ќе додава датотеката во директориумот Не го менувајте почетниот код. */ #include<iostream> #include<cstring> using namespace std; enum Extension { pdf, txt, exe }; char ex[3][4] = {"pdf", "txt", "exe"}; class File { private: char *name; Extension ext; char *owner; int size; public: File() { this->name = new char[100]; this->owner = new char[100]; } File(char *name1, char *owner1, int size1, Extension ext1) { this->name = new char[100]; this->owner = new char[100]; strcpy(this->name, name1); strcpy(this->owner, owner1); this->size = size1; this->ext = ext1; } File(const File &other) : File(other.name, other.owner, other.size, other.ext) {} ~File() { delete[] this->name; delete[] this->owner; } File &operator=(const File &other) { if (this == &other) { return *this; } strcpy(this->name, other.name); strcpy(this->owner, other.owner); this->size = other.size; this->ext = other.ext; return *this; } void print() { cout << "File name: " << this->name << "." << ex[this->ext] << endl; cout << "File owner: " << this->owner << endl; cout << "File size: " << this->size << endl; } bool equals(const File &other) { if (strcmp(this->name, other.name) == 0) if (strcmp(this->owner, other.owner) == 0) if (this->ext == other.ext) return true; return false; } bool equalsType(const File &other) { if (strcmp(this->name, other.name) == 0) if (this->ext == other.ext) return true; return false; } }; class Folder { private: char *name; int files; File *f; public: Folder(const char *name1) { this->name = new char[100]; this->files = 0; this->f = new File[100]; strcpy(this->name, name1); } ~Folder() { delete[] this->name; delete[] this->f; } void print() { cout << "Folder name: " << this->name << endl; for (int i = 0; i < files; i++) this->f[i].print(); } void remove(const File &other) { for (int i = 0; i < this->files; i++) if (this->f[i].equals(other)) { for (int j = i; j < files - 1; j++) this->f[j] = this->f[j + 1]; files--; break; } } void add(const File &other) { this->f[files] = other; files++; } }; int main() { char fileName[20]; char fileOwner[20]; int ext; int fileSize; int testCase; cin >> testCase; if (testCase == 1) { cout << "======= FILE CONSTRUCTORS AND = OPERATOR =======" << endl; cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File created = File(fileName, fileOwner, fileSize, (Extension) ext); File copied = File(created); File assigned = created; cout << "======= CREATED =======" << endl; created.print(); cout << endl; cout << "======= COPIED =======" << endl; copied.print(); cout << endl; cout << "======= ASSIGNED =======" << endl; assigned.print(); } else if (testCase == 2) { cout << "======= FILE EQUALS & EQUALS TYPE =======" << endl; cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File first(fileName, fileOwner, fileSize, (Extension) ext); first.print(); cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File second(fileName, fileOwner, fileSize, (Extension) ext); second.print(); cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File third(fileName, fileOwner, fileSize, (Extension) ext); third.print(); bool equals = first.equals(second); cout << "FIRST EQUALS SECOND: "; if (equals) cout << "TRUE" << endl; else cout << "FALSE" << endl; equals = first.equals(third); cout << "FIRST EQUALS THIRD: "; if (equals) cout << "TRUE" << endl; else cout << "FALSE" << endl; bool equalsType = first.equalsType(second); cout << "FIRST EQUALS TYPE SECOND: "; if (equalsType) cout << "TRUE" << endl; else cout << "FALSE" << endl; equalsType = second.equals(third); cout << "SECOND EQUALS TYPE THIRD: "; if (equalsType) cout << "TRUE" << endl; else cout << "FALSE" << endl; } else if (testCase == 3) { cout << "======= FOLDER CONSTRUCTOR =======" << endl; cin >> fileName; Folder folder(fileName); folder.print(); } else if (testCase == 4) { cout << "======= ADD FILE IN FOLDER =======" << endl; char name[20]; cin >> name; Folder folder(name); int iter; cin >> iter; while (iter > 0) { cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File file(fileName, fileOwner, fileSize, (Extension) ext); folder.add(file); iter--; } folder.print(); } else { cout << "======= REMOVE FILE FROM FOLDER =======" << endl; char name[20]; cin >> name; Folder folder(name); int iter; cin >> iter; while (iter > 0) { cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File file(fileName, fileOwner, fileSize, (Extension) ext); folder.add(file); iter--; } cin >> fileName; cin >> fileOwner; cin >> fileSize; cin >> ext; File file(fileName, fileOwner, fileSize, (Extension) ext); folder.remove(file); folder.print(); } return 0; }
[ "stefan@heckgaming.com" ]
stefan@heckgaming.com
83d074f3c55df7e163167fc8adf91435a1be7276
fcb47577b4cde9b49edc289457ee661b63e77dc8
/src/app/providermodel.cpp
daa04234de346e0f853cf4d9743476e57d7b0318
[]
no_license
ibatullin/rosa-cloud
8b4c613ec5a5f78810b80e51dd8e28ca6d90fe3d
540af17487471ae877027e0cbbaded1655738fcf
refs/heads/master
2021-01-12T20:54:48.007965
2014-11-21T14:11:30
2014-11-21T14:11:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
963
cpp
#include "providermodel.h" ProviderModel::ProviderModel(QObject *parent) : QAbstractListModel(parent) { } ProviderModel::~ProviderModel() { } QVariant ProviderModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if (row < 0 || row >= m_providers.size()) return QVariant(); const Provider &service = m_providers[row]; switch (role) { case Name: return service.name(); case Host: return service.url(); case Active: return service.isActive(); } return QVariant(); } int ProviderModel::rowCount(const QModelIndex &) const { return m_providers.size(); } void ProviderModel::addProvider(const QString &name, const QUrl &url) { int rows = m_providers.size(); beginInsertRows(QModelIndex(), rows, rows); Provider provider(name, url); m_providers.append(provider); endInsertRows(); }
[ "tibatullin@smartlabs.tv" ]
tibatullin@smartlabs.tv
bd9cfc3f2c76e5b309bab4d513f56cb5bbc411b5
dfd4ba77611164e44503180f90a90a97b81af3f4
/Kalmanfilter/log.h
aa1d3c7979543d05863a5b64a2722c89184d8f1b
[]
no_license
andrekor/Eurobot2.0
98bb41174cfe0f9fdd6f995833a16a79f9325579
5971e3eda2155064c2514ec560b955808c96bf6b
refs/heads/master
2016-09-05T15:58:24.993867
2015-06-03T16:17:59
2015-06-03T16:17:59
35,883,902
0
0
null
null
null
null
UTF-8
C++
false
false
126
h
#include <iostream> #ifdef DEBUG #define LOG(x) std::cerr << "[LOG] " << x << std::endl; #else #define LOG(x) #endif // DEBUG
[ "andrekor@ifi.uio.no" ]
andrekor@ifi.uio.no
935bc6621466c60a1ce3289997c7ed6bbb3c4ce2
e97df84ff53437ed48601ab0305b47d6bec0cc85
/LeetCode&PAT/PAT/ad_1076.cpp
2c90162441acf31993732a6959e028ed4b2caddb
[]
no_license
ChhYoung/Coding_Diary
ebab091a954db488ce9915c64d589b4257c9f551
4a148a212cb47950f358a4a943018398c811d7a8
refs/heads/master
2022-10-04T14:19:34.108089
2020-05-31T13:17:08
2020-05-31T13:17:08
178,336,070
4
2
null
2019-03-29T08:57:40
2019-03-29T05:07:16
Jupyter Notebook
UTF-8
C++
false
false
1,364
cpp
#include<vector> #include<iostream> #include<queue> #include<algorithm> using namespace std; const int maxn = 1010; struct node{ int id; int level; }; // 邻接表 vector<node> G[maxn]; // 是否已经加过队列 bool inq[maxn] = {false}; // 利用 bfs // start : 起始节点, L : max level int bfs(int start, int L){ // 转发数 int forwardNum = 0; queue<node> que; node st; st.id = start; st.level = 0; que.push(st); inq[st.id] = true; while(!que.empty()){ auto Node = que.front(); que.pop(); for(int i=0; i<G[Node.id].size(); ++i){ node next = G[Node.id][i]; next.level = Node.level + 1; if(inq[next.id] == false && next.level <= L){ que.push(next); inq[next.id] = true; forwardNum++; } } } return forwardNum; } int main(){ node user; int n, L, numFollower, idFollow; cin>>n>>L; for(int i=1; i<=n; ++i){ user.id = i; cin>>numFollower; for(int j=0; j<numFollower; ++j){ cin>>idFollow; G[idFollow].push_back(user); } } int numQuery,s; cin>>numQuery; for(int i=0; i<numQuery; ++i){ fill(inq, inq+maxn, false); cin>>s; cout<<bfs(s,L)<<endl; } return 0; }
[ "984924255@qq.com" ]
984924255@qq.com
664ea0bf433b5509fb546f0b4aaba9d90f1258e0
1fd9af55307154026e491f0635110add28a5ea6d
/Cameras/SWFO/InjectableGenericCameraSystem/System.h
3da013a948cac1c4111babaa77601e25e271a921
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
zanzo420/InjectableGenericCameraSystem
a9a51e4f5899dad0f16788b04a632c6e5efd74e4
3c2be6fbfcdc3a54f5a54bbb8b281b67325cbcef
refs/heads/master
2021-06-12T16:43:22.306527
2020-04-04T20:05:24
2020-04-04T20:05:24
254,359,574
0
0
BSD-2-Clause
2020-04-09T12:03:03
2020-04-09T12:01:46
null
UTF-8
C++
false
false
2,769
h
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2019, Frans Bouma // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "stdafx.h" #include "Camera.h" #include "Gamepad.h" #include <map> #include "AOBBlock.h" namespace IGCS { class System { public: System(); ~System(); void start(LPBYTE hostBaseAddress, DWORD hostImageSize); private: void mainLoop(); void initialize(); void updateFrame(); void handleUserInput(); void displayCameraState(); void toggleCameraMovementLockState(bool newValue); void handleKeyboardCameraMovement(float multiplier); void handleMouseCameraMovement(float multiplier); void handleGamePadMovement(float multiplierBase); void waitForCameraStructAddresses(); void toggleInputBlockState(bool newValue); void takeMultiShot(bool isTestRun); void takeSingleScreenshot(); Camera _camera; LPBYTE _hostImageAddress; DWORD _hostImageSize; bool _timeStopped = false; bool _cameraMovementLocked = false; bool _cameraStructFound = false; map<string, AOBBlock*> _aobBlocks; bool _applyHammerPrevention = false; // set to true by a keyboard action and which triggers a sleep before keyboard handling is performed. }; }
[ "frans@sd.nl" ]
frans@sd.nl
079341c31f748cda50941392459534d9e546bb4d
97756c60216574b0dcdc05dfcbd25d0246a071f7
/lib/libbullet/src/btGImpactCollisionAlgorithm.h
4210f0e92eaf4451fabe7038ec0adced7f337e45
[ "Apache-2.0" ]
permissive
hivesolutions/mariachi
1b703ed004922d8140caace3ea98c788858c26e6
b8dc552e1c961f5faca1e9331d2b2ea45bdbdc76
refs/heads/master
2020-12-24T16:34:54.606556
2020-01-02T16:33:04
2020-01-02T16:33:04
27,374,575
1
0
null
null
null
null
UTF-8
C++
false
false
9,839
h
/*! \file btGImpactShape.h \author Francisco Len Nfljera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BVH_CONCAVE_COLLISION_ALGORITHM_H #define BVH_CONCAVE_COLLISION_ALGORITHM_H #include "btActivatingCollisionAlgorithm.h" #include "btDispatcher.h" #include "btBroadphaseInterface.h" #include "btPersistentManifold.h" class btDispatcher; #include "btBroadphaseProxy.h" #include "btCollisionCreateFunc.h" #include "btCollisionDispatcher.h" #include "btAlignedObjectArray.h" #include "btGImpactShape.h" #include "btStaticPlaneShape.h" #include "btCompoundShape.h" #include "btConvexConvexAlgorithm.h" #include "btIDebugDraw.h" //! Collision Algorithm for GImpact Shapes /*! For register this algorithm in Bullet, proceed as following: \code btCollisionDispatcher * dispatcher = static_cast<btCollisionDispatcher *>(m_dynamicsWorld ->getDispatcher()); btGImpactCollisionAlgorithm::registerAlgorithm(dispatcher); \endcode */ class btGImpactCollisionAlgorithm : public btActivatingCollisionAlgorithm { protected: btCollisionAlgorithm * m_convex_algorithm; btPersistentManifold * m_manifoldPtr; btManifoldResult* m_resultOut; const btDispatcherInfo * m_dispatchInfo; int m_triface0; int m_part0; int m_triface1; int m_part1; //! Creates a new contact point SIMD_FORCE_INLINE btPersistentManifold* newContactManifold(btCollisionObject* body0,btCollisionObject* body1) { m_manifoldPtr = m_dispatcher->getNewManifold(body0,body1); return m_manifoldPtr; } SIMD_FORCE_INLINE void destroyConvexAlgorithm() { if(m_convex_algorithm) { m_convex_algorithm->~btCollisionAlgorithm(); m_dispatcher->freeCollisionAlgorithm( m_convex_algorithm); m_convex_algorithm = NULL; } } SIMD_FORCE_INLINE void destroyContactManifolds() { if(m_manifoldPtr == NULL) return; m_dispatcher->releaseManifold(m_manifoldPtr); m_manifoldPtr = NULL; } SIMD_FORCE_INLINE void clearCache() { destroyContactManifolds(); destroyConvexAlgorithm(); m_triface0 = -1; m_part0 = -1; m_triface1 = -1; m_part1 = -1; } SIMD_FORCE_INLINE btPersistentManifold* getLastManifold() { return m_manifoldPtr; } // Call before process collision SIMD_FORCE_INLINE void checkManifold(btCollisionObject* body0,btCollisionObject* body1) { if(getLastManifold() == 0) { newContactManifold(body0,body1); } m_resultOut->setPersistentManifold(getLastManifold()); } // Call before process collision SIMD_FORCE_INLINE btCollisionAlgorithm * newAlgorithm(btCollisionObject* body0,btCollisionObject* body1) { checkManifold(body0,body1); btCollisionAlgorithm * convex_algorithm = m_dispatcher->findAlgorithm( body0,body1,getLastManifold()); return convex_algorithm ; } // Call before process collision SIMD_FORCE_INLINE void checkConvexAlgorithm(btCollisionObject* body0,btCollisionObject* body1) { if(m_convex_algorithm) return; m_convex_algorithm = newAlgorithm(body0,body1); } void addContactPoint(btCollisionObject * body0, btCollisionObject * body1, const btVector3 & point, const btVector3 & normal, btScalar distance); //! Collision routines //!@{ void collide_gjk_triangles(btCollisionObject * body0, btCollisionObject * body1, btGImpactMeshShapePart * shape0, btGImpactMeshShapePart * shape1, const int * pairs, int pair_count); void collide_sat_triangles(btCollisionObject * body0, btCollisionObject * body1, btGImpactMeshShapePart * shape0, btGImpactMeshShapePart * shape1, const int * pairs, int pair_count); void shape_vs_shape_collision( btCollisionObject * body0, btCollisionObject * body1, btCollisionShape * shape0, btCollisionShape * shape1); void convex_vs_convex_collision(btCollisionObject * body0, btCollisionObject * body1, btCollisionShape * shape0, btCollisionShape * shape1); void gimpact_vs_gimpact_find_pairs( const btTransform & trans0, const btTransform & trans1, btGImpactShapeInterface * shape0, btGImpactShapeInterface * shape1,btPairSet & pairset); void gimpact_vs_shape_find_pairs( const btTransform & trans0, const btTransform & trans1, btGImpactShapeInterface * shape0, btCollisionShape * shape1, btAlignedObjectArray<int> & collided_primitives); void gimpacttrimeshpart_vs_plane_collision( btCollisionObject * body0, btCollisionObject * body1, btGImpactMeshShapePart * shape0, btStaticPlaneShape * shape1,bool swapped); public: btGImpactCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1); virtual ~btGImpactCollisionAlgorithm(); virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { if (m_manifoldPtr) manifoldArray.push_back(m_manifoldPtr); } struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btGImpactCollisionAlgorithm)); return new(mem) btGImpactCollisionAlgorithm(ci,body0,body1); } }; //! Use this function for register the algorithm externally static void registerAlgorithm(btCollisionDispatcher * dispatcher); //! Gets the average time in miliseconds of tree collisions static float getAverageTreeCollisionTime(); //! Gets the average time in miliseconds of triangle collisions static float getAverageTriangleCollisionTime(); //! Collides two gimpact shapes /*! \pre shape0 and shape1 couldn't be btGImpactMeshShape objects */ void gimpact_vs_gimpact(btCollisionObject * body0, btCollisionObject * body1, btGImpactShapeInterface * shape0, btGImpactShapeInterface * shape1); void gimpact_vs_shape(btCollisionObject * body0, btCollisionObject * body1, btGImpactShapeInterface * shape0, btCollisionShape * shape1,bool swapped); void gimpact_vs_compoundshape(btCollisionObject * body0, btCollisionObject * body1, btGImpactShapeInterface * shape0, btCompoundShape * shape1,bool swapped); void gimpact_vs_concave( btCollisionObject * body0, btCollisionObject * body1, btGImpactShapeInterface * shape0, btConcaveShape * shape1,bool swapped); /// Accessor/Mutator pairs for Part and triangleID void setFace0(int value) { m_triface0 = value; } int getFace0() { return m_triface0; } void setFace1(int value) { m_triface1 = value; } int getFace1() { return m_triface1; } void setPart0(int value) { m_part0 = value; } int getPart0() { return m_part0; } void setPart1(int value) { m_part1 = value; } int getPart1() { return m_part1; } }; //algorithm details //#define BULLET_TRIANGLE_COLLISION 1 #define GIMPACT_VS_PLANE_COLLISION 1 #endif //BVH_CONCAVE_COLLISION_ALGORITHM_H
[ "joamag@gmail.com" ]
joamag@gmail.com
ed28b329f31ad0b9d424cf35c67e28d36e705c3b
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/testing/android/native_test_util.cc
7d5f02539738da400fe578ef006494f824a02bf0
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
1,522
cc
// Copyright (c) 2013 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 "testing/android/native_test_util.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" namespace { void ParseArgsFromString(const std::string& command_line, std::vector<std::string>* args) { base::StringTokenizer tokenizer(command_line, base::kWhitespaceASCII); tokenizer.set_quote_chars("\""); while (tokenizer.GetNext()) { std::string token; base::RemoveChars(tokenizer.token(), "\"", &token); args->push_back(token); } } } // namespace namespace testing { namespace native_test_util { void ParseArgsFromCommandLineFile( const char* path, std::vector<std::string>* args) { base::FilePath command_line(path); std::string command_line_string; if (base::ReadFileToString(command_line, &command_line_string)) { ParseArgsFromString(command_line_string, args); } } int ArgsToArgv(const std::vector<std::string>& args, std::vector<char*>* argv) { // We need to pass in a non-const char**. int argc = args.size(); argv->resize(argc + 1); for (int i = 0; i < argc; ++i) { (*argv)[i] = const_cast<char*>(args[i].c_str()); } (*argv)[argc] = NULL; // argv must be NULL terminated. return argc; } } // namespace native_test_util } // namespace testing
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
0fff9693a11469306d5f7a295762bb3601ba01aa
e3e14afd9c330be84c92a54a465b586520ad1ee4
/acmp/0814.cpp
5cb2ef759a1cd60d54d31957a5fcd09fb7703c3f
[]
no_license
zv-proger/ol_programms
ab5a6eeca4fa1c3eb30dc49b4ebd223eb0b8deb5
acf305c1216ab10f507a737d8f4bcf29f0e2024b
refs/heads/master
2022-12-14T22:56:18.294281
2020-09-18T09:54:25
2020-09-18T09:54:25
279,568,502
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
680
cpp
/* Автор кода: Вадим Зинов (zv.proger@yandex.ru) Решение задачи 0814 с сайта acmp.ru */ #include<bits/stdc++.h> using namespace std; bool simp[10000]; void init() { for(int i = 2; i*i < 10000; i++) { if (simp[i]) { simp[i] = 0; continue; } if (!simp[i]) { simp[i] = 1; for (int j = i * i; j < 10000; j += i) { simp[j] = 1; } } } } int main() { init(); int n; cin >> n; int ans = 0; for (int i = 2; i * 2 <= n; i++) { ans += simp[i] && simp[n-i]; } cout << ans; }
[ "zv.proger@yandex.ru" ]
zv.proger@yandex.ru
15d8fb70c52f60ff405085f051cf0cb7e6d66f29
2eea0f894c6d1d7b72ae17287f54d361549a06ad
/src/frovedis/ml/fpm/fp_growth_model.hpp
ccb0e287c96a9db5c63825900a5b46a9d8d5e4db
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
uestc-chen/frovedis
0e7160dcb7827a8a0fd81902ff485cd5e64b6a77
3cb2918792426d5f04c8f847ec0cc3257bf4e51e
refs/heads/master
2022-04-22T04:37:14.637910
2020-03-25T05:43:50
2020-03-25T05:43:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
hpp
#ifndef _FP_GROWTH_MODEL_ #define _FP_GROWTH_MODEL_ #include <frovedis/dataframe.hpp> #include <typeinfo> namespace frovedis { struct association_rule{ association_rule() {} association_rule(std::vector<dftable>& rs): rule(rs){} void debug_print(); void save (const std::string& fname); void savebinary (const std::string& fname); void load (const std::string& fname); void loadbinary (const std::string& fname); std::vector<dftable> rule; SERIALIZE(rule) }; struct fp_growth_model { fp_growth_model() {} fp_growth_model(std::vector<dftable>& it ): item(it) {} void debug_print(); std::vector<dftable> get_frequent_itemset(); association_rule generate_rules(double confidence); void load (const std::string& fname); void loadbinary (const std::string& fname); void save (const std::string& fname); void savebinary (const std::string& fname); std::vector<dftable> item; SERIALIZE(item) }; dftable create_antacedent(dftable, int); dftable calculate_confidence(dftable&, dftable&, double); } #endif
[ "t-araki@dc.jp.nec.com" ]
t-araki@dc.jp.nec.com
e528c773b85c7016450b0281f1657eaa2289d1d1
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/6/4049.c
9efcfaaa2e645bdde953da58249a859c5e6f2dd3
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
949
c
int v[100][100]; //class mat //{ //public: // int m; // int n; // int **v; // //public: // mat(int mm,int nn) // { // m=mm; // n=nn; // v=new int*[m]; // for(int i=0;i<mm;i++) // { // v[i]=new int[n]; // } // } int sum(int m,int n) { int su=0; if(n>=2 && m>=2) { for(int i=0;i<n;i++) { su+=v[0][i]; su+=v[m-1][i]; } for(int i=1;i<m-1;i++) { su+=v[i][0]; su+=v[i][n-1]; } } else if(n>=2 && m==1) { for(int i=0;i<n;i++) { su+=v[0][i]; } } else if(m>=2 && n==1) { for(int i=0;i<n;i++) { su+=v[i][0]; } } else { su=v[0][0]; } return su; } //}; int main() { int times; cin>>times; for(int k=0;k<times;k++) { int a,b; cin>>a>>b; for(int i=0;i<a;i++) for(int j=0;j<b;j++) cin>>v[i][j]; cout<<sum(a,b)<<endl; } }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
73dac718a8410902a4c1cab889b0ee578ae86455
62c87d66b28bdfa79b80a5b6148d2ecaea92d05e
/223_Rectangle Area.cpp
9d4d57fa7080b069514550d7f1429d7f76733bc6
[]
no_license
ivanzjj/Leetcode
33a5e51d4d9ecd4fb4eea11a48e9291c4d657018
1ab4a1943a9408a74d07356f1076d0e8b03a73be
refs/heads/master
2021-01-10T10:28:01.022182
2015-06-18T08:34:55
2015-06-18T08:34:55
36,235,435
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
/* first check whether this two rectangle is not intersected if two rectangle is intersected, then calculate the area of intersected part. */ class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int left = 0; if (max (A,C) < min (E,G) || max (E,G) < min (A,C) || max (B,D) < min (F,H) || max (F,H) < min (B,D)) left = 0; else { int a = min (C,G) - max (A,E); int b = min (D,H) - max (B,F); left = a * b; } return (C - A) * (D - B) + (G - E) * (H - F) - left; } };
[ "ivanzjjcsu@gmail.com" ]
ivanzjjcsu@gmail.com
6e5affbfbb8db644deb459fb40439b2cbedcc534
a2bf0ffd0846a43ac3e9d817a480e9f04b025112
/Projeto_Head_RC/Head_RC/Head_RC.ino
e4e0a492b0cb9d263cd60f8f863ea4e1fdf2821b
[]
permissive
angelicadri/HeadRC
c897f567a792f6f5206cd5f2dd1fe561ab9a7b69
94959a95aa575c4b039799b1a3be9170207d5742
refs/heads/main
2023-06-10T22:40:36.478685
2021-07-06T21:18:00
2021-07-06T21:18:00
365,498,765
0
0
MIT
2021-05-08T11:36:55
2021-05-08T11:36:54
null
UTF-8
C++
false
false
2,885
ino
// INCLUSÃO DE BIBLIOTECAS #include <MPU6050_tockn.h> #include <Wire.h> #include <IRremote.h> // DEFINIÇÕES //#define MPU6050_ADDR 0x68 // ENDEREÇO QUANDO O PINO AD0 ESTIVER LIGADO AO GND //#define MPU6050_ADDR 0x69 // ENDEREÇO QUANDO O PINO AD0 ESTIVER LIGADO AO VCC #define DEBUG // INSTANCIANDO OBJETOS MPU6050 mpu6050(Wire); // DECLARAÇÃO DE VARIÁVEIS float anguloX; float anguloY; IRsend irsend; unsigned long valor; decode_results res; // ACIONADOR EXTERNO int piezoPin = a; // sensor piezo no pino a int threshold = b; // valor mínimo a ser lido pelo sensor para ativação bool ligado = False; // armazena o estado do dispositivo void setup() { Serial.begin(9600); Wire.begin(); mpu6050.begin(); mpu6050.calcGyroOffsets(false);// MUDAR PARA "true" SE QUISER VISUALIZAR INFORMAÇÕES DE CALIBRAÇÃO NO MONITOR SERIAL #ifdef DEBUG Serial.println("Fim Setup"); #endif } void loop() { if ((analogRead(piezoPin)) >= threshold && (ligado == False)){ //se o valor do sensor atingir o threshold e estiver desligado, o dispositivo é acionado ligado = True; // muda o estado do dispositivo mpu6050.update(); // GUARDA NA MEMÓRIA OS VALORES ENVIADOS PELO GIROSCOPIO anguloX = mpu6050.getAngleX(); anguloY = mpu6050.getAngleY(); // VERIFICA SE GIROU NO EIXO X if (anguloX >= 25){ valor=0xE0E09E61;// SMART HUB irsend.sendNEC(0xE0E09E61, 32); Serial.println(valor,HEX); Serial.println("Para baixo - SMART HUB"); } else if (anguloX <= -25){ valor=0xE0E040BF;// POWER irsend.sendNEC(E0E040BF, 32); Serial.println(valor,HEX); Serial.println("Para Cima - liga a TV"); } // VERIFICA SE GIROU NO EIXO Y if (anguloY >= 25){ valor=0xE0E0D02F;// VOL- irsend.sendNEC(0xE0E0D02F, 32); Serial.println(valor,HEX); Serial.println("ESQUERDA - DIMINUI O VOLUME"); } else if (anguloY <= -25){ valor=0xE0E0E01F;// VOL+ irsend.sendNEC(0xE0E0E01F, 32); Serial.println(valor,HEX); Serial.println("DIREITA - AUMENTA VOLUME"); } } if ((analogRead(piezoPin) >= threshold) && (ligado == True)){ //~se o valor do sensor atingir o threshold e estiver ligado, o dispositivo é acionado ligado = False; // muda o estado do dispositivo } }
[ "adsq04@hotmail.com" ]
adsq04@hotmail.com
7c7e368acdbcf90d43bc9bed242bbc0a2982ff92
16edc75f0a71f87b253d3414eb48b0dfbe63bf6d
/trunk/src/app/srs_app_hds.cpp
7e154560e6c0b6da1d3f888d1ad14529d7b0f1f8
[]
no_license
shilonghai/srs-with-hevc-support
26733a3f147ebb21f97bcfd1da207f97dc94bc66
0b51931aa2172bd9ac62e4e2295edfdf51573445
refs/heads/master
2020-04-28T23:18:32.863563
2019-03-15T13:02:42
2019-03-15T13:02:42
175,650,022
2
2
null
null
null
null
UTF-8
C++
false
false
19,994
cpp
/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <srs_app_hds.hpp> #ifdef SRS_AUTO_HDS #include <unistd.h> #include <string> #include <vector> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace std; #include <srs_app_hds.hpp> #include <srs_rtmp_stack.hpp> #include <srs_kernel_log.hpp> #include <srs_kernel_codec.hpp> #include <srs_rtmp_stack.hpp> #include <srs_kernel_stream.hpp> #include <srs_core_autofree.hpp> #include <srs_kernel_utility.hpp> #include <srs_app_config.hpp> static void update_box(char *start, int size) { char *p_size = (char*)&size; start[0] = p_size[3]; start[1] = p_size[2]; start[2] = p_size[1]; start[3] = p_size[0]; } char flv_header[] = {'F', 'L', 'V', 0x01, 0x05, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00}; string serialFlv(SrsSharedPtrMessage *msg) { SrsStream *stream = new SrsStream; int size = 15 + msg->size; char *byte = new char[size]; stream->initialize(byte, size); // tag header long long dts = msg->timestamp; char type = msg->is_video() ? 0x09 : 0x08; stream->write_1bytes(type); stream->write_3bytes(msg->size); stream->write_3bytes((int32_t)dts); stream->write_1bytes(dts >> 24 & 0xFF); stream->write_3bytes(0); stream->write_bytes(msg->payload, msg->size); // pre tag size int preTagSize = msg->size + 11; stream->write_4bytes(preTagSize); string ret(stream->data(), stream->size()); delete stream; delete [] byte; return ret; } class SrsHdsFragment { public: SrsHdsFragment(SrsRequest *r) : req(r) , index(-1) , start_time(0) , videoSh(NULL) , audioSh(NULL) { } ~SrsHdsFragment() { srs_freep(videoSh); srs_freep(audioSh); // clean msgs list<SrsSharedPtrMessage *>::iterator iter; for (iter = msgs.begin(); iter != msgs.end(); ++iter) { SrsSharedPtrMessage *msg = *iter; srs_freep(msg); } } void on_video(SrsSharedPtrMessage *msg) { SrsSharedPtrMessage *_msg = msg->copy(); msgs.push_back(_msg); } void on_audio(SrsSharedPtrMessage *msg) { SrsSharedPtrMessage *_msg = msg->copy(); msgs.push_back(_msg); } /*! flush data to disk. */ int flush() { string data; if (videoSh) { videoSh->timestamp = start_time; data.append(serialFlv(videoSh)); } if (audioSh) { audioSh->timestamp = start_time; data.append(serialFlv(audioSh)); } list<SrsSharedPtrMessage *>::iterator iter; for (iter = msgs.begin(); iter != msgs.end(); ++iter) { SrsSharedPtrMessage *msg = *iter; data.append(serialFlv(msg)); } char box_header[8]; SrsStream ss; ss.initialize(box_header, 8); ss.write_4bytes(8 + (int32_t)(data.size())); ss.write_string("mdat"); data = string(ss.data(), ss.size()) + data; const char *file_path = path.c_str(); int fd = open(file_path, O_WRONLY | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH); if (fd < 0) { srs_error("open fragment file failed, path=%s", file_path); return -1; } if (write(fd, data.data(), data.size()) != (int)data.size()) { srs_error("write fragment file failed, path=", file_path); close(fd); return -1; } close(fd); srs_trace("build fragment success=%s", file_path); return ERROR_SUCCESS; } /*! calc the segment duration in milliseconds. @return 0 if no msgs or the last msg dts minus the first msg dts. */ int duration() { int duration_ms = 0; long long first_msg_ts = 0; long long last_msg_ts = 0; if (msgs.size() >= 2) { SrsSharedPtrMessage *first_msg = msgs.front(); first_msg_ts = first_msg->timestamp; SrsSharedPtrMessage *last_msg = msgs.back(); last_msg_ts = last_msg->timestamp; duration_ms = (int)(last_msg_ts - first_msg_ts); } return duration_ms; } /*! set/get index */ inline void set_index(int idx) { char file_path[1024] = {0}; sprintf(file_path, "%s/%s/%sSeg1-Frag%d", _srs_config->get_hds_path(req->vhost).c_str() , req->app.c_str(), req->stream.c_str(), idx); path = file_path; index = idx; } inline int get_index() { return index; } /*! set/get start time */ inline void set_start_time(long long st) { start_time = st; } inline long long get_start_time() { return start_time; } void set_video_sh(SrsSharedPtrMessage *msg) { srs_freep(videoSh); videoSh = msg->copy(); } void set_audio_sh(SrsSharedPtrMessage *msg) { srs_freep(audioSh); audioSh = msg->copy(); } string fragment_path() { return path; } private: SrsRequest *req; list<SrsSharedPtrMessage *> msgs; /*! the index of this fragment */ int index; long long start_time; SrsSharedPtrMessage *videoSh; SrsSharedPtrMessage *audioSh; string path; }; SrsHds::SrsHds(SrsSource *s) : currentSegment(NULL) , fragment_index(1) , video_sh(NULL) , audio_sh(NULL) , hds_req(NULL) , hds_enabled(false) { } SrsHds::~SrsHds() { } int SrsHds::on_publish(SrsRequest *req) { int ret = ERROR_SUCCESS; if (hds_enabled) { return ret; } std::string vhost = req->vhost; if (!_srs_config->get_hds_enabled(vhost)) { hds_enabled = false; return ret; } hds_enabled = true; hds_req = req->copy(); return flush_mainfest(); } int SrsHds::on_unpublish() { int ret = ERROR_SUCCESS; if (!hds_enabled) { return ret; } hds_enabled = false; srs_freep(video_sh); srs_freep(audio_sh); srs_freep(hds_req); // clean fragments list<SrsHdsFragment *>::iterator iter; for (iter = fragments.begin(); iter != fragments.end(); ++iter) { SrsHdsFragment *st = *iter; srs_freep(st); } fragments.clear(); srs_freep(currentSegment); srs_trace("HDS un-published"); return ret; } int SrsHds::on_video(SrsSharedPtrMessage* msg) { int ret = ERROR_SUCCESS; if (!hds_enabled) { return ret; } if (SrsFlvCodec::video_h264_is_sequence_header(msg->payload, msg->size)) { srs_freep(video_sh); video_sh = msg->copy(); } if (!currentSegment) { currentSegment = new SrsHdsFragment(hds_req); currentSegment->set_index(fragment_index++); currentSegment->set_start_time(msg->timestamp); if (video_sh) currentSegment->set_video_sh(video_sh); if (audio_sh) currentSegment->set_audio_sh(audio_sh); } currentSegment->on_video(msg); double fragment_duration = _srs_config->get_hds_fragment(hds_req->vhost) * 1000; if (currentSegment->duration() >= fragment_duration) { // flush segment if ((ret = currentSegment->flush()) != ERROR_SUCCESS) { srs_error("flush segment failed."); return ret; } srs_trace("flush Segment success."); fragments.push_back(currentSegment); currentSegment = NULL; adjust_windows(); // flush bootstrap if ((ret = flush_bootstrap()) != ERROR_SUCCESS) { srs_error("flush bootstrap failed."); return ret; } srs_trace("flush BootStrap success."); } return ret; } int SrsHds::on_audio(SrsSharedPtrMessage* msg) { int ret = ERROR_SUCCESS; if (!hds_enabled) { return ret; } if (SrsFlvCodec::audio_is_sequence_header(msg->payload, msg->size)) { srs_freep(audio_sh); audio_sh = msg->copy(); } if (!currentSegment) { currentSegment = new SrsHdsFragment(hds_req); currentSegment->set_index(fragment_index++); currentSegment->set_start_time(msg->timestamp); if (video_sh) currentSegment->set_video_sh(video_sh); if (audio_sh) currentSegment->set_audio_sh(audio_sh); } currentSegment->on_audio(msg); double fragment_duration = _srs_config->get_hds_fragment(hds_req->vhost) * 1000; if (currentSegment->duration() >= fragment_duration) { // flush segment if ((ret = currentSegment->flush()) != ERROR_SUCCESS) { srs_error("flush segment failed."); return ret; } srs_info("flush Segment success."); // reset the current segment fragments.push_back(currentSegment); currentSegment = NULL; adjust_windows(); // flush bootstrap if ((ret = flush_bootstrap()) != ERROR_SUCCESS) { srs_error("flush bootstrap failed."); return ret; } srs_info("flush BootStrap success."); } return ret; } int SrsHds::flush_mainfest() { int ret = ERROR_SUCCESS; char buf[1024] = {0}; sprintf(buf, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" "<manifest xmlns=\"http://ns.adobe.com/f4m/1.0\">\n\t" "<id>%s.f4m</id>\n\t" "<streamType>live</streamType>\n\t" "<deliveryType>streaming</deliveryType>\n\t" "<bootstrapInfo profile=\"named\" url=\"%s.abst\" id=\"bootstrap0\" />\n\t" "<media bitrate=\"0\" url=\"%s\" bootstrapInfoId=\"bootstrap0\"></media>\n" "</manifest>" , hds_req->stream.c_str(), hds_req->stream.c_str(), hds_req->stream.c_str()); string dir = _srs_config->get_hds_path(hds_req->vhost) + "/" + hds_req->app; if ((ret = srs_create_dir_recursively(dir)) != ERROR_SUCCESS) { srs_error("hds create dir failed. ret=%d", ret); return ret; } string path = dir + "/" + hds_req->stream + ".f4m"; int fd = open(path.c_str(), O_WRONLY | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH); if (fd < 0) { srs_error("open manifest file failed, path=%s", path.c_str()); ret = ERROR_HDS_OPEN_F4M_FAILED; return ret; } int f4m_size = (int)strlen(buf); if (write(fd, buf, f4m_size) != f4m_size) { srs_error("write manifest file failed, path=", path.c_str()); close(fd); ret = ERROR_HDS_WRITE_F4M_FAILED; return ret; } close(fd); srs_trace("build manifest success=%s", path.c_str()); return ERROR_SUCCESS; } int SrsHds::flush_bootstrap() { int ret = ERROR_SUCCESS; SrsStream abst; int size = 1024*100; char *start_abst = new char[1024*100]; SrsAutoFreeA(char, start_abst); int size_abst = 0; char *start_asrt = NULL; int size_asrt = 0; char *start_afrt = NULL; int size_afrt = 0; if ((ret = abst.initialize(start_abst, size)) != ERROR_SUCCESS) { return ret; } // @see video_file_format_spec_v10_1 // page: 46 abst.write_4bytes(0); abst.write_string("abst"); abst.write_1bytes(0x00); // Either 0 or 1 abst.write_3bytes(0x00); // Flags always 0 size_abst += 12; /*! @BootstrapinfoVersion UI32 The version number of the bootstrap information. When the Update field is set, BootstrapinfoVersion indicates the version number that is being updated. we assume this is the last. */ abst.write_4bytes(fragment_index - 1); // BootstrapinfoVersion abst.write_1bytes(0x20); // profile, live, update abst.write_4bytes(1000); // TimeScale Typically, the value is 1000, for a unit of milliseconds size_abst += 9; /*! The timestamp in TimeScale units of the latest available Fragment in the media presentation. This timestamp is used to request the right fragment number. The CurrentMedia Time can be the total duration. For media presentations that are not live, CurrentMediaTime can be 0. */ SrsHdsFragment *st = fragments.back(); abst.write_8bytes(st->get_start_time()); // SmpteTimeCodeOffset abst.write_8bytes(0); size_abst += 16; /*! @MovieIdentifier STRING The identifier of this presentation. we write null string. */ abst.write_1bytes(0); size_abst += 1; /*! @ServerEntryCount UI8 The number of ServerEntryTable entries. The minimum value is 0. */ abst.write_1bytes(0); size_abst += 1; /*! @ServerEntryTable because we write 0 of ServerEntryCount, so this feild is ignored. */ /*! @QualityEntryCount UI8 The number of QualityEntryTable entries, which is also the number of available quality levels. The minimum value is 0. Available quality levels are for, for example, multi bit rate files or trick files. */ abst.write_1bytes(0); size_abst += 1; /*! @QualityEntryTable because we write 0 of QualityEntryCount, so this feild is ignored. */ /*! @DrmData STRING Null or null-terminated UTF-8 string. This string holds Digital Rights Management metadata. Encrypted files use this metadata to get the necessary keys and licenses for decryption and play back. we write null string. */ abst.write_1bytes(0); size_abst += 1; /*! @MetaData STRING Null or null-terminated UTF - 8 string that holds metadata. we write null string. */ abst.write_1bytes(0); size_abst += 1; /*! @SegmentRunTableCount UI8 The number of entries in SegmentRunTableEntries. The minimum value is 1. Typically, one table contains all segment runs. However, this count provides the flexibility to define the segment runs individually for each quality level (or trick file). */ abst.write_1bytes(1); size_abst += 1; start_asrt = start_abst + size_abst; // follows by asrt abst.write_4bytes(0); abst.write_string("asrt"); size_asrt += 8; /*! @Version UI8 @Flags UI24 */ abst.write_4bytes(0); size_asrt += 4; /*! @QualityEntryCount UI8 The number of QualitySegmen tUrlModifiers (quality level references) that follow. If 0, this Segment Run Table applies to all quality levels, and there shall be only one Segment Run Table box in the Bootstrap Info box. */ abst.write_1bytes(0); size_asrt += 1; /*! @QualitySegmentUrlModifiers ignored. */ /*! @SegmentRunEntryCount The number of items in this SegmentRunEn tryTable. The minimum value is 1. */ abst.write_4bytes(1); size_asrt += 4; /*! @SegmentRunEntryTable */ for (int i = 0; i < 1; ++i) { /*! @FirstSegment UI32 The identifying number of the first segment in the run of segments containing the same number of fragments. The segment corresponding to the FirstSegment in the next SEGMENTRUNENTRY will terminate this run. */ abst.write_4bytes(1); /*! @FragmentsPerSegment UI32 The number of fragments in each segment in this run. */ abst.write_4bytes(fragment_index - 1); size_asrt += 8; } update_box(start_asrt, size_asrt); size_abst += size_asrt; /*! @FragmentRunTableCount UI8 The number of entries in FragmentRunTable-Entries. The min i mum value is 1. */ abst.write_1bytes(1); size_abst += 1; // follows by afrt start_afrt = start_abst + size_abst; abst.write_4bytes(0); abst.write_string("afrt"); size_afrt += 8; /*! @Version UI8 @Flags UI24 */ abst.write_4bytes(0); size_afrt += 4; /*! @TimeScale UI32 The number of time units per second, used in the FirstFragmentTime stamp and Fragment Duration fields. Typically, the value is 1000. */ abst.write_4bytes(1000); size_afrt += 4; /*! @QualityEntryCount UI8 The number of QualitySegment Url Modifiers (quality level references) that follow. If 0, this Fragment Run Table applies to all quality levels, and there shall be only one Fragment Run Table box in the Bootstrap Info box. */ abst.write_1bytes(0); size_afrt += 1; /*! @FragmentRunEntryCount UI32 The number of items in this FragmentRunEntryTable. The minimum value is 1. */ abst.write_4bytes((int32_t)(fragments.size())); size_afrt += 4; list<SrsHdsFragment *>::iterator iter; for (iter = fragments.begin(); iter != fragments.end(); ++iter) { SrsHdsFragment *st = *iter; abst.write_4bytes(st->get_index()); abst.write_8bytes(st->get_start_time()); abst.write_4bytes(st->duration()); size_afrt += 16; } update_box(start_afrt, size_afrt); size_abst += size_afrt; update_box(start_abst, size_abst); string path = _srs_config->get_hds_path(hds_req->vhost) + "/" + hds_req->app + "/" + hds_req->stream +".abst"; int fd = open(path.c_str(), O_WRONLY | O_CREAT, S_IRWXU | S_IRGRP | S_IROTH); if (fd < 0) { srs_error("open bootstrap file failed, path=%s", path.c_str()); ret = ERROR_HDS_OPEN_BOOTSTRAP_FAILED; return ret; } if (write(fd, start_abst, size_abst) != size_abst) { srs_error("write bootstrap file failed, path=", path.c_str()); close(fd); ret = ERROR_HDS_WRITE_BOOTSTRAP_FAILED; return ret; } close(fd); srs_trace("build bootstrap success=%s", path.c_str()); return ERROR_SUCCESS; } void SrsHds::adjust_windows() { int windows_size = 0; list<SrsHdsFragment *>::iterator iter; for (iter = fragments.begin(); iter != fragments.end(); ++iter) { SrsHdsFragment *fragment = *iter; windows_size += fragment->duration(); } double windows_size_limit = _srs_config->get_hds_window(hds_req->vhost) * 1000; if (windows_size > windows_size_limit ) { SrsHdsFragment *fragment = fragments.front(); unlink(fragment->fragment_path().c_str()); fragments.erase(fragments.begin()); srs_freep(fragment); } } #endif
[ "timedog1@sina.com" ]
timedog1@sina.com
1d707f1132e3a31e20edd0ebfc30a9dd466309b9
ff33e78882775c7061afb915fc5536874051e7a4
/include/asr/util/logger/Config.h
9628979336bf4daa72bf06d6cdb8fbdec2448f14
[ "MIT" ]
permissive
asura/logger
0c78a6993009cc0bbef5a2dd129577036acaf1f6
3bbf95dd30adb32110855ac78d4055511bf43970
refs/heads/master
2023-02-03T11:35:19.832955
2019-10-16T19:43:07
2019-10-16T19:43:07
208,600,789
0
0
MIT
2023-01-24T18:35:26
2019-09-15T13:48:37
C++
UTF-8
C++
false
false
1,277
h
#ifndef ASR_UTIL_LOGGER_CONFIG_H #define ASR_UTIL_LOGGER_CONFIG_H #include <yaml-cpp/yaml.h> #include <istream> #include <memory> // std::unique_ptr #include <string> #include <vector> namespace asr { namespace util { namespace logger { class Config { public: struct Spdlog { struct Sink { std::string type; std::string level; std::unique_ptr<std::string> pattern; std::unique_ptr<std::string> ident; Sink() = delete; explicit Sink(const YAML::Node& node); Sink(const Sink&) = delete; Sink(Sink&& the_other) = default; }; std::string level; std::string name; std::vector<Sink> sinks; Spdlog() = delete; explicit Spdlog(const YAML::Node& node); }; struct TopLevel { std::string logger; std::unique_ptr<Spdlog> spdlog; TopLevel() = delete; explicit TopLevel(const YAML::Node& node); }; private: TopLevel m_data; public: Config() = delete; explicit Config(std::istream& the_istream); const TopLevel& data() const { return m_data; } }; } // namespace logger } // namespace util } // namespace asr #endif // ASR_UTIL_LOGGER_CONFIG_H
[ "quanyangyi0323@gmail.com" ]
quanyangyi0323@gmail.com
fbd6a5674329cae6e373b80ffd7483351064a82c
e7cdddb3f82ae553d6c53463950dd94d65e0599c
/Coding Ninjas/longestSubsequence.cpp
1e15b3c26c7e9389513587711337d44bea510e32
[]
no_license
IAMWILLROCK/Competetive-Programming
9d06aaa8efc6cf6d3ac683ac08767ab8d180a428
4b6fe6680542ee568ee25603321283afa954abe8
refs/heads/master
2023-01-28T14:09:41.640729
2020-12-10T12:50:18
2020-12-10T12:50:18
284,974,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
#include<iostream> #include<bits/stdc++.h> using namespace std; vector<int> longestSubsequence(int *arr,int n){ set<int> s; set<int>::iterator it; map<int,int> m; vector<int> ans; for(int i=0;i<n;i++){ m.insert(pair<int,int>(arr[i],i)); } for(int i=0;i<n;i++){ s.insert(arr[i]); } int length=1,maxLength=0,start=arr[0],startc=arr[0]; for(it=s.begin();it!=s.end();it++){ while(s.find(++start)!=s.end()){ length++; } if(length>maxLength){ maxLength=length; startc= start-length; }else if(length==maxLength){ if(m.find(start-1)->second < m.find(startc)->second){ cout<<"start:"<<start<<" length:"<<length<<" startc:"<<startc<<endl; startc=start-length; } } length=1; start=*(++it); it--; } for(it=s.find(startc);it!=s.end();it=s.find(++startc)){ ans.push_back(*it); } return ans; } main(){ int n=6; int arr[]={4,7,3,7,8,4}; vector<int> ans; ans=longestSubsequence(arr,n); vector<int>::iterator it; for(it=ans.begin();it!=ans.end();it++){ cout<<*it<<" "; // cout<<"Hey"; } }
[ "sfardinhussain@gmail.com" ]
sfardinhussain@gmail.com
626baf7013f35787add659be0fc09d4cfa8249a5
545eaa27866eefdfffe867c073d531253c14495c
/SimpleDirectUI/WebBrowserControl.h
b03362edeb3a8a6919f1e3015b718ed6748ecd86
[]
no_license
yongsticky/WebgameLauncher
1468dfc4e0df71645c7d111488b085c4fdad7de4
3cad4b0200403b61f78aed0365dd044c833e15ae
refs/heads/master
2021-01-15T08:14:06.894138
2017-10-12T08:25:53
2017-10-12T08:25:53
99,560,944
2
2
null
null
null
null
UTF-8
C++
false
false
1,772
h
#pragma once #include "Control.h" #include "Application.h" namespace SDUI { class CWebBrowserEvents; class COleClientSiteImpl; class CWebBrowserControl : public CControl, public _IMessageFilter { public: CWebBrowserControl(); virtual ~CWebBrowserControl(); DYNAMIC_OBJECT_DECLARE(CWebBrowserControl, CObjectx) virtual bool preTranslateMessage(LPMSG lpMsg); virtual bool createFromXml(CXmlAttribute* attr); virtual unsigned int addChild(CControl* control); virtual void show(bool show); public: void setPage(const std::string& page); void setTransAcc(bool transAcc); void setTransRb(const std::string& transRb); void setChild(bool child); void setDebug(bool debug); bool navigate(const std::string& url); bool stop(); bool refresh(); protected: virtual int onMessage(unsigned int message, unsigned int wparam, int lparam, bool& handled); int _onChildMessage(unsigned int message, unsigned int wparam, int lparam, bool& handled); int _onLinkageMessage(unsigned int message, unsigned int wparam, int lparam, bool& handled); bool _initWebBrowserActiveX(); protected: std::string m_page; bool m_transacc; std::string m_transrb; bool m_rb; bool m_child; bool m_debug; typedef CWinTraits<WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_TOOLWINDOW> _CAcxHostWindowxTraits; class _CAcxHostWindow : public CWindowImpl<_CAcxHostWindow, CAxWindow, _CAcxHostWindowxTraits> { public: _CAcxHostWindow() {} virtual ~_CAcxHostWindow() {} BEGIN_MSG_MAP(_CAcxHostWindow) END_MSG_MAP() }; _CAcxHostWindow m_acxWindow; CComPtr<IWebBrowser2> m_spWebBrowser; CComObject<COleClientSiteImpl>* m_pOleClientSite; CComObject<CWebBrowserEvents>* m_pDWebBrowserEventsObj; }; };
[ "54995288@qq.com" ]
54995288@qq.com
b32233babb65a3a1ef22f2dc9a7f7bbea5c7412e
c6ab85ee22953a3a4756972da00c943f37f2aac8
/BladeEngine/src/mesh_utils.cpp
8e2aee3106cfafc04d5d3fbbad70190866d1e822
[]
no_license
agkountis/GFXI
c073ec0616a2f84077e42cd0a19d1c91c2d603b3
b8aad0c93a33870e74fe4e4298a273c53a28048f
refs/heads/master
2021-06-19T02:28:59.438295
2017-06-19T13:43:11
2017-06-19T13:43:11
81,095,883
0
1
null
null
null
null
UTF-8
C++
false
false
9,225
cpp
#include "mesh_utils.h" #include "math_utils.h" namespace Blade { namespace MeshUtils { Mesh* GenerateCube(float size, VertexWinding vertex_winding) noexcept { Mesh* m{ new Mesh }; float half_size{ size / 2.0f }; //front m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); //right m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, -half_size, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, -half_size, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 0.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, half_size, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 0.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, half_size, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 0.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); //left m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, half_size, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, half_size, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, -half_size, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, -half_size, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); //back m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f ,1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, half_size, 1.0f }, Vec4f{ 0.0f, 0.0f, 1.0f, 1.0f }, Vec4f{ -1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); //top m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, half_size, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, -half_size, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, half_size, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); //bottom m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, -half_size, 1.0f }, Vec4f{ 0.0f, -1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, half_size, 1.0f }, Vec4f{ 0.0f, -1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 0.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, -half_size, 1.0f }, Vec4f{ 0.0f, -1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, 0.0f, 0.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, half_size, 1.0f }, Vec4f{ 0.0f, -1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->GenerateIndices(vertex_winding); if (vertex_winding == VertexWinding::ANTICLOCKWISE) { FlipNormals(m); } m->InitiazeBufferObjects(); return m; } Mesh* GenerateUvSphere(float radius, int slices, int stacks, float urange, float vrange) noexcept { Mesh* m{ new Mesh }; Vertex tmp_vert; if (slices < 4) { slices = 4; } if (stacks < 2) { stacks = 2; } int u_verts = slices + 1; int v_verts = stacks + 1; float du = urange / static_cast<float>(u_verts - 1); float dv = vrange / static_cast<float>(v_verts - 1); float u = 0.0; for (int i = 0; i < u_verts; i++) { float theta = (u * 2.0 * MathUtils::PI_F) * urange; float v = 0.0; for (int j = 0; j < v_verts; j++) { float phi = v * MathUtils::PI_F * vrange; tmp_vert.position = Vec4f{ MathUtils::SphericalToCartesian(theta, phi, radius), 1.0f }; tmp_vert.normal = tmp_vert.position; tmp_vert.tangent = MathUtils::Normalize( Vec4f{ (MathUtils::SphericalToCartesian(theta + 1.0, MathUtils::PI_F / 2.0f) - MathUtils::SphericalToCartesian(theta - 1.0, MathUtils::PI_F / 2.0f)) , 1.0f }); tmp_vert.texcoord.x = u * urange; tmp_vert.texcoord.y = v * vrange; if (i < slices && j < stacks) { int idx = i * v_verts + j; int idx1 = idx; int idx2 = idx + 1; int idx3 = idx + v_verts + 1; int idx4 = idx; int idx5 = idx + v_verts + 1; int idx6 = idx + v_verts; m->AddIndex(idx1); m->AddIndex(idx2); m->AddIndex(idx3); m->AddIndex(idx4); m->AddIndex(idx5); m->AddIndex(idx6); } m->AddVertex(tmp_vert); v += dv; } u += du; } m->InitiazeBufferObjects(); return m; } Mesh* GeneratePlaneXy(float size) noexcept { Mesh* m{ new Mesh }; float half_size{ size / 2.0f }; //front m->AddVertex( Vertex{ Vec4f{ -half_size, -half_size, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 0.0f }, Vec4f{}, Vec4f{ 0.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ -half_size, half_size, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 0.0f }, Vec4f{}, Vec4f{ 0.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, -half_size, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 0.0f }, Vec4f{}, Vec4f{ 1.0f, 1.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->AddVertex( Vertex{ Vec4f{ half_size, half_size, 0.0f, 1.0f }, Vec4f{ 0.0f, 0.0f, -1.0f, 0.0f }, Vec4f{}, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f }, Vec4f{ 1.0f, 0.0f, 0.0f, 1.0f } }); m->GenerateIndices(VertexWinding::CLOCKWISE); m->InitiazeBufferObjects(); return m; } void FlipNormals(const Mesh* m) noexcept { Vertex* varr{ m->GetVertexData() }; for (int i = 0; i < m->GetVertexCount(); ++i) { varr[i].normal = -varr[i].normal; } } } }
[ "agelosbb@gmail.com" ]
agelosbb@gmail.com
22fb9f56db696cb5d77f96e82da58f84cfeac1d2
0fe7cfb034db0d37b3761c5a2b0d902782f89cea
/programs/funcanal/FuncView/CompMatrixView.h
0e401216d0064fdcb4a81e8a95abf399010136c1
[]
no_license
dewhisna/m6811dis
a7fc0310dfa9ccfe5e626fc64a1f99350c567b2e
ab345e6fa714c8607ca85cbc885b53a9aa782710
refs/heads/master
2021-07-13T17:53:21.249108
2021-07-03T20:16:34
2021-07-03T20:16:34
42,601,302
1
0
null
null
null
null
UTF-8
C++
false
false
2,560
h
// CompMatrixView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: CompMatrixView.h,v $ // Revision 1.1 2003/09/13 05:45:38 dewhisna // Initial Revision // // #if !defined(AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_) #define AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "GridCtrl.h" class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView view class CCompMatrixView : public CView { protected: CCompMatrixView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CCompMatrixView) // Attributes public: CFuncViewPrjDoc* GetDocument(); protected: CGridCtrl *m_pGridCtrl; // Operations public: protected: void FillMatrixHeaders(); void FillMatrixData(int nSingleRow = -1, int nSingleCol = -1); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCompMatrixView) public: virtual void OnInitialUpdate(); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnDraw(CDC* pDC); //}}AFX_VIRTUAL // Implementation protected: virtual ~CCompMatrixView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CCompMatrixView) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnSymbolsAdd(); afx_msg void OnUpdateSymbolsAdd(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in CompMatrixView.cpp inline CFuncViewPrjDoc* CCompMatrixView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_)
[ "dewhisna@users.noreply.github.com" ]
dewhisna@users.noreply.github.com
2c4cccfc403f54b8130f1ad9c00d7022e2028187
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_1/C++/wap5/A.cpp
21d22de894a48e8b1c1ff2f9cddf856ef014e1aa
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
917
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; int main() { freopen("lin", "r", stdin); freopen("lout", "w", stdout); int tt; int r, c, w, ans; scanf("%d", &tt); for (int qq=1;qq<=tt;qq++) { printf("Case #%d: ", qq); ans=0; cin>>r>>c>>w; if (c%w==0) { ans=c/w+w-1; } else { ans=c/w+w; } ans+=c/w*(r-1); cout<<ans<<endl; cerr<<ans<<endl; } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
96c2a0ef8ac717b47274e4219072828c6944563c
ef5293888c681e234c476aada1e234098008d849
/src/dataServer/definition/ValueRecordList.cpp
11ec0037117c4c35541813c3cb15c52de30a358d
[ "MIT" ]
permissive
fmidev/smartmet-library-grid-content
5a76dcf35e0bda79ab2b8da3c524ff2a2361103e
71e4b24bab79a5f6238a163bb951091cac23f04e
refs/heads/master
2023-08-04T06:45:03.732347
2023-08-03T07:32:36
2023-08-03T07:32:36
91,444,640
0
0
null
null
null
null
UTF-8
C++
false
false
3,656
cpp
#include "ValueRecordList.h" #include <macgyver/Exception.h> #include <grid-files/common/GeneralFunctions.h> namespace SmartMet { namespace T { ValueRecordList::ValueRecordList() { try { } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } ValueRecordList::ValueRecordList(ValueRecordList& valueRecordList) { try { uint sz = valueRecordList.getLength(); for (uint t=0; t<sz; t++) { ValueRecord *rec = valueRecordList.getValueRecordByIndex(t); if (rec != nullptr) mList.emplace_back(new ValueRecord(*rec)); } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } ValueRecordList::ValueRecordList(ContentInfoList& contentInfoList,CoordinateType coordinateType,short interpolationMethod,double x,double y) { try { uint sz = contentInfoList.getLength(); for (uint t=0; t<sz; t++) { ContentInfo *contentInfo = contentInfoList.getContentInfoByIndex(t); ValueRecord *rec = new ValueRecord(); rec->mFileId = contentInfo->mFileId; rec->mMessageIndex = contentInfo->mMessageIndex; rec->mCoordinateType = coordinateType; rec->mAreaInterpolationMethod = interpolationMethod; rec->mX = x; rec->mY = y; mList.emplace_back(new ValueRecord(*rec)); } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } ValueRecordList::~ValueRecordList() { try { uint sz = mList.size(); for (uint t=0; t<sz; t++) { ValueRecord *rec = mList[t]; if (rec != nullptr) delete rec; } mList.clear(); } catch (...) { Fmi::Exception exception(BCP,"Destructor failed",nullptr); exception.printError(); } } ValueRecordList& ValueRecordList::operator=(ValueRecordList& valueRecordList) { try { if (&valueRecordList == this) return *this; clear(); uint sz = valueRecordList.getLength(); for (uint t=0; t<sz; t++) { ValueRecord *rec = valueRecordList.getValueRecordByIndex(t); if (rec != nullptr) mList.emplace_back(new ValueRecord(*rec)); } return *this; } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void ValueRecordList::addValueRecord(ValueRecord *valueRecord) { try { mList.emplace_back(valueRecord); } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void ValueRecordList::clear() { try { uint sz = mList.size(); for (uint t=0; t<sz; t++) { ValueRecord *rec = mList[t]; if (rec != nullptr) delete rec; } mList.clear(); } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } ValueRecord* ValueRecordList::getValueRecordByIndex(uint index) const { try { if (index >= mList.size()) return nullptr; return mList[index]; } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } uint ValueRecordList::getLength() const { try { return mList.size(); } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void ValueRecordList::print(std::ostream& stream,uint level,uint optionFlags) const { try { stream << space(level) << "ValueRecordList\n"; stream << space(level) << "- mList = \n"; uint sz = mList.size(); for (uint t=0; t<sz; t++) { ValueRecord *rec = mList[t]; if (rec != nullptr) rec->print(stream,level+2,optionFlags); } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } } }
[ "markku.koskela@fmi.fi" ]
markku.koskela@fmi.fi
c34cfb4b1a1ecadc175c5c6054b7e8a7c98da988
598eec950b0212dbedcd5e5408fecf92f573cd34
/Project6/Engine/Grafica/Sprite.h
dc1be9228bcec63af31f1a9e19ddc86017d08eb1
[]
no_license
GhineaAlex/2D-OpenGL-Game
8e7a510126e21cb3a9590928c09e2e6988c93b22
b8df4725388ed0038cf4adfd1d0938f05cc2f12e
refs/heads/master
2020-03-09T05:36:39.771617
2018-04-15T20:21:51
2018-04-15T20:21:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
h
//display propriu-zis a texturii in fereastra #pragma once #ifndef Proiect #define Proiect #include "GLFW/glfw3.h" #include "Texture.h" #include "../Mate/Vector3p.h" #include <string> #include <iostream> using namespace std; class Sprite { public: Sprite(); Sprite(string imagePath); Sprite(string imagePath, Vector3p _pos); void Refresh(); void Render(); void setViteza(float x); void setVitezaCu(float x); void TranslateTo(Vector3p v); //muta void TranslateCu(Vector3p v); //muta cu void TranslateStg(); //merge stg void TranslateDr(); //mers dr void TranslateSus(); void TranslateJos(); void RotateLa(float x); void RotitCu(float x); void setScalare(float x); void setScalare(Vector3p v); Vector3p * getPos(); float * getRotatie(); Vector3p * getScalare(); Vector3p * getSize(); private: Texture texture; float viteza; Vector3p pos; Vector3p scale; Vector3p size; float rotatie; }; #endif
[ "alexg9797@gmail.com" ]
alexg9797@gmail.com
00a6a884115359c092a3389d95958133fc9bd7cc
a0e51e3d3c91ef9e938361e90392d32c832235ff
/include/boost/ui/web_widget.hpp
dcc9e0aa436422067e57bb3335b6979d52878b7e
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
kosenko/ui
22f6d332f74f303e0f7d39792a6e24bda108cf68
275d5ca12f229c1a7926a89f3244f111b03978b6
refs/heads/master
2022-09-05T21:22:52.881325
2022-08-16T22:55:45
2022-08-16T22:55:45
104,901,602
293
24
null
2018-11-04T22:05:52
2017-09-26T15:16:38
C++
UTF-8
C++
false
false
1,374
hpp
// Copyright (c) 2017 Kolya Kosenko // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt /// @file web_widget.hpp @brief Web widget #ifndef BOOST_UI_WEB_WIDGET_HPP #define BOOST_UI_WEB_WIDGET_HPP #include <boost/ui/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #include <boost/ui/widget.hpp> namespace boost { namespace ui { /// @brief Widget that renders HTML /// @see <a href="http://en.wikipedia.org/wiki/Web_browser_engine">Web browser engine (Wikipedia)</a> /// @see <a href="http://www.w3.org/TR/html-markup/iframe.html">iframe (W3C)</a> /// @ingroup info class BOOST_UI_DECL web_widget : public widget { public: web_widget() {} ///@{ Creates web_widget widget explicit web_widget(widget& parent) { create(parent); } web_widget& create(widget& parent); ///@} /// @brief Sets HTML content /// @see <a href="http://en.wikipedia.org/wiki/HTML">HTML (Wikipedia)</a> web_widget& html(const uistring& html); /// @brief Loads content from the URL /// @see <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator">Uniform resource locator (Wikipedia)</a> web_widget& load(const uistring& url); private: class detail_impl; detail_impl* get_impl(); }; } // namespace ui } // namespace boost #endif // BOOST_UI_WEB_WIDGET_HPP
[ "kolya.kosenko@gmail.com" ]
kolya.kosenko@gmail.com
235ea0ce3b6b73794be99f6467101c7cc4424086
fbbc663c607c9687452fa3192b02933b9eb3656d
/tags/1.20.03.00/mptrack/Mpt_midi.cpp
8f7455726f70659aa8532d651547d55290096919
[ "BSD-3-Clause" ]
permissive
svn2github/OpenMPT
594837f3adcb28ba92a324e51c6172a8c1e8ea9c
a2943f028d334a8751b9f16b0512a5e0b905596a
refs/heads/master
2021-07-10T05:07:18.298407
2019-01-19T10:27:21
2019-01-19T10:27:21
106,434,952
2
1
null
null
null
null
UTF-8
C++
false
false
4,361
cpp
/* * MPT_MIDI.cpp * ------------ * Purpose: MIDI Input handling code. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include <mmsystem.h> #include "mainfrm.h" #include "dlsbank.h" #include "../soundlib/MIDIEvents.h" #include "Moptions.h" // for OPTIONS_PAGE_MIDI //#define MPTMIDI_RECORDLOG // Midi Input globals HMIDIIN CMainFrame::shMidiIn = NULL; //Get Midi message(dwParam1), apply MIDI settings having effect on volume, and return //the volume value [0, 256]. In addition value -1 is used as 'use default value'-indicator. int CMainFrame::ApplyVolumeRelatedSettings(const DWORD &dwParam1, const BYTE midivolume) //-------------------------------------------------------------------------------------- { int nVol = MIDIEvents::GetDataByte2FromEvent(dwParam1); if (CMainFrame::GetSettings().m_dwMidiSetup & MIDISETUP_RECORDVELOCITY) { nVol = (CDLSBank::DLSMidiVolumeToLinear(nVol)+255) >> 8; nVol *= CMainFrame::GetSettings().midiVelocityAmp / 100; Limit(nVol, 1, 256); if(CMainFrame::GetSettings().m_dwMidiSetup & MIDISETUP_MIDIVOL_TO_NOTEVOL) nVol = static_cast<int>((midivolume / 127.0) * nVol); } else //Case: No velocity record. { if(CMainFrame::GetSettings().m_dwMidiSetup & MIDISETUP_MIDIVOL_TO_NOTEVOL) nVol = 4*((midivolume+1)/2); else //Use default volume nVol = -1; } return nVol; } void ApplyTransposeKeyboardSetting(CMainFrame &rMainFrm, DWORD &dwParam1) //----------------------------------------------------------------------- { if ( (CMainFrame::GetSettings().m_dwMidiSetup & MIDISETUP_TRANSPOSEKEYBOARD) && (MIDIEvents::GetChannelFromEvent(dwParam1) != 9) ) { int nTranspose = rMainFrm.GetBaseOctave() - 4; if (nTranspose) { int note = MIDIEvents::GetDataByte1FromEvent(dwParam1); if (note < 0x80) { note += nTranspose * 12; Limit(note, 0, NOTE_MAX - NOTE_MIN); dwParam1 &= 0xffff00ff; dwParam1 |= (note << 8); } } } } ///////////////////////////////////////////////////////////////////////////// // MMSYSTEM Midi Record DWORD gdwLastMidiEvtTime = 0; void CALLBACK MidiInCallBack(HMIDIIN, UINT wMsg, DWORD, DWORD dwParam1, DWORD dwParam2) //------------------------------------------------------------------------------------- { CMainFrame *pMainFrm = CMainFrame::GetMainFrame(); HWND hWndMidi; if (!pMainFrm) return; #ifdef MPTMIDI_RECORDLOG DWORD dwMidiStatus = dwParam1 & 0xFF; DWORD dwMidiByte1 = (dwParam1 >> 8) & 0xFF; DWORD dwMidiByte2 = (dwParam1 >> 16) & 0xFF; DWORD dwTimeStamp = dwParam2; Log("time=%8dms status=%02X data=%02X.%02X\n", dwTimeStamp, dwMidiStatus, dwMidiByte1, dwMidiByte2); #endif hWndMidi = pMainFrm->GetMidiRecordWnd(); if ((hWndMidi) && ((wMsg == MIM_DATA) || (wMsg == MIM_MOREDATA))) { switch(MIDIEvents::GetTypeFromEvent(dwParam1)) { case MIDIEvents::evSystem: // Midi Clock if (wMsg == MIM_DATA) { DWORD dwTime = timeGetTime(); const DWORD timediff = dwTime - gdwLastMidiEvtTime; if (timediff < 20 * 3) break; gdwLastMidiEvtTime = dwTime; // continue } else break; case MIDIEvents::evNoteOff: // Note Off case MIDIEvents::evNoteOn: // Note On ApplyTransposeKeyboardSetting(*pMainFrm, dwParam1); default: ::PostMessage(hWndMidi, WM_MOD_MIDIMSG, dwParam1, dwParam2); break; } } } BOOL CMainFrame::midiOpenDevice() //------------------------------- { if (shMidiIn) return TRUE; try { if (midiInOpen(&shMidiIn, GetSettings().m_nMidiDevice, (DWORD)MidiInCallBack, 0, CALLBACK_FUNCTION) != MMSYSERR_NOERROR) { shMidiIn = NULL; // Show MIDI configuration on fail. CMainFrame::m_nLastOptionsPage = OPTIONS_PAGE_MIDI; CMainFrame::GetMainFrame()->OnViewOptions(); return FALSE; } midiInStart(shMidiIn); } catch (...) {} return TRUE; } void CMainFrame::midiCloseDevice() //-------------------------------- { if (shMidiIn) { midiInClose(shMidiIn); shMidiIn = NULL; } } void CMainFrame::OnMidiRecord() //----------------------------- { if (shMidiIn) { midiCloseDevice(); } else { midiOpenDevice(); } } void CMainFrame::OnUpdateMidiRecord(CCmdUI *pCmdUI) //------------------------------------------------- { if (pCmdUI) pCmdUI->SetCheck((shMidiIn) ? TRUE : FALSE); }
[ "saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27" ]
saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27
e0fd6c4965607045905ce21d8149c2b080e443cd
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/11_2407_70.cpp
2fd485ff715826e85b29398ddee8b1b48646cce4
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,160
cpp
#include <stdio.h> #include <stdlib.h> #define B 0 #define O 1 #define MAX(x,y) ((x > y) ? x : y) #define MIN(x,y) ((x < y) ? x : y) typedef struct command_s command_t; typedef struct robot_s robot_t; struct robot_s { int position; command_t *cmdlist; robot_t *oth; }; struct command_s { int robot; int button; int n; command_t *next; }; int main(int argc, char *argv[]) { FILE *in, *out; int lines; int commands; int n; robot_t robot[2]; if(argc != 3) { return(1); } in = fopen(argv[1], "r"); out = fopen(argv[2], "w+"); if(!in || !out) { return(1); } fscanf(in, "%d", &lines); printf("%d lines\n", lines); for(n = 0; n < lines; n++) { command_t *c; int ttime, m; robot_t *rob; ttime = 0; rob = NULL; robot[O].cmdlist = NULL; robot[B].cmdlist = NULL; robot[O].position = 1; robot[B].position = 1; robot[O].oth = &robot[B]; robot[B].oth = &robot[O]; fscanf(in, "%d", &commands); printf("%d commands\n", commands); for(m = 0; m < commands; m++) { command_t *cmd; char r; cmd = malloc(sizeof(command_t)); cmd->robot = -1; cmd->button = 0; cmd->n = m; cmd->next = NULL; fscanf(in, " %c %d", &r, &cmd->button); switch(r) { case 'O': cmd->robot = O; break; case 'B': cmd->robot = B; break; default: printf("Oops...\n"); } if(robot[cmd->robot].cmdlist) { command_t *p = robot[cmd->robot].cmdlist; while(p->next) { p = p->next; } p->next = cmd; } else { robot[cmd->robot].cmdlist = cmd; } if(!rob) { /* this robot has the first command */ rob = &robot[cmd->robot]; } } m = 0; c = robot[O].cmdlist; while(c) { c = c->next; m++; } printf("Rob[O] has %d commands\n", m); m = 0; c = robot[B].cmdlist; while(c) { c = c->next; m++; } printf("Rob[B] has %d commands\n", m); m = 0; while(rob->cmdlist || rob->oth->cmdlist) { int btn_pressed = 0; if(rob->cmdlist) { if(rob->position < rob->cmdlist->button) { rob->position++; } else if(rob->position > rob->cmdlist->button) { rob->position--; } else { if(rob->cmdlist->n == m) { /* press button */ command_t *cur; btn_pressed = 1; cur = rob->cmdlist; rob->cmdlist = rob->cmdlist->next; printf("Button %d pressed after %ds [Rob %d]\n", cur->button, ttime, cur->robot); free(cur); } /* else wait */ } } if(rob->oth->cmdlist) { if(rob->oth->position < rob->oth->cmdlist->button) { rob->oth->position++; } else if(rob->oth->position > rob->oth->cmdlist->button) { rob->oth->position--; } else { if(rob->oth->cmdlist->n == m) { /* press button */ command_t *cur; btn_pressed = 1; cur = rob->oth->cmdlist; rob->oth->cmdlist = rob->oth->cmdlist->next; printf("Button %d pressed after %ds [Rob %d]\n", cur->button, ttime, cur->robot); free(cur); } /* else wait */ } } if(btn_pressed) { m++; } ttime++; } fprintf(out, "Case #%d: %d\n", n+1, ttime); } fclose(in); fclose(out); return(0); }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
0edf38e32c8ba6af07a54c7a71a435f4e8ed9697
804ae22c671252096d850dda693db074cbdcf240
/MiniMath/inc/MiniMath/Ast/Environment.hpp
43cde76fff5df10ada36c246e2702b378b3a83f1
[]
no_license
Dimension4/MiniMath
f15490db899a15baf2a7fff72be5aae02fccdb99
1677675f5c33be8901390b80e768ae0558e312eb
refs/heads/main
2023-04-29T21:42:32.105216
2021-05-20T14:44:14
2021-05-20T14:44:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
hpp
#pragma once #include "MiniMath/Utility.hpp" #include <fmt/format.h> #include <map> #include <string> #include <functional> #include <filesystem> namespace mm { class Expr; namespace ast { class Environment { public: using ConstIterator = std::map<std::string, Expr, std::less<>>::const_iterator; [[nodiscard]] Environment() = default; [[nodiscard]] Environment(std::initializer_list<std::pair<const std::string, Expr>> bindings); [[nodiscard]] Expr const* tryGet(std::string_view name) const noexcept; template <ExprType T> [[nodiscard]] T const* tryGetAs(std::string_view name) const noexcept { auto expr = tryGet(name); return expr ? tryGetExpr<T>(*expr) : nullptr; } [[nodiscard]] Environment with(std::string name, Expr value) const; [[nodiscard]] std::filesystem::path const& getDir() const noexcept; void setDir(std::filesystem::path path); void add(std::string name, Expr value); void merge(Environment&& other); [[nodiscard]] ConstIterator begin() const noexcept; [[nodiscard]] ConstIterator end() const noexcept; friend bool operator==(Environment const&, Environment const&) = default; private: std::map<std::string, Expr, std::less<>> bindings_; std::filesystem::path dir_ = "."; }; } } template <> struct fmt::formatter<mm::ast::Environment> { constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(mm::ast::Environment const& env, FormatContext& ctx) { fmt::format_to(ctx.out(), "{{\n"); for (auto const& [name, val] : env) fmt::format_to(ctx.out(), " {} = {}\n", name, val); fmt::format_to(ctx.out(), "}}"); return ctx.out(); } };
[ "Dimension4@users.noreply.github.com" ]
Dimension4@users.noreply.github.com
4d828145e1bb846dcbfb3d62621529e03acd3554
5f9a7b06bb4610ada8d2aebd2bfc229362a4a9f1
/include/slog/TimeSpan.h
704bcdfe36d3fa65eee24221ee84109a3a08c783
[]
no_license
koba290/slog
338b13d3e55fdc356980d4fb7fdbb08c56e776b5
4544aad5a644a7d9092682aa4ea1a50ecb2c00b7
refs/heads/master
2021-01-18T04:25:54.377018
2012-03-18T10:15:02
2012-03-18T10:15:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
h
/* * Copyright (C) 2011 log-tools.net * * 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 * * 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. */ /*! * \file TimeSpan.h * \brief 経過時間クラス * \author Copyright 2011 log-tools.net */ #pragma once #include "slog/slog.h" namespace slog { /*! * \brief 経過時間クラス */ class TimeSpan { #if defined(__x86_64) uint64_t mMS; //!< ミリ秒 #else uint32_t mMS; //!< ミリ秒 #endif public: TimeSpan(); uint32_t operator-(const TimeSpan& timeSpan) const; }; /*! * \brief コンストラクタ */ TimeSpan::TimeSpan() { #if defined(_WINDOWS) mMS = (uint32_t)timeGetTime(); #else mMS = clock() / (CLOCKS_PER_SEC / 1000); #endif } /*! * \brief 差を取得する */ uint32_t TimeSpan::operator-(const TimeSpan& timeSpan) const { #if !defined(__x86_64) if (mMS < timeSpan.mMS) return ((0xFFFFFFFF - timeSpan.mMS + 1) + mMS); #endif return (mMS - timeSpan.mMS); } } // namespace slog
[ "coffeemam@gmail.com" ]
coffeemam@gmail.com
e0c7e85730e203c65bc6fd1aa0ef96d61370bf09
be2744f43865b43c3e9983a02e13426129b283c4
/Source/Engine/Core/Core_TypeId.cpp
9d3fe3a2e420bb1ff7e01ac59a120a4fa63d6121
[]
no_license
BryanRobertson/Alba
e94ef8f2b68c6f97023cbcf9ba977056fd38e739
cba532d0c7ef2631a240f70f07bf1d258867bb3a
refs/heads/master
2023-02-20T08:22:59.884655
2021-01-23T00:50:15
2021-01-23T00:50:15
112,042,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
#include "Core_Precompile.hpp" #include "Core_TypeId.hpp" namespace Alba { namespace Core { template TypeId GetTypeId<bool>(); template TypeId GetTypeId<char>(); template TypeId GetTypeId<unsigned char>(); template TypeId GetTypeId<short>(); template TypeId GetTypeId<unsigned short>(); template TypeId GetTypeId<int>(); template TypeId GetTypeId<unsigned int>(); template TypeId GetTypeId<long>(); template TypeId GetTypeId<unsigned long>(); template TypeId GetTypeId<long long>(); template TypeId GetTypeId<unsigned long long>(); template TypeId GetTypeId<uint16>(); template TypeId GetTypeId<int16>(); template TypeId GetTypeId<uint32>(); template TypeId GetTypeId<int32>(); template TypeId GetTypeId<uint64>(); template TypeId GetTypeId<int64>(); template TypeId GetTypeId<String>(); template TypeId GetTypeId<StringHash32>(); template TypeId GetTypeId<StringHash64>(); template TypeId GetTypeId<NoCaseStringHash32>(); template TypeId GetTypeId<NoCaseStringHash64>(); } }
[ "bryanericrobertson+github@gmail.com" ]
bryanericrobertson+github@gmail.com
57b1a899b64dde8eb74c1b2674f60d9c1e877f1d
39f066872ab9fcc7541e165c33c161a4017e4354
/src/qt/bitcoin.cpp
5375591a37249d1d27c9935279e8c0cde5c39183
[ "MIT" ]
permissive
hansendm/growers
15547f5a0268ebd6255ee95e43d898275daf7ed1
659288932346761d25be1ef51c65ffdae89eba14
refs/heads/master
2022-04-02T21:20:44.693055
2019-12-24T18:19:53
2019-12-24T18:31:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,393
cpp
/* * W.J. van der Laan 2011-2012 */ #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "paymentserver.h" #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTimer> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal), Q_ARG(unsigned int, style)); } else { LogPrintf("%s: %s\n", caption, message); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } } static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63)); QApplication::instance()->processEvents(); } LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Growers can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char * msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { fHaveGUI = true; // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Install qDebug() message handler to route to debug.log #if QT_VERSION < 0x050000 qInstallMsgHandler(DebugMessageHandler); #else qInstallMessageHandler(DebugMessageHandler); #endif // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Growers", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Growers"); //XXX app.setOrganizationDomain(""); if(GetBoolArg("-testnet", false)) // Separate UI settings for testnet app.setApplicationName("Growers-Qt-testnet"); else app.setApplicationName("Growers-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false)) { splash.show(); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { if (fUseBlackTheme) GUIUtil::SetBlackThemeQSS(app); // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). paymentServer->setOptionsModel(&optionsModel); if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min", false)) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
[ "growersintl@gmail.com" ]
growersintl@gmail.com
1ae91ff52e06f354c545740a4863078ced3fa052
d12d935f52c8a5ec7c858300e24689e7114ed2d4
/src/bitcoin-cli.cpp
48efa2cdf0e4173878259c9a037f84d797d44aac
[ "MIT" ]
permissive
coindroid42/test
4784cd9bc23f0dc6e2b3dca3409da0f00b8f110f
f763f7726902f7af299bf3402774c0070e69be8f
refs/heads/master
2023-01-30T11:03:52.050590
2020-12-08T14:23:47
2020-12-08T14:23:47
319,660,642
0
0
null
null
null
null
UTF-8
C++
false
false
9,713
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" #include "clientversion.h" #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "utilstrencodings.h" #include <boost/filesystem/operations.hpp> #define _(x) std::string(x) /* Keep the _() around in case gettext or such will be used later to translate non-UI */ using namespace std; using namespace json_spirit; std::string HelpMessageCli() { string strUsage; strUsage += _("Options:") + "\n"; strUsage += " -? " + _("This help message") + "\n"; strUsage += " -conf=<file> " + strprintf(_("Specify configuration file (default: %s)"), "bitcoin.conf") + "\n"; strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -testnet " + _("Use the test network") + "\n"; strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " "solved instantly. This is intended for regression testing tools and app development.") + "\n"; strUsage += " -rpcconnect=<ip> " + strprintf(_("Send commands to node running on <ip> (default: %s)"), "127.0.0.1") + "\n"; strUsage += " -rpcport=<port> " + strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), 65535, 65531) + "\n"; strUsage += " -rpcwait " + _("Wait for RPC server to start") + "\n"; strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (argc<2 || mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("DogCoin RPC client version") + " " + FormatFullVersion() + "\n"; if (!mapArgs.count("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " bitcoin-cli [options] <command> [params] " + _("Send command to DogCoin") + "\n" + " bitcoin-cli [options] help " + _("List commands") + "\n" + " bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); return false; } if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) if (!SelectBaseParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } return true; } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl", false); boost::asio::io_service io_service; boost::asio::ssl::context context(boost::asio::ssl::context::sslv23); context.set_options(boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::no_sslv3); boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<boost::asio::ip::tcp> d(sslStream, fUseSSL); boost::iostreams::stream< SSLIOStreamDevice<boost::asio::ip::tcp> > stream(d); const bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(BaseParams().RPCPort()))); if (!fConnected) throw CConnectionFailed("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto, std::numeric_limits<size_t>::max()); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute and handle connection failures with -rpcwait const bool fWait = GetBoolArg("-rpcwait", false); do { try { const Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error const int code = find_value(error.get_obj(), "code").get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + write_string(error, false); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed&) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); try { if(!AppInitRPC(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; }
[ "you@example.com" ]
you@example.com
1b9799ab7d045a580fd5564b2557ebdc4577bcc9
0fda86164369bcbe5f3c3c2ae7c0d72fdfbaa6f7
/llvm-project/clang-tools-extra/clangd/Protocol.h
1ccfa587bf8727d9987a1cfccce3cd6610bc1fcd
[ "MIT", "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
ananthdurbha/llvm-mlir
74923e50dace37e840f75b79ed2b6c02a36079bc
a5e0b8903b83c777fa40a0fa538fbdb8176fd5ac
refs/heads/master
2022-12-20T02:25:52.994086
2019-12-16T07:11:19
2019-12-16T07:11:19
228,313,885
0
0
MIT
2022-12-12T02:36:52
2019-12-16T06:01:46
C++
UTF-8
C++
false
false
45,225
h
//===--- Protocol.h - Language Server Protocol Implementation ---*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains structs based on the LSP specification at // https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md // // This is not meant to be a complete implementation, new interfaces are added // when they're needed. // // Each struct has a toJSON and fromJSON function, that converts between // the struct and a JSON representation. (See JSON.h) // // Some structs also have operator<< serialization. This is for debugging and // tests, and is not generally machine-readable. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H #include "URI.h" #include "index/SymbolID.h" #include "clang/Index/IndexSymbol.h" #include "llvm/ADT/Optional.h" #include "llvm/Support/JSON.h" #include "llvm/Support/raw_ostream.h" #include <bitset> #include <memory> #include <string> #include <vector> namespace clang { namespace clangd { enum class ErrorCode { // Defined by JSON RPC. ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603, ServerNotInitialized = -32002, UnknownErrorCode = -32001, // Defined by the protocol. RequestCancelled = -32800, }; // Models an LSP error as an llvm::Error. class LSPError : public llvm::ErrorInfo<LSPError> { public: std::string Message; ErrorCode Code; static char ID; LSPError(std::string Message, ErrorCode Code) : Message(std::move(Message)), Code(Code) {} void log(llvm::raw_ostream &OS) const override { OS << int(Code) << ": " << Message; } std::error_code convertToErrorCode() const override { return llvm::inconvertibleErrorCode(); } }; // URI in "file" scheme for a file. struct URIForFile { URIForFile() = default; /// Canonicalizes \p AbsPath via URI. /// /// File paths in URIForFile can come from index or local AST. Path from /// index goes through URI transformation, and the final path is resolved by /// URI scheme and could potentially be different from the original path. /// Hence, we do the same transformation for all paths. /// /// Files can be referred to by several paths (e.g. in the presence of links). /// Which one we prefer may depend on where we're coming from. \p TUPath is a /// hint, and should usually be the main entrypoint file we're processing. static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath); static llvm::Expected<URIForFile> fromURI(const URI &U, llvm::StringRef HintPath); /// Retrieves absolute path to the file. llvm::StringRef file() const { return File; } explicit operator bool() const { return !File.empty(); } std::string uri() const { return URI::createFile(File).toString(); } friend bool operator==(const URIForFile &LHS, const URIForFile &RHS) { return LHS.File == RHS.File; } friend bool operator!=(const URIForFile &LHS, const URIForFile &RHS) { return !(LHS == RHS); } friend bool operator<(const URIForFile &LHS, const URIForFile &RHS) { return LHS.File < RHS.File; } private: explicit URIForFile(std::string &&File) : File(std::move(File)) {} std::string File; }; /// Serialize/deserialize \p URIForFile to/from a string URI. llvm::json::Value toJSON(const URIForFile &U); bool fromJSON(const llvm::json::Value &, URIForFile &); struct TextDocumentIdentifier { /// The text document's URI. URIForFile uri; }; llvm::json::Value toJSON(const TextDocumentIdentifier &); bool fromJSON(const llvm::json::Value &, TextDocumentIdentifier &); struct Position { /// Line position in a document (zero-based). int line = 0; /// Character offset on a line in a document (zero-based). /// WARNING: this is in UTF-16 codepoints, not bytes or characters! /// Use the functions in SourceCode.h to construct/interpret Positions. int character = 0; friend bool operator==(const Position &LHS, const Position &RHS) { return std::tie(LHS.line, LHS.character) == std::tie(RHS.line, RHS.character); } friend bool operator!=(const Position &LHS, const Position &RHS) { return !(LHS == RHS); } friend bool operator<(const Position &LHS, const Position &RHS) { return std::tie(LHS.line, LHS.character) < std::tie(RHS.line, RHS.character); } friend bool operator<=(const Position &LHS, const Position &RHS) { return std::tie(LHS.line, LHS.character) <= std::tie(RHS.line, RHS.character); } }; bool fromJSON(const llvm::json::Value &, Position &); llvm::json::Value toJSON(const Position &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Position &); struct Range { /// The range's start position. Position start; /// The range's end position. Position end; friend bool operator==(const Range &LHS, const Range &RHS) { return std::tie(LHS.start, LHS.end) == std::tie(RHS.start, RHS.end); } friend bool operator!=(const Range &LHS, const Range &RHS) { return !(LHS == RHS); } friend bool operator<(const Range &LHS, const Range &RHS) { return std::tie(LHS.start, LHS.end) < std::tie(RHS.start, RHS.end); } bool contains(Position Pos) const { return start <= Pos && Pos < end; } bool contains(Range Rng) const { return start <= Rng.start && Rng.end <= end; } }; bool fromJSON(const llvm::json::Value &, Range &); llvm::json::Value toJSON(const Range &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Range &); struct Location { /// The text document's URI. URIForFile uri; Range range; friend bool operator==(const Location &LHS, const Location &RHS) { return LHS.uri == RHS.uri && LHS.range == RHS.range; } friend bool operator!=(const Location &LHS, const Location &RHS) { return !(LHS == RHS); } friend bool operator<(const Location &LHS, const Location &RHS) { return std::tie(LHS.uri, LHS.range) < std::tie(RHS.uri, RHS.range); } }; llvm::json::Value toJSON(const Location &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Location &); struct TextEdit { /// The range of the text document to be manipulated. To insert /// text into a document create a range where start === end. Range range; /// The string to be inserted. For delete operations use an /// empty string. std::string newText; }; inline bool operator==(const TextEdit &L, const TextEdit &R) { return std::tie(L.newText, L.range) == std::tie(R.newText, R.range); } bool fromJSON(const llvm::json::Value &, TextEdit &); llvm::json::Value toJSON(const TextEdit &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TextEdit &); struct TextDocumentItem { /// The text document's URI. URIForFile uri; /// The text document's language identifier. std::string languageId; /// The version number of this document (it will strictly increase after each int version = 0; /// The content of the opened text document. std::string text; }; bool fromJSON(const llvm::json::Value &, TextDocumentItem &); enum class TraceLevel { Off = 0, Messages = 1, Verbose = 2, }; bool fromJSON(const llvm::json::Value &E, TraceLevel &Out); struct NoParams {}; inline bool fromJSON(const llvm::json::Value &, NoParams &) { return true; } using ShutdownParams = NoParams; using ExitParams = NoParams; /// Defines how the host (editor) should sync document changes to the language /// server. enum class TextDocumentSyncKind { /// Documents should not be synced at all. None = 0, /// Documents are synced by always sending the full content of the document. Full = 1, /// Documents are synced by sending the full content on open. After that /// only incremental updates to the document are send. Incremental = 2, }; /// The kind of a completion entry. enum class CompletionItemKind { Missing = 0, Text = 1, Method = 2, Function = 3, Constructor = 4, Field = 5, Variable = 6, Class = 7, Interface = 8, Module = 9, Property = 10, Unit = 11, Value = 12, Enum = 13, Keyword = 14, Snippet = 15, Color = 16, File = 17, Reference = 18, Folder = 19, EnumMember = 20, Constant = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, }; bool fromJSON(const llvm::json::Value &, CompletionItemKind &); constexpr auto CompletionItemKindMin = static_cast<size_t>(CompletionItemKind::Text); constexpr auto CompletionItemKindMax = static_cast<size_t>(CompletionItemKind::TypeParameter); using CompletionItemKindBitset = std::bitset<CompletionItemKindMax + 1>; bool fromJSON(const llvm::json::Value &, CompletionItemKindBitset &); CompletionItemKind adjustKindToCapability(CompletionItemKind Kind, CompletionItemKindBitset &SupportedCompletionItemKinds); /// A symbol kind. enum class SymbolKind { File = 1, Module = 2, Namespace = 3, Package = 4, Class = 5, Method = 6, Property = 7, Field = 8, Constructor = 9, Enum = 10, Interface = 11, Function = 12, Variable = 13, Constant = 14, String = 15, Number = 16, Boolean = 17, Array = 18, Object = 19, Key = 20, Null = 21, EnumMember = 22, Struct = 23, Event = 24, Operator = 25, TypeParameter = 26 }; bool fromJSON(const llvm::json::Value &, SymbolKind &); constexpr auto SymbolKindMin = static_cast<size_t>(SymbolKind::File); constexpr auto SymbolKindMax = static_cast<size_t>(SymbolKind::TypeParameter); using SymbolKindBitset = std::bitset<SymbolKindMax + 1>; bool fromJSON(const llvm::json::Value &, SymbolKindBitset &); SymbolKind adjustKindToCapability(SymbolKind Kind, SymbolKindBitset &supportedSymbolKinds); // Convert a index::SymbolKind to clangd::SymbolKind (LSP) // Note, some are not perfect matches and should be improved when this LSP // issue is addressed: // https://github.com/Microsoft/language-server-protocol/issues/344 SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind); // Determines the encoding used to measure offsets and lengths of source in LSP. enum class OffsetEncoding { // Any string is legal on the wire. Unrecognized encodings parse as this. UnsupportedEncoding, // Length counts code units of UTF-16 encoded text. (Standard LSP behavior). UTF16, // Length counts bytes of UTF-8 encoded text. (Clangd extension). UTF8, // Length counts codepoints in unicode text. (Clangd extension). UTF32, }; llvm::json::Value toJSON(const OffsetEncoding &); bool fromJSON(const llvm::json::Value &, OffsetEncoding &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, OffsetEncoding); // Describes the content type that a client supports in various result literals // like `Hover`, `ParameterInfo` or `CompletionItem`. enum class MarkupKind { PlainText, Markdown, }; bool fromJSON(const llvm::json::Value &, MarkupKind &); llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind); // This struct doesn't mirror LSP! // The protocol defines deeply nested structures for client capabilities. // Instead of mapping them all, this just parses out the bits we care about. struct ClientCapabilities { /// The supported set of SymbolKinds for workspace/symbol. /// workspace.symbol.symbolKind.valueSet llvm::Optional<SymbolKindBitset> WorkspaceSymbolKinds; /// Whether the client accepts diagnostics with codeActions attached inline. /// textDocument.publishDiagnostics.codeActionsInline. bool DiagnosticFixes = false; /// Whether the client accepts diagnostics with related locations. /// textDocument.publishDiagnostics.relatedInformation. bool DiagnosticRelatedInformation = false; /// Whether the client accepts diagnostics with category attached to it /// using the "category" extension. /// textDocument.publishDiagnostics.categorySupport bool DiagnosticCategory = false; /// Client supports snippets as insert text. /// textDocument.completion.completionItem.snippetSupport bool CompletionSnippets = false; /// Client supports completions with additionalTextEdit near the cursor. /// This is a clangd extension. (LSP says this is for unrelated text only). /// textDocument.completion.editsNearCursor bool CompletionFixes = false; /// Client supports hierarchical document symbols. /// textDocument.documentSymbol.hierarchicalDocumentSymbolSupport bool HierarchicalDocumentSymbol = false; /// Client supports signature help. /// textDocument.signatureHelp bool HasSignatureHelp = false; /// Client supports processing label offsets instead of a simple label string. /// textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport bool OffsetsInSignatureHelp = false; /// The supported set of CompletionItemKinds for textDocument/completion. /// textDocument.completion.completionItemKind.valueSet llvm::Optional<CompletionItemKindBitset> CompletionItemKinds; /// Client supports CodeAction return value for textDocument/codeAction. /// textDocument.codeAction.codeActionLiteralSupport. bool CodeActionStructure = false; /// Client supports semantic highlighting. /// textDocument.semanticHighlightingCapabilities.semanticHighlighting bool SemanticHighlighting = false; /// Supported encodings for LSP character offsets. (clangd extension). llvm::Optional<std::vector<OffsetEncoding>> offsetEncoding; /// The content format that should be used for Hover requests. /// textDocument.hover.contentEncoding MarkupKind HoverContentFormat = MarkupKind::PlainText; /// The client supports testing for validity of rename operations /// before execution. bool RenamePrepareSupport = false; }; bool fromJSON(const llvm::json::Value &, ClientCapabilities &); /// Clangd extension that's used in the 'compilationDatabaseChanges' in /// workspace/didChangeConfiguration to record updates to the in-memory /// compilation database. struct ClangdCompileCommand { std::string workingDirectory; std::vector<std::string> compilationCommand; }; bool fromJSON(const llvm::json::Value &, ClangdCompileCommand &); /// Clangd extension: parameters configurable at any time, via the /// `workspace/didChangeConfiguration` notification. /// LSP defines this type as `any`. struct ConfigurationSettings { // Changes to the in-memory compilation database. // The key of the map is a file name. std::map<std::string, ClangdCompileCommand> compilationDatabaseChanges; }; bool fromJSON(const llvm::json::Value &, ConfigurationSettings &); /// Clangd extension: parameters configurable at `initialize` time. /// LSP defines this type as `any`. struct InitializationOptions { // What we can change throught the didChangeConfiguration request, we can // also set through the initialize request (initializationOptions field). ConfigurationSettings ConfigSettings; llvm::Optional<std::string> compilationDatabasePath; // Additional flags to be included in the "fallback command" used when // the compilation database doesn't describe an opened file. // The command used will be approximately `clang $FILE $fallbackFlags`. std::vector<std::string> fallbackFlags; /// Clients supports show file status for textDocument/clangd.fileStatus. bool FileStatus = false; }; bool fromJSON(const llvm::json::Value &, InitializationOptions &); struct InitializeParams { /// The process Id of the parent process that started /// the server. Is null if the process has not been started by another /// process. If the parent process is not alive then the server should exit /// (see exit notification) its process. llvm::Optional<int> processId; /// The rootPath of the workspace. Is null /// if no folder is open. /// /// @deprecated in favour of rootUri. llvm::Optional<std::string> rootPath; /// The rootUri of the workspace. Is null if no /// folder is open. If both `rootPath` and `rootUri` are set /// `rootUri` wins. llvm::Optional<URIForFile> rootUri; // User provided initialization options. // initializationOptions?: any; /// The capabilities provided by the client (editor or tool) ClientCapabilities capabilities; /// The initial trace setting. If omitted trace is disabled ('off'). llvm::Optional<TraceLevel> trace; /// User-provided initialization options. InitializationOptions initializationOptions; }; bool fromJSON(const llvm::json::Value &, InitializeParams &); enum class MessageType { /// An error message. Error = 1, /// A warning message. Warning = 2, /// An information message. Info = 3, /// A log message. Log = 4, }; llvm::json::Value toJSON(const MessageType &); /// The show message notification is sent from a server to a client to ask the /// client to display a particular message in the user interface. struct ShowMessageParams { /// The message type. MessageType type = MessageType::Info; /// The actual message. std::string message; }; llvm::json::Value toJSON(const ShowMessageParams &); struct DidOpenTextDocumentParams { /// The document that was opened. TextDocumentItem textDocument; }; bool fromJSON(const llvm::json::Value &, DidOpenTextDocumentParams &); struct DidCloseTextDocumentParams { /// The document that was closed. TextDocumentIdentifier textDocument; }; bool fromJSON(const llvm::json::Value &, DidCloseTextDocumentParams &); struct TextDocumentContentChangeEvent { /// The range of the document that changed. llvm::Optional<Range> range; /// The length of the range that got replaced. llvm::Optional<int> rangeLength; /// The new text of the range/document. std::string text; }; bool fromJSON(const llvm::json::Value &, TextDocumentContentChangeEvent &); struct DidChangeTextDocumentParams { /// The document that did change. The version number points /// to the version after all provided content changes have /// been applied. TextDocumentIdentifier textDocument; /// The actual content changes. std::vector<TextDocumentContentChangeEvent> contentChanges; /// Forces diagnostics to be generated, or to not be generated, for this /// version of the file. If not set, diagnostics are eventually consistent: /// either they will be provided for this version or some subsequent one. /// This is a clangd extension. llvm::Optional<bool> wantDiagnostics; }; bool fromJSON(const llvm::json::Value &, DidChangeTextDocumentParams &); enum class FileChangeType { /// The file got created. Created = 1, /// The file got changed. Changed = 2, /// The file got deleted. Deleted = 3 }; bool fromJSON(const llvm::json::Value &E, FileChangeType &Out); struct FileEvent { /// The file's URI. URIForFile uri; /// The change type. FileChangeType type = FileChangeType::Created; }; bool fromJSON(const llvm::json::Value &, FileEvent &); struct DidChangeWatchedFilesParams { /// The actual file events. std::vector<FileEvent> changes; }; bool fromJSON(const llvm::json::Value &, DidChangeWatchedFilesParams &); struct DidChangeConfigurationParams { ConfigurationSettings settings; }; bool fromJSON(const llvm::json::Value &, DidChangeConfigurationParams &); // Note: we do not parse FormattingOptions for *FormattingParams. // In general, we use a clang-format style detected from common mechanisms // (.clang-format files and the -fallback-style flag). // It would be possible to override these with FormatOptions, but: // - the protocol makes FormatOptions mandatory, so many clients set them to // useless values, and we can't tell when to respect them // - we also format in other places, where FormatOptions aren't available. struct DocumentRangeFormattingParams { /// The document to format. TextDocumentIdentifier textDocument; /// The range to format Range range; }; bool fromJSON(const llvm::json::Value &, DocumentRangeFormattingParams &); struct DocumentOnTypeFormattingParams { /// The document to format. TextDocumentIdentifier textDocument; /// The position at which this request was sent. Position position; /// The character that has been typed. std::string ch; }; bool fromJSON(const llvm::json::Value &, DocumentOnTypeFormattingParams &); struct DocumentFormattingParams { /// The document to format. TextDocumentIdentifier textDocument; }; bool fromJSON(const llvm::json::Value &, DocumentFormattingParams &); struct DocumentSymbolParams { // The text document to find symbols in. TextDocumentIdentifier textDocument; }; bool fromJSON(const llvm::json::Value &, DocumentSymbolParams &); /// Represents a related message and source code location for a diagnostic. /// This should be used to point to code locations that cause or related to a /// diagnostics, e.g when duplicating a symbol in a scope. struct DiagnosticRelatedInformation { /// The location of this related diagnostic information. Location location; /// The message of this related diagnostic information. std::string message; }; llvm::json::Value toJSON(const DiagnosticRelatedInformation &); struct CodeAction; struct Diagnostic { /// The range at which the message applies. Range range; /// The diagnostic's severity. Can be omitted. If omitted it is up to the /// client to interpret diagnostics as error, warning, info or hint. int severity = 0; /// The diagnostic's code. Can be omitted. std::string code; /// A human-readable string describing the source of this /// diagnostic, e.g. 'typescript' or 'super lint'. std::string source; /// The diagnostic's message. std::string message; /// An array of related diagnostic information, e.g. when symbol-names within /// a scope collide all definitions can be marked via this property. llvm::Optional<std::vector<DiagnosticRelatedInformation>> relatedInformation; /// The diagnostic's category. Can be omitted. /// An LSP extension that's used to send the name of the category over to the /// client. The category typically describes the compilation stage during /// which the issue was produced, e.g. "Semantic Issue" or "Parse Issue". llvm::Optional<std::string> category; /// Clangd extension: code actions related to this diagnostic. /// Only with capability textDocument.publishDiagnostics.codeActionsInline. /// (These actions can also be obtained using textDocument/codeAction). llvm::Optional<std::vector<CodeAction>> codeActions; }; llvm::json::Value toJSON(const Diagnostic &); /// A LSP-specific comparator used to find diagnostic in a container like /// std:map. /// We only use the required fields of Diagnostic to do the comparsion to avoid /// any regression issues from LSP clients (e.g. VScode), see /// https://git.io/vbr29 struct LSPDiagnosticCompare { bool operator()(const Diagnostic &LHS, const Diagnostic &RHS) const { return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message); } }; bool fromJSON(const llvm::json::Value &, Diagnostic &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Diagnostic &); struct CodeActionContext { /// An array of diagnostics. std::vector<Diagnostic> diagnostics; }; bool fromJSON(const llvm::json::Value &, CodeActionContext &); struct CodeActionParams { /// The document in which the command was invoked. TextDocumentIdentifier textDocument; /// The range for which the command was invoked. Range range; /// Context carrying additional information. CodeActionContext context; }; bool fromJSON(const llvm::json::Value &, CodeActionParams &); struct WorkspaceEdit { /// Holds changes to existing resources. llvm::Optional<std::map<std::string, std::vector<TextEdit>>> changes; /// Note: "documentChanges" is not currently used because currently there is /// no support for versioned edits. }; bool fromJSON(const llvm::json::Value &, WorkspaceEdit &); llvm::json::Value toJSON(const WorkspaceEdit &WE); /// Arguments for the 'applyTweak' command. The server sends these commands as a /// response to the textDocument/codeAction request. The client can later send a /// command back to the server if the user requests to execute a particular code /// tweak. struct TweakArgs { /// A file provided by the client on a textDocument/codeAction request. URIForFile file; /// A selection provided by the client on a textDocument/codeAction request. Range selection; /// ID of the tweak that should be executed. Corresponds to Tweak::id(). std::string tweakID; }; bool fromJSON(const llvm::json::Value &, TweakArgs &); llvm::json::Value toJSON(const TweakArgs &A); /// Exact commands are not specified in the protocol so we define the /// ones supported by Clangd here. The protocol specifies the command arguments /// to be "any[]" but to make this safer and more manageable, each command we /// handle maps to a certain llvm::Optional of some struct to contain its /// arguments. Different commands could reuse the same llvm::Optional as /// arguments but a command that needs different arguments would simply add a /// new llvm::Optional and not use any other ones. In practice this means only /// one argument type will be parsed and set. struct ExecuteCommandParams { // Command to apply fix-its. Uses WorkspaceEdit as argument. const static llvm::StringLiteral CLANGD_APPLY_FIX_COMMAND; // Command to apply the code action. Uses TweakArgs as argument. const static llvm::StringLiteral CLANGD_APPLY_TWEAK; /// The command identifier, e.g. CLANGD_APPLY_FIX_COMMAND std::string command; // Arguments llvm::Optional<WorkspaceEdit> workspaceEdit; llvm::Optional<TweakArgs> tweakArgs; }; bool fromJSON(const llvm::json::Value &, ExecuteCommandParams &); struct Command : public ExecuteCommandParams { std::string title; }; llvm::json::Value toJSON(const Command &C); /// A code action represents a change that can be performed in code, e.g. to fix /// a problem or to refactor code. /// /// A CodeAction must set either `edit` and/or a `command`. If both are /// supplied, the `edit` is applied first, then the `command` is executed. struct CodeAction { /// A short, human-readable, title for this code action. std::string title; /// The kind of the code action. /// Used to filter code actions. llvm::Optional<std::string> kind; const static llvm::StringLiteral QUICKFIX_KIND; const static llvm::StringLiteral REFACTOR_KIND; const static llvm::StringLiteral INFO_KIND; /// The diagnostics that this code action resolves. llvm::Optional<std::vector<Diagnostic>> diagnostics; /// The workspace edit this code action performs. llvm::Optional<WorkspaceEdit> edit; /// A command this code action executes. If a code action provides an edit /// and a command, first the edit is executed and then the command. llvm::Optional<Command> command; }; llvm::json::Value toJSON(const CodeAction &); /// Represents programming constructs like variables, classes, interfaces etc. /// that appear in a document. Document symbols can be hierarchical and they /// have two ranges: one that encloses its definition and one that points to its /// most interesting range, e.g. the range of an identifier. struct DocumentSymbol { /// The name of this symbol. std::string name; /// More detail for this symbol, e.g the signature of a function. std::string detail; /// The kind of this symbol. SymbolKind kind; /// Indicates if this symbol is deprecated. bool deprecated; /// The range enclosing this symbol not including leading/trailing whitespace /// but everything else like comments. This information is typically used to /// determine if the clients cursor is inside the symbol to reveal in the /// symbol in the UI. Range range; /// The range that should be selected and revealed when this symbol is being /// picked, e.g the name of a function. Must be contained by the `range`. Range selectionRange; /// Children of this symbol, e.g. properties of a class. std::vector<DocumentSymbol> children; }; llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S); llvm::json::Value toJSON(const DocumentSymbol &S); /// Represents information about programming constructs like variables, classes, /// interfaces etc. struct SymbolInformation { /// The name of this symbol. std::string name; /// The kind of this symbol. SymbolKind kind; /// The location of this symbol. Location location; /// The name of the symbol containing this symbol. std::string containerName; }; llvm::json::Value toJSON(const SymbolInformation &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &); /// Represents information about identifier. /// This is returned from textDocument/symbolInfo, which is a clangd extension. struct SymbolDetails { std::string name; std::string containerName; /// Unified Symbol Resolution identifier /// This is an opaque string uniquely identifying a symbol. /// Unlike SymbolID, it is variable-length and somewhat human-readable. /// It is a common representation across several clang tools. /// (See USRGeneration.h) std::string USR; llvm::Optional<SymbolID> ID; }; llvm::json::Value toJSON(const SymbolDetails &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &); bool operator==(const SymbolDetails &, const SymbolDetails &); /// The parameters of a Workspace Symbol Request. struct WorkspaceSymbolParams { /// A non-empty query string std::string query; }; bool fromJSON(const llvm::json::Value &, WorkspaceSymbolParams &); struct ApplyWorkspaceEditParams { WorkspaceEdit edit; }; llvm::json::Value toJSON(const ApplyWorkspaceEditParams &); struct ApplyWorkspaceEditResponse { bool applied = true; llvm::Optional<std::string> failureReason; }; bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &); struct TextDocumentPositionParams { /// The text document. TextDocumentIdentifier textDocument; /// The position inside the text document. Position position; }; bool fromJSON(const llvm::json::Value &, TextDocumentPositionParams &); enum class CompletionTriggerKind { /// Completion was triggered by typing an identifier (24x7 code /// complete), manual invocation (e.g Ctrl+Space) or via API. Invoked = 1, /// Completion was triggered by a trigger character specified by /// the `triggerCharacters` properties of the `CompletionRegistrationOptions`. TriggerCharacter = 2, /// Completion was re-triggered as the current completion list is incomplete. TriggerTriggerForIncompleteCompletions = 3 }; struct CompletionContext { /// How the completion was triggered. CompletionTriggerKind triggerKind = CompletionTriggerKind::Invoked; /// The trigger character (a single character) that has trigger code complete. /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` std::string triggerCharacter; }; bool fromJSON(const llvm::json::Value &, CompletionContext &); struct CompletionParams : TextDocumentPositionParams { CompletionContext context; }; bool fromJSON(const llvm::json::Value &, CompletionParams &); struct MarkupContent { MarkupKind kind = MarkupKind::PlainText; std::string value; }; llvm::json::Value toJSON(const MarkupContent &MC); struct Hover { /// The hover's content MarkupContent contents; /// An optional range is a range inside a text document /// that is used to visualize a hover, e.g. by changing the background color. llvm::Optional<Range> range; }; llvm::json::Value toJSON(const Hover &H); /// Defines whether the insert text in a completion item should be interpreted /// as plain text or a snippet. enum class InsertTextFormat { Missing = 0, /// The primary text to be inserted is treated as a plain string. PlainText = 1, /// The primary text to be inserted is treated as a snippet. /// /// A snippet can define tab stops and placeholders with `$1`, `$2` /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end /// of the snippet. Placeholders with equal identifiers are linked, that is /// typing in one will update others too. /// /// See also: /// https//github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md Snippet = 2, }; struct CompletionItem { /// The label of this completion item. By default also the text that is /// inserted when selecting this completion. std::string label; /// The kind of this completion item. Based of the kind an icon is chosen by /// the editor. CompletionItemKind kind = CompletionItemKind::Missing; /// A human-readable string with additional information about this item, like /// type or symbol information. std::string detail; /// A human-readable string that represents a doc-comment. std::string documentation; /// A string that should be used when comparing this item with other items. /// When `falsy` the label is used. std::string sortText; /// A string that should be used when filtering a set of completion items. /// When `falsy` the label is used. std::string filterText; /// A string that should be inserted to a document when selecting this /// completion. When `falsy` the label is used. std::string insertText; /// The format of the insert text. The format applies to both the `insertText` /// property and the `newText` property of a provided `textEdit`. InsertTextFormat insertTextFormat = InsertTextFormat::Missing; /// An edit which is applied to a document when selecting this completion. /// When an edit is provided `insertText` is ignored. /// /// Note: The range of the edit must be a single line range and it must /// contain the position at which completion has been requested. llvm::Optional<TextEdit> textEdit; /// An optional array of additional text edits that are applied when selecting /// this completion. Edits must not overlap with the main edit nor with /// themselves. std::vector<TextEdit> additionalTextEdits; /// Indicates if this item is deprecated. bool deprecated = false; // TODO(krasimir): The following optional fields defined by the language // server protocol are unsupported: // // data?: any - A data entry field that is preserved on a completion item // between a completion and a completion resolve request. }; llvm::json::Value toJSON(const CompletionItem &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const CompletionItem &); bool operator<(const CompletionItem &, const CompletionItem &); /// Represents a collection of completion items to be presented in the editor. struct CompletionList { /// The list is not complete. Further typing should result in recomputing the /// list. bool isIncomplete = false; /// The completion items. std::vector<CompletionItem> items; }; llvm::json::Value toJSON(const CompletionList &); /// A single parameter of a particular signature. struct ParameterInformation { /// The label of this parameter. Ignored when labelOffsets is set. std::string labelString; /// Inclusive start and exclusive end offsets withing the containing signature /// label. /// Offsets are computed by lspLength(), which counts UTF-16 code units by /// default but that can be overriden, see its documentation for details. llvm::Optional<std::pair<unsigned, unsigned>> labelOffsets; /// The documentation of this parameter. Optional. std::string documentation; }; llvm::json::Value toJSON(const ParameterInformation &); /// Represents the signature of something callable. struct SignatureInformation { /// The label of this signature. Mandatory. std::string label; /// The documentation of this signature. Optional. std::string documentation; /// The parameters of this signature. std::vector<ParameterInformation> parameters; }; llvm::json::Value toJSON(const SignatureInformation &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SignatureInformation &); /// Represents the signature of a callable. struct SignatureHelp { /// The resulting signatures. std::vector<SignatureInformation> signatures; /// The active signature. int activeSignature = 0; /// The active parameter of the active signature. int activeParameter = 0; /// Position of the start of the argument list, including opening paren. e.g. /// foo("first arg", "second arg", /// ^-argListStart ^-cursor /// This is a clangd-specific extension, it is only available via C++ API and /// not currently serialized for the LSP. Position argListStart; }; llvm::json::Value toJSON(const SignatureHelp &); struct RenameParams { /// The document that was opened. TextDocumentIdentifier textDocument; /// The position at which this request was sent. Position position; /// The new name of the symbol. std::string newName; }; bool fromJSON(const llvm::json::Value &, RenameParams &); enum class DocumentHighlightKind { Text = 1, Read = 2, Write = 3 }; /// A document highlight is a range inside a text document which deserves /// special attention. Usually a document highlight is visualized by changing /// the background color of its range. struct DocumentHighlight { /// The range this highlight applies to. Range range; /// The highlight kind, default is DocumentHighlightKind.Text. DocumentHighlightKind kind = DocumentHighlightKind::Text; friend bool operator<(const DocumentHighlight &LHS, const DocumentHighlight &RHS) { int LHSKind = static_cast<int>(LHS.kind); int RHSKind = static_cast<int>(RHS.kind); return std::tie(LHS.range, LHSKind) < std::tie(RHS.range, RHSKind); } friend bool operator==(const DocumentHighlight &LHS, const DocumentHighlight &RHS) { return LHS.kind == RHS.kind && LHS.range == RHS.range; } }; llvm::json::Value toJSON(const DocumentHighlight &DH); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DocumentHighlight &); enum class TypeHierarchyDirection { Children = 0, Parents = 1, Both = 2 }; bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out); /// The type hierarchy params is an extension of the /// `TextDocumentPositionsParams` with optional properties which can be used to /// eagerly resolve the item when requesting from the server. struct TypeHierarchyParams : public TextDocumentPositionParams { /// The hierarchy levels to resolve. `0` indicates no level. int resolve = 0; /// The direction of the hierarchy levels to resolve. TypeHierarchyDirection direction = TypeHierarchyDirection::Parents; }; bool fromJSON(const llvm::json::Value &, TypeHierarchyParams &); struct TypeHierarchyItem { /// The human readable name of the hierarchy item. std::string name; /// Optional detail for the hierarchy item. It can be, for instance, the /// signature of a function or method. llvm::Optional<std::string> detail; /// The kind of the hierarchy item. For instance, class or interface. SymbolKind kind; /// `true` if the hierarchy item is deprecated. Otherwise, `false`. bool deprecated = false; /// The URI of the text document where this type hierarchy item belongs to. URIForFile uri; /// The range enclosing this type hierarchy item not including /// leading/trailing whitespace but everything else like comments. This /// information is typically used to determine if the client's cursor is /// inside the type hierarch item to reveal in the symbol in the UI. Range range; /// The range that should be selected and revealed when this type hierarchy /// item is being picked, e.g. the name of a function. Must be contained by /// the `range`. Range selectionRange; /// If this type hierarchy item is resolved, it contains the direct parents. /// Could be empty if the item does not have direct parents. If not defined, /// the parents have not been resolved yet. llvm::Optional<std::vector<TypeHierarchyItem>> parents; /// If this type hierarchy item is resolved, it contains the direct children /// of the current item. Could be empty if the item does not have any /// descendants. If not defined, the children have not been resolved. llvm::Optional<std::vector<TypeHierarchyItem>> children; /// An optional 'data' filed, which can be used to identify a type hierarchy /// item in a resolve request. llvm::Optional<std::string> data; }; llvm::json::Value toJSON(const TypeHierarchyItem &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TypeHierarchyItem &); bool fromJSON(const llvm::json::Value &, TypeHierarchyItem &); /// Parameters for the `typeHierarchy/resolve` request. struct ResolveTypeHierarchyItemParams { /// The item to resolve. TypeHierarchyItem item; /// The hierarchy levels to resolve. `0` indicates no level. int resolve; /// The direction of the hierarchy levels to resolve. TypeHierarchyDirection direction; }; bool fromJSON(const llvm::json::Value &, ResolveTypeHierarchyItemParams &); struct ReferenceParams : public TextDocumentPositionParams { // For now, no options like context.includeDeclaration are supported. }; bool fromJSON(const llvm::json::Value &, ReferenceParams &); /// Clangd extension: indicates the current state of the file in clangd, /// sent from server via the `textDocument/clangd.fileStatus` notification. struct FileStatus { /// The text document's URI. URIForFile uri; /// The human-readable string presents the current state of the file, can be /// shown in the UI (e.g. status bar). std::string state; // FIXME: add detail messages. }; llvm::json::Value toJSON(const FileStatus &FStatus); /// Represents a semantic highlighting information that has to be applied on a /// specific line of the text document. struct SemanticHighlightingInformation { /// The line these highlightings belong to. int Line = 0; /// The base64 encoded string of highlighting tokens. std::string Tokens; /// Is the line in an inactive preprocessor branch? /// This is a clangd extension. /// An inactive line can still contain highlighting tokens as well; /// clients should combine line style and token style if possible. bool IsInactive = false; }; bool operator==(const SemanticHighlightingInformation &Lhs, const SemanticHighlightingInformation &Rhs); llvm::json::Value toJSON(const SemanticHighlightingInformation &Highlighting); /// Parameters for the semantic highlighting (server-side) push notification. struct SemanticHighlightingParams { /// The textdocument these highlightings belong to. TextDocumentIdentifier TextDocument; /// The lines of highlightings that should be sent. std::vector<SemanticHighlightingInformation> Lines; }; llvm::json::Value toJSON(const SemanticHighlightingParams &Highlighting); struct SelectionRangeParams { /// The text document. TextDocumentIdentifier textDocument; /// The positions inside the text document. std::vector<Position> positions; }; bool fromJSON(const llvm::json::Value &, SelectionRangeParams &); struct SelectionRange { /** * The range of this selection range. */ Range range; /** * The parent selection range containing this range. Therefore `parent.range` * must contain `this.range`. */ std::unique_ptr<SelectionRange> parent; }; llvm::json::Value toJSON(const SelectionRange &); /// Parameters for the document link request. struct DocumentLinkParams { /// The document to provide document links for. TextDocumentIdentifier textDocument; }; bool fromJSON(const llvm::json::Value &, DocumentLinkParams &); /// A range in a text document that links to an internal or external resource, /// like another text document or a web site. struct DocumentLink { /// The range this link applies to. Range range; /// The uri this link points to. If missing a resolve request is sent later. URIForFile target; // TODO(forster): The following optional fields defined by the language // server protocol are unsupported: // // data?: any - A data entry field that is preserved on a document link // between a DocumentLinkRequest and a // DocumentLinkResolveRequest. friend bool operator==(const DocumentLink &LHS, const DocumentLink &RHS) { return LHS.range == RHS.range && LHS.target == RHS.target; } friend bool operator!=(const DocumentLink &LHS, const DocumentLink &RHS) { return !(LHS == RHS); } }; llvm::json::Value toJSON(const DocumentLink &DocumentLink); } // namespace clangd } // namespace clang namespace llvm { template <> struct format_provider<clang::clangd::Position> { static void format(const clang::clangd::Position &Pos, raw_ostream &OS, StringRef Style) { assert(Style.empty() && "style modifiers for this type are not supported"); OS << Pos; } }; } // namespace llvm #endif
[ "ananth.durbha@getcruise.com" ]
ananth.durbha@getcruise.com
b97ba983209896cfc09fe461e3e21118e33bf955
7e3b429db7c3c16684897e41146a99c27335e424
/Algorithms/DP/DPAgain/Addit/VerticalOrderTravusingmap.cpp
a9eac842a5c80d11570bda0f2fe32d7bfa6d8858
[]
no_license
kailasspawar/DS-ALGO-PROGRAMS
21d2ef01bbbcc82d3894ceb48104620b79cd387e
4ae363d1d51406248b8afb38347c3e4cd92af5c3
refs/heads/master
2020-04-05T20:48:26.510384
2018-11-12T10:28:11
2018-11-12T10:28:11
157,195,857
0
0
null
null
null
null
UTF-8
C++
false
false
916
cpp
#include<iostream> #include"bst.h" #include<map> #include<vector> using namespace std; void verticalOrder(bnode root,int hd,map<int,vector<int> >&m) { if(!root) return; m[hd].push_back(root->data); verticalOrder(root->left,hd-1,m); verticalOrder(root->right,hd+1,m); } void printVertical(bnode root,map<int,vector<int> >&m) { for(auto itr = m.begin();itr!=m.end();itr++) { for(auto it = itr->second.begin();it!=itr->second.end();it++) cout<<*it<<" "; cout<<endl; } } void vertical(bnode root) { map<int,vector<int> >m; verticalOrder(root,0,m); printVertical(root,m); } int main() { bnode root = newNode(10); root->left = newNode(9); root->left->left = newNode(7); root->left->right = newNode(5); root->right = newNode(8); root->right->left = newNode(3); root->right->left->right = newNode(11); root->right->right = newNode(2); vertical(root); return 0; }
[ "kailas462@gmail.com" ]
kailas462@gmail.com
ccc3b203a1195d126107413532ede8866f92536e
1315da08233b6a5ed4079c8035a069844d222633
/extensions/glTFLoader/glTFLoader/tiny_gltf.h
7f0f489dce5237eee0f8f912259db938c9389ff2
[]
no_license
favcode/Bifrost3D
7093a1ea6d3659a78bd60f3a05941bf3c7180bbc
9be8d66be963c4a9e93dcc380aed1c3d8a967d24
refs/heads/master
2023-01-04T00:47:42.548085
2020-10-25T19:10:14
2020-10-25T19:10:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
165,792
h
// // Header-only tiny glTF 2.0 loader and serializer. // // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Syoyo Fujita, Aurélien Chatelain and many // contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Version: // - v2.2.0 Add loading 16bit PNG support. Add Sparse accessor support(Thanks // to @Ybalrid) // - v2.1.0 Add draco compression. // - v2.0.1 Add comparsion feature(Thanks to @Selmar). // - v2.0.0 glTF 2.0!. // // Tiny glTF loader is using following third party libraries: // // - jsonhpp: C++ JSON library. // - base64: base64 decode/encode library. // - stb_image: Image loading library. // #ifndef TINY_GLTF_H_ #define TINY_GLTF_H_ #include <array> #include <cassert> #include <cstdint> #include <cstdlib> #include <cstring> #include <map> #include <string> #include <vector> #ifdef __ANDROID__ #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS #include <android/asset_manager.h> #endif #endif namespace tinygltf { #define TINYGLTF_MODE_POINTS (0) #define TINYGLTF_MODE_LINE (1) #define TINYGLTF_MODE_LINE_LOOP (2) #define TINYGLTF_MODE_LINE_STRIP (3) #define TINYGLTF_MODE_TRIANGLES (4) #define TINYGLTF_MODE_TRIANGLE_STRIP (5) #define TINYGLTF_MODE_TRIANGLE_FAN (6) #define TINYGLTF_COMPONENT_TYPE_BYTE (5120) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_COMPONENT_TYPE_SHORT (5122) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123) #define TINYGLTF_COMPONENT_TYPE_INT (5124) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125) #define TINYGLTF_COMPONENT_TYPE_FLOAT (5126) #define TINYGLTF_COMPONENT_TYPE_DOUBLE (5130) #define TINYGLTF_TEXTURE_FILTER_NEAREST (9728) #define TINYGLTF_TEXTURE_FILTER_LINEAR (9729) #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984) #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985) #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986) #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987) #define TINYGLTF_TEXTURE_WRAP_REPEAT (10497) #define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071) #define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648) // Redeclarations of the above for technique.parameters. #define TINYGLTF_PARAMETER_TYPE_BYTE (5120) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_PARAMETER_TYPE_SHORT (5122) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123) #define TINYGLTF_PARAMETER_TYPE_INT (5124) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125) #define TINYGLTF_PARAMETER_TYPE_FLOAT (5126) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666) #define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667) #define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668) #define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669) #define TINYGLTF_PARAMETER_TYPE_BOOL (35670) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676) #define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678) // End parameter types #define TINYGLTF_TYPE_VEC2 (2) #define TINYGLTF_TYPE_VEC3 (3) #define TINYGLTF_TYPE_VEC4 (4) #define TINYGLTF_TYPE_MAT2 (32 + 2) #define TINYGLTF_TYPE_MAT3 (32 + 3) #define TINYGLTF_TYPE_MAT4 (32 + 4) #define TINYGLTF_TYPE_SCALAR (64 + 1) #define TINYGLTF_TYPE_VECTOR (64 + 4) #define TINYGLTF_TYPE_MATRIX (64 + 16) #define TINYGLTF_IMAGE_FORMAT_JPEG (0) #define TINYGLTF_IMAGE_FORMAT_PNG (1) #define TINYGLTF_IMAGE_FORMAT_BMP (2) #define TINYGLTF_IMAGE_FORMAT_GIF (3) #define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406) #define TINYGLTF_TEXTURE_FORMAT_RGB (6407) #define TINYGLTF_TEXTURE_FORMAT_RGBA (6408) #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409) #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410) #define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553) #define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_TARGET_ARRAY_BUFFER (34962) #define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963) #define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633) #define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632) #define TINYGLTF_DOUBLE_EPS (1.e-12) #define TINYGLTF_DOUBLE_EQUAL(a, b) (std::fabs((b) - (a)) < TINYGLTF_DOUBLE_EPS) #ifdef __ANDROID__ #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS AAssetManager *asset_manager = nullptr; #endif #endif typedef enum { NULL_TYPE = 0, NUMBER_TYPE = 1, INT_TYPE = 2, BOOL_TYPE = 3, STRING_TYPE = 4, ARRAY_TYPE = 5, BINARY_TYPE = 6, OBJECT_TYPE = 7 } Type; static inline int32_t GetComponentSizeInBytes(uint32_t componentType) { if (componentType == TINYGLTF_COMPONENT_TYPE_BYTE) { return 1; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) { return 1; } else if (componentType == TINYGLTF_COMPONENT_TYPE_SHORT) { return 2; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) { return 2; } else if (componentType == TINYGLTF_COMPONENT_TYPE_INT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE) { return 8; } else { // Unknown componenty type return -1; } } static inline int32_t GetTypeSizeInBytes(uint32_t ty) { if (ty == TINYGLTF_TYPE_SCALAR) { return 1; } else if (ty == TINYGLTF_TYPE_VEC2) { return 2; } else if (ty == TINYGLTF_TYPE_VEC3) { return 3; } else if (ty == TINYGLTF_TYPE_VEC4) { return 4; } else if (ty == TINYGLTF_TYPE_MAT2) { return 4; } else if (ty == TINYGLTF_TYPE_MAT3) { return 9; } else if (ty == TINYGLTF_TYPE_MAT4) { return 16; } else { // Unknown componenty type return -1; } } bool IsDataURI(const std::string &in); bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type, const std::string &in, size_t reqBytes, bool checkSize); #ifdef __clang__ #pragma clang diagnostic push // Suppress warning for : static Value null_value // https://stackoverflow.com/questions/15708411/how-to-deal-with-global-constructor-warning-in-clang #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wpadded" #endif // Simple class to represent JSON object class Value { public: typedef std::vector<Value> Array; typedef std::map<std::string, Value> Object; Value() : type_(NULL_TYPE) {} explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; } explicit Value(int i) : type_(INT_TYPE) { int_value_ = i; } explicit Value(double n) : type_(NUMBER_TYPE) { number_value_ = n; } explicit Value(const std::string &s) : type_(STRING_TYPE) { string_value_ = s; } explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) { binary_value_.resize(n); memcpy(binary_value_.data(), p, n); } explicit Value(const Array &a) : type_(ARRAY_TYPE) { array_value_ = Array(a); } explicit Value(const Object &o) : type_(OBJECT_TYPE) { object_value_ = Object(o); } char Type() const { return static_cast<const char>(type_); } bool IsBool() const { return (type_ == BOOL_TYPE); } bool IsInt() const { return (type_ == INT_TYPE); } bool IsNumber() const { return (type_ == NUMBER_TYPE); } bool IsString() const { return (type_ == STRING_TYPE); } bool IsBinary() const { return (type_ == BINARY_TYPE); } bool IsArray() const { return (type_ == ARRAY_TYPE); } bool IsObject() const { return (type_ == OBJECT_TYPE); } // Accessor template <typename T> const T &Get() const; template <typename T> T &Get(); // Lookup value from an array const Value &Get(int idx) const { static Value null_value; assert(IsArray()); assert(idx >= 0); return (static_cast<size_t>(idx) < array_value_.size()) ? array_value_[static_cast<size_t>(idx)] : null_value; } // Lookup value from a key-value pair const Value &Get(const std::string &key) const { static Value null_value; assert(IsObject()); Object::const_iterator it = object_value_.find(key); return (it != object_value_.end()) ? it->second : null_value; } size_t ArrayLen() const { if (!IsArray()) return 0; return array_value_.size(); } // Valid only for object type. bool Has(const std::string &key) const { if (!IsObject()) return false; Object::const_iterator it = object_value_.find(key); return (it != object_value_.end()) ? true : false; } // List keys std::vector<std::string> Keys() const { std::vector<std::string> keys; if (!IsObject()) return keys; // empty for (Object::const_iterator it = object_value_.begin(); it != object_value_.end(); ++it) { keys.push_back(it->first); } return keys; } size_t Size() const { return (IsArray() ? ArrayLen() : Keys().size()); } bool operator==(const tinygltf::Value &other) const; protected: int type_; int int_value_; double number_value_; std::string string_value_; std::vector<unsigned char> binary_value_; Array array_value_; Object object_value_; bool boolean_value_; }; #ifdef __clang__ #pragma clang diagnostic pop #endif #define TINYGLTF_VALUE_GET(ctype, var) \ template <> \ inline const ctype &Value::Get<ctype>() const { \ return var; \ } \ template <> \ inline ctype &Value::Get<ctype>() { \ return var; \ } TINYGLTF_VALUE_GET(bool, boolean_value_) TINYGLTF_VALUE_GET(double, number_value_) TINYGLTF_VALUE_GET(int, int_value_) TINYGLTF_VALUE_GET(std::string, string_value_) TINYGLTF_VALUE_GET(std::vector<unsigned char>, binary_value_) TINYGLTF_VALUE_GET(Value::Array, array_value_) TINYGLTF_VALUE_GET(Value::Object, object_value_) #undef TINYGLTF_VALUE_GET #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #pragma clang diagnostic ignored "-Wpadded" #endif /// Agregate object for representing a color using ColorValue = std::array<double, 4>; struct Parameter { bool bool_value = false; bool has_number_value = false; std::string string_value; std::vector<double> number_array; std::map<std::string, double> json_double_value; double number_value = 0.0; // context sensitive methods. depending the type of the Parameter you are // accessing, these are either valid or not // If this parameter represent a texture map in a material, will return the // texture index /// Return the index of a texture if this Parameter is a texture map. /// Returned value is only valid if the parameter represent a texture from a /// material int TextureIndex() const { const auto it = json_double_value.find("index"); if (it != std::end(json_double_value)) { return int(it->second); } return -1; } /// Return the index of a texture coordinate set if this Parameter is a /// texture map. Returned value is only valid if the parameter represent a /// texture from a material int TextureTexCoord() const { const auto it = json_double_value.find("texCoord"); if (it != std::end(json_double_value)) { return int(it->second); } // As per the spec, if texCoord is ommited, this parameter is 0 return 0; } /// Return the scale of a texture if this Parameter is a normal texture map. /// Returned value is only valid if the parameter represent a normal texture /// from a material double TextureScale() const { const auto it = json_double_value.find("scale"); if (it != std::end(json_double_value)) { return it->second; } // As per the spec, if scale is ommited, this paramter is 1 return 1; } /// Return the strength of a texture if this Parameter is a an occlusion map. /// Returned value is only valid if the parameter represent an occlusion map /// from a material double TextureStrength() const { const auto it = json_double_value.find("strength"); if (it != std::end(json_double_value)) { return it->second; } // As per the spec, if strenghth is ommited, this parameter is 1 return 1; } /// Material factor, like the roughness or metalness of a material /// Returned value is only valid if the parameter represent a texture from a /// material double Factor() const { return number_value; } /// Return the color of a material /// Returned value is only valid if the parameter represent a texture from a /// material ColorValue ColorFactor() const { return { {// this agregate intialize the std::array object, and uses C++11 RVO. number_array[0], number_array[1], number_array[2], (number_array.size() > 3 ? number_array[3] : 1.0)}}; } bool operator==(const Parameter &) const; }; #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif typedef std::map<std::string, Parameter> ParameterMap; typedef std::map<std::string, Value> ExtensionMap; struct AnimationChannel { int sampler; // required int target_node; // required (index of the node to target) std::string target_path; // required in ["translation", "rotation", "scale", // "weights"] Value extras; AnimationChannel() : sampler(-1), target_node(-1) {} bool operator==(const AnimationChannel &) const; }; struct AnimationSampler { int input; // required int output; // required std::string interpolation; // "LINEAR", "STEP","CUBICSPLINE" or user defined // string. default "LINEAR" Value extras; AnimationSampler() : input(-1), output(-1), interpolation("LINEAR") {} bool operator==(const AnimationSampler &) const; }; struct Animation { std::string name; std::vector<AnimationChannel> channels; std::vector<AnimationSampler> samplers; Value extras; bool operator==(const Animation &) const; }; struct Skin { std::string name; int inverseBindMatrices; // required here but not in the spec int skeleton; // The index of the node used as a skeleton root std::vector<int> joints; // Indices of skeleton nodes Skin() { inverseBindMatrices = -1; skeleton = -1; } bool operator==(const Skin &) const; }; struct Sampler { std::string name; int minFilter; // ["NEAREST", "LINEAR", "NEAREST_MIPMAP_LINEAR", // "LINEAR_MIPMAP_NEAREST", "NEAREST_MIPMAP_LINEAR", // "LINEAR_MIPMAP_LINEAR"] int magFilter; // ["NEAREST", "LINEAR"] int wrapS; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default // "REPEAT" int wrapT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default // "REPEAT" int wrapR; // TinyGLTF extension Value extras; Sampler() : minFilter(TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR), magFilter(TINYGLTF_TEXTURE_FILTER_LINEAR), wrapS(TINYGLTF_TEXTURE_WRAP_REPEAT), wrapT(TINYGLTF_TEXTURE_WRAP_REPEAT), wrapR(TINYGLTF_TEXTURE_WRAP_REPEAT) {} bool operator==(const Sampler &) const; }; struct Image { std::string name; int width; int height; int component; int bits; // bit depth per channel. 8(byte), 16 or 32. int pixel_type; // pixel type(TINYGLTF_COMPONENT_TYPE_***). usually // UBYTE(bits = 8) or USHORT(bits = 16) std::vector<unsigned char> image; int bufferView; // (required if no uri) std::string mimeType; // (required if no uri) ["image/jpeg", "image/png", // "image/bmp", "image/gif"] std::string uri; // (required if no mimeType) Value extras; ExtensionMap extensions; // When this flag is true, data is stored to `image` in as-is format(e.g. jpeg // compressed for "image/jpeg" mime) This feature is good if you use custom // image loader function. (e.g. delayed decoding of images for faster glTF // parsing) Default parser for Image does not provide as-is loading feature at // the moment. (You can manipulate this by providing your own LoadImageData // function) bool as_is; Image() : as_is(false) { bufferView = -1; width = -1; height = -1; component = -1; } bool operator==(const Image &) const; }; struct Texture { std::string name; int sampler; int source; Value extras; ExtensionMap extensions; Texture() : sampler(-1), source(-1) {} bool operator==(const Texture &) const; }; // Each extension should be stored in a ParameterMap. // members not in the values could be included in the ParameterMap // to keep a single material model struct Material { std::string name; ParameterMap values; // PBR metal/roughness workflow ParameterMap additionalValues; // normal/occlusion/emissive values ExtensionMap extensions; Value extras; bool operator==(const Material &) const; }; struct BufferView { std::string name; int buffer; // Required size_t byteOffset; // minimum 0, default 0 size_t byteLength; // required, minimum 1 size_t byteStride; // minimum 4, maximum 252 (multiple of 4), default 0 = // understood to be tightly packed int target; // ["ARRAY_BUFFER", "ELEMENT_ARRAY_BUFFER"] Value extras; bool dracoDecoded; // Flag indicating this has been draco decoded BufferView() : byteOffset(0), byteStride(0), dracoDecoded(false) {} bool operator==(const BufferView &) const; }; struct Accessor { int bufferView; // optional in spec but required here since sparse accessor // are not supported std::string name; size_t byteOffset; bool normalized; // optional. int componentType; // (required) One of TINYGLTF_COMPONENT_TYPE_*** size_t count; // required int type; // (required) One of TINYGLTF_TYPE_*** .. Value extras; std::vector<double> minValues; // optional std::vector<double> maxValues; // optional struct { int count; bool isSparse; struct { int byteOffset; int bufferView; int componentType; // a TINYGLTF_COMPONENT_TYPE_ value } indices; struct { int bufferView; int byteOffset; } values; } sparse; /// /// Utility function to compute byteStride for a given bufferView object. /// Returns -1 upon invalid glTF value or parameter configuration. /// int ByteStride(const BufferView &bufferViewObject) const { if (bufferViewObject.byteStride == 0) { // Assume data is tightly packed. int componentSizeInBytes = GetComponentSizeInBytes(static_cast<uint32_t>(componentType)); if (componentSizeInBytes <= 0) { return -1; } int typeSizeInBytes = GetTypeSizeInBytes(static_cast<uint32_t>(type)); if (typeSizeInBytes <= 0) { return -1; } return componentSizeInBytes * typeSizeInBytes; } else { // Check if byteStride is a mulple of the size of the accessor's component // type. int componentSizeInBytes = GetComponentSizeInBytes(static_cast<uint32_t>(componentType)); if (componentSizeInBytes <= 0) { return -1; } if ((bufferViewObject.byteStride % uint32_t(componentSizeInBytes)) != 0) { return -1; } return static_cast<int>(bufferViewObject.byteStride); } return 0; } Accessor() { bufferView = -1; sparse.isSparse = false; } bool operator==(const tinygltf::Accessor &) const; }; struct PerspectiveCamera { double aspectRatio; // min > 0 double yfov; // required. min > 0 double zfar; // min > 0 double znear; // required. min > 0 PerspectiveCamera() : aspectRatio(0.0), yfov(0.0), zfar(0.0) // 0 = use infinite projecton matrix , znear(0.0) {} bool operator==(const PerspectiveCamera &) const; ExtensionMap extensions; Value extras; }; struct OrthographicCamera { double xmag; // required. must not be zero. double ymag; // required. must not be zero. double zfar; // required. `zfar` must be greater than `znear`. double znear; // required OrthographicCamera() : xmag(0.0), ymag(0.0), zfar(0.0), znear(0.0) {} bool operator==(const OrthographicCamera &) const; ExtensionMap extensions; Value extras; }; struct Camera { std::string type; // required. "perspective" or "orthographic" std::string name; PerspectiveCamera perspective; OrthographicCamera orthographic; Camera() {} bool operator==(const Camera &) const; ExtensionMap extensions; Value extras; }; struct Primitive { std::map<std::string, int> attributes; // (required) A dictionary object of // integer, where each integer // is the index of the accessor // containing an attribute. int material; // The index of the material to apply to this primitive // when rendering. int indices; // The index of the accessor that contains the indices. int mode; // one of TINYGLTF_MODE_*** std::vector<std::map<std::string, int> > targets; // array of morph targets, // where each target is a dict with attribues in ["POSITION, "NORMAL", // "TANGENT"] pointing // to their corresponding accessors ExtensionMap extensions; Value extras; Primitive() { material = -1; indices = -1; } bool operator==(const Primitive &) const; }; struct Mesh { std::string name; std::vector<Primitive> primitives; std::vector<double> weights; // weights to be applied to the Morph Targets ExtensionMap extensions; Value extras; bool operator==(const Mesh &) const; }; class Node { public: Node() : camera(-1), skin(-1), mesh(-1) {} // TODO(syoyo): Could use `default` Node(const Node &rhs) { camera = rhs.camera; name = rhs.name; skin = rhs.skin; mesh = rhs.mesh; children = rhs.children; rotation = rhs.rotation; scale = rhs.scale; translation = rhs.translation; matrix = rhs.matrix; weights = rhs.weights; extensions = rhs.extensions; extras = rhs.extras; } ~Node() {} Node &operator=(const Node &rhs) = default; bool operator==(const Node &) const; int camera; // the index of the camera referenced by this node std::string name; int skin; int mesh; std::vector<int> children; std::vector<double> rotation; // length must be 0 or 4 std::vector<double> scale; // length must be 0 or 3 std::vector<double> translation; // length must be 0 or 3 std::vector<double> matrix; // length must be 0 or 16 std::vector<double> weights; // The weights of the instantiated Morph Target ExtensionMap extensions; Value extras; }; struct Buffer { std::string name; std::vector<unsigned char> data; std::string uri; // considered as required here but not in the spec (need to clarify) Value extras; bool operator==(const Buffer &) const; }; struct Asset { std::string version; // required std::string generator; std::string minVersion; std::string copyright; ExtensionMap extensions; Value extras; bool operator==(const Asset &) const; }; struct Scene { std::string name; std::vector<int> nodes; ExtensionMap extensions; Value extras; bool operator==(const Scene &) const; }; struct Light { std::string name; std::vector<double> color; std::string type; bool operator==(const Light &) const; }; class Model { public: Model() {} Model(const Model &) = default; Model &operator=(const Model &) = default; ~Model() {} bool operator==(const Model &) const; std::vector<Accessor> accessors; std::vector<Animation> animations; std::vector<Buffer> buffers; std::vector<BufferView> bufferViews; std::vector<Material> materials; std::vector<Mesh> meshes; std::vector<Node> nodes; std::vector<Texture> textures; std::vector<Image> images; std::vector<Skin> skins; std::vector<Sampler> samplers; std::vector<Camera> cameras; std::vector<Scene> scenes; std::vector<Light> lights; ExtensionMap extensions; int defaultScene; std::vector<std::string> extensionsUsed; std::vector<std::string> extensionsRequired; Asset asset; Value extras; }; enum SectionCheck { NO_REQUIRE = 0x00, REQUIRE_VERSION = 0x01, REQUIRE_SCENE = 0x02, REQUIRE_SCENES = 0x04, REQUIRE_NODES = 0x08, REQUIRE_ACCESSORS = 0x10, REQUIRE_BUFFERS = 0x20, REQUIRE_BUFFER_VIEWS = 0x40, REQUIRE_ALL = 0x7f }; /// /// LoadImageDataFunction type. Signature for custom image loading callbacks. /// typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *, std::string *, int, int, const unsigned char *, int, void *); /// /// WriteImageDataFunction type. Signature for custom image writing callbacks. /// typedef bool (*WriteImageDataFunction)(const std::string *, const std::string *, Image *, bool, void *); #ifndef TINYGLTF_NO_STB_IMAGE // Declaration of default image loader callback bool LoadImageData(Image *image, const int image_idx, std::string *err, std::string *warn, int req_width, int req_height, const unsigned char *bytes, int size, void *); #endif #ifndef TINYGLTF_NO_STB_IMAGE_WRITE // Declaration of default image writer callback bool WriteImageData(const std::string *basepath, const std::string *filename, Image *image, bool embedImages, void *); #endif /// /// FilExistsFunction type. Signature for custom filesystem callbacks. /// typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *); /// /// ExpandFilePathFunction type. Signature for custom filesystem callbacks. /// typedef std::string (*ExpandFilePathFunction)(const std::string &, void *); /// /// ReadWholeFileFunction type. Signature for custom filesystem callbacks. /// typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *, std::string *, const std::string &, void *); /// /// WriteWholeFileFunction type. Signature for custom filesystem callbacks. /// typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &, const std::vector<unsigned char> &, void *); /// /// A structure containing all required filesystem callbacks and a pointer to /// their user data. /// struct FsCallbacks { FileExistsFunction FileExists; ExpandFilePathFunction ExpandFilePath; ReadWholeFileFunction ReadWholeFile; WriteWholeFileFunction WriteWholeFile; void *user_data; // An argument that is passed to all fs callbacks }; #ifndef TINYGLTF_NO_FS // Declaration of default filesystem callbacks bool FileExists(const std::string &abs_filename, void *); std::string ExpandFilePath(const std::string &filepath, void *); bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err, const std::string &filepath, void *); bool WriteWholeFile(std::string *err, const std::string &filepath, const std::vector<unsigned char> &contents, void *); #endif class TinyGLTF { public: #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #endif TinyGLTF() : bin_data_(nullptr), bin_size_(0), is_binary_(false) {} #ifdef __clang__ #pragma clang diagnostic pop #endif ~TinyGLTF() {} /// /// Loads glTF ASCII asset from a file. /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadASCIIFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF ASCII asset from string(memory). /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadASCIIFromString(Model *model, std::string *err, std::string *warn, const char *str, const unsigned int length, const std::string &base_dir, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF binary asset from a file. /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadBinaryFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF binary asset from memory. /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn, const unsigned char *bytes, const unsigned int length, const std::string &base_dir = "", unsigned int check_sections = REQUIRE_VERSION); /// /// Write glTF to file. /// bool WriteGltfSceneToFile(Model *model, const std::string &filename, bool embedImages, bool embedBuffers, bool prettyPrint, bool writeBinary); /// /// Set callback to use for loading image data /// void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data); /// /// Set callback to use for writing image data /// void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data); /// /// Set callbacks to use for filesystem (fs) access and their user data /// void SetFsCallbacks(FsCallbacks callbacks); private: /// /// Loads glTF asset from string(memory). /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts /// Returns false and set error string to `err` if there's an error. /// bool LoadFromString(Model *model, std::string *err, std::string *warn, const char *str, const unsigned int length, const std::string &base_dir, unsigned int check_sections); const unsigned char *bin_data_; size_t bin_size_; bool is_binary_; FsCallbacks fs = { #ifndef TINYGLTF_NO_FS &tinygltf::FileExists, &tinygltf::ExpandFilePath, &tinygltf::ReadWholeFile, &tinygltf::WriteWholeFile, nullptr // Fs callback user data #else nullptr, nullptr, nullptr, nullptr, nullptr // Fs callback user data #endif }; LoadImageDataFunction LoadImageData = #ifndef TINYGLTF_NO_STB_IMAGE &tinygltf::LoadImageData; #else nullptr; #endif void *load_image_user_data_ = reinterpret_cast<void *>(&fs); WriteImageDataFunction WriteImageData = #ifndef TINYGLTF_NO_STB_IMAGE_WRITE &tinygltf::WriteImageData; #else nullptr; #endif void *write_image_user_data_ = reinterpret_cast<void *>(&fs); }; #ifdef __clang__ #pragma clang diagnostic pop // -Wpadded #endif } // namespace tinygltf #endif // TINY_GLTF_H_ #if defined(TINYGLTF_IMPLEMENTATION) || defined(__INTELLISENSE__) #include <algorithm> //#include <cassert> #ifndef TINYGLTF_NO_FS #include <fstream> #endif #include <sstream> #ifdef __clang__ // Disable some warnings for external files. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wfloat-equal" #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wc++98-compat" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #pragma clang diagnostic ignored "-Wswitch-enum" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #pragma clang diagnostic ignored "-Wweak-vtables" #pragma clang diagnostic ignored "-Wcovered-switch-default" #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" #endif #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wmissing-variable-declarations") #pragma clang diagnostic ignored "-Wmissing-variable-declarations" #endif #if __has_warning("-Wmissing-prototypes") #pragma clang diagnostic ignored "-Wmissing-prototypes" #endif #if __has_warning("-Wcast-align") #pragma clang diagnostic ignored "-Wcast-align" #endif #if __has_warning("-Wnewline-eof") #pragma clang diagnostic ignored "-Wnewline-eof" #endif #if __has_warning("-Wunused-parameter") #pragma clang diagnostic ignored "-Wunused-parameter" #endif #if __has_warning("-Wmismatched-tags") #pragma clang diagnostic ignored "-Wmismatched-tags" #endif #endif // Disable GCC warnigs #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" #endif // __GNUC__ #ifndef TINYGLTF_NO_INCLUDE_JSON #include "json.hpp" #endif #ifdef TINYGLTF_ENABLE_DRACO #include "draco/compression/decode.h" #include "draco/core/decoder_buffer.h" #endif #ifndef TINYGLTF_NO_STB_IMAGE #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE #include "stb_image.h" #endif #endif #ifndef TINYGLTF_NO_STB_IMAGE_WRITE #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE #include "stb_image_write.h" #endif #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef _WIN32 // issue 143. // Define NOMINMAX to avoid min/max defines, // but undef it after included windows.h #ifndef NOMINMAX #define TINYGLTF_INTERNAL_NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN #endif #include <windows.h> // include API for expanding a file path #ifdef TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #endif #if defined(TINYGLTF_INTERNAL_NOMINMAX) #undef NOMINMAX #endif #elif !defined(__ANDROID__) #include <wordexp.h> #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU #define TINYGLTF_LITTLE_ENDIAN 1 #endif #endif using nlohmann::json; #ifdef __APPLE__ #include "TargetConditionals.h" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #endif namespace tinygltf { // Equals function for Value, for recursivity static bool Equals(const tinygltf::Value &one, const tinygltf::Value &other) { if (one.Type() != other.Type()) return false; switch (one.Type()) { case NULL_TYPE: return true; case BOOL_TYPE: return one.Get<bool>() == other.Get<bool>(); case NUMBER_TYPE: return TINYGLTF_DOUBLE_EQUAL(one.Get<double>(), other.Get<double>()); case INT_TYPE: return one.Get<int>() == other.Get<int>(); case OBJECT_TYPE: { auto oneObj = one.Get<tinygltf::Value::Object>(); auto otherObj = other.Get<tinygltf::Value::Object>(); if (oneObj.size() != otherObj.size()) return false; for (auto &it : oneObj) { auto otherIt = otherObj.find(it.first); if (otherIt == otherObj.end()) return false; if (!Equals(it.second, otherIt->second)) return false; } return true; } case ARRAY_TYPE: { if (one.Size() != other.Size()) return false; for (int i = 0; i < int(one.Size()); ++i) if (!Equals(one.Get(i), other.Get(i))) return false; return true; } case STRING_TYPE: return one.Get<std::string>() == other.Get<std::string>(); case BINARY_TYPE: return one.Get<std::vector<unsigned char> >() == other.Get<std::vector<unsigned char> >(); default: { // unhandled type return false; } } } // Equals function for std::vector<double> using TINYGLTF_DOUBLE_EPSILON static bool Equals(const std::vector<double> &one, const std::vector<double> &other) { if (one.size() != other.size()) return false; for (int i = 0; i < int(one.size()); ++i) { if (!TINYGLTF_DOUBLE_EQUAL(one[size_t(i)], other[size_t(i)])) return false; } return true; } bool Accessor::operator==(const Accessor &other) const { return this->bufferView == other.bufferView && this->byteOffset == other.byteOffset && this->componentType == other.componentType && this->count == other.count && this->extras == other.extras && Equals(this->maxValues, other.maxValues) && Equals(this->minValues, other.minValues) && this->name == other.name && this->normalized == other.normalized && this->type == other.type; } bool Animation::operator==(const Animation &other) const { return this->channels == other.channels && this->extras == other.extras && this->name == other.name && this->samplers == other.samplers; } bool AnimationChannel::operator==(const AnimationChannel &other) const { return this->extras == other.extras && this->target_node == other.target_node && this->target_path == other.target_path && this->sampler == other.sampler; } bool AnimationSampler::operator==(const AnimationSampler &other) const { return this->extras == other.extras && this->input == other.input && this->interpolation == other.interpolation && this->output == other.output; } bool Asset::operator==(const Asset &other) const { return this->copyright == other.copyright && this->extensions == other.extensions && this->extras == other.extras && this->generator == other.generator && this->minVersion == other.minVersion && this->version == other.version; } bool Buffer::operator==(const Buffer &other) const { return this->data == other.data && this->extras == other.extras && this->name == other.name && this->uri == other.uri; } bool BufferView::operator==(const BufferView &other) const { return this->buffer == other.buffer && this->byteLength == other.byteLength && this->byteOffset == other.byteOffset && this->byteStride == other.byteStride && this->name == other.name && this->target == other.target && this->extras == other.extras && this->dracoDecoded == other.dracoDecoded; } bool Camera::operator==(const Camera &other) const { return this->name == other.name && this->extensions == other.extensions && this->extras == other.extras && this->orthographic == other.orthographic && this->perspective == other.perspective && this->type == other.type; } bool Image::operator==(const Image &other) const { return this->bufferView == other.bufferView && this->component == other.component && this->extras == other.extras && this->height == other.height && this->image == other.image && this->mimeType == other.mimeType && this->name == other.name && this->uri == other.uri && this->width == other.width; } bool Light::operator==(const Light &other) const { return Equals(this->color, other.color) && this->name == other.name && this->type == other.type; } bool Material::operator==(const Material &other) const { return this->additionalValues == other.additionalValues && this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->values == other.values; } bool Mesh::operator==(const Mesh &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->primitives == other.primitives; } bool Model::operator==(const Model &other) const { return this->accessors == other.accessors && this->animations == other.animations && this->asset == other.asset && this->buffers == other.buffers && this->bufferViews == other.bufferViews && this->cameras == other.cameras && this->defaultScene == other.defaultScene && this->extensions == other.extensions && this->extensionsRequired == other.extensionsRequired && this->extensionsUsed == other.extensionsUsed && this->extras == other.extras && this->images == other.images && this->lights == other.lights && this->materials == other.materials && this->meshes == other.meshes && this->nodes == other.nodes && this->samplers == other.samplers && this->scenes == other.scenes && this->skins == other.skins && this->textures == other.textures; } bool Node::operator==(const Node &other) const { return this->camera == other.camera && this->children == other.children && this->extensions == other.extensions && this->extras == other.extras && Equals(this->matrix, other.matrix) && this->mesh == other.mesh && this->name == other.name && Equals(this->rotation, other.rotation) && Equals(this->scale, other.scale) && this->skin == other.skin && Equals(this->translation, other.translation) && Equals(this->weights, other.weights); } bool OrthographicCamera::operator==(const OrthographicCamera &other) const { return this->extensions == other.extensions && this->extras == other.extras && TINYGLTF_DOUBLE_EQUAL(this->xmag, other.xmag) && TINYGLTF_DOUBLE_EQUAL(this->ymag, other.ymag) && TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) && TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear); } bool Parameter::operator==(const Parameter &other) const { if (this->bool_value != other.bool_value || this->has_number_value != other.has_number_value) return false; if (!TINYGLTF_DOUBLE_EQUAL(this->number_value, other.number_value)) return false; if (this->json_double_value.size() != other.json_double_value.size()) return false; for (auto &it : this->json_double_value) { auto otherIt = other.json_double_value.find(it.first); if (otherIt == other.json_double_value.end()) return false; if (!TINYGLTF_DOUBLE_EQUAL(it.second, otherIt->second)) return false; } if (!Equals(this->number_array, other.number_array)) return false; if (this->string_value != other.string_value) return false; return true; } bool PerspectiveCamera::operator==(const PerspectiveCamera &other) const { return TINYGLTF_DOUBLE_EQUAL(this->aspectRatio, other.aspectRatio) && this->extensions == other.extensions && this->extras == other.extras && TINYGLTF_DOUBLE_EQUAL(this->yfov, other.yfov) && TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) && TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear); } bool Primitive::operator==(const Primitive &other) const { return this->attributes == other.attributes && this->extras == other.extras && this->indices == other.indices && this->material == other.material && this->mode == other.mode && this->targets == other.targets; } bool Sampler::operator==(const Sampler &other) const { return this->extras == other.extras && this->magFilter == other.magFilter && this->minFilter == other.minFilter && this->name == other.name && this->wrapR == other.wrapR && this->wrapS == other.wrapS && this->wrapT == other.wrapT; } bool Scene::operator==(const Scene &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->nodes == other.nodes; ; } bool Skin::operator==(const Skin &other) const { return this->inverseBindMatrices == other.inverseBindMatrices && this->joints == other.joints && this->name == other.name && this->skeleton == other.skeleton; } bool Texture::operator==(const Texture &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->sampler == other.sampler && this->source == other.source; } bool Value::operator==(const Value &other) const { return Equals(*this, other); } static void swap4(unsigned int *val) { #ifdef TINYGLTF_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static std::string JoinPath(const std::string &path0, const std::string &path1) { if (path0.empty()) { return path1; } else { // check '/' char lastChar = *path0.rbegin(); if (lastChar != '/') { return path0 + std::string("/") + path1; } else { return path0 + path1; } } } static std::string FindFile(const std::vector<std::string> &paths, const std::string &filepath, FsCallbacks *fs) { if (fs == nullptr || fs->ExpandFilePath == nullptr || fs->FileExists == nullptr) { // Error, fs callback[s] missing return std::string(); } for (size_t i = 0; i < paths.size(); i++) { std::string absPath = fs->ExpandFilePath(JoinPath(paths[i], filepath), fs->user_data); if (fs->FileExists(absPath, fs->user_data)) { return absPath; } } return std::string(); } static std::string GetFilePathExtension(const std::string &FileName) { if (FileName.find_last_of(".") != std::string::npos) return FileName.substr(FileName.find_last_of(".") + 1); return ""; } static std::string GetBaseDir(const std::string &filepath) { if (filepath.find_last_of("/\\") != std::string::npos) return filepath.substr(0, filepath.find_last_of("/\\")); return ""; } // https://stackoverflow.com/questions/8520560/get-a-file-name-from-a-path static std::string GetBaseFilename(const std::string &filepath) { return filepath.substr(filepath.find_last_of("/\\") + 1); } std::string base64_encode(unsigned char const *, unsigned int len); std::string base64_decode(std::string const &s); /* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wconversion" #endif static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while ((i++ < 3)) ret += '='; } return ret; } std::string base64_decode(std::string const &encoded_string) { int in_len = static_cast<int>(encoded_string.size()); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i < 4; i++) char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i])); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j < 4; j++) char_array_4[j] = 0; for (j = 0; j < 4; j++) char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j])); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } #ifdef __clang__ #pragma clang diagnostic pop #endif static bool LoadExternalFile(std::vector<unsigned char> *out, std::string *err, std::string *warn, const std::string &filename, const std::string &basedir, bool required, size_t reqBytes, bool checkSize, FsCallbacks *fs) { if (fs == nullptr || fs->FileExists == nullptr || fs->ExpandFilePath == nullptr || fs->ReadWholeFile == nullptr) { // This is a developer error, assert() ? if (err) { (*err) += "FS callback[s] not set\n"; } return false; } std::string *failMsgOut = required ? err : warn; out->clear(); std::vector<std::string> paths; paths.push_back(basedir); paths.push_back("."); std::string filepath = FindFile(paths, filename, fs); if (filepath.empty() || filename.empty()) { if (failMsgOut) { (*failMsgOut) += "File not found : " + filename + "\n"; } return false; } std::vector<unsigned char> buf; std::string fileReadErr; bool fileRead = fs->ReadWholeFile(&buf, &fileReadErr, filepath, fs->user_data); if (!fileRead) { if (failMsgOut) { (*failMsgOut) += "File read error : " + filepath + " : " + fileReadErr + "\n"; } return false; } size_t sz = buf.size(); if (sz == 0) { if (failMsgOut) { (*failMsgOut) += "File is empty : " + filepath + "\n"; } return false; } if (checkSize) { if (reqBytes == sz) { out->swap(buf); return true; } else { std::stringstream ss; ss << "File size mismatch : " << filepath << ", requestedBytes " << reqBytes << ", but got " << sz << std::endl; if (failMsgOut) { (*failMsgOut) += ss.str(); } return false; } } out->swap(buf); return true; } void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) { LoadImageData = func; load_image_user_data_ = user_data; } #ifndef TINYGLTF_NO_STB_IMAGE bool LoadImageData(Image *image, const int image_idx, std::string *err, std::string *warn, int req_width, int req_height, const unsigned char *bytes, int size, void *user_data) { (void)user_data; (void)warn; int w, h, comp, req_comp; unsigned char *data = nullptr; // force 32-bit textures for common Vulkan compatibility. It appears that // some GPU drivers do not support 24-bit images for Vulkan req_comp = 4; int bits = 8; int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE; // It is possible that the image we want to load is a 16bit per channel image // We are going to attempt to load it as 16bit per channel, and if it worked, // set the image data accodingly. We are casting the returned pointer into // unsigned char, because we are representing "bytes". But we are updating // the Image metadata to signal that this image uses 2 bytes (16bits) per // channel: if (stbi_is_16_bit_from_memory(bytes, size)) { data = (unsigned char *)stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp); if (data) { bits = 16; pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT; } } // at this point, if data is still NULL, it means that the image wasn't // 16bit per channel, we are going to load it as a normal 8bit per channel // mage as we used to do: // if image cannot be decoded, ignore parsing and keep it by its path // don't break in this case // FIXME we should only enter this function if the image is embedded. If // image->uri references // an image file, it should be left as it is. Image loading should not be // mandatory (to support other formats) if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp); if (!data) { // NOTE: you can use `warn` instead of `err` if (err) { (*err) += "Unknown image format. STB cannot decode image data for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\".\n"; } return false; } if (w < 1 || h < 1) { stbi_image_free(data); if (err) { (*err) += "Invalid image data for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } if (req_width > 0) { if (req_width != w) { stbi_image_free(data); if (err) { (*err) += "Image width mismatch for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } } if (req_height > 0) { if (req_height != h) { stbi_image_free(data); if (err) { (*err) += "Image height mismatch. for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } } image->width = w; image->height = h; image->component = req_comp; image->bits = bits; image->pixel_type = pixel_type; image->image.resize(static_cast<size_t>(w * h * req_comp) * (bits / 8)); std::copy(data, data + w * h * req_comp * (bits / 8), image->image.begin()); stbi_image_free(data); return true; } #endif void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) { WriteImageData = func; write_image_user_data_ = user_data; } #ifndef TINYGLTF_NO_STB_IMAGE_WRITE static void WriteToMemory_stbi(void *context, void *data, int size) { std::vector<unsigned char> *buffer = reinterpret_cast<std::vector<unsigned char> *>(context); unsigned char *pData = reinterpret_cast<unsigned char *>(data); buffer->insert(buffer->end(), pData, pData + size); } bool WriteImageData(const std::string *basepath, const std::string *filename, Image *image, bool embedImages, void *fsPtr) { const std::string ext = GetFilePathExtension(*filename); // Write image to temporary buffer std::string header; std::vector<unsigned char> data; if (ext == "png") { if ((image->bits != 8) || (image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) { // Unsupported pixel format return false; } if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0], 0)) { return false; } header = "data:image/png;base64,"; } else if (ext == "jpg") { if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0], 100)) { return false; } header = "data:image/jpeg;base64,"; } else if (ext == "bmp") { if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0])) { return false; } header = "data:image/bmp;base64,"; } else if (!embedImages) { // Error: can't output requested format to file return false; } if (embedImages) { // Embed base64-encoded image into URI if (data.size()) { image->uri = header + base64_encode(&data[0], static_cast<unsigned int>(data.size())); } else { // Throw error? } } else { // Write image to disc FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr); if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) { const std::string imagefilepath = JoinPath(*basepath, *filename); std::string writeError; if (!fs->WriteWholeFile(&writeError, imagefilepath, data, fs->user_data)) { // Could not write image file to disc; Throw error ? return false; } } else { // Throw error? } image->uri = *filename; } return true; } #endif void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; } #ifndef TINYGLTF_NO_FS // Default implementations of filesystem functions bool FileExists(const std::string &abs_filename, void *) { bool ret; #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS if (asset_manager) { AAsset *asset = AAssetManager_open(asset_manager, abs_filename.c_str(), AASSET_MODE_STREAMING); if (!asset) { return false; } AAsset_close(asset); ret = true; } else { return false; } #else #ifdef _WIN32 FILE *fp; errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb"); if (err != 0) { return false; } #else FILE *fp = fopen(abs_filename.c_str(), "rb"); #endif if (fp) { ret = true; fclose(fp); } else { ret = false; } #endif return ret; } std::string ExpandFilePath(const std::string &filepath, void *) { #ifdef _WIN32 DWORD len = ExpandEnvironmentStringsA(filepath.c_str(), NULL, 0); char *str = new char[len]; ExpandEnvironmentStringsA(filepath.c_str(), str, len); std::string s(str); delete[] str; return s; #else #if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) || \ defined(__ANDROID__) || defined(__EMSCRIPTEN__) // no expansion std::string s = filepath; #else std::string s; wordexp_t p; if (filepath.empty()) { return ""; } // char** w; int ret = wordexp(filepath.c_str(), &p, 0); if (ret) { // err s = filepath; return s; } // Use first element only. if (p.we_wordv) { s = std::string(p.we_wordv[0]); wordfree(&p); } else { s = filepath; } #endif return s; #endif } bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err, const std::string &filepath, void *) { #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS if (asset_manager) { AAsset *asset = AAssetManager_open(asset_manager, filepath.c_str(), AASSET_MODE_STREAMING); if (!asset) { if (err) { (*err) += "File open error : " + filepath + "\n"; } return false; } size_t size = AAsset_getLength(asset); if (size <= 0) { if (err) { (*err) += "Invalid file size : " + filepath + " (does the path point to a directory?)"; } } out->resize(size); AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size); AAsset_close(asset); return true; } else { if (err) { (*err) += "No asset manager specified : " + filepath + "\n"; } return false; } #else std::ifstream f(filepath.c_str(), std::ifstream::binary); if (!f) { if (err) { (*err) += "File open error : " + filepath + "\n"; } return false; } f.seekg(0, f.end); size_t sz = static_cast<size_t>(f.tellg()); f.seekg(0, f.beg); if (int(sz) < 0) { if (err) { (*err) += "Invalid file size : " + filepath + " (does the path point to a directory?)"; } return false; } else if (sz == 0) { if (err) { (*err) += "File is empty : " + filepath + "\n"; } return false; } out->resize(sz); f.read(reinterpret_cast<char *>(&out->at(0)), static_cast<std::streamsize>(sz)); f.close(); return true; #endif } bool WriteWholeFile(std::string *err, const std::string &filepath, const std::vector<unsigned char> &contents, void *) { std::ofstream f(filepath.c_str(), std::ofstream::binary); if (!f) { if (err) { (*err) += "File open error for writing : " + filepath + "\n"; } return false; } f.write(reinterpret_cast<const char *>(&contents.at(0)), static_cast<std::streamsize>(contents.size())); if (!f) { if (err) { (*err) += "File write error: " + filepath + "\n"; } return false; } f.close(); return true; } #endif // TINYGLTF_NO_FS static std::string MimeToExt(const std::string &mimeType) { if (mimeType == "image/jpeg") { return "jpg"; } else if (mimeType == "image/png") { return "png"; } else if (mimeType == "image/bmp") { return "bmp"; } else if (mimeType == "image/gif") { return "gif"; } return ""; } static void UpdateImageObject(Image &image, std::string &baseDir, int index, bool embedImages, WriteImageDataFunction *WriteImageData = nullptr, void *user_data = nullptr) { std::string filename; std::string ext; // If image have uri. Use it it as a filename if (image.uri.size()) { filename = GetBaseFilename(image.uri); ext = GetFilePathExtension(filename); } else if (image.name.size()) { ext = MimeToExt(image.mimeType); // Otherwise use name as filename filename = image.name + "." + ext; } else { ext = MimeToExt(image.mimeType); // Fallback to index of image as filename filename = std::to_string(index) + "." + ext; } // If callback is set, modify image data object if (*WriteImageData != nullptr) { std::string uri; (*WriteImageData)(&baseDir, &filename, &image, embedImages, user_data); } } bool IsDataURI(const std::string &in) { std::string header = "data:application/octet-stream;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/jpeg;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/png;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/bmp;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/gif;base64,"; if (in.find(header) == 0) { return true; } header = "data:text/plain;base64,"; if (in.find(header) == 0) { return true; } header = "data:application/gltf-buffer;base64,"; if (in.find(header) == 0) { return true; } return false; } bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type, const std::string &in, size_t reqBytes, bool checkSize) { std::string header = "data:application/octet-stream;base64,"; std::string data; if (in.find(header) == 0) { data = base64_decode(in.substr(header.size())); // cut mime string. } if (data.empty()) { header = "data:image/jpeg;base64,"; if (in.find(header) == 0) { mime_type = "image/jpeg"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/png;base64,"; if (in.find(header) == 0) { mime_type = "image/png"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/bmp;base64,"; if (in.find(header) == 0) { mime_type = "image/bmp"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/gif;base64,"; if (in.find(header) == 0) { mime_type = "image/gif"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:text/plain;base64,"; if (in.find(header) == 0) { mime_type = "text/plain"; data = base64_decode(in.substr(header.size())); } } if (data.empty()) { header = "data:application/gltf-buffer;base64,"; if (in.find(header) == 0) { data = base64_decode(in.substr(header.size())); } } if (data.empty()) { return false; } if (checkSize) { if (data.size() != reqBytes) { return false; } out->resize(reqBytes); } else { out->resize(data.size()); } std::copy(data.begin(), data.end(), out->begin()); return true; } static bool ParseJsonAsValue(Value *ret, const json &o) { Value val{}; switch (o.type()) { case json::value_t::object: { Value::Object value_object; for (auto it = o.begin(); it != o.end(); it++) { Value entry; ParseJsonAsValue(&entry, it.value()); if (entry.Type() != NULL_TYPE) value_object[it.key()] = entry; } if (value_object.size() > 0) val = Value(value_object); } break; case json::value_t::array: { Value::Array value_array; for (auto it = o.begin(); it != o.end(); it++) { Value entry; ParseJsonAsValue(&entry, it.value()); if (entry.Type() != NULL_TYPE) value_array.push_back(entry); } if (value_array.size() > 0) val = Value(value_array); } break; case json::value_t::string: val = Value(o.get<std::string>()); break; case json::value_t::boolean: val = Value(o.get<bool>()); break; case json::value_t::number_integer: case json::value_t::number_unsigned: val = Value(static_cast<int>(o.get<int64_t>())); break; case json::value_t::number_float: val = Value(o.get<double>()); break; case json::value_t::null: case json::value_t::discarded: // default: break; } if (ret) *ret = val; return val.Type() != NULL_TYPE; } static bool ParseExtrasProperty(Value *ret, const json &o) { json::const_iterator it = o.find("extras"); if (it == o.end()) { return false; } return ParseJsonAsValue(ret, it.value()); } static bool ParseBooleanProperty(bool *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_boolean()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a bool type.\n"; } } return false; } if (ret) { (*ret) = it.value().get<bool>(); } return true; } static bool ParseIntegerProperty(int *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_number_integer()) { if (required) { if (err) { (*err) += "'" + property + "' property is not an integer type.\n"; } } return false; } if (ret) { (*ret) = it.value().get<int>(); } return true; } static bool ParseUnsignedProperty(size_t *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_number_unsigned()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a positive integer.\n"; } } return false; } if (ret) { (*ret) = it.value().get<size_t>(); } return true; } static bool ParseNumberProperty(double *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_number()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a number type.\n"; } } return false; } if (ret) { (*ret) = it.value().get<double>(); } return true; } static bool ParseNumberArrayProperty(std::vector<double> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_array()) { if (required) { if (err) { (*err) += "'" + property + "' property is not an array"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->clear(); for (json::const_iterator i = it.value().begin(); i != it.value().end(); i++) { if (!i.value().is_number()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a number.\n"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->push_back(i.value()); } return true; } static bool ParseIntegerArrayProperty(std::vector<int> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!it.value().is_array()) { if (required) { if (err) { (*err) += "'" + property + "' property is not an array"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->clear(); for (json::const_iterator i = it.value().begin(); i != it.value().end(); i++) { if (!i.value().is_number_integer()) { if (required) { if (err) { (*err) += "'" + property + "' property is not an integer type.\n"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->push_back(i.value()); } return true; } static bool ParseStringProperty( std::string *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = std::string()) { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (parent_node.empty()) { (*err) += ".\n"; } else { (*err) += " in `" + parent_node + "'.\n"; } } } return false; } if (!it.value().is_string()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a string type.\n"; } } return false; } if (ret) { (*ret) = it.value().get<std::string>(); } return true; } static bool ParseStringIntegerProperty(std::map<std::string, int> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent = "") { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { if (!parent.empty()) { (*err) += "'" + property + "' property is missing in " + parent + ".\n"; } else { (*err) += "'" + property + "' property is missing.\n"; } } } return false; } // Make sure we are dealing with an object / dictionary. if (!it.value().is_object()) { if (required) { if (err) { (*err) += "'" + property + "' property is not an object.\n"; } } return false; } ret->clear(); const json &dict = it.value(); json::const_iterator dictIt(dict.begin()); json::const_iterator dictItEnd(dict.end()); for (; dictIt != dictItEnd; ++dictIt) { if (!dictIt.value().is_number_integer()) { if (required) { if (err) { (*err) += "'" + property + "' value is not an integer type.\n"; } } return false; } // Insert into the list. (*ret)[dictIt.key()] = dictIt.value(); } return true; } static bool ParseJSONProperty(std::map<std::string, double> *ret, std::string *err, const json &o, const std::string &property, bool required) { json::const_iterator it = o.find(property); if (it == o.end()) { if (required) { if (err) { (*err) += "'" + property + "' property is missing. \n'"; } } return false; } if (!it.value().is_object()) { if (required) { if (err) { (*err) += "'" + property + "' property is not a JSON object.\n"; } } return false; } ret->clear(); const json &obj = it.value(); json::const_iterator it2(obj.begin()); json::const_iterator itEnd(obj.end()); for (; it2 != itEnd; it2++) { if (it2.value().is_number()) ret->insert(std::pair<std::string, double>(it2.key(), it2.value())); } return true; } static bool ParseParameterProperty(Parameter *param, std::string *err, const json &o, const std::string &prop, bool required) { // A parameter value can either be a string or an array of either a boolean or // a number. Booleans of any kind aren't supported here. Granted, it // complicates the Parameter structure and breaks it semantically in the sense // that the client probably works off the assumption that if the string is // empty the vector is used, etc. Would a tagged union work? if (ParseStringProperty(&param->string_value, err, o, prop, false)) { // Found string property. return true; } else if (ParseNumberArrayProperty(&param->number_array, err, o, prop, false)) { // Found a number array. return true; } else if (ParseNumberProperty(&param->number_value, err, o, prop, false)) { return param->has_number_value = true; } else if (ParseJSONProperty(&param->json_double_value, err, o, prop, false)) { return true; } else if (ParseBooleanProperty(&param->bool_value, err, o, prop, false)) { return true; } else { if (required) { if (err) { (*err) += "parameter must be a string or number / number array.\n"; } } return false; } } static bool ParseExtensionsProperty(ExtensionMap *ret, std::string *err, const json &o) { (void)err; json::const_iterator it = o.find("extensions"); if (it == o.end()) { return false; } if (!it.value().is_object()) { return false; } ExtensionMap extensions; json::const_iterator extIt = it.value().begin(); for (; extIt != it.value().end(); extIt++) { if (!extIt.value().is_object()) continue; if (!ParseJsonAsValue(&extensions[extIt.key()], extIt.value())) { if (!extIt.key().empty()) { // create empty object so that an extension object is still of type // object extensions[extIt.key()] = Value{Value::Object{}}; } } } if (ret) { (*ret) = extensions; } return true; } static bool ParseAsset(Asset *asset, std::string *err, const json &o) { ParseStringProperty(&asset->version, err, o, "version", true, "Asset"); ParseStringProperty(&asset->generator, err, o, "generator", false, "Asset"); ParseStringProperty(&asset->minVersion, err, o, "minVersion", false, "Asset"); ParseExtensionsProperty(&asset->extensions, err, o); // Unity exporter version is added as extra here ParseExtrasProperty(&(asset->extras), o); return true; } static bool ParseImage(Image *image, const int image_idx, std::string *err, std::string *warn, const json &o, const std::string &basedir, FsCallbacks *fs, LoadImageDataFunction *LoadImageData = nullptr, void *load_image_user_data = nullptr) { // A glTF image must either reference a bufferView or an image uri // schema says oneOf [`bufferView`, `uri`] // TODO(syoyo): Check the type of each parameters. bool hasBufferView = (o.find("bufferView") != o.end()); bool hasURI = (o.find("uri") != o.end()); ParseStringProperty(&image->name, err, o, "name", false); if (hasBufferView && hasURI) { // Should not both defined. if (err) { (*err) += "Only one of `bufferView` or `uri` should be defined, but both are " "defined for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } if (!hasBufferView && !hasURI) { if (err) { (*err) += "Neither required `bufferView` nor `uri` defined for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } ParseExtensionsProperty(&image->extensions, err, o); ParseExtrasProperty(&image->extras, o); if (hasBufferView) { int bufferView = -1; if (!ParseIntegerProperty(&bufferView, err, o, "bufferView", true)) { if (err) { (*err) += "Failed to parse `bufferView` for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } std::string mime_type; ParseStringProperty(&mime_type, err, o, "mimeType", false); int width = 0; ParseIntegerProperty(&width, err, o, "width", false); int height = 0; ParseIntegerProperty(&height, err, o, "height", false); // Just only save some information here. Loading actual image data from // bufferView is done after this `ParseImage` function. image->bufferView = bufferView; image->mimeType = mime_type; image->width = width; image->height = height; return true; } // Parse URI & Load image data. std::string uri; std::string tmp_err; if (!ParseStringProperty(&uri, &tmp_err, o, "uri", true)) { if (err) { (*err) += "Failed to parse `uri` for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\".\n"; } return false; } std::vector<unsigned char> img; if (IsDataURI(uri)) { if (!DecodeDataURI(&img, image->mimeType, uri, 0, false)) { if (err) { (*err) += "Failed to decode 'uri' for image[" + std::to_string(image_idx) + "] name = [" + image->name + "]\n"; } return false; } } else { // Assume external file // Keep texture path (for textures that cannot be decoded) image->uri = uri; #ifdef TINYGLTF_NO_EXTERNAL_IMAGE return true; #endif if (!LoadExternalFile(&img, err, warn, uri, basedir, false, 0, false, fs)) { if (warn) { (*warn) += "Failed to load external 'uri' for image[" + std::to_string(image_idx) + "] name = [" + image->name + "]\n"; } // If the image cannot be loaded, keep uri as image->uri. return true; } if (img.empty()) { if (warn) { (*warn) += "Image data is empty for image[" + std::to_string(image_idx) + "] name = [" + image->name + "] \n"; } return false; } } if (*LoadImageData == nullptr) { if (err) { (*err) += "No LoadImageData callback specified.\n"; } return false; } return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0), static_cast<int>(img.size()), load_image_user_data); } static bool ParseTexture(Texture *texture, std::string *err, const json &o, const std::string &basedir) { (void)basedir; int sampler = -1; int source = -1; ParseIntegerProperty(&sampler, err, o, "sampler", false); ParseIntegerProperty(&source, err, o, "source", false); texture->sampler = sampler; texture->source = source; ParseExtensionsProperty(&texture->extensions, err, o); ParseExtrasProperty(&texture->extras, o); ParseStringProperty(&texture->name, err, o, "name", false); return true; } static bool ParseBuffer(Buffer *buffer, std::string *err, const json &o, FsCallbacks *fs, const std::string &basedir, bool is_binary = false, const unsigned char *bin_data = nullptr, size_t bin_size = 0) { size_t byteLength; if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true, "Buffer")) { return false; } // In glTF 2.0, uri is not mandatory anymore buffer->uri.clear(); ParseStringProperty(&buffer->uri, err, o, "uri", false, "Buffer"); // having an empty uri for a non embedded image should not be valid if (!is_binary && buffer->uri.empty()) { if (err) { (*err) += "'uri' is missing from non binary glTF file buffer.\n"; } } json::const_iterator type = o.find("type"); if (type != o.end()) { if (type.value().is_string()) { const std::string &ty = type.value(); if (ty.compare("arraybuffer") == 0) { // buffer.type = "arraybuffer"; } } } if (is_binary) { // Still binary glTF accepts external dataURI. if (!buffer->uri.empty()) { // First try embedded data URI. if (IsDataURI(buffer->uri)) { std::string mime_type; if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength, true)) { if (err) { (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n"; } return false; } } else { // External .bin file. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, buffer->uri, basedir, true, byteLength, true, fs)) { return false; } } } else { // load data from (embedded) binary data if ((bin_size == 0) || (bin_data == nullptr)) { if (err) { (*err) += "Invalid binary data in `Buffer'.\n"; } return false; } if (byteLength > bin_size) { if (err) { std::stringstream ss; ss << "Invalid `byteLength'. Must be equal or less than binary size: " "`byteLength' = " << byteLength << ", binary size = " << bin_size << std::endl; (*err) += ss.str(); } return false; } // Read buffer data buffer->data.resize(static_cast<size_t>(byteLength)); memcpy(&(buffer->data.at(0)), bin_data, static_cast<size_t>(byteLength)); } } else { if (IsDataURI(buffer->uri)) { std::string mime_type; if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength, true)) { if (err) { (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n"; } return false; } } else { // Assume external .bin file. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, buffer->uri, basedir, true, byteLength, true, fs)) { return false; } } } ParseStringProperty(&buffer->name, err, o, "name", false); return true; } static bool ParseBufferView(BufferView *bufferView, std::string *err, const json &o) { int buffer = -1; if (!ParseIntegerProperty(&buffer, err, o, "buffer", true, "BufferView")) { return false; } size_t byteOffset = 0; ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false); size_t byteLength = 1; if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true, "BufferView")) { return false; } size_t byteStride = 0; if (!ParseUnsignedProperty(&byteStride, err, o, "byteStride", false)) { // Spec says: When byteStride of referenced bufferView is not defined, it // means that accessor elements are tightly packed, i.e., effective stride // equals the size of the element. // We cannot determine the actual byteStride until Accessor are parsed, thus // set 0(= tightly packed) here(as done in OpenGL's VertexAttribPoiner) byteStride = 0; } if ((byteStride > 252) || ((byteStride % 4) != 0)) { if (err) { std::stringstream ss; ss << "Invalid `byteStride' value. `byteStride' must be the multiple of " "4 : " << byteStride << std::endl; (*err) += ss.str(); } return false; } int target = 0; ParseIntegerProperty(&target, err, o, "target", false); if ((target == TINYGLTF_TARGET_ARRAY_BUFFER) || (target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) { // OK } else { target = 0; } bufferView->target = target; ParseStringProperty(&bufferView->name, err, o, "name", false); bufferView->buffer = buffer; bufferView->byteOffset = byteOffset; bufferView->byteLength = byteLength; bufferView->byteStride = byteStride; return true; } static bool ParseSparseAccessor(Accessor *accessor, std::string *err, const json &o) { accessor->sparse.isSparse = true; int count = 0; ParseIntegerProperty(&count, err, o, "count", true); const auto indices_iterator = o.find("indices"); const auto values_iterator = o.find("values"); if (indices_iterator == o.end()) { (*err) = "the sparse object of this accessor doesn't have indices"; return false; } if (values_iterator == o.end()) { (*err) = "the sparse object ob ths accessor doesn't have values"; return false; } const json &indices_obj = *indices_iterator; const json &values_obj = *values_iterator; int indices_buffer_view = 0, indices_byte_offset = 0, component_type = 0; ParseIntegerProperty(&indices_buffer_view, err, indices_obj, "bufferView", true); ParseIntegerProperty(&indices_byte_offset, err, indices_obj, "byteOffset", true); ParseIntegerProperty(&component_type, err, indices_obj, "componentType", true); int values_buffer_view = 0, values_byte_offset = 0; ParseIntegerProperty(&values_buffer_view, err, values_obj, "bufferView", true); ParseIntegerProperty(&values_byte_offset, err, values_obj, "byteOffset", true); accessor->sparse.count = count; accessor->sparse.indices.bufferView = indices_buffer_view; accessor->sparse.indices.byteOffset = indices_byte_offset; accessor->sparse.indices.componentType = component_type; accessor->sparse.values.bufferView = values_buffer_view; accessor->sparse.values.byteOffset = values_byte_offset; // todo check theses values return true; } static bool ParseAccessor(Accessor *accessor, std::string *err, const json &o) { int bufferView = -1; ParseIntegerProperty(&bufferView, err, o, "bufferView", false, "Accessor"); size_t byteOffset = 0; ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false, "Accessor"); bool normalized = false; ParseBooleanProperty(&normalized, err, o, "normalized", false, "Accessor"); size_t componentType = 0; if (!ParseUnsignedProperty(&componentType, err, o, "componentType", true, "Accessor")) { return false; } size_t count = 0; if (!ParseUnsignedProperty(&count, err, o, "count", true, "Accessor")) { return false; } std::string type; if (!ParseStringProperty(&type, err, o, "type", true, "Accessor")) { return false; } if (type.compare("SCALAR") == 0) { accessor->type = TINYGLTF_TYPE_SCALAR; } else if (type.compare("VEC2") == 0) { accessor->type = TINYGLTF_TYPE_VEC2; } else if (type.compare("VEC3") == 0) { accessor->type = TINYGLTF_TYPE_VEC3; } else if (type.compare("VEC4") == 0) { accessor->type = TINYGLTF_TYPE_VEC4; } else if (type.compare("MAT2") == 0) { accessor->type = TINYGLTF_TYPE_MAT2; } else if (type.compare("MAT3") == 0) { accessor->type = TINYGLTF_TYPE_MAT3; } else if (type.compare("MAT4") == 0) { accessor->type = TINYGLTF_TYPE_MAT4; } else { std::stringstream ss; ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n"; if (err) { (*err) += ss.str(); } return false; } ParseStringProperty(&accessor->name, err, o, "name", false); accessor->minValues.clear(); accessor->maxValues.clear(); ParseNumberArrayProperty(&accessor->minValues, err, o, "min", false, "Accessor"); ParseNumberArrayProperty(&accessor->maxValues, err, o, "max", false, "Accessor"); accessor->count = count; accessor->bufferView = bufferView; accessor->byteOffset = byteOffset; accessor->normalized = normalized; { if (componentType >= TINYGLTF_COMPONENT_TYPE_BYTE && componentType <= TINYGLTF_COMPONENT_TYPE_DOUBLE) { // OK accessor->componentType = int(componentType); } else { std::stringstream ss; ss << "Invalid `componentType` in accessor. Got " << componentType << "\n"; if (err) { (*err) += ss.str(); } return false; } } ParseExtrasProperty(&(accessor->extras), o); // check if accessor has a "sparse" object: const auto iterator = o.find("sparse"); if (iterator != o.end()) { // here this accessor has a "sparse" subobject return ParseSparseAccessor(accessor, err, *iterator); } return true; } #ifdef TINYGLTF_ENABLE_DRACO static void DecodeIndexBuffer(draco::Mesh *mesh, size_t componentSize, std::vector<uint8_t> &outBuffer) { if (componentSize == 4) { assert(sizeof(mesh->face(draco::FaceIndex(0))[0]) == componentSize); memcpy(outBuffer.data(), &mesh->face(draco::FaceIndex(0))[0], outBuffer.size()); } else { size_t faceStride = componentSize * 3; for (draco::FaceIndex f(0); f < mesh->num_faces(); ++f) { const draco::Mesh::Face &face = mesh->face(f); if (componentSize == 2) { uint16_t indices[3] = {(uint16_t)face[0].value(), (uint16_t)face[1].value(), (uint16_t)face[2].value()}; memcpy(outBuffer.data() + f.value() * faceStride, &indices[0], faceStride); } else { uint8_t indices[3] = {(uint8_t)face[0].value(), (uint8_t)face[1].value(), (uint8_t)face[2].value()}; memcpy(outBuffer.data() + f.value() * faceStride, &indices[0], faceStride); } } } } template <typename T> static bool GetAttributeForAllPoints(draco::Mesh *mesh, const draco::PointAttribute *pAttribute, std::vector<uint8_t> &outBuffer) { size_t byteOffset = 0; T values[4] = {0, 0, 0, 0}; for (draco::PointIndex i(0); i < mesh->num_points(); ++i) { const draco::AttributeValueIndex val_index = pAttribute->mapped_index(i); if (!pAttribute->ConvertValue<T>(val_index, pAttribute->num_components(), values)) return false; memcpy(outBuffer.data() + byteOffset, &values[0], sizeof(T) * pAttribute->num_components()); byteOffset += sizeof(T) * pAttribute->num_components(); } return true; } static bool GetAttributeForAllPoints(uint32_t componentType, draco::Mesh *mesh, const draco::PointAttribute *pAttribute, std::vector<uint8_t> &outBuffer) { bool decodeResult = false; switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: decodeResult = GetAttributeForAllPoints<uint8_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_BYTE: decodeResult = GetAttributeForAllPoints<int8_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: decodeResult = GetAttributeForAllPoints<uint16_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_SHORT: decodeResult = GetAttributeForAllPoints<int16_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_INT: decodeResult = GetAttributeForAllPoints<int32_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: decodeResult = GetAttributeForAllPoints<uint32_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_FLOAT: decodeResult = GetAttributeForAllPoints<float>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_DOUBLE: decodeResult = GetAttributeForAllPoints<double>(mesh, pAttribute, outBuffer); break; default: return false; } return decodeResult; } static bool ParseDracoExtension(Primitive *primitive, Model *model, std::string *err, const Value &dracoExtensionValue) { auto bufferViewValue = dracoExtensionValue.Get("bufferView"); if (!bufferViewValue.IsInt()) return false; auto attributesValue = dracoExtensionValue.Get("attributes"); if (!attributesValue.IsObject()) return false; auto attributesObject = attributesValue.Get<Value::Object>(); int bufferView = bufferViewValue.Get<int>(); BufferView &view = model->bufferViews[bufferView]; Buffer &buffer = model->buffers[view.buffer]; // BufferView has already been decoded if (view.dracoDecoded) return true; view.dracoDecoded = true; const char *bufferViewData = reinterpret_cast<const char *>(buffer.data.data() + view.byteOffset); size_t bufferViewSize = view.byteLength; // decode draco draco::DecoderBuffer decoderBuffer; decoderBuffer.Init(bufferViewData, bufferViewSize); draco::Decoder decoder; auto decodeResult = decoder.DecodeMeshFromBuffer(&decoderBuffer); if (!decodeResult.ok()) { return false; } const std::unique_ptr<draco::Mesh> &mesh = decodeResult.value(); // create new bufferView for indices if (primitive->indices >= 0) { int32_t componentSize = GetComponentSizeInBytes( model->accessors[primitive->indices].componentType); Buffer decodedIndexBuffer; decodedIndexBuffer.data.resize(mesh->num_faces() * 3 * componentSize); DecodeIndexBuffer(mesh.get(), componentSize, decodedIndexBuffer.data); model->buffers.emplace_back(std::move(decodedIndexBuffer)); BufferView decodedIndexBufferView; decodedIndexBufferView.buffer = int(model->buffers.size() - 1); decodedIndexBufferView.byteLength = int(mesh->num_faces() * 3 * componentSize); decodedIndexBufferView.byteOffset = 0; decodedIndexBufferView.byteStride = 0; decodedIndexBufferView.target = TINYGLTF_TARGET_ARRAY_BUFFER; model->bufferViews.emplace_back(std::move(decodedIndexBufferView)); model->accessors[primitive->indices].bufferView = int(model->bufferViews.size() - 1); model->accessors[primitive->indices].count = int(mesh->num_faces() * 3); } for (const auto &attribute : attributesObject) { if (!attribute.second.IsInt()) return false; auto primitiveAttribute = primitive->attributes.find(attribute.first); if (primitiveAttribute == primitive->attributes.end()) return false; int dracoAttributeIndex = attribute.second.Get<int>(); const auto pAttribute = mesh->GetAttributeByUniqueId(dracoAttributeIndex); const auto pBuffer = pAttribute->buffer(); const auto componentType = model->accessors[primitiveAttribute->second].componentType; // Create a new buffer for this decoded buffer Buffer decodedBuffer; size_t bufferSize = mesh->num_points() * pAttribute->num_components() * GetComponentSizeInBytes(componentType); decodedBuffer.data.resize(bufferSize); if (!GetAttributeForAllPoints(componentType, mesh.get(), pAttribute, decodedBuffer.data)) return false; model->buffers.emplace_back(std::move(decodedBuffer)); BufferView decodedBufferView; decodedBufferView.buffer = int(model->buffers.size() - 1); decodedBufferView.byteLength = bufferSize; decodedBufferView.byteOffset = pAttribute->byte_offset(); decodedBufferView.byteStride = pAttribute->byte_stride(); decodedBufferView.target = primitive->indices >= 0 ? TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER : TINYGLTF_TARGET_ARRAY_BUFFER; model->bufferViews.emplace_back(std::move(decodedBufferView)); model->accessors[primitiveAttribute->second].bufferView = int(model->bufferViews.size() - 1); model->accessors[primitiveAttribute->second].count = int(mesh->num_points()); } return true; } #endif static bool ParsePrimitive(Primitive *primitive, Model *model, std::string *err, const json &o) { int material = -1; ParseIntegerProperty(&material, err, o, "material", false); primitive->material = material; int mode = TINYGLTF_MODE_TRIANGLES; ParseIntegerProperty(&mode, err, o, "mode", false); primitive->mode = mode; // Why only triangled were supported ? int indices = -1; ParseIntegerProperty(&indices, err, o, "indices", false); primitive->indices = indices; if (!ParseStringIntegerProperty(&primitive->attributes, err, o, "attributes", true, "Primitive")) { return false; } // Look for morph targets json::const_iterator targetsObject = o.find("targets"); if ((targetsObject != o.end()) && targetsObject.value().is_array()) { for (json::const_iterator i = targetsObject.value().begin(); i != targetsObject.value().end(); i++) { std::map<std::string, int> targetAttribues; const json &dict = i.value(); json::const_iterator dictIt(dict.begin()); json::const_iterator dictItEnd(dict.end()); for (; dictIt != dictItEnd; ++dictIt) { targetAttribues[dictIt.key()] = static_cast<int>(dictIt.value()); } primitive->targets.push_back(targetAttribues); } } ParseExtrasProperty(&(primitive->extras), o); ParseExtensionsProperty(&primitive->extensions, err, o); #ifdef TINYGLTF_ENABLE_DRACO auto dracoExtension = primitive->extensions.find("KHR_draco_mesh_compression"); if (dracoExtension != primitive->extensions.end()) { ParseDracoExtension(primitive, model, err, dracoExtension->second); } #else (void)model; #endif return true; } static bool ParseMesh(Mesh *mesh, Model *model, std::string *err, const json &o) { ParseStringProperty(&mesh->name, err, o, "name", false); mesh->primitives.clear(); json::const_iterator primObject = o.find("primitives"); if ((primObject != o.end()) && primObject.value().is_array()) { for (json::const_iterator i = primObject.value().begin(); i != primObject.value().end(); i++) { Primitive primitive; if (ParsePrimitive(&primitive, model, err, i.value())) { // Only add the primitive if the parsing succeeds. mesh->primitives.push_back(primitive); } } } // Should probably check if has targets and if dimensions fit ParseNumberArrayProperty(&mesh->weights, err, o, "weights", false); ParseExtensionsProperty(&mesh->extensions, err, o); ParseExtrasProperty(&(mesh->extras), o); return true; } static bool ParseLight(Light *light, std::string *err, const json &o) { ParseStringProperty(&light->name, err, o, "name", false); ParseNumberArrayProperty(&light->color, err, o, "color", false); ParseStringProperty(&light->type, err, o, "type", false); return true; } static bool ParseNode(Node *node, std::string *err, const json &o) { ParseStringProperty(&node->name, err, o, "name", false); int skin = -1; ParseIntegerProperty(&skin, err, o, "skin", false); node->skin = skin; // Matrix and T/R/S are exclusive if (!ParseNumberArrayProperty(&node->matrix, err, o, "matrix", false)) { ParseNumberArrayProperty(&node->rotation, err, o, "rotation", false); ParseNumberArrayProperty(&node->scale, err, o, "scale", false); ParseNumberArrayProperty(&node->translation, err, o, "translation", false); } int camera = -1; ParseIntegerProperty(&camera, err, o, "camera", false); node->camera = camera; int mesh = -1; ParseIntegerProperty(&mesh, err, o, "mesh", false); node->mesh = mesh; node->children.clear(); ParseIntegerArrayProperty(&node->children, err, o, "children", false); ParseExtensionsProperty(&node->extensions, err, o); ParseExtrasProperty(&(node->extras), o); return true; } static bool ParseMaterial(Material *material, std::string *err, const json &o) { material->values.clear(); material->extensions.clear(); material->additionalValues.clear(); json::const_iterator it(o.begin()); json::const_iterator itEnd(o.end()); for (; it != itEnd; it++) { if (it.key() == "pbrMetallicRoughness") { if (it.value().is_object()) { const json &values_object = it.value(); json::const_iterator itVal(values_object.begin()); json::const_iterator itValEnd(values_object.end()); for (; itVal != itValEnd; itVal++) { Parameter param; if (ParseParameterProperty(&param, err, values_object, itVal.key(), false)) { material->values[itVal.key()] = param; } } } } else if (it.key() == "extensions" || it.key() == "extras") { // done later, skip, otherwise poorly parsed contents will be saved in the // parametermap and serialized again later } else { Parameter param; if (ParseParameterProperty(&param, err, o, it.key(), false)) { // names of materials have already been parsed. Putting it in this map // doesn't correctly reflext the glTF specification if (it.key() != "name") material->additionalValues[it.key()] = param; } } } ParseExtensionsProperty(&material->extensions, err, o); ParseExtrasProperty(&(material->extras), o); return true; } static bool ParseAnimationChannel(AnimationChannel *channel, std::string *err, const json &o) { int samplerIndex = -1; int targetIndex = -1; if (!ParseIntegerProperty(&samplerIndex, err, o, "sampler", true, "AnimationChannel")) { if (err) { (*err) += "`sampler` field is missing in animation channels\n"; } return false; } json::const_iterator targetIt = o.find("target"); if ((targetIt != o.end()) && targetIt.value().is_object()) { const json &target_object = targetIt.value(); if (!ParseIntegerProperty(&targetIndex, err, target_object, "node", true)) { if (err) { (*err) += "`node` field is missing in animation.channels.target\n"; } return false; } if (!ParseStringProperty(&channel->target_path, err, target_object, "path", true)) { if (err) { (*err) += "`path` field is missing in animation.channels.target\n"; } return false; } } channel->sampler = samplerIndex; channel->target_node = targetIndex; ParseExtrasProperty(&(channel->extras), o); return true; } static bool ParseAnimation(Animation *animation, std::string *err, const json &o) { { json::const_iterator channelsIt = o.find("channels"); if ((channelsIt != o.end()) && channelsIt.value().is_array()) { for (json::const_iterator i = channelsIt.value().begin(); i != channelsIt.value().end(); i++) { AnimationChannel channel; if (ParseAnimationChannel(&channel, err, i.value())) { // Only add the channel if the parsing succeeds. animation->channels.push_back(channel); } } } } { json::const_iterator samplerIt = o.find("samplers"); if ((samplerIt != o.end()) && samplerIt.value().is_array()) { const json &sampler_array = samplerIt.value(); json::const_iterator it = sampler_array.begin(); json::const_iterator itEnd = sampler_array.end(); for (; it != itEnd; it++) { const json &s = it->get<json>(); AnimationSampler sampler; int inputIndex = -1; int outputIndex = -1; if (!ParseIntegerProperty(&inputIndex, err, s, "input", true)) { if (err) { (*err) += "`input` field is missing in animation.sampler\n"; } return false; } ParseStringProperty(&sampler.interpolation, err, s, "interpolation", false); if (!ParseIntegerProperty(&outputIndex, err, s, "output", true)) { if (err) { (*err) += "`output` field is missing in animation.sampler\n"; } return false; } sampler.input = inputIndex; sampler.output = outputIndex; ParseExtrasProperty(&(sampler.extras), s); animation->samplers.push_back(sampler); } } } ParseStringProperty(&animation->name, err, o, "name", false); ParseExtrasProperty(&(animation->extras), o); return true; } static bool ParseSampler(Sampler *sampler, std::string *err, const json &o) { ParseStringProperty(&sampler->name, err, o, "name", false); int minFilter = TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR; int magFilter = TINYGLTF_TEXTURE_FILTER_LINEAR; int wrapS = TINYGLTF_TEXTURE_WRAP_REPEAT; int wrapT = TINYGLTF_TEXTURE_WRAP_REPEAT; ParseIntegerProperty(&minFilter, err, o, "minFilter", false); ParseIntegerProperty(&magFilter, err, o, "magFilter", false); ParseIntegerProperty(&wrapS, err, o, "wrapS", false); ParseIntegerProperty(&wrapT, err, o, "wrapT", false); sampler->minFilter = minFilter; sampler->magFilter = magFilter; sampler->wrapS = wrapS; sampler->wrapT = wrapT; ParseExtrasProperty(&(sampler->extras), o); return true; } static bool ParseSkin(Skin *skin, std::string *err, const json &o) { ParseStringProperty(&skin->name, err, o, "name", false, "Skin"); std::vector<int> joints; if (!ParseIntegerArrayProperty(&joints, err, o, "joints", false, "Skin")) { return false; } skin->joints = std::move(joints); int skeleton = -1; ParseIntegerProperty(&skeleton, err, o, "skeleton", false, "Skin"); skin->skeleton = skeleton; int invBind = -1; ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin"); skin->inverseBindMatrices = invBind; return true; } static bool ParsePerspectiveCamera(PerspectiveCamera *camera, std::string *err, const json &o) { double yfov = 0.0; if (!ParseNumberProperty(&yfov, err, o, "yfov", true, "OrthographicCamera")) { return false; } double znear = 0.0; if (!ParseNumberProperty(&znear, err, o, "znear", true, "PerspectiveCamera")) { return false; } double aspectRatio = 0.0; // = invalid ParseNumberProperty(&aspectRatio, err, o, "aspectRatio", false, "PerspectiveCamera"); double zfar = 0.0; // = invalid ParseNumberProperty(&zfar, err, o, "zfar", false, "PerspectiveCamera"); camera->aspectRatio = aspectRatio; camera->zfar = zfar; camera->yfov = yfov; camera->znear = znear; ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); // TODO(syoyo): Validate parameter values. return true; } static bool ParseOrthographicCamera(OrthographicCamera *camera, std::string *err, const json &o) { double xmag = 0.0; if (!ParseNumberProperty(&xmag, err, o, "xmag", true, "OrthographicCamera")) { return false; } double ymag = 0.0; if (!ParseNumberProperty(&ymag, err, o, "ymag", true, "OrthographicCamera")) { return false; } double zfar = 0.0; if (!ParseNumberProperty(&zfar, err, o, "zfar", true, "OrthographicCamera")) { return false; } double znear = 0.0; if (!ParseNumberProperty(&znear, err, o, "znear", true, "OrthographicCamera")) { return false; } ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); camera->xmag = xmag; camera->ymag = ymag; camera->zfar = zfar; camera->znear = znear; // TODO(syoyo): Validate parameter values. return true; } static bool ParseCamera(Camera *camera, std::string *err, const json &o) { if (!ParseStringProperty(&camera->type, err, o, "type", true, "Camera")) { return false; } if (camera->type.compare("orthographic") == 0) { if (o.find("orthographic") == o.end()) { if (err) { std::stringstream ss; ss << "Orhographic camera description not found." << std::endl; (*err) += ss.str(); } return false; } const json &v = o.find("orthographic").value(); if (!v.is_object()) { if (err) { std::stringstream ss; ss << "\"orthographic\" is not a JSON object." << std::endl; (*err) += ss.str(); } return false; } if (!ParseOrthographicCamera(&camera->orthographic, err, v.get<json>())) { return false; } } else if (camera->type.compare("perspective") == 0) { if (o.find("perspective") == o.end()) { if (err) { std::stringstream ss; ss << "Perspective camera description not found." << std::endl; (*err) += ss.str(); } return false; } const json &v = o.find("perspective").value(); if (!v.is_object()) { if (err) { std::stringstream ss; ss << "\"perspective\" is not a JSON object." << std::endl; (*err) += ss.str(); } return false; } if (!ParsePerspectiveCamera(&camera->perspective, err, v.get<json>())) { return false; } } else { if (err) { std::stringstream ss; ss << "Invalid camera type: \"" << camera->type << "\". Must be \"perspective\" or \"orthographic\"" << std::endl; (*err) += ss.str(); } return false; } ParseStringProperty(&camera->name, err, o, "name", false); ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); return true; } bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn, const char *str, unsigned int length, const std::string &base_dir, unsigned int check_sections) { if (length < 4) { if (err) { (*err) = "JSON string too short.\n"; } return false; } json v; #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || \ defined(_CPPUNWIND)) && \ not defined(TINYGLTF_NOEXCEPTION) try { v = json::parse(str, str + length); } catch (const std::exception &e) { if (err) { (*err) = e.what(); } return false; } #else { v = json::parse(str, str + length, nullptr, /* exception */ false); if (!v.is_object()) { // Assume parsing was failed. if (err) { (*err) = "Failed to parse JSON object\n"; } return false; } } #endif if (!v.is_object()) { // root is not an object. if (err) { (*err) = "Root element is not a JSON object\n"; } return false; } { bool version_found = false; json::const_iterator it = v.find("asset"); if ((it != v.end()) && it.value().is_object()) { json::const_iterator version_it = it.value().find("version"); if ((version_it != it.value().end() && version_it.value().is_string())) { version_found = true; } } if (version_found) { // OK } else if (check_sections & REQUIRE_VERSION) { if (err) { (*err) += "\"asset\" object not found in .gltf or not an object type\n"; } return false; } } // scene is not mandatory. // FIXME Maybe a better way to handle it than removing the code { json::const_iterator it = v.find("scenes"); if ((it != v.end()) && it.value().is_array()) { // OK } else if (check_sections & REQUIRE_SCENES) { if (err) { (*err) += "\"scenes\" object not found in .gltf or not an array type\n"; } return false; } } { json::const_iterator it = v.find("nodes"); if ((it != v.end()) && it.value().is_array()) { // OK } else if (check_sections & REQUIRE_NODES) { if (err) { (*err) += "\"nodes\" object not found in .gltf\n"; } return false; } } { json::const_iterator it = v.find("accessors"); if ((it != v.end()) && it.value().is_array()) { // OK } else if (check_sections & REQUIRE_ACCESSORS) { if (err) { (*err) += "\"accessors\" object not found in .gltf\n"; } return false; } } { json::const_iterator it = v.find("buffers"); if ((it != v.end()) && it.value().is_array()) { // OK } else if (check_sections & REQUIRE_BUFFERS) { if (err) { (*err) += "\"buffers\" object not found in .gltf\n"; } return false; } } { json::const_iterator it = v.find("bufferViews"); if ((it != v.end()) && it.value().is_array()) { // OK } else if (check_sections & REQUIRE_BUFFER_VIEWS) { if (err) { (*err) += "\"bufferViews\" object not found in .gltf\n"; } return false; } } model->buffers.clear(); model->bufferViews.clear(); model->accessors.clear(); model->meshes.clear(); model->cameras.clear(); model->nodes.clear(); model->extensionsUsed.clear(); model->extensionsRequired.clear(); model->extensions.clear(); model->defaultScene = -1; // 1. Parse Asset { json::const_iterator it = v.find("asset"); if ((it != v.end()) && it.value().is_object()) { const json &root = it.value(); ParseAsset(&model->asset, err, root); } } // 2. Parse extensionUsed { json::const_iterator it = v.find("extensionsUsed"); if ((it != v.end()) && it.value().is_array()) { const json &root = it.value(); for (unsigned int i = 0; i < root.size(); ++i) { model->extensionsUsed.push_back(root[i].get<std::string>()); } } } { json::const_iterator it = v.find("extensionsRequired"); if ((it != v.end()) && it.value().is_array()) { const json &root = it.value(); for (unsigned int i = 0; i < root.size(); ++i) { model->extensionsRequired.push_back(root[i].get<std::string>()); } } } // 3. Parse Buffer { json::const_iterator rootIt = v.find("buffers"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`buffers' does not contain an JSON object."; } return false; } Buffer buffer; if (!ParseBuffer(&buffer, err, it->get<json>(), &fs, base_dir, is_binary_, bin_data_, bin_size_)) { return false; } model->buffers.push_back(buffer); } } } // 4. Parse BufferView { json::const_iterator rootIt = v.find("bufferViews"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`bufferViews' does not contain an JSON object."; } return false; } BufferView bufferView; if (!ParseBufferView(&bufferView, err, it->get<json>())) { return false; } model->bufferViews.push_back(bufferView); } } } // 5. Parse Accessor { json::const_iterator rootIt = v.find("accessors"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`accessors' does not contain an JSON object."; } return false; } Accessor accessor; if (!ParseAccessor(&accessor, err, it->get<json>())) { return false; } model->accessors.push_back(accessor); } } } // 6. Parse Mesh { json::const_iterator rootIt = v.find("meshes"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`meshes' does not contain an JSON object."; } return false; } Mesh mesh; if (!ParseMesh(&mesh, model, err, it->get<json>())) { return false; } model->meshes.push_back(mesh); } } } // Assign missing bufferView target types // - Look for missing Mesh indices // - Look for missing bufferView targets for (auto &mesh : model->meshes) { for (auto &primitive : mesh.primitives) { if (primitive.indices > -1) // has indices from parsing step, must be Element Array Buffer { if (size_t(primitive.indices) >= model->accessors.size()) { if (err) { (*err) += "primitive indices accessor out of bounds"; } return false; } auto bufferView = model->accessors[primitive.indices].bufferView; if (bufferView < 0 || size_t(bufferView) >= model->bufferViews.size()) { if (err) { (*err) += "accessor[" + std::to_string(primitive.indices) + "] invalid bufferView"; } return false; } model->bufferViews[bufferView].target = TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER; // we could optionally check if acessors' bufferView type is Scalar, as // it should be } } } // find any missing targets, must be an array buffer type if not fulfilled // from previous check for (auto &bufferView : model->bufferViews) { if (bufferView.target == 0) // missing target type { bufferView.target = TINYGLTF_TARGET_ARRAY_BUFFER; } } // 7. Parse Node { json::const_iterator rootIt = v.find("nodes"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`nodes' does not contain an JSON object."; } return false; } Node node; if (!ParseNode(&node, err, it->get<json>())) { return false; } model->nodes.push_back(node); } } } // 8. Parse scenes. { json::const_iterator rootIt = v.find("scenes"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!(it.value().is_object())) { if (err) { (*err) += "`scenes' does not contain an JSON object."; } return false; } const json &o = it->get<json>(); std::vector<int> nodes; if (!ParseIntegerArrayProperty(&nodes, err, o, "nodes", false)) { return false; } Scene scene; scene.nodes = std::move(nodes); ParseStringProperty(&scene.name, err, o, "name", false); ParseExtensionsProperty(&scene.extensions, err, o); ParseExtrasProperty(&scene.extras, o); model->scenes.push_back(scene); } } } // 9. Parse default scenes. { json::const_iterator rootIt = v.find("scene"); if ((rootIt != v.end()) && rootIt.value().is_number_integer()) { const int defaultScene = rootIt.value(); model->defaultScene = defaultScene; } } // 10. Parse Material { json::const_iterator rootIt = v.find("materials"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`materials' does not contain an JSON object."; } return false; } json jsonMaterial = it->get<json>(); Material material; ParseStringProperty(&material.name, err, jsonMaterial, "name", false); if (!ParseMaterial(&material, err, jsonMaterial)) { return false; } model->materials.push_back(material); } } } // 11. Parse Image { json::const_iterator rootIt = v.find("images"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); int idx = 0; for (; it != itEnd; it++, idx++) { if (!it.value().is_object()) { if (err) { (*err) += "image[" + std::to_string(idx) + "] is not a JSON object."; } return false; } Image image; if (!ParseImage(&image, idx, err, warn, it.value(), base_dir, &fs, &this->LoadImageData, load_image_user_data_)) { return false; } if (image.bufferView != -1) { // Load image from the buffer view. if (size_t(image.bufferView) >= model->bufferViews.size()) { if (err) { std::stringstream ss; ss << "image[" << idx << "] bufferView \"" << image.bufferView << "\" not found in the scene." << std::endl; (*err) += ss.str(); } return false; } const BufferView &bufferView = model->bufferViews[size_t(image.bufferView)]; if (size_t(bufferView.buffer) >= model->buffers.size()) { if (err) { std::stringstream ss; ss << "image[" << idx << "] buffer \"" << bufferView.buffer << "\" not found in the scene." << std::endl; (*err) += ss.str(); } return false; } const Buffer &buffer = model->buffers[size_t(bufferView.buffer)]; if (*LoadImageData == nullptr) { if (err) { (*err) += "No LoadImageData callback specified.\n"; } return false; } bool ret = LoadImageData( &image, idx, err, warn, image.width, image.height, &buffer.data[bufferView.byteOffset], static_cast<int>(bufferView.byteLength), load_image_user_data_); if (!ret) { return false; } } model->images.push_back(image); } } } // 12. Parse Texture { json::const_iterator rootIt = v.find("textures"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; it++) { if (!it.value().is_object()) { if (err) { (*err) += "`textures' does not contain an JSON object."; } return false; } Texture texture; if (!ParseTexture(&texture, err, it->get<json>(), base_dir)) { return false; } model->textures.push_back(texture); } } } // 13. Parse Animation { json::const_iterator rootIt = v.find("animations"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; ++it) { if (!it.value().is_object()) { if (err) { (*err) += "`animations' does not contain an JSON object."; } return false; } Animation animation; if (!ParseAnimation(&animation, err, it->get<json>())) { return false; } model->animations.push_back(animation); } } } // 14. Parse Skin { json::const_iterator rootIt = v.find("skins"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; ++it) { if (!it.value().is_object()) { if (err) { (*err) += "`skins' does not contain an JSON object."; } return false; } Skin skin; if (!ParseSkin(&skin, err, it->get<json>())) { return false; } model->skins.push_back(skin); } } } // 15. Parse Sampler { json::const_iterator rootIt = v.find("samplers"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; ++it) { if (!it.value().is_object()) { if (err) { (*err) += "`samplers' does not contain an JSON object."; } return false; } Sampler sampler; if (!ParseSampler(&sampler, err, it->get<json>())) { return false; } model->samplers.push_back(sampler); } } } // 16. Parse Camera { json::const_iterator rootIt = v.find("cameras"); if ((rootIt != v.end()) && rootIt.value().is_array()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; ++it) { if (!it.value().is_object()) { if (err) { (*err) += "`cameras' does not contain an JSON object."; } return false; } Camera camera; if (!ParseCamera(&camera, err, it->get<json>())) { return false; } model->cameras.push_back(camera); } } } // 17. Parse Extensions ParseExtensionsProperty(&model->extensions, err, v); // 18. Specific extension implementations { json::const_iterator rootIt = v.find("extensions"); if ((rootIt != v.end()) && rootIt.value().is_object()) { const json &root = rootIt.value(); json::const_iterator it(root.begin()); json::const_iterator itEnd(root.end()); for (; it != itEnd; ++it) { // parse KHR_lights_cmn extension if ((it.key().compare("KHR_lights_cmn") == 0) && it.value().is_object()) { const json &object = it.value(); json::const_iterator itLight(object.find("lights")); json::const_iterator itLightEnd(object.end()); if (itLight == itLightEnd) { continue; } if (!itLight.value().is_array()) { continue; } const json &lights = itLight.value(); json::const_iterator arrayIt(lights.begin()); json::const_iterator arrayItEnd(lights.end()); for (; arrayIt != arrayItEnd; ++arrayIt) { Light light; if (!ParseLight(&light, err, arrayIt.value())) { return false; } model->lights.push_back(light); } } } } } // 19. Parse Extras ParseExtrasProperty(&model->extras, v); return true; } bool TinyGLTF::LoadASCIIFromString(Model *model, std::string *err, std::string *warn, const char *str, unsigned int length, const std::string &base_dir, unsigned int check_sections) { is_binary_ = false; bin_data_ = nullptr; bin_size_ = 0; return LoadFromString(model, err, warn, str, length, base_dir, check_sections); } bool TinyGLTF::LoadASCIIFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections) { std::stringstream ss; if (fs.ReadWholeFile == nullptr) { // Programmer error, assert() ? ss << "Failed to read file: " << filename << ": one or more FS callback not set" << std::endl; if (err) { (*err) = ss.str(); } return false; } std::vector<unsigned char> data; std::string fileerr; bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data); if (!fileread) { ss << "Failed to read file: " << filename << ": " << fileerr << std::endl; if (err) { (*err) = ss.str(); } return false; } size_t sz = data.size(); if (sz == 0) { if (err) { (*err) = "Empty file."; } return false; } std::string basedir = GetBaseDir(filename); bool ret = LoadASCIIFromString( model, err, warn, reinterpret_cast<const char *>(&data.at(0)), static_cast<unsigned int>(data.size()), basedir, check_sections); return ret; } bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn, const unsigned char *bytes, unsigned int size, const std::string &base_dir, unsigned int check_sections) { if (size < 20) { if (err) { (*err) = "Too short data size for glTF Binary."; } return false; } if (bytes[0] == 'g' && bytes[1] == 'l' && bytes[2] == 'T' && bytes[3] == 'F') { // ok } else { if (err) { (*err) = "Invalid magic."; } return false; } unsigned int version; // 4 bytes unsigned int length; // 4 bytes unsigned int model_length; // 4 bytes unsigned int model_format; // 4 bytes; // @todo { Endian swap for big endian machine. } memcpy(&version, bytes + 4, 4); swap4(&version); memcpy(&length, bytes + 8, 4); swap4(&length); memcpy(&model_length, bytes + 12, 4); swap4(&model_length); memcpy(&model_format, bytes + 16, 4); swap4(&model_format); // In case the Bin buffer is not present, the size is exactly 20 + size of // JSON contents, // so use "greater than" operator. if ((20 + model_length > size) || (model_length < 1) || (length > size) || (model_format != 0x4E4F534A)) { // 0x4E4F534A = JSON format. if (err) { (*err) = "Invalid glTF binary."; } return false; } // Extract JSON string. std::string jsonString(reinterpret_cast<const char *>(&bytes[20]), model_length); is_binary_ = true; bin_data_ = bytes + 20 + model_length + 8; // 4 bytes (buffer_length) + 4 bytes(buffer_format) bin_size_ = length - (20 + model_length); // extract header + JSON scene data. bool ret = LoadFromString(model, err, warn, reinterpret_cast<const char *>(&bytes[20]), model_length, base_dir, check_sections); if (!ret) { return ret; } return true; } bool TinyGLTF::LoadBinaryFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections) { std::stringstream ss; if (fs.ReadWholeFile == nullptr) { // Programmer error, assert() ? ss << "Failed to read file: " << filename << ": one or more FS callback not set" << std::endl; if (err) { (*err) = ss.str(); } return false; } std::vector<unsigned char> data; std::string fileerr; bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data); if (!fileread) { ss << "Failed to read file: " << filename << ": " << fileerr << std::endl; if (err) { (*err) = ss.str(); } return false; } std::string basedir = GetBaseDir(filename); bool ret = LoadBinaryFromMemory(model, err, warn, &data.at(0), static_cast<unsigned int>(data.size()), basedir, check_sections); return ret; } /////////////////////// // GLTF Serialization /////////////////////// // typedef std::pair<std::string, json> json_object_pair; template <typename T> static void SerializeNumberProperty(const std::string &key, T number, json &obj) { // obj.insert( // json_object_pair(key, json(static_cast<double>(number)))); // obj[key] = static_cast<double>(number); obj[key] = number; } template <typename T> static void SerializeNumberArrayProperty(const std::string &key, const std::vector<T> &value, json &obj) { json o; json vals; for (unsigned int i = 0; i < value.size(); ++i) { vals.push_back(static_cast<T>(value[i])); } if (!vals.is_null()) { obj[key] = vals; } } static void SerializeStringProperty(const std::string &key, const std::string &value, json &obj) { obj[key] = value; } static void SerializeStringArrayProperty(const std::string &key, const std::vector<std::string> &value, json &obj) { json o; json vals; for (unsigned int i = 0; i < value.size(); ++i) { vals.push_back(value[i]); } obj[key] = vals; } static bool ValueToJson(const Value &value, json *ret) { json obj; switch (value.Type()) { case NUMBER_TYPE: obj = json(value.Get<double>()); break; case INT_TYPE: obj = json(value.Get<int>()); break; case BOOL_TYPE: obj = json(value.Get<bool>()); break; case STRING_TYPE: obj = json(value.Get<std::string>()); break; case ARRAY_TYPE: { for (unsigned int i = 0; i < value.ArrayLen(); ++i) { Value elementValue = value.Get(int(i)); json elementJson; if (ValueToJson(value.Get(int(i)), &elementJson)) obj.push_back(elementJson); } break; } case BINARY_TYPE: // TODO // obj = json(value.Get<std::vector<unsigned char>>()); return false; break; case OBJECT_TYPE: { Value::Object objMap = value.Get<Value::Object>(); for (auto &it : objMap) { json elementJson; if (ValueToJson(it.second, &elementJson)) obj[it.first] = elementJson; } break; } case NULL_TYPE: default: return false; } if (ret) *ret = obj; return true; } static void SerializeValue(const std::string &key, const Value &value, json &obj) { json ret; if (ValueToJson(value, &ret)) obj[key] = ret; } static void SerializeGltfBufferData(const std::vector<unsigned char> &data, json &o) { std::string header = "data:application/octet-stream;base64,"; std::string encodedData = base64_encode(&data[0], static_cast<unsigned int>(data.size())); SerializeStringProperty("uri", header + encodedData, o); } static bool SerializeGltfBufferData(const std::vector<unsigned char> &data, const std::string &binFilename) { std::ofstream output(binFilename.c_str(), std::ofstream::binary); if (!output.is_open()) return false; output.write(reinterpret_cast<const char *>(&data[0]), std::streamsize(data.size())); output.close(); return true; } static void SerializeParameterMap(ParameterMap &param, json &o) { for (ParameterMap::iterator paramIt = param.begin(); paramIt != param.end(); ++paramIt) { if (paramIt->second.number_array.size()) { SerializeNumberArrayProperty<double>(paramIt->first, paramIt->second.number_array, o); } else if (paramIt->second.json_double_value.size()) { json json_double_value; for (std::map<std::string, double>::iterator it = paramIt->second.json_double_value.begin(); it != paramIt->second.json_double_value.end(); ++it) { if (it->first == "index") { json_double_value[it->first] = paramIt->second.TextureIndex(); } else { json_double_value[it->first] = it->second; } } o[paramIt->first] = json_double_value; } else if (!paramIt->second.string_value.empty()) { SerializeStringProperty(paramIt->first, paramIt->second.string_value, o); } else if (paramIt->second.has_number_value) { o[paramIt->first] = paramIt->second.number_value; } else { o[paramIt->first] = paramIt->second.bool_value; } } } static void SerializeExtensionMap(ExtensionMap &extensions, json &o) { if (!extensions.size()) return; json extMap; for (ExtensionMap::iterator extIt = extensions.begin(); extIt != extensions.end(); ++extIt) { json extension_values; // Allow an empty object for extension(#97) json ret; if (ValueToJson(extIt->second, &ret)) { extMap[extIt->first] = ret; } if (ret.is_null()) { if (!(extIt->first.empty())) { // name should not be empty, but for sure // create empty object so that an extension name is still included in // json. extMap[extIt->first] = json({}); } } } o["extensions"] = extMap; } static void SerializeGltfAccessor(Accessor &accessor, json &o) { SerializeNumberProperty<int>("bufferView", accessor.bufferView, o); if (accessor.byteOffset != 0.0) SerializeNumberProperty<int>("byteOffset", int(accessor.byteOffset), o); SerializeNumberProperty<int>("componentType", accessor.componentType, o); SerializeNumberProperty<size_t>("count", accessor.count, o); SerializeNumberArrayProperty<double>("min", accessor.minValues, o); SerializeNumberArrayProperty<double>("max", accessor.maxValues, o); SerializeValue("normalized", Value(accessor.normalized), o); std::string type; switch (accessor.type) { case TINYGLTF_TYPE_SCALAR: type = "SCALAR"; break; case TINYGLTF_TYPE_VEC2: type = "VEC2"; break; case TINYGLTF_TYPE_VEC3: type = "VEC3"; break; case TINYGLTF_TYPE_VEC4: type = "VEC4"; break; case TINYGLTF_TYPE_MAT2: type = "MAT2"; break; case TINYGLTF_TYPE_MAT3: type = "MAT3"; break; case TINYGLTF_TYPE_MAT4: type = "MAT4"; break; } SerializeStringProperty("type", type, o); if (!accessor.name.empty()) SerializeStringProperty("name", accessor.name, o); if (accessor.extras.Type() != NULL_TYPE) { SerializeValue("extras", accessor.extras, o); } } static void SerializeGltfAnimationChannel(AnimationChannel &channel, json &o) { SerializeNumberProperty("sampler", channel.sampler, o); json target; SerializeNumberProperty("node", channel.target_node, target); SerializeStringProperty("path", channel.target_path, target); o["target"] = target; if (channel.extras.Type() != NULL_TYPE) { SerializeValue("extras", channel.extras, o); } } static void SerializeGltfAnimationSampler(AnimationSampler &sampler, json &o) { SerializeNumberProperty("input", sampler.input, o); SerializeNumberProperty("output", sampler.output, o); SerializeStringProperty("interpolation", sampler.interpolation, o); if (sampler.extras.Type() != NULL_TYPE) { SerializeValue("extras", sampler.extras, o); } } static void SerializeGltfAnimation(Animation &animation, json &o) { if (!animation.name.empty()) SerializeStringProperty("name", animation.name, o); json channels; for (unsigned int i = 0; i < animation.channels.size(); ++i) { json channel; AnimationChannel gltfChannel = animation.channels[i]; SerializeGltfAnimationChannel(gltfChannel, channel); channels.push_back(channel); } o["channels"] = channels; json samplers; for (unsigned int i = 0; i < animation.samplers.size(); ++i) { json sampler; AnimationSampler gltfSampler = animation.samplers[i]; SerializeGltfAnimationSampler(gltfSampler, sampler); samplers.push_back(sampler); } o["samplers"] = samplers; if (animation.extras.Type() != NULL_TYPE) { SerializeValue("extras", animation.extras, o); } } static void SerializeGltfAsset(Asset &asset, json &o) { if (!asset.generator.empty()) { SerializeStringProperty("generator", asset.generator, o); } if (!asset.copyright.empty()) { SerializeStringProperty("copyright", asset.copyright, o); } if (!asset.version.empty()) { SerializeStringProperty("version", asset.version, o); } if (asset.extras.Keys().size()) { SerializeValue("extras", asset.extras, o); } SerializeExtensionMap(asset.extensions, o); } static void SerializeGltfBuffer(Buffer &buffer, json &o) { SerializeNumberProperty("byteLength", buffer.data.size(), o); SerializeGltfBufferData(buffer.data, o); if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o); if (buffer.extras.Type() != NULL_TYPE) { SerializeValue("extras", buffer.extras, o); } } static bool SerializeGltfBuffer(Buffer &buffer, json &o, const std::string &binFilename, const std::string &binBaseFilename) { if (!SerializeGltfBufferData(buffer.data, binFilename)) return false; SerializeNumberProperty("byteLength", buffer.data.size(), o); SerializeStringProperty("uri", binBaseFilename, o); if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o); if (buffer.extras.Type() != NULL_TYPE) { SerializeValue("extras", buffer.extras, o); } return true; } static void SerializeGltfBufferView(BufferView &bufferView, json &o) { SerializeNumberProperty("buffer", bufferView.buffer, o); SerializeNumberProperty<size_t>("byteLength", bufferView.byteLength, o); // byteStride is optional, minimum allowed is 4 if (bufferView.byteStride >= 4) { SerializeNumberProperty<size_t>("byteStride", bufferView.byteStride, o); } // byteOffset is optional, default is 0 if (bufferView.byteOffset > 0) { SerializeNumberProperty<size_t>("byteOffset", bufferView.byteOffset, o); } // Target is optional, check if it contains a valid value if (bufferView.target == TINYGLTF_TARGET_ARRAY_BUFFER || bufferView.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER) { SerializeNumberProperty("target", bufferView.target, o); } if (bufferView.name.size()) { SerializeStringProperty("name", bufferView.name, o); } if (bufferView.extras.Type() != NULL_TYPE) { SerializeValue("extras", bufferView.extras, o); } } static void SerializeGltfImage(Image &image, json &o) { // if uri empty, the mimeType and bufferview should be set if (image.uri.empty()) { SerializeStringProperty("mimeType", image.mimeType, o); SerializeNumberProperty<int>("bufferView", image.bufferView, o); } else { SerializeStringProperty("uri", image.uri, o); } if (image.name.size()) { SerializeStringProperty("name", image.name, o); } if (image.extras.Type() != NULL_TYPE) { SerializeValue("extras", image.extras, o); } SerializeExtensionMap(image.extensions, o); } static void SerializeGltfMaterial(Material &material, json &o) { if (material.extras.Size()) SerializeValue("extras", material.extras, o); SerializeExtensionMap(material.extensions, o); if (material.values.size()) { json pbrMetallicRoughness; SerializeParameterMap(material.values, pbrMetallicRoughness); o["pbrMetallicRoughness"] = pbrMetallicRoughness; } SerializeParameterMap(material.additionalValues, o); if (material.name.size()) { SerializeStringProperty("name", material.name, o); } if (material.extras.Type() != NULL_TYPE) { SerializeValue("extras", material.extras, o); } } static void SerializeGltfMesh(Mesh &mesh, json &o) { json primitives; for (unsigned int i = 0; i < mesh.primitives.size(); ++i) { json primitive; json attributes; Primitive gltfPrimitive = mesh.primitives[i]; for (std::map<std::string, int>::iterator attrIt = gltfPrimitive.attributes.begin(); attrIt != gltfPrimitive.attributes.end(); ++attrIt) { SerializeNumberProperty<int>(attrIt->first, attrIt->second, attributes); } primitive["attributes"] = attributes; // Indicies is optional if (gltfPrimitive.indices > -1) { SerializeNumberProperty<int>("indices", gltfPrimitive.indices, primitive); } // Material is optional if (gltfPrimitive.material > -1) { SerializeNumberProperty<int>("material", gltfPrimitive.material, primitive); } SerializeNumberProperty<int>("mode", gltfPrimitive.mode, primitive); // Morph targets if (gltfPrimitive.targets.size()) { json targets; for (unsigned int k = 0; k < gltfPrimitive.targets.size(); ++k) { json targetAttributes; std::map<std::string, int> targetData = gltfPrimitive.targets[k]; for (std::map<std::string, int>::iterator attrIt = targetData.begin(); attrIt != targetData.end(); ++attrIt) { SerializeNumberProperty<int>(attrIt->first, attrIt->second, targetAttributes); } targets.push_back(targetAttributes); } primitive["targets"] = targets; } if (gltfPrimitive.extras.Type() != NULL_TYPE) { SerializeValue("extras", gltfPrimitive.extras, primitive); } primitives.push_back(primitive); } o["primitives"] = primitives; if (mesh.weights.size()) { SerializeNumberArrayProperty<double>("weights", mesh.weights, o); } if (mesh.name.size()) { SerializeStringProperty("name", mesh.name, o); } if (mesh.extras.Type() != NULL_TYPE) { SerializeValue("extras", mesh.extras, o); } } static void SerializeGltfLight(Light &light, json &o) { if (!light.name.empty()) SerializeStringProperty("name", light.name, o); SerializeNumberArrayProperty("color", light.color, o); SerializeStringProperty("type", light.type, o); } static void SerializeGltfNode(Node &node, json &o) { if (node.translation.size() > 0) { SerializeNumberArrayProperty<double>("translation", node.translation, o); } if (node.rotation.size() > 0) { SerializeNumberArrayProperty<double>("rotation", node.rotation, o); } if (node.scale.size() > 0) { SerializeNumberArrayProperty<double>("scale", node.scale, o); } if (node.matrix.size() > 0) { SerializeNumberArrayProperty<double>("matrix", node.matrix, o); } if (node.mesh != -1) { SerializeNumberProperty<int>("mesh", node.mesh, o); } if (node.skin != -1) { SerializeNumberProperty<int>("skin", node.skin, o); } if (node.camera != -1) { SerializeNumberProperty<int>("camera", node.camera, o); } if (node.extras.Type() != NULL_TYPE) { SerializeValue("extras", node.extras, o); } SerializeExtensionMap(node.extensions, o); if (!node.name.empty()) SerializeStringProperty("name", node.name, o); SerializeNumberArrayProperty<int>("children", node.children, o); } static void SerializeGltfSampler(Sampler &sampler, json &o) { SerializeNumberProperty("magFilter", sampler.magFilter, o); SerializeNumberProperty("minFilter", sampler.minFilter, o); SerializeNumberProperty("wrapR", sampler.wrapR, o); SerializeNumberProperty("wrapS", sampler.wrapS, o); SerializeNumberProperty("wrapT", sampler.wrapT, o); if (sampler.extras.Type() != NULL_TYPE) { SerializeValue("extras", sampler.extras, o); } } static void SerializeGltfOrthographicCamera(const OrthographicCamera &camera, json &o) { SerializeNumberProperty("zfar", camera.zfar, o); SerializeNumberProperty("znear", camera.znear, o); SerializeNumberProperty("xmag", camera.xmag, o); SerializeNumberProperty("ymag", camera.ymag, o); if (camera.extras.Type() != NULL_TYPE) { SerializeValue("extras", camera.extras, o); } } static void SerializeGltfPerspectiveCamera(const PerspectiveCamera &camera, json &o) { SerializeNumberProperty("zfar", camera.zfar, o); SerializeNumberProperty("znear", camera.znear, o); if (camera.aspectRatio > 0) { SerializeNumberProperty("aspectRatio", camera.aspectRatio, o); } if (camera.yfov > 0) { SerializeNumberProperty("yfov", camera.yfov, o); } if (camera.extras.Type() != NULL_TYPE) { SerializeValue("extras", camera.extras, o); } } static void SerializeGltfCamera(const Camera &camera, json &o) { SerializeStringProperty("type", camera.type, o); if (!camera.name.empty()) { SerializeStringProperty("name", camera.name, o); } if (camera.type.compare("orthographic") == 0) { json orthographic; SerializeGltfOrthographicCamera(camera.orthographic, orthographic); o["orthographic"] = orthographic; } else if (camera.type.compare("perspective") == 0) { json perspective; SerializeGltfPerspectiveCamera(camera.perspective, perspective); o["perspective"] = perspective; } else { // ??? } } static void SerializeGltfScene(Scene &scene, json &o) { SerializeNumberArrayProperty<int>("nodes", scene.nodes, o); if (scene.name.size()) { SerializeStringProperty("name", scene.name, o); } if (scene.extras.Type() != NULL_TYPE) { SerializeValue("extras", scene.extras, o); } SerializeExtensionMap(scene.extensions, o); } static void SerializeGltfSkin(Skin &skin, json &o) { if (skin.inverseBindMatrices != -1) SerializeNumberProperty("inverseBindMatrices", skin.inverseBindMatrices, o); SerializeNumberArrayProperty<int>("joints", skin.joints, o); SerializeNumberProperty("skeleton", skin.skeleton, o); if (skin.name.size()) { SerializeStringProperty("name", skin.name, o); } } static void SerializeGltfTexture(Texture &texture, json &o) { if (texture.sampler > -1) { SerializeNumberProperty("sampler", texture.sampler, o); } if (texture.source > -1) { SerializeNumberProperty("source", texture.source, o); } if (texture.name.size()) { SerializeStringProperty("name", texture.name, o); } if (texture.extras.Type() != NULL_TYPE) { SerializeValue("extras", texture.extras, o); } SerializeExtensionMap(texture.extensions, o); } static bool WriteGltfFile(const std::string &output, const std::string &content) { std::ofstream gltfFile(output.c_str()); if (!gltfFile.is_open()) return false; gltfFile << content << std::endl; return true; } static void WriteBinaryGltfFile(const std::string &output, const std::string &content) { std::ofstream gltfFile(output.c_str(), std::ios::binary); const std::string header = "glTF"; const int version = 2; const int padding_size = content.size() % 4; // 12 bytes for header, JSON content length, 8 bytes for JSON chunk info, // padding const int length = 12 + 8 + int(content.size()) + padding_size; gltfFile.write(header.c_str(), header.size()); gltfFile.write(reinterpret_cast<const char *>(&version), sizeof(version)); gltfFile.write(reinterpret_cast<const char *>(&length), sizeof(length)); // JSON chunk info, then JSON data const int model_length = int(content.size()) + padding_size; const int model_format = 0x4E4F534A; gltfFile.write(reinterpret_cast<const char *>(&model_length), sizeof(model_length)); gltfFile.write(reinterpret_cast<const char *>(&model_format), sizeof(model_format)); gltfFile.write(content.c_str(), content.size()); // Chunk must be multiplies of 4, so pad with spaces if (padding_size > 0) { const std::string padding = std::string(padding_size, ' '); gltfFile.write(padding.c_str(), padding.size()); } } bool TinyGLTF::WriteGltfSceneToFile(Model *model, const std::string &filename, bool embedImages = false, bool embedBuffers = false, bool prettyPrint = true, bool writeBinary = false) { json output; // ACCESSORS json accessors; for (unsigned int i = 0; i < model->accessors.size(); ++i) { json accessor; SerializeGltfAccessor(model->accessors[i], accessor); accessors.push_back(accessor); } output["accessors"] = accessors; // ANIMATIONS if (model->animations.size()) { json animations; for (unsigned int i = 0; i < model->animations.size(); ++i) { if (model->animations[i].channels.size()) { json animation; SerializeGltfAnimation(model->animations[i], animation); animations.push_back(animation); } } output["animations"] = animations; } // ASSET json asset; SerializeGltfAsset(model->asset, asset); output["asset"] = asset; std::string defaultBinFilename = GetBaseFilename(filename); std::string defaultBinFileExt = ".bin"; std::string::size_type pos = defaultBinFilename.rfind('.', defaultBinFilename.length()); if (pos != std::string::npos) { defaultBinFilename = defaultBinFilename.substr(0, pos); } std::string baseDir = GetBaseDir(filename); if (baseDir.empty()) { baseDir = "./"; } // BUFFERS std::vector<std::string> usedUris; json buffers; for (unsigned int i = 0; i < model->buffers.size(); ++i) { json buffer; if (embedBuffers) { SerializeGltfBuffer(model->buffers[i], buffer); } else { std::string binSavePath; std::string binUri; if (!model->buffers[i].uri.empty() && !IsDataURI(model->buffers[i].uri)) { binUri = model->buffers[i].uri; } else { binUri = defaultBinFilename + defaultBinFileExt; bool inUse = true; int numUsed = 0; while (inUse) { inUse = false; for (const std::string &usedName : usedUris) { if (binUri.compare(usedName) != 0) continue; inUse = true; binUri = defaultBinFilename + std::to_string(numUsed++) + defaultBinFileExt; break; } } } usedUris.push_back(binUri); binSavePath = JoinPath(baseDir, binUri); if (!SerializeGltfBuffer(model->buffers[i], buffer, binSavePath, binUri)) { return false; } } buffers.push_back(buffer); } output["buffers"] = buffers; // BUFFERVIEWS json bufferViews; for (unsigned int i = 0; i < model->bufferViews.size(); ++i) { json bufferView; SerializeGltfBufferView(model->bufferViews[i], bufferView); bufferViews.push_back(bufferView); } output["bufferViews"] = bufferViews; // Extensions used if (model->extensionsUsed.size()) { SerializeStringArrayProperty("extensionsUsed", model->extensionsUsed, output); } // Extensions required if (model->extensionsRequired.size()) { SerializeStringArrayProperty("extensionsRequired", model->extensionsRequired, output); } // IMAGES if (model->images.size()) { json images; for (unsigned int i = 0; i < model->images.size(); ++i) { json image; UpdateImageObject(model->images[i], baseDir, int(i), embedImages, &this->WriteImageData, this->write_image_user_data_); SerializeGltfImage(model->images[i], image); images.push_back(image); } output["images"] = images; } // MATERIALS if (model->materials.size()) { json materials; for (unsigned int i = 0; i < model->materials.size(); ++i) { json material; SerializeGltfMaterial(model->materials[i], material); materials.push_back(material); } output["materials"] = materials; } // MESHES if (model->meshes.size()) { json meshes; for (unsigned int i = 0; i < model->meshes.size(); ++i) { json mesh; SerializeGltfMesh(model->meshes[i], mesh); meshes.push_back(mesh); } output["meshes"] = meshes; } // NODES if (model->nodes.size()) { json nodes; for (unsigned int i = 0; i < model->nodes.size(); ++i) { json node; SerializeGltfNode(model->nodes[i], node); nodes.push_back(node); } output["nodes"] = nodes; } // SCENE if (model->defaultScene > -1) { SerializeNumberProperty<int>("scene", model->defaultScene, output); } // SCENES if (model->scenes.size()) { json scenes; for (unsigned int i = 0; i < model->scenes.size(); ++i) { json currentScene; SerializeGltfScene(model->scenes[i], currentScene); scenes.push_back(currentScene); } output["scenes"] = scenes; } // SKINS if (model->skins.size()) { json skins; for (unsigned int i = 0; i < model->skins.size(); ++i) { json skin; SerializeGltfSkin(model->skins[i], skin); skins.push_back(skin); } output["skins"] = skins; } // TEXTURES if (model->textures.size()) { json textures; for (unsigned int i = 0; i < model->textures.size(); ++i) { json texture; SerializeGltfTexture(model->textures[i], texture); textures.push_back(texture); } output["textures"] = textures; } // SAMPLERS if (model->samplers.size()) { json samplers; for (unsigned int i = 0; i < model->samplers.size(); ++i) { json sampler; SerializeGltfSampler(model->samplers[i], sampler); samplers.push_back(sampler); } output["samplers"] = samplers; } // CAMERAS if (model->cameras.size()) { json cameras; for (unsigned int i = 0; i < model->cameras.size(); ++i) { json camera; SerializeGltfCamera(model->cameras[i], camera); cameras.push_back(camera); } output["cameras"] = cameras; } // EXTENSIONS SerializeExtensionMap(model->extensions, output); // LIGHTS as KHR_lights_cmn if (model->lights.size()) { json lights; for (unsigned int i = 0; i < model->lights.size(); ++i) { json light; SerializeGltfLight(model->lights[i], light); lights.push_back(light); } json khr_lights_cmn; khr_lights_cmn["lights"] = lights; json ext_j; if (output.find("extensions") != output.end()) { ext_j = output["extensions"]; } ext_j["KHR_lights_cmn"] = khr_lights_cmn; output["extensions"] = ext_j; } // EXTRAS if (model->extras.Type() != NULL_TYPE) { SerializeValue("extras", model->extras, output); } if (writeBinary) { WriteBinaryGltfFile(filename, output.dump()); } else { WriteGltfFile(filename, output.dump(prettyPrint ? 2 : -1)); } return true; } } // namespace tinygltf #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TINYGLTF_IMPLEMENTATION
[ "asger.hoedt@3shape.com" ]
asger.hoedt@3shape.com
ce57e9ae70cf760c00a8023e5a88e263b5dfc48e
6e969b3cd1c95bf7897cb1cbaa03eddf99a8aa47
/sqf/outbreak_code/config/cfgZombies/cfgZombies.hpp
90105fdeebc4f3eb1a9f47241fde370c448d40dd
[]
no_license
thewanderer8891/Outbreak
e0963fb589e7d2e92fb3b43a6a99c5dceb521602
d85d1d58b70a5e0b4e1b2ef819d663e91522c66d
refs/heads/master
2021-01-16T00:22:35.577935
2015-11-07T17:58:59
2015-11-07T17:58:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
702
hpp
class CfgZombies { #include "cfgZombieClothes.hpp" }; class CfgFaces { class Man_A3; // External class reference class ZombieFace : Man_A3 { class Default { displayname = "Zombie Face"; texture = "\outbreak_assets\textures\faces\zombie_face_01.paa"; head = "DefaultHead_A3"; identityTypes[] = {}; material = "A3\Characters_F\Heads\Data\m_White_01.rvmat"; textureHL = "\A3\Characters_F\Heads\Data\hl_White_hairy_1_co.paa"; materialHL = "\A3\Characters_F\Heads\Data\hl_White_hairy_muscular.rvmat"; textureHL2 = "\A3\Characters_F\Heads\Data\hl_White_hairy_1_co.paa"; materialHL2 = "\A3\Characters_F\Heads\Data\hl_White_hairy_muscular.rvmat"; disabled = 0; }; }; };
[ "quacksterr.15@gmail.com" ]
quacksterr.15@gmail.com
d49c66415329c69301edeefe4798b2ff5efb2ae6
2b9418cfadd7ccbcf1754b5bf8014c49b9aef42e
/packages/directxtk_desktop_2017.2021.1.10.1/include/Audio.h
a026c2896e3524564c96ae75291e2a34e207f5de
[ "MIT" ]
permissive
SButtan93-dev/DX11Starter_ECSEngine
2d3064cd461e74d717e790d27531b0774ff55185
4031431f5c617155e82c8c901fc22a3046488dac
refs/heads/master
2023-07-16T22:15:31.108483
2021-09-02T05:38:18
2021-09-02T05:38:18
342,885,925
3
0
MIT
2021-07-20T23:56:53
2021-02-27T15:12:29
C++
UTF-8
C++
false
false
28,055
h
//-------------------------------------------------------------------------------------- // File: Audio.h // // DirectXTK for Audio header // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <string> #include <vector> #include <objbase.h> #include <mmreg.h> #include <Audioclient.h> #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) #include <xma2defs.h> #pragma comment(lib,"acphal.lib") #endif #ifndef XAUDIO2_HELPER_FUNCTIONS #define XAUDIO2_HELPER_FUNCTIONS #endif #if defined(USING_XAUDIO2_REDIST) || (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/) || defined(_XBOX_ONE) #define USING_XAUDIO2_9 #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) #define USING_XAUDIO2_8 #elif (_WIN32_WINNT >= 0x0601 /*_WIN32_WINNT_WIN7*/) #error Windows 7 SP1 requires the XAudio2Redist NuGet package https://aka.ms/xaudio2redist #else #error DirectX Tool Kit for Audio not supported on this platform #endif #include <xaudio2.h> #include <xaudio2fx.h> #include <x3daudio.h> #include <xapofx.h> #ifndef USING_XAUDIO2_REDIST #if defined(USING_XAUDIO2_8) && defined(NTDDI_WIN10) && !defined(_M_IX86) // The xaudio2_8.lib in the Windows 10 SDK for x86 is incorrectly annotated as __cdecl instead of __stdcall, so avoid using it in this case. #pragma comment(lib,"xaudio2_8.lib") #else #pragma comment(lib,"xaudio2.lib") #endif #endif #include <DirectXMath.h> namespace DirectX { class SoundEffectInstance; class SoundStreamInstance; //---------------------------------------------------------------------------------- struct AudioStatistics { size_t playingOneShots; // Number of one-shot sounds currently playing size_t playingInstances; // Number of sound effect instances currently playing size_t allocatedInstances; // Number of SoundEffectInstance allocated size_t allocatedVoices; // Number of XAudio2 voices allocated (standard, 3D, one-shots, and idle one-shots) size_t allocatedVoices3d; // Number of XAudio2 voices allocated for 3D size_t allocatedVoicesOneShot; // Number of XAudio2 voices allocated for one-shot sounds size_t allocatedVoicesIdle; // Number of XAudio2 voices allocated for one-shot sounds but not currently in use size_t audioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks #if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX) size_t xmaAudioBytes; // Total wave data (in bytes) in SoundEffects and in-memory WaveBanks allocated with ApuAlloc #endif size_t streamingBytes; // Total size of streaming buffers (in bytes) in streaming WaveBanks }; //---------------------------------------------------------------------------------- class IVoiceNotify { public: virtual ~IVoiceNotify() = default; IVoiceNotify(const IVoiceNotify&) = delete; IVoiceNotify& operator=(const IVoiceNotify&) = delete; IVoiceNotify(IVoiceNotify&&) = default; IVoiceNotify& operator=(IVoiceNotify&&) = default; virtual void __cdecl OnBufferEnd() = 0; // Notfication that a voice buffer has finished // Note this is called from XAudio2's worker thread, so it should perform very minimal and thread-safe operations virtual void __cdecl OnCriticalError() = 0; // Notification that the audio engine encountered a critical error virtual void __cdecl OnReset() = 0; // Notification of an audio engine reset virtual void __cdecl OnUpdate() = 0; // Notification of an audio engine per-frame update (opt-in) virtual void __cdecl OnDestroyEngine() noexcept = 0; // Notification that the audio engine is being destroyed virtual void __cdecl OnTrim() = 0; // Notification of a request to trim the voice pool virtual void __cdecl GatherStatistics(AudioStatistics& stats) const = 0; // Contribute to statistics request virtual void __cdecl OnDestroyParent() noexcept = 0; // Optional notification used by some objects protected: IVoiceNotify() = default; }; //---------------------------------------------------------------------------------- enum AUDIO_ENGINE_FLAGS : uint32_t { AudioEngine_Default = 0x0, AudioEngine_EnvironmentalReverb = 0x1, AudioEngine_ReverbUseFilters = 0x2, AudioEngine_UseMasteringLimiter = 0x4, AudioEngine_Debug = 0x10000, AudioEngine_ThrowOnNoAudioHW = 0x20000, AudioEngine_DisableVoiceReuse = 0x40000, }; enum SOUND_EFFECT_INSTANCE_FLAGS : uint32_t { SoundEffectInstance_Default = 0x0, SoundEffectInstance_Use3D = 0x1, SoundEffectInstance_ReverbUseFilters = 0x2, SoundEffectInstance_NoSetPitch = 0x4, SoundEffectInstance_UseRedirectLFE = 0x10000, }; enum AUDIO_ENGINE_REVERB : unsigned int { Reverb_Off, Reverb_Default, Reverb_Generic, Reverb_Forest, Reverb_PaddedCell, Reverb_Room, Reverb_Bathroom, Reverb_LivingRoom, Reverb_StoneRoom, Reverb_Auditorium, Reverb_ConcertHall, Reverb_Cave, Reverb_Arena, Reverb_Hangar, Reverb_CarpetedHallway, Reverb_Hallway, Reverb_StoneCorridor, Reverb_Alley, Reverb_City, Reverb_Mountains, Reverb_Quarry, Reverb_Plain, Reverb_ParkingLot, Reverb_SewerPipe, Reverb_Underwater, Reverb_SmallRoom, Reverb_MediumRoom, Reverb_LargeRoom, Reverb_MediumHall, Reverb_LargeHall, Reverb_Plate, Reverb_MAX }; enum SoundState { STOPPED = 0, PLAYING, PAUSED }; //---------------------------------------------------------------------------------- class AudioEngine { public: explicit AudioEngine( AUDIO_ENGINE_FLAGS flags = AudioEngine_Default, _In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const wchar_t* deviceId = nullptr, AUDIO_STREAM_CATEGORY category = AudioCategory_GameEffects) noexcept(false); AudioEngine(AudioEngine&& moveFrom) noexcept; AudioEngine& operator= (AudioEngine&& moveFrom) noexcept; AudioEngine(AudioEngine const&) = delete; AudioEngine& operator= (AudioEngine const&) = delete; virtual ~AudioEngine(); bool __cdecl Update(); // Performs per-frame processing for the audio engine, returns false if in 'silent mode' bool __cdecl Reset(_In_opt_ const WAVEFORMATEX* wfx = nullptr, _In_opt_z_ const wchar_t* deviceId = nullptr); // Reset audio engine from critical error/silent mode using a new device; can also 'migrate' the graph // Returns true if succesfully reset, false if in 'silent mode' due to no default device // Note: One shots are lost, all SoundEffectInstances are in the STOPPED state after successful reset void __cdecl Suspend() noexcept; void __cdecl Resume(); // Suspend/resumes audio processing (i.e. global pause/resume) float __cdecl GetMasterVolume() const noexcept; void __cdecl SetMasterVolume(float volume); // Master volume property for all sounds void __cdecl SetReverb(AUDIO_ENGINE_REVERB reverb); void __cdecl SetReverb(_In_opt_ const XAUDIO2FX_REVERB_PARAMETERS* native); // Sets environmental reverb for 3D positional audio (if active) void __cdecl SetMasteringLimit(int release, int loudness); // Sets the mastering volume limiter properties (if active) AudioStatistics __cdecl GetStatistics() const; // Gathers audio engine statistics WAVEFORMATEXTENSIBLE __cdecl GetOutputFormat() const noexcept; // Returns the format consumed by the mastering voice (which is the same as the device output if defaults are used) uint32_t __cdecl GetChannelMask() const noexcept; // Returns the output channel mask unsigned int __cdecl GetOutputChannels() const noexcept; // Returns the number of output channels bool __cdecl IsAudioDevicePresent() const noexcept; // Returns true if the audio graph is operating normally, false if in 'silent mode' bool __cdecl IsCriticalError() const noexcept; // Returns true if the audio graph is halted due to a critical error (which also places the engine into 'silent mode') // Voice pool management. void __cdecl SetDefaultSampleRate(int sampleRate); // Sample rate for voices in the reuse pool (defaults to 44100) void __cdecl SetMaxVoicePool(size_t maxOneShots, size_t maxInstances); // Maximum number of voices to allocate for one-shots and instances // Note: one-shots over this limit are ignored; too many instance voices throws an exception void __cdecl TrimVoicePool(); // Releases any currently unused voices // Internal-use functions void __cdecl AllocateVoice(_In_ const WAVEFORMATEX* wfx, SOUND_EFFECT_INSTANCE_FLAGS flags, bool oneshot, _Outptr_result_maybenull_ IXAudio2SourceVoice** voice); void __cdecl DestroyVoice(_In_ IXAudio2SourceVoice* voice) noexcept; // Should only be called for instance voices, not one-shots void __cdecl RegisterNotify(_In_ IVoiceNotify* notify, bool usesUpdate); void __cdecl UnregisterNotify(_In_ IVoiceNotify* notify, bool usesOneShots, bool usesUpdate); // XAudio2 interface access IXAudio2* __cdecl GetInterface() const noexcept; IXAudio2MasteringVoice* __cdecl GetMasterVoice() const noexcept; IXAudio2SubmixVoice* __cdecl GetReverbVoice() const noexcept; X3DAUDIO_HANDLE& __cdecl Get3DHandle() const noexcept; // Static functions struct RendererDetail { std::wstring deviceId; std::wstring description; }; static std::vector<RendererDetail> __cdecl GetRendererDetails(); // Returns a list of valid audio endpoint devices private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; }; //---------------------------------------------------------------------------------- class WaveBank { public: WaveBank(_In_ AudioEngine* engine, _In_z_ const wchar_t* wbFileName); WaveBank(WaveBank&& moveFrom) noexcept; WaveBank& operator= (WaveBank&& moveFrom) noexcept; WaveBank(WaveBank const&) = delete; WaveBank& operator= (WaveBank const&) = delete; virtual ~WaveBank(); void __cdecl Play(unsigned int index); void __cdecl Play(unsigned int index, float volume, float pitch, float pan); void __cdecl Play(_In_z_ const char* name); void __cdecl Play(_In_z_ const char* name, float volume, float pitch, float pan); std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); std::unique_ptr<SoundStreamInstance> __cdecl CreateStreamInstance(unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); std::unique_ptr<SoundStreamInstance> __cdecl CreateStreamInstance(_In_z_ const char* name, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); bool __cdecl IsPrepared() const noexcept; bool __cdecl IsInUse() const noexcept; bool __cdecl IsStreamingBank() const noexcept; size_t __cdecl GetSampleSizeInBytes(unsigned int index) const noexcept; // Returns size of wave audio data size_t __cdecl GetSampleDuration(unsigned int index) const noexcept; // Returns the duration in samples size_t __cdecl GetSampleDurationMS(unsigned int index) const noexcept; // Returns the duration in milliseconds const WAVEFORMATEX* __cdecl GetFormat(unsigned int index, _Out_writes_bytes_(maxsize) WAVEFORMATEX* wfx, size_t maxsize) const noexcept; int __cdecl Find(_In_z_ const char* name) const; #ifdef USING_XAUDIO2_9 bool __cdecl FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; #else void __cdecl FillSubmitBuffer(unsigned int index, _Out_ XAUDIO2_BUFFER& buffer) const; #endif void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance); HANDLE __cdecl GetAsyncHandle() const noexcept; bool __cdecl GetPrivateData(unsigned int index, _Out_writes_bytes_(datasize) void* data, size_t datasize); private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; }; //---------------------------------------------------------------------------------- class SoundEffect { public: SoundEffect(_In_ AudioEngine* engine, _In_z_ const wchar_t* waveFileName); SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData, _In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes); SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData, _In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes, uint32_t loopStart, uint32_t loopLength); #ifdef USING_XAUDIO2_9 SoundEffect(_In_ AudioEngine* engine, _Inout_ std::unique_ptr<uint8_t[]>& wavData, _In_ const WAVEFORMATEX* wfx, _In_reads_bytes_(audioBytes) const uint8_t* startAudio, size_t audioBytes, _In_reads_(seekCount) const uint32_t* seekTable, size_t seekCount); #endif SoundEffect(SoundEffect&& moveFrom) noexcept; SoundEffect& operator= (SoundEffect&& moveFrom) noexcept; SoundEffect(SoundEffect const&) = delete; SoundEffect& operator= (SoundEffect const&) = delete; virtual ~SoundEffect(); void __cdecl Play(); void __cdecl Play(float volume, float pitch, float pan); std::unique_ptr<SoundEffectInstance> __cdecl CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); bool __cdecl IsInUse() const noexcept; size_t __cdecl GetSampleSizeInBytes() const noexcept; // Returns size of wave audio data size_t __cdecl GetSampleDuration() const noexcept; // Returns the duration in samples size_t __cdecl GetSampleDurationMS() const noexcept; // Returns the duration in milliseconds const WAVEFORMATEX* __cdecl GetFormat() const noexcept; #ifdef USING_XAUDIO2_9 bool __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer, _Out_ XAUDIO2_BUFFER_WMA& wmaBuffer) const; #else void __cdecl FillSubmitBuffer(_Out_ XAUDIO2_BUFFER& buffer) const; #endif void __cdecl UnregisterInstance(_In_ IVoiceNotify* instance); private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; }; //---------------------------------------------------------------------------------- struct AudioListener : public X3DAUDIO_LISTENER { AudioListener() noexcept { memset(this, 0, sizeof(X3DAUDIO_LISTENER)); OrientFront.z = -1.f; OrientTop.y = 1.f; } void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), v); } void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; Position.z = pos.z; } void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v); } void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; Velocity.z = vel.z; } void XM_CALLCONV SetOrientation(FXMVECTOR forward, FXMVECTOR up) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up); } void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept { OrientFront.x = forward.x; OrientTop.x = up.x; OrientFront.y = forward.y; OrientTop.y = up.y; OrientFront.z = forward.z; OrientTop.z = up.z; } void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept { XMVECTOR forward = XMVector3Rotate(g_XMIdentityR2, quat); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward); XMVECTOR up = XMVector3Rotate(g_XMIdentityR1, quat); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up); } void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept // Updates velocity and orientation by tracking changes in position over time... { if (dt > 0.f) { XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&Position)); XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); XMVECTOR vt = XMVectorReplicate(dt); XMVECTOR v = XMVectorDivide(vDelta, vt); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v); vDelta = XMVector3Normalize(vDelta); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), vDelta); v = XMVector3Cross(upDir, vDelta); v = XMVector3Normalize(v); v = XMVector3Cross(vDelta, v); v = XMVector3Normalize(v); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), v); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), newPos); } } }; //---------------------------------------------------------------------------------- struct AudioEmitter : public X3DAUDIO_EMITTER { float EmitterAzimuths[XAUDIO2_MAX_AUDIO_CHANNELS]; AudioEmitter() noexcept : EmitterAzimuths{} { memset(this, 0, sizeof(X3DAUDIO_EMITTER)); OrientFront.z = -1.f; OrientTop.y = ChannelRadius = CurveDistanceScaler = DopplerScaler = 1.f; ChannelCount = 1; pChannelAzimuths = EmitterAzimuths; InnerRadiusAngle = X3DAUDIO_PI / 4.0f; } void XM_CALLCONV SetPosition(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), v); } void __cdecl SetPosition(const XMFLOAT3& pos) noexcept { Position.x = pos.x; Position.y = pos.y; Position.z = pos.z; } void XM_CALLCONV SetVelocity(FXMVECTOR v) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v); } void __cdecl SetVelocity(const XMFLOAT3& vel) noexcept { Velocity.x = vel.x; Velocity.y = vel.y; Velocity.z = vel.z; } void XM_CALLCONV SetOrientation(FXMVECTOR forward, FXMVECTOR up) noexcept { XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up); } void __cdecl SetOrientation(const XMFLOAT3& forward, const XMFLOAT3& up) noexcept { OrientFront.x = forward.x; OrientTop.x = up.x; OrientFront.y = forward.y; OrientTop.y = up.y; OrientFront.z = forward.z; OrientTop.z = up.z; } void XM_CALLCONV SetOrientationFromQuaternion(FXMVECTOR quat) noexcept { XMVECTOR forward = XMVector3Rotate(g_XMIdentityR2, quat); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), forward); XMVECTOR up = XMVector3Rotate(g_XMIdentityR1, quat); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), up); } void XM_CALLCONV Update(FXMVECTOR newPos, XMVECTOR upDir, float dt) noexcept // Updates velocity and orientation by tracking changes in position over time... { if (dt > 0.f) { XMVECTOR lastPos = XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&Position)); XMVECTOR vDelta = XMVectorSubtract(newPos, lastPos); XMVECTOR vt = XMVectorReplicate(dt); XMVECTOR v = XMVectorDivide(vDelta, vt); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Velocity), v); vDelta = XMVector3Normalize(vDelta); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientFront), vDelta); v = XMVector3Cross(upDir, vDelta); v = XMVector3Normalize(v); v = XMVector3Cross(vDelta, v); v = XMVector3Normalize(v); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&OrientTop), v); XMStoreFloat3(reinterpret_cast<XMFLOAT3*>(&Position), newPos); } } }; //---------------------------------------------------------------------------------- class SoundEffectInstance { public: SoundEffectInstance(SoundEffectInstance&& moveFrom) noexcept; SoundEffectInstance& operator= (SoundEffectInstance&& moveFrom) noexcept; SoundEffectInstance(SoundEffectInstance const&) = delete; SoundEffectInstance& operator= (SoundEffectInstance const&) = delete; virtual ~SoundEffectInstance(); void __cdecl Play(bool loop = false); void __cdecl Stop(bool immediate = true) noexcept; void __cdecl Pause() noexcept; void __cdecl Resume(); void __cdecl SetVolume(float volume); void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; // Private constructors SoundEffectInstance(_In_ AudioEngine* engine, _In_ SoundEffect* effect, SOUND_EFFECT_INSTANCE_FLAGS flags); SoundEffectInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); friend std::unique_ptr<SoundEffectInstance> __cdecl SoundEffect::CreateInstance(SOUND_EFFECT_INSTANCE_FLAGS); friend std::unique_ptr<SoundEffectInstance> __cdecl WaveBank::CreateInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS); }; //---------------------------------------------------------------------------------- class SoundStreamInstance { public: SoundStreamInstance(SoundStreamInstance&& moveFrom) noexcept; SoundStreamInstance& operator= (SoundStreamInstance&& moveFrom) noexcept; SoundStreamInstance(SoundStreamInstance const&) = delete; SoundStreamInstance& operator= (SoundStreamInstance const&) = delete; virtual ~SoundStreamInstance(); void __cdecl Play(bool loop = false); void __cdecl Stop(bool immediate = true) noexcept; void __cdecl Pause() noexcept; void __cdecl Resume(); void __cdecl SetVolume(float volume); void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); bool __cdecl IsLooped() const noexcept; SoundState __cdecl GetState() noexcept; IVoiceNotify* __cdecl GetVoiceNotify() const noexcept; private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; // Private constructors SoundStreamInstance(_In_ AudioEngine* engine, _In_ WaveBank* effect, unsigned int index, SOUND_EFFECT_INSTANCE_FLAGS flags); friend std::unique_ptr<SoundStreamInstance> __cdecl WaveBank::CreateStreamInstance(unsigned int, SOUND_EFFECT_INSTANCE_FLAGS); }; //---------------------------------------------------------------------------------- class DynamicSoundEffectInstance { public: DynamicSoundEffectInstance(_In_ AudioEngine* engine, _In_opt_ std::function<void __cdecl(DynamicSoundEffectInstance*)> bufferNeeded, int sampleRate, int channels, int sampleBits = 16, SOUND_EFFECT_INSTANCE_FLAGS flags = SoundEffectInstance_Default); DynamicSoundEffectInstance(DynamicSoundEffectInstance&& moveFrom) noexcept; DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance&& moveFrom) noexcept; DynamicSoundEffectInstance(DynamicSoundEffectInstance const&) = delete; DynamicSoundEffectInstance& operator= (DynamicSoundEffectInstance const&) = delete; virtual ~DynamicSoundEffectInstance(); void __cdecl Play(); void __cdecl Stop(bool immediate = true) noexcept; void __cdecl Pause() noexcept; void __cdecl Resume(); void __cdecl SetVolume(float volume); void __cdecl SetPitch(float pitch); void __cdecl SetPan(float pan); void __cdecl Apply3D(const AudioListener& listener, const AudioEmitter& emitter, bool rhcoords = true); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, size_t audioBytes); void __cdecl SubmitBuffer(_In_reads_bytes_(audioBytes) const uint8_t* pAudioData, uint32_t offset, size_t audioBytes); SoundState __cdecl GetState() noexcept; size_t __cdecl GetSampleDuration(size_t bytes) const noexcept; // Returns duration in samples of a buffer of a given size size_t __cdecl GetSampleDurationMS(size_t bytes) const noexcept; // Returns duration in milliseconds of a buffer of a given size size_t __cdecl GetSampleSizeInBytes(uint64_t duration) const noexcept; // Returns size of a buffer for a duration given in milliseconds int __cdecl GetPendingBufferCount() const noexcept; const WAVEFORMATEX* __cdecl GetFormat() const noexcept; private: // Private implementation. class Impl; std::unique_ptr<Impl> pImpl; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec" #endif DEFINE_ENUM_FLAG_OPERATORS(AUDIO_ENGINE_FLAGS); DEFINE_ENUM_FLAG_OPERATORS(SOUND_EFFECT_INSTANCE_FLAGS); #ifdef __clang__ #pragma clang diagnostic pop #endif }
[ "saurabhbuttan1749@gmail.com" ]
saurabhbuttan1749@gmail.com
2480526a9c47d126cf223c77a664a57e0336fd02
4c7f04313e055ff08de887d76007a4aa96377396
/gazebo7_7.14.0_exercise/gazebo/sensors/WideAngleCameraSensor.cc
a2296489d30097e596cf1b323ee15998f5cedd62
[ "Apache-2.0" ]
permissive
WalteR-MittY-pro/Gazebo-MPI
8ef51f80b49bcf56510337fdb67f1d2f4b605275
6e3f702463e6ac2d59194aac1c8a9a37ef4d0153
refs/heads/master
2023-03-31T07:41:44.718326
2020-03-02T07:22:13
2020-03-02T07:22:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,911
cc
/* * Copyright (C) 2015 Open Source Robotics Foundation * * 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 * * 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 <mutex> #include <boost/algorithm/string.hpp> #include "gazebo/common/Events.hh" #include "gazebo/common/Exception.hh" #include "gazebo/common/Image.hh" #include "gazebo/transport/transport.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/physics/World.hh" #include "gazebo/rendering/RenderEngine.hh" #include "gazebo/rendering/Camera.hh" #include "gazebo/rendering/WideAngleCamera.hh" #include "gazebo/rendering/Scene.hh" #include "gazebo/rendering/RenderingIface.hh" #include "gazebo/sensors/SensorFactory.hh" #include "gazebo/sensors/CameraSensor.hh" #include "gazebo/sensors/Noise.hh" #include "gazebo/sensors/WideAngleCameraSensorPrivate.hh" #include "gazebo/sensors/WideAngleCameraSensor.hh" using namespace gazebo; using namespace sensors; GZ_REGISTER_STATIC_SENSOR("wideanglecamera", WideAngleCameraSensor) ////////////////////////////////////////////////// WideAngleCameraSensor::WideAngleCameraSensor() : CameraSensor(), dataPtr(new WideAngleCameraSensorPrivate) { } ////////////////////////////////////////////////// void WideAngleCameraSensor::Init() { if (rendering::RenderEngine::Instance()->GetRenderPathType() == rendering::RenderEngine::NONE) { gzerr << "Unable to create WideAngleCameraSensor. Rendering is disabled." << std::endl; return; } std::string worldName = this->world->GetName(); if (!worldName.empty()) { this->scene = rendering::get_scene(worldName); if (!this->scene) { this->scene = rendering::create_scene(worldName, false, true); // This usually means rendering is not available if (!this->scene) { gzerr << "Unable to create WideAngleCameraSensor." << std::endl; return; } } this->camera = this->scene->CreateWideAngleCamera( this->sdf->Get<std::string>("name"), false); if (!this->camera) { gzerr << "Unable to create wide angle camera sensor[mono_camera]" << std::endl; return; } this->camera->SetCaptureData(true); sdf::ElementPtr cameraSdf = this->sdf->GetElement("camera"); this->camera->Load(cameraSdf); // Do some sanity checks if (this->camera->ImageWidth() == 0 || this->camera->ImageHeight() == 0) { gzerr << "image has zero size" << std::endl; return; } this->camera->Init(); this->camera->CreateRenderTexture(this->Name() + "_RttTex"); ignition::math::Pose3d cameraPose = this->pose; if (cameraSdf->HasElement("pose")) cameraPose = cameraSdf->Get<ignition::math::Pose3d>("pose") + cameraPose; this->camera->SetWorldPose(cameraPose); this->camera->AttachToVisual(this->ParentId(), true); if (cameraSdf->HasElement("noise")) { this->noises[CAMERA_NOISE] = NoiseFactory::NewNoiseModel(cameraSdf->GetElement("noise"), this->Type()); this->noises[CAMERA_NOISE]->SetCamera(this->camera); } } else gzerr << "No world name" << std::endl; // Disable clouds and moon on server side until fixed and also to improve // performance this->scene->SetSkyXMode(rendering::Scene::GZ_SKYX_ALL & ~rendering::Scene::GZ_SKYX_CLOUDS & ~rendering::Scene::GZ_SKYX_MOON); Sensor::Init(); } ////////////////////////////////////////////////// void WideAngleCameraSensor::Load(const std::string &_worldName) { Sensor::Load(_worldName); this->imagePub = this->node->Advertise<msgs::ImageStamped>( this->Topic(), 50); std::string lensTopicName = "~/"; lensTopicName += this->ParentName() + "/" + this->Name() + "/lens/"; boost::replace_all(lensTopicName, "::", "/"); sdf::ElementPtr lensSdf = this->sdf->GetElement("camera")->GetElement("lens"); // create a topic that publishes lens states this->dataPtr->lensPub = this->node->Advertise<msgs::CameraLens>( lensTopicName+"info", 1); this->dataPtr->lensSub = this->node->Subscribe(lensTopicName + "control", &WideAngleCameraSensor::OnCtrlMessage, this); } ////////////////////////////////////////////////// void WideAngleCameraSensor::Fini() { this->dataPtr->lensPub.reset(); this->dataPtr->lensSub.reset(); CameraSensor::Fini(); } ////////////////////////////////////////////////// bool WideAngleCameraSensor::UpdateImpl(const bool _force) { if (!CameraSensor::UpdateImpl(_force)) return false; if (this->dataPtr->lensPub && this->dataPtr->lensPub->HasConnections()) { std::lock_guard<std::mutex> lock(this->dataPtr->lensCmdMutex); for (; !this->dataPtr->hfovCmdQueue.empty(); this->dataPtr->hfovCmdQueue.pop()) { this->camera->SetHFOV(ignition::math::Angle( this->dataPtr->hfovCmdQueue.front())); } msgs::CameraLens msg; rendering::WideAngleCameraPtr wcamera = boost::dynamic_pointer_cast<rendering::WideAngleCamera>( this->camera); const rendering::CameraLens *lens = wcamera->Lens(); msg.set_type(lens->Type()); msg.set_c1(lens->C1()); msg.set_c2(lens->C2()); msg.set_c3(lens->C3()); msg.set_f(lens->F()); msg.set_fun(lens->Fun()); msg.set_scale_to_hfov(lens->ScaleToHFOV()); msg.set_cutoff_angle(lens->CutOffAngle()); msg.set_hfov(wcamera->HFOV().Radian()); msg.set_env_texture_size(wcamera->EnvTextureSize()); this->dataPtr->lensPub->Publish(msg); } return true; } ////////////////////////////////////////////////// void WideAngleCameraSensor::OnCtrlMessage(ConstCameraLensPtr &_msg) { std::lock_guard<std::mutex> lock(this->dataPtr->lensCmdMutex); rendering::WideAngleCameraPtr wcamera = boost::dynamic_pointer_cast<rendering::WideAngleCamera>( this->camera); rendering::CameraLens *lens = (wcamera->Lens()); if (_msg->has_type()) lens->SetType(_msg->type()); if (_msg->has_c1()) lens->SetC1(_msg->c1()); if (_msg->has_c2()) lens->SetC2(_msg->c2()); if (_msg->has_c3()) lens->SetC3(_msg->c3()); if (_msg->has_f()) lens->SetF(_msg->f()); if (_msg->has_cutoff_angle()) lens->SetCutOffAngle(_msg->cutoff_angle()); if (_msg->has_hfov()) this->dataPtr->hfovCmdQueue.push(_msg->hfov()); if (_msg->has_fun()) lens->SetFun(_msg->fun()); if (_msg->has_scale_to_hfov()) lens->SetScaleToHFOV(_msg->scale_to_hfov()); }
[ "tjpu_zenglei@sina.com" ]
tjpu_zenglei@sina.com
bfe0f921eeb1b30aeb87454eeb2a4fefe876cbf4
81be1588059136c70fef297c428e6a3f461cd12e
/src/dsu.cpp
44bfbf68576fc3e69c40ea8ebdd4bad725d2f9cf
[]
no_license
JohnXinhua/icpc
c3515625f54bdaac5ab0b3e3ec57a14482246cec
129738ac5c11f15879d8c3375ded0987d93c40af
refs/heads/master
2020-12-25T21:23:30.407286
2015-05-04T10:34:55
2015-05-04T10:34:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
void make_set(int v) { parent[v] = v; rank[v] = 0; } int find_set(int v) { if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank[a] < rank[b]) swap(a, b); parent[b] = a; if (rank[a] == rank[b]) ++rank[a]; } }
[ "thomas@ahle.dk" ]
thomas@ahle.dk
2c357b5d7fc2e3e843b94a7d3c1550219d862777
63e6cc4d88a45987a3ca56da885e554daddae430
/src/common/log/LogD.cpp
dd13774bfe2319fce6677f5f160bcf3217f7b0c5
[ "MIT" ]
permissive
MicroTargetEngine/MTE-Core
206618d3f471600a32dc8a2ba5fe754ac31e31b1
36a801171f5dc8fae51abdf30b7e36407fc31687
refs/heads/master
2021-01-19T09:00:19.392500
2016-10-08T15:19:22
2016-10-08T15:19:22
82,081,294
0
0
null
null
null
null
UTF-8
C++
false
false
2,028
cpp
/********************************************************************* File: LogD.cpp Description: LogD Source Part. Author: Doohoon Kim (Gabriel Kim, invi.dh.kim@gmail.com) Created: 2016/09/18 Copyright (c) 2016, Team "FireBase", Open Robot Marathon, IRC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ #include "LogD.hpp" #if defined(_LogD_hpp_) #if !defined(NO_LOG_MODE) void LogD::Logging(const char *CallValueString, const char *Message, ...) { #if defined(LOG_WRITE_MODE) va_list _TArgument_List; char _TStr[BUFFER_MAX_4096] = { 0, }; string _TString; va_start(_TArgument_List, Message); vsprintf(_TStr, std::string(Message).append("\n").c_str(), _TArgument_List); va_end(_TArgument_List); TLogCallback(CallValueString, _TStr); #endif } #endif void LogD::SetCallback(void (*TCallbackFunc) (const char *, const char *)) { #if defined(LOG_WRITE_MODE) TLogCallback = TCallbackFunc; #endif } #endif // _LogD_hpp_
[ "invi.dh.kim@gmail.com" ]
invi.dh.kim@gmail.com
9112cf6e69124f97fb41e42ca34441b5c4d6737c
7d02ec35e8230c05fbe3d797b43b2cb1fd2947af
/5_longest_palindromic_substring.cpp
2341f48d670762a39e52d7613cc18b2efb0d60e0
[]
no_license
lip23/leetcode
0f4343d9ce925df4f753ff90367193521496e05c
c821da8d04278a2f2b59c8021572ffcdb1100e58
refs/heads/master
2021-05-26T07:43:22.728268
2020-04-10T16:32:56
2020-04-10T16:32:56
127,937,590
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
// file: 5_longest_palindromic_substring.cpp // author:lipcat // time: 2020-01-08 23:55 class Solution { public: // solution // 依次判断s[i:j]是否回文 string longestPalindrome(string s) { string ans; for (int i = 0; i < s.length(); ++i) { for (int j = s.length() - 1; j >= i && j - i + 1 > ans.length(); --j) { int beg = i; int end = j; while (beg < end && s[beg] == s[end]) { ++beg; --end; } if (beg >= end) { ans = s.substr(i, j - i + 1); break; } } } return ans; } }; class Solution { public: // solution // dp O(n*n) // dp[i][j] 表示 s[i:j]是否回文 // dp[i][j] = 1 if (s[i] == s[j] && dp[i + 1][j - 1] && j - i > 1) // = 0 else string longestPalindrome(string s) { string ans; vector<vector<int>> dp(s.length(), vector<int>(s.length(), 0)); for (int l = 1; l <= s.length(); ++l) { for (int i = 0; i <= s.length() - l; ++i) { int j = i + l - 1; if (s[i] == s[j] && (l <= 2 || dp[i + 1][j - 1])) { dp[i][j] = 1; if (l > ans.length()) { ans = s.substr(i, l); } } } } return ans; } };
[ "liptju@163.com" ]
liptju@163.com
221c2ca0c4f2cbc4810b25d0e6cfcddf26503649
ba444c530390b369d92d2a446b2667ed10674ac4
/problems/11661.cpp
46b8d4edbf6e416af81792059171379946c730e8
[]
no_license
mkroflin/UVa
62c00eede8b803487fa96c6f34dc089b7ea80df5
aa9815f710db094fb67ceafb485b139de58e9745
refs/heads/master
2022-03-21T05:04:32.445579
2018-11-15T19:44:19
2018-11-15T19:44:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
#include <iostream> using namespace std; int main() { int n; while (cin >> n, n) { string s; cin >> s; int dist = n; for (int i = 0; i < n; ++i) { if (s[i] == 'Z') { dist = 0; break; } if (s[i] != '.') { int j = i + 1; while (s[j] == '.' && j < n) j++; if (j == n || s[j] == s[i]) continue; if (j - i < dist) dist = j - i; } } cout << dist << '\n'; } }
[ "matej.kroflin@gmail.com" ]
matej.kroflin@gmail.com
f2226a8ddb2100450d037989479ef6e5f34ae771
7c17e5606be4ad8d1785226deb3fe5677e04d099
/stuff/urho3d/Source/Samples/00_ignition/relative_pose/_zzz/pioneer_src/ui/TextEntry.h
b3934ee5cfc2ff9792ae55ac31f1ad8f0e6dedb2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
z80/ignition
a4fa4adb32fed843ee41bcdc83e41ba3d70f048b
629c9d998d53de33f3b123910770f73c9e783234
refs/heads/master
2023-07-21T17:46:52.510964
2023-04-04T17:18:41
2023-04-04T17:18:41
206,724,558
14
3
null
2022-06-23T00:02:44
2019-09-06T06:06:22
C++
UTF-8
C++
false
false
1,069
h
// Copyright © 2008-2020 Pioneer Developers. See AUTHORS.txt for details // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt #ifndef UI_TEXTENTRY_H #define UI_TEXTENTRY_H #include "Container.h" #include "Label.h" #include "graphics/Drawables.h" namespace UI { class TextEntry : public Container { public: virtual Point PreferredSize(); virtual void Layout(); virtual void Update(); virtual void Draw(); TextEntry *SetText(const std::string &text); const std::string &GetText() const { return m_label->GetText(); } virtual bool IsSelectable() const { return true; } sigc::signal<void, const std::string &> onChange; sigc::signal<void, const std::string &> onEnter; protected: friend class Context; TextEntry(Context *context, const std::string &text); virtual void HandleKeyDown(const KeyboardEvent &event); virtual void HandleTextInput(const TextInputEvent &event); private: Label *m_label; Uint32 m_cursor; vector3f m_cursorVertices[2]; Graphics::Drawables::Lines m_lines; }; } // namespace UI #endif
[ "bashkirov.sergey@gmail.com" ]
bashkirov.sergey@gmail.com
3c1460933a526b0b3497dec1823bd27a5c2b2e29
82ffbe324536805b25cf01bb068d93fe0f6f26ab
/leetcode C++/DP/2D/Palindrome_Partitioning_II/answer.cpp
37b3922b23052ce4dd936eadb315ffbb875b5f92
[]
no_license
caixiaomo/leetcode-ans1
b4e0fab2da42036f8409b9adb6ccf33e22bbac11
d6ba2b76a3cf469abb97b170caa2f99c1564306f
refs/heads/master
2020-03-31T01:23:08.989746
2015-03-02T14:31:13
2015-03-02T14:31:13
31,544,222
1
1
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
/* Palindrome Partitioning II Total Accepted: 6637 Total Submissions: 38258 My Submissions Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. */ /* Two dp 1.find if the string s.substr(i, j - i + 1) is parlindrome 2.find the min cut */ class Solution { public: int minCut(string s) { int size = s.size(); vector<vector<bool>> palin(size, vector<bool>(size, false)); //first dp for(int i = size - 1; i >= 0; i--){ for(int j = i; j <= size - 1; j++){ if(s[i] == s[j] && (j - i < 2 || palin[i + 1][j - 1])){ palin[i][j] = true; } } } vector<int> matrix(s.size() + 1, INT_MAX); matrix[s.size()] = -1; //second dp for(int i = s.size() - 1; i >= 0; i--){ for(int j = i + 1; j <= s.size(); j++){ if(palin[i][j - 1]){ matrix[i] = min(matrix[i], matrix[j] + 1); } } } return matrix[0]; } };
[ "caixiaomo1993@gmail.com" ]
caixiaomo1993@gmail.com
bc68fd5fb288097fd6ae1b01603631fc57369b25
a50268b0fb485f13f040acb89b75db79c7b857b1
/swordCode/27_ConvertBinarySearchTree.cpp
0b6d67b4a8c6be5a2ce699fbe51d86bde97300c9
[]
no_license
MasonSu/leetcode
6957403f5c1e14a2a25ee62295cd9ba32a4b28f9
d4d8a425684784f204defef04c9a2d9d94db7d11
refs/heads/master
2021-01-21T15:07:25.303110
2020-05-20T14:45:14
2020-05-20T14:45:14
59,660,754
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
cpp
/** * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序 * 的双向链表。要求不能创建任何新的结点,只能调整树 * 中结点指针的指向。 */ #include <iostream> #include <stack> using std::stack; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x): val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* Convert(TreeNode* pRootOfTree) { if (pRootOfTree == NULL) return NULL; TreeNode *pre = NULL, *root = pRootOfTree; stack<TreeNode*> nodes; while (pRootOfTree || nodes.size()) { if (pRootOfTree) { nodes.push(pRootOfTree); pRootOfTree = pRootOfTree->left; } else { TreeNode *node = nodes.top(); nodes.pop(); if (pre == NULL) pre = node; else { pre->right = node; node->left = pre; pre = node; } pRootOfTree = node->right; } } while (root->left) root = root->left; return root; } };
[ "xiaxzheng@gmail.com" ]
xiaxzheng@gmail.com
8724b32a9ae725a0cdeeef0e44142bbff6019e4d
653f49d47f6f88c7c8c0b0343b02e8a5bb8ae66d
/dart_Lite/src/dynamics/BodyNodeDynamics.h
bbcbb02d2116fc66e7a53b1cebf9d3999d60475b
[]
no_license
ana-GT/huboCode
53a860454c40090fc61d68ba8c3d6b205e810e42
a45fd1b78b7c3c6a9b37d6097dddfeca831994e4
refs/heads/master
2021-01-10T14:30:48.400413
2013-05-12T04:05:07
2013-05-12T04:05:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,770
h
/* * Copyright (c) 2011, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Sumit Jain <sumit@cc.gatech.edu> * Date: 07/21/2011 * * Geoorgia Tech Graphics Lab and Humanoid Robotics Lab * * Directed by Prof. C. Karen Liu and Prof. Mike Stilman * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNAMICS_BODYNODE_DYNAMICS_H #define DYNAMICS_BODYNODE_DYNAMICS_H #include <vector> #include <Eigen/Dense> #include "kinematics/BodyNode.h" #include "utils/EigenHelper.h" namespace dynamics{ /** @brief BodyNodeDynamics class represents a single node of the skeleton for dynamics */ class BodyNodeDynamics : public kinematics::BodyNode{ public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // we need this aligned allocator because we have Matrix4d as members in this class BodyNodeDynamics(const char *_name = NULL); ///< Default constructor. The name can be up to 128 virtual ~BodyNodeDynamics(); ///< Default destructor // Following functions called automatically by the skeleton: computeInverseDynamicsLinear and computeDynamics respectively void initInverseDynamics(); ///< initialize data structures for linear inverse dynamics computation void initDynamics(); ///< initialize data structures for non-recursive dynamics computation // Inverse Dynamics Eigen::MatrixXd mJwJoint; ///< Jacobian matrix for the parent joint Eigen::MatrixXd mJwDotJoint; ///< Time derivative of the Jacobian matrix for the parent joint Eigen::Vector3d mVelBody; ///< linear velocity expressed in the *local frame* of the body Eigen::Vector3d mVelDotBody; ///< linear acceleration expressed in the *local frame* of the body Eigen::Vector3d mOmegaBody; ///< angular velocity expressed in the *local frame* of the body Eigen::Vector3d mOmegaDotBody; ///< angular acceleration expressed in the *local frame* of the body Eigen::Vector3d mForceJointBody; ///< the constraint joint force in Cartesian coordinates, expressed in the local frame of the body instead of the joint Eigen::Vector3d mTorqueJointBody; ///< the torque in Cartesian coordinates for the joint expressed in the local frame of the body instead of the joint Eigen::Vector3d mExtForceBody; ///< the external Cartesian force applied to the body; usually computed from mContacts Eigen::Vector3d mExtTorqueBody; ///< the external Cartesian torque applied to the body; usually directly supplied from outside; contribution of the linear force will be considered later in the computation void computeInvDynVelocities( const Eigen::Vector3d &_gravity, const Eigen::VectorXd *_qdot, const Eigen::VectorXd *_qdotdot, bool _computeJacobians=true ); ///< computes the velocities in the first pass of the algorithm; also computes Transform W etc using updateTransform; computes Jacobians Jv and Jw if the flag is true; replaces updateFirstDerivatives of non-recursive dynamics void computeInvDynForces( const Eigen::Vector3d &_gravity, const Eigen::VectorXd *_qdot, const Eigen::VectorXd *_qdotdot, bool _withExternalForces ); ///< computes the forces in the second pass of the algorithm // non-recursive Dynamics formulation - M*qdd + C*qdot + g = 0 void updateSecondDerivatives(); ///< Update the second derivatives of the transformations void updateSecondDerivatives(Eigen::Vector3d _offset); ///< Update the second derivatives of the transformations Eigen::Vector3d mVel; ///< Linear velocity in the world frame Eigen::Vector3d mOmega; ///< Angular velocity in the world frame Eigen::MatrixXd mM; ///< Mass matrix of dimension numDependentDofs x numDependentDofs; to be added carefully to the skeleton mass matrix Eigen::MatrixXd mC; ///< Coriolis matrix of dimension numDependentDofs x numDependentDofs; to be added carefully to the skeleton Coriolis matrix Eigen::VectorXd mCvec; ///< Coriolis vector of dimension numDependentDofs x 1; mCvec = mC*qdot Eigen::VectorXd mG; ///< Gravity vector or generalized gravity forces; dimension numDependentDofs x 1 Eigen::VectorXd mFext; ///< generalized external forces this node contributes: J^TF; dimension numDependentDofs x 1 void evalVelocity(const Eigen::VectorXd &_qDotSkel); ///< evaluates the velocity of the COM in the world frame void evalOmega(const Eigen::VectorXd &_qDotSkel); ///< evaluates the Omega in the world frame void evalMassMatrix(); ///< evaluates the mass matrix mM void evalCoriolisMatrix(const Eigen::VectorXd &_qDotSkel); ///< evaluates the Coriolis matrix mC void evalCoriolisVector(const Eigen::VectorXd &_qDotSkel); ///< evaluates the Coriolis vector mCvec directy: i.e. shortcut for mC*qdot void evalGravityVector(const Eigen::Vector3d &_gravity); ///< evaluates the gravity vector mG in the generalized coordinates void evalExternalForces( Eigen::VectorXd& _extForce ); ///< evaluates the external forces mFext in the generalized coordinates as J^TF void evalExternalForcesRecursive( Eigen::VectorXd& _extForce ); ///< evaluates the external forces mFext in the generalized coordinates recursively void jointCartesianToGeneralized( const Eigen::Vector3d& _cForce, Eigen::VectorXd& _gForce, bool _isTorque=true ); ///< convert cartesian forces in joint frame to generalized forces void bodyCartesianToGeneralized( const Eigen::Vector3d& _cForce, Eigen::VectorXd& _gForce, bool _isTorque=true ); ///< convert cartesian forces in body com frame to generalized forces void getGeneralized( Eigen::VectorXd& _gForce ); ///< convert coriolis forces in cartesian space to generalized forces // add functions to add to the existing *full* matrices typically for the entire skeleton void aggregateMass(Eigen::MatrixXd &_M); void aggregateCoriolis(Eigen::MatrixXd &_C); void aggregateCoriolisVec(Eigen::VectorXd &_Cvec); void aggregateGravity(Eigen::VectorXd &_G); // add and remove contact points where forces are applied void addExtForce( const Eigen::Vector3d& _offset, const Eigen::Vector3d& _force, bool _isOffsetLocal=true, bool _isForceLocal=false ); ///< apply linear Cartesian forces to this node. A force is defined by a point of application and a force vector. The last two parameters specify frames of the first two parameters. Coordinate transformations are applied when needed. The point of application and the force in local coordinates are stored in mContacts. When conversion is needed, make sure the transformations are avaialble void addExtTorque( const Eigen::Vector3d& _torque, bool _isLocal); ///< apply Cartesian torque to the node. The torque in local coordinates is accumulated in mExtTorqueBody void clearExternalForces(); ///< clean up structures that store external forces: mContacts, mFext, mExtForceBody and mExtTorqueBody; called from @SkeletonDynamics::clearExternalForces Eigen::Vector3d evalLinMomentum(); Eigen::Vector3d evalAngMomentum(Eigen::Vector3d _pivot); inline Eigen::MatrixXd getJvDeriv(int _qIndex) const { return mJvq[_qIndex]; }; protected: bool mInitializedInvDyn; ///< true if linear inverse dynamics is initialized; init functions initialize only if false bool mInitializedNonRecursiveDyn; ///< true if non recursive dynamics is initialized; init function initialize only if false // non-recursive Dynamics formulation - second derivatives EIGEN_VV_MAT4D mTqq; ///< Partial derivative of local transformation wrt local dofs; each element is a 4x4 matrix EIGEN_VV_MAT4D mWqq; ///< Partial derivative of world transformation wrt all dependent dofs; each element is a 4x4 matrix std::vector<Eigen::MatrixXd> mJvq; ///< Linear Jacobian derivative wrt to all the dependent dofs std::vector<Eigen::MatrixXd> mJwq; ///< Angular Jacobian derivative wrt to all the dependent dofs Eigen::MatrixXd mJvDot; ///< Time derivative of the Linear velocity Jacobian Eigen::MatrixXd mJwDot; ///< Time derivative of the Angular velocity Jacobian std::vector< std::pair<Eigen::Vector3d, Eigen::Vector3d> > mContacts; ///< list of contact points where external forces are applied ///< contact points are a pair of (local point offset, Cartesian force in local coordinates) Eigen::Matrix4d getLocalSecondDeriv(const kinematics::Dof *_q1, const kinematics::Dof *_q2) const; void evalJacDerivLin(int _qi, Eigen::Vector3d _offset); ///< Evaluate the first derivatives of the linear Jacobian wrt to the dependent dofs void evalJacDerivAng(int _qi); ///< Evaluate the first derivatives of the angular Jacobian wrt to the dependent dofs void evalJacDotLin(const Eigen::VectorXd &_qDotSkel); ///< Evaluate time derivative of the linear Jacobian of this body node (num cols == num dependent dofs) void evalJacDotAng(const Eigen::VectorXd &_qDotSkel); ///< Evaluate time derivative of the angular Jacobian of this body node (num cols == num dependent dofs) }; } // namespace dynamics #endif // #ifndef DYNAMICS_BODYNODE_DYNAMICS_H
[ "ahuaman3@gatech.edu" ]
ahuaman3@gatech.edu
1441bc6e4e043e5c41144e21c9f25a65cc0832eb
ef317a2be1c57ac37742b3764f42b32aaf73b578
/Manager/NI_XFSMgr.cpp
d0854c6dcfecc92365b813d990238629e85ecfae
[]
no_license
bytewerk-public/openxfs
e09b485afdc73b58a371b65eca1663524758749a
5774f66bb107c0da114232bdbdd26b432c0c0365
refs/heads/master
2023-03-30T18:12:38.868002
2020-07-01T19:18:50
2020-07-01T19:18:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,074
cpp
// NI_XFSMgr.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "NI_XFSMgr.h" #include "NI_XFSManager.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // // Note! // // If this DLL is dynamically linked against the MFC // DLLs, any functions exported from this DLL which // call into MFC must have the AFX_MANAGE_STATE macro // added at the very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // ///////////////////////////////////////////////////////////////////////////// // CNI_XFSMgrApp BEGIN_MESSAGE_MAP(CNI_XFSMgrApp, CWinApp) //{{AFX_MSG_MAP(CNI_XFSMgrApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNI_XFSMgrApp construction CNI_XFSMgrApp::CNI_XFSMgrApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CNI_XFSMgrApp object CNI_XFSMgrApp theApp; ///////////////////////////////////////////////////////////////////////////// // CNI_XFSMgrApp initialization BOOL CNI_XFSMgrApp::InitInstance() { if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; } return TRUE; }
[ "amochkin@bytewerk.com" ]
amochkin@bytewerk.com
553b0a0da3c92650281e7091feb5a1809320afab
9b7291d81a416bde2ec181229601eb2e33c7b8b2
/monophoton/phoMet/phi.cc
db56d634a3fa7465f0266a5887579e78e6ed66cf
[]
no_license
MiT-HEP/MonoX
ab1528e72dad2590a0ae64f1a1d47195139e1749
224ee01107a94cedf8563c497edb2f326b99d9b1
refs/heads/master
2021-01-24T06:04:16.645559
2019-11-15T09:18:40
2019-11-15T09:18:40
41,823,403
1
9
null
2018-07-19T17:05:30
2015-09-02T19:33:33
Python
UTF-8
C++
false
false
4,662
cc
#include "TreeEntries_simpletree.h" #include "TTree.h" #include "TFile.h" #include "TH1.h" #include "TLorentzVector.h" #include "math.h" void phi(TTree* _input, char const* _outputName, double _sampleWeight = 1., TH1* _npvweight = 0) { printf("Running skim\n"); simpletree::Event event; event.setStatus(*_input, false, {"*"}); event.setAddress(*_input, {"run", "lumi", "event", "weight", "npv", "photons", "jets", "t1Met"}); TFile* outputFile(TFile::Open(_outputName, "recreate")); TTree* output(new TTree("skim", "efficiency")); double weight; simpletree::PhotonCollection outTag("tag"); outTag.init(); simpletree::PhotonCollection outProbe("probe"); outProbe.init(); float probeMass[1]; bool probeIsPhoton[1]; float probePtRaw[1]; float probePtCorrUp[1]; float probePtCorrDown[1]; unsigned short njets; simpletree::LorentzVectorM recoil; float recoilPt; float recoilEta; float recoilPhi; float recoilMass; output->Branch("run", &event.run, "run/i"); output->Branch("lumi", &event.lumi, "lumi/i"); output->Branch("event", &event.event, "event/i"); output->Branch("weight", &weight, "weight/D"); output->Branch("npv", &event.npv, "npv/s"); outTag.book(*output); outProbe.book(*output); output->Branch("probe.mass", probeMass, "probe.mass[probe.size]/F"); output->Branch("probe.isPhoton", probeIsPhoton, "probe.isPhoton[probe.size]/O"); output->Branch("probe.ptRaw", probePtRaw, "probe.ptRaw[probe.size]/F"); output->Branch("probe.ptCorrUp", probePtCorrUp, "probe.ptCorrUp[probe.size]/F"); output->Branch("probe.ptCorrDown", probePtCorrDown, "probe.ptCorrDown[probe.size]/F"); output->Branch("njets", &njets, "njets/s"); output->Branch("recoil.pt", &recoilPt, "recoil.pt/F"); output->Branch("recoil.eta", &recoilEta, "recoil.eta/F"); output->Branch("recoil.phi", &recoilPhi, "recoil.phi/F"); output->Branch("recoil.mass", &recoilMass, "recoil.mass/F"); output->Branch("t1Met.met", &event.t1Met.met, "t1Met.met/F"); output->Branch("t1Met.phi", &event.t1Met.phi, "t1Met.phi/F"); long iEntry(0); while (_input->GetEntry(iEntry++) > 0) { if (iEntry % 1000000 == 0) printf("Event %ld\n", iEntry); auto& photons(event.photons); auto& jets(event.jets); auto& t1Met(event.t1Met); recoil.SetCoordinates(0.,0.,0.,0.); unsigned pair[] = {unsigned(-1), unsigned(-1)}; for (unsigned iTag(0); iTag != photons.size(); ++iTag) { auto& tag(photons[iTag]); if ( !(tag.medium && tag.pt > 175. && tag.isEB)) continue; // printf("Tag found\n"); for (unsigned iPho(0); iPho != photons.size(); ++iPho) { auto& pho(photons[iPho]); if ( !(pho.pt > 30.)) continue; // printf("Medium photon found for probe\n"); if (std::abs(tag.dPhi(pho)) < 2.5) continue; // printf("tag/probe back to back\n"); outTag.resize(1); outTag[0] = tag; outProbe.resize(1); outProbe[0] = pho; probeMass[0] = 0.; probeIsPhoton[0] = true; probePtRaw[0] = -1.; probePtCorrUp[0] = -1.; probePtCorrDown[0] = -1.; pair[0] = iTag; pair[1] = iPho; break; } if (pair[0] < photons.size()) break; for (unsigned iJet(0); iJet != jets.size(); ++iJet) { auto& jet(jets[iJet]); if ( !(jet.pt > 30.)) continue; // printf("Medium photon found for probe\n"); if (std::abs(tag.dPhi(jet)) < 2.5) continue; // printf("tag/probe back to back\n"); outTag.resize(1); outTag[0] = tag; outProbe.resize(1); outProbe[0].pt = jet.pt; outProbe[0].eta = jet.eta; outProbe[0].phi = jet.phi; probeMass[0] = jet.mass; probeIsPhoton[0] = false; probePtRaw[0] = jet.ptRaw; probePtCorrUp[0] = jet.ptCorrUp; probePtCorrDown[0] = jet.ptCorrDown; pair[0] = iTag; pair[1] = iJet; break; } if (pair[0] < photons.size()) break; } if (pair[0] > photons.size()) continue; // printf("Pass TnP pair selection\n"); njets = 0; for (unsigned iJet(0); iJet != jets.size(); ++iJet) { if (iJet == pair[1]) continue; auto& jet(jets[iJet]); if (jet.pt > 30.) { njets++; recoil += jet.p4(); } } recoilPt = recoil.Pt(); recoilEta = recoil.Eta(); recoilPhi = recoil.Phi(); recoilMass = recoil.M(); weight = _sampleWeight * event.weight; if (_npvweight) { int iX(_npvweight->FindFixBin(event.npv)); if (iX == 0) iX = 1; if (iX > _npvweight->GetNbinsX()) iX = _npvweight->GetNbinsX(); weight *= _npvweight->GetBinContent(iX); } output->Fill(); } outputFile->cd(); output->Write(); delete outputFile; printf("Finished skim.\n"); }
[ "ballen@mit.edu" ]
ballen@mit.edu
15f9d30cf6d6cd100bbc22072c6f1ff78b3bab61
6fb7464f6bad513e4a72f182b4848fda9de5380c
/periodfind/ce.cpp
c3777d9279dc217f2766273c10bdf8b3f4a44e46
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
bfhealy/periodfind
0ef852f1eed7c4cdf02f776ce0bc71a801f9f6b1
3b42ed10a2a5bccb62d98def8a1f871aba2ff993
refs/heads/master
2023-04-07T10:36:36.751721
2021-04-11T03:18:36
2021-04-11T03:18:36
null
0
0
null
null
null
null
UTF-8
C++
false
true
454,194
cpp
/* Generated by Cython 0.29.21 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_29_21" #define CYTHON_HEX_VERSION 0x001D15F0 #define CYTHON_FUTURE_DIVISION 1 #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #ifndef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef __cplusplus #error "Cython files generated with the C++ option must be compiled with a C++ compiler." #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #else #define CYTHON_INLINE inline #endif #endif template<typename T> void __Pyx_call_destructor(T& x) { x.~T(); } template<typename T> class __Pyx_FakeReference { public: __Pyx_FakeReference() : ptr(NULL) { } __Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { } T *operator->() { return ptr; } T *operator&() { return ptr; } operator T&() { return *ptr; } template<typename U> bool operator ==(U other) { return *ptr == other; } template<typename U> bool operator !=(U other) { return *ptr != other; } private: T *ptr; }; #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 #define PyMem_RawMalloc(n) PyMem_Malloc(n) #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) #define PyMem_RawFree(p) PyMem_Free(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) #include "pythread.h" #define Py_tss_NEEDS_INIT 0 typedef int Py_tss_t; static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { *key = PyThread_create_key(); return 0; } static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); *key = Py_tss_NEEDS_INIT; return key; } static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { PyObject_Free(key); } static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { return *key != Py_tss_NEEDS_INIT; } static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { PyThread_delete_key(*key); *key = Py_tss_NEEDS_INIT; } static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { return PyThread_set_key_value(*key, value); } static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { return PyThread_get_key_value(*key); } #endif #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) #else #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) #endif #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #ifndef PyObject_Unicode #define PyObject_Unicode PyObject_Str #endif #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #if PY_VERSION_HEX >= 0x030900A4 #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) #else #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) #endif #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #else #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_MARK_ERR_POS(f_index, lineno) \ { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } #define __PYX_ERR(f_index, lineno, Ln_error) \ { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__periodfind__ce #define __PYX_HAVE_API__periodfind__ce /* Early includes */ #include <string.h> #include <stdio.h> #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" /* NumPy API declarations from "numpy/__init__.pxd" */ #include <stddef.h> #include "ios" #include "new" #include "stdexcept" #include "typeinfo" #include <vector> #include "./cuda/ce.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "periodfind/ce.pyx", "stringsource", "__init__.pxd", "type.pxd", }; /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":697 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":698 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":699 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":700 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":704 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":705 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":706 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":707 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":711 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":712 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":721 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":722 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":723 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":725 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":726 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":727 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":729 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":730 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":732 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":733 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":734 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ struct __pyx_obj_10periodfind_2ce_ConditionalEntropy; struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc; struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":736 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":737 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":738 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":740 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; /* "periodfind/ce.pyx":47 * const size_t num_p_dts) const; * * cdef class ConditionalEntropy: # <<<<<<<<<<<<<< * """Conditional Entropy based light curve analysis. * */ struct __pyx_obj_10periodfind_2ce_ConditionalEntropy { PyObject_HEAD ConditionalEntropy *ce; }; /* "periodfind/ce.pyx":88 * mag_bin_extent) * * def calc(self, # <<<<<<<<<<<<<< * list times, * list mags, */ struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc { PyObject_HEAD std::vector<size_t> __pyx_v_mags_lens; std::vector<size_t> __pyx_v_times_lens; }; /* "periodfind/ce.pyx":182 * * # Make sure the individual lengths match * if any(t != m for t, m in zip(times_lens, mags_lens)): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr { PyObject_HEAD struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *__pyx_outer_scope; PyObject *__pyx_v_m; PyObject *__pyx_v_t; }; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* IterFinish.proto */ static CYTHON_INLINE int __Pyx_IterFinish(void); /* UnpackItemEndCheck.proto */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /* IsLittleEndian.proto */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); /* BufferFormatCheck.proto */ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /* BufferGetAndValidate.proto */ #define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)\ ((obj == Py_None || obj == NULL) ?\ (__Pyx_ZeroBuffer(buf), 0) :\ __Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)) static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static void __Pyx_ZeroBuffer(Py_buffer* buf); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static Py_ssize_t __Pyx_minusones[] = { -1, -1, -1, -1, -1, -1, -1, -1 }; static Py_ssize_t __Pyx_zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; /* PyDictVersioning.proto */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS #define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } #define __Pyx_GetModuleGlobalNameUncached(var, name) {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFallbackError.proto */ static void __Pyx_RaiseBufferFallbackError(void); /* BufferIndexError.proto */ static void __Pyx_RaiseBufferIndexError(int axis); #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif /* PyObjectCall2Args.proto */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* PyFloatBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyFloat_AddObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check); #else #define __Pyx_PyFloat_AddObjC(op1, op2, floatval, inplace, zerodivision_check)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* ListAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* GetItemInt.proto */ #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); #define __Pyx_PyObject_Dict_GetItem(obj, name)\ (likely(PyDict_CheckExact(obj)) ?\ __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) #endif /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* PyObject_GenericGetAttrNoDict.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr #endif /* PyObject_GenericGetAttr.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr #endif /* PyObjectGetAttrStrNoError.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); /* TypeImport.proto */ #ifndef __PYX_HAVE_RT_ImportType_proto #define __PYX_HAVE_RT_ImportType_proto enum __Pyx_ImportType_CheckSize { __Pyx_ImportType_CheckSize_Error = 0, __Pyx_ImportType_CheckSize_Warn = 1, __Pyx_ImportType_CheckSize_Ignore = 2 }; static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* CppExceptionConversion.proto */ #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { try { if (PyErr_Occurred()) ; // let the latest Python exn pass through and ignore the current one else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::bad_typeid& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif /* None.proto */ #include <new> /* RealImag.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* CIntFromPy.proto */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) /* FetchCommonType.proto */ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* PyObjectGetMethod.proto */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); /* PyObjectCallMethod1.proto */ static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); /* CoroutineBase.proto */ typedef PyObject *(*__pyx_coroutine_body_t)(PyObject *, PyThreadState *, PyObject *); #if CYTHON_USE_EXC_INFO_STACK #define __Pyx_ExcInfoStruct _PyErr_StackItem #else typedef struct { PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; } __Pyx_ExcInfoStruct; #endif typedef struct { PyObject_HEAD __pyx_coroutine_body_t body; PyObject *closure; __Pyx_ExcInfoStruct gi_exc_state; PyObject *gi_weakreflist; PyObject *classobj; PyObject *yieldfrom; PyObject *gi_name; PyObject *gi_qualname; PyObject *gi_modulename; PyObject *gi_code; int resume_label; char is_running; } __pyx_CoroutineObject; static __pyx_CoroutineObject *__Pyx__Coroutine_New( PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name); static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name); static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); static int __Pyx_Coroutine_clear(PyObject *self); static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); static PyObject *__Pyx_Coroutine_Close(PyObject *self); static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); #if CYTHON_USE_EXC_INFO_STACK #define __Pyx_Coroutine_SwapException(self) #define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) #else #define __Pyx_Coroutine_SwapException(self) {\ __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ } #define __Pyx_Coroutine_ResetAndClearException(self) {\ __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ } #endif #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) #else #define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) #endif static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); /* PatchModuleWithCoroutine.proto */ static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); /* PatchGeneratorABC.proto */ static int __Pyx_patch_abc(void); /* Generator.proto */ #define __Pyx_Generator_USED static PyTypeObject *__pyx_GeneratorType = 0; #define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType) #define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ __Pyx__Coroutine_New(__pyx_GeneratorType, body, code, closure, name, qualname, module_name) static PyObject *__Pyx_Generator_Next(PyObject *self); static int __pyx_Generator_init(void); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'cpython.mem' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void); /*proto*/ /* Module declarations from 'libc.stddef' */ /* Module declarations from 'libcpp.vector' */ /* Module declarations from 'periodfind.ce' */ static PyTypeObject *__pyx_ptype_10periodfind_2ce_ConditionalEntropy = 0; static PyTypeObject *__pyx_ptype_10periodfind_2ce___pyx_scope_struct__calc = 0; static PyTypeObject *__pyx_ptype_10periodfind_2ce___pyx_scope_struct_1_genexpr = 0; static PyObject *__pyx_convert_vector_to_py_size_t(const std::vector<size_t> &); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t = { "float32_t", NULL, sizeof(__pyx_t_5numpy_float32_t), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "periodfind.ce" extern int __pyx_module_is_main_periodfind__ce; int __pyx_module_is_main_periodfind__ce = 0; /* Implementation of 'periodfind.ce' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_NotImplementedError; static PyObject *__pyx_builtin_zip; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_ImportError; static const char __pyx_k_n[] = "n"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_max[] = "max"; static const char __pyx_k_min[] = "min"; static const char __pyx_k_zip[] = "zip"; static const char __pyx_k_args[] = "args"; static const char __pyx_k_mags[] = "mags"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_name[] = "__name__"; static const char __pyx_k_send[] = "send"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_close[] = "close"; static const char __pyx_k_dtype[] = "dtype"; static const char __pyx_k_n_mag[] = "n_mag"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_stats[] = "stats"; static const char __pyx_k_throw[] = "throw"; static const char __pyx_k_times[] = "times"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_output[] = "output"; static const char __pyx_k_reduce[] = "__reduce__"; static const char __pyx_k_float32[] = "float32"; static const char __pyx_k_genexpr[] = "genexpr"; static const char __pyx_k_n_phase[] = "n_phase"; static const char __pyx_k_n_stats[] = "n_stats"; static const char __pyx_k_periods[] = "periods"; static const char __pyx_k_stdmean[] = "stdmean"; static const char __pyx_k_getstate[] = "__getstate__"; static const char __pyx_k_setstate[] = "__setstate__"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_normalize[] = "normalize"; static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; static const char __pyx_k_Statistics[] = "Statistics"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_period_dts[] = "period_dts"; static const char __pyx_k_periodfind[] = "periodfind"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_Periodogram[] = "Periodogram"; static const char __pyx_k_periodogram[] = "periodogram"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_periodfind_ce[] = "periodfind.ce"; static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; static const char __pyx_k_mag_bin_extent[] = "mag_bin_extent"; static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; static const char __pyx_k_phase_bin_extent[] = "phase_bin_extent"; static const char __pyx_k_significance_type[] = "significance_type"; static const char __pyx_k_ConditionalEntropy[] = "ConditionalEntropy"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_NotImplementedError[] = "NotImplementedError"; static const char __pyx_k_calc_locals_genexpr[] = "calc.<locals>.genexpr"; static const char __pyx_k_statistics_from_data[] = "statistics_from_data"; static const char __pyx_k_Provides_an_interface_for_analy[] = "\nProvides an interface for analyzing light curves using the Conditional Entropy\nalgorithm.\n"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_Only_stats_output_is_implemented[] = "Only \"stats\" output is implemented"; static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_ConditionalEntropy; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_s_NotImplementedError; static PyObject *__pyx_kp_u_Only_stats_output_is_implemented; static PyObject *__pyx_n_s_Periodogram; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_Statistics; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_args; static PyObject *__pyx_n_s_calc_locals_genexpr; static PyObject *__pyx_n_s_cline_in_traceback; static PyObject *__pyx_n_s_close; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_float32; static PyObject *__pyx_n_s_genexpr; static PyObject *__pyx_n_s_getstate; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_mag_bin_extent; static PyObject *__pyx_n_s_mags; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_max; static PyObject *__pyx_n_s_min; static PyObject *__pyx_n_s_n; static PyObject *__pyx_n_s_n_mag; static PyObject *__pyx_n_s_n_phase; static PyObject *__pyx_n_s_n_stats; static PyObject *__pyx_n_s_name; static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; static PyObject *__pyx_n_s_normalize; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_output; static PyObject *__pyx_n_s_period_dts; static PyObject *__pyx_n_s_periodfind; static PyObject *__pyx_n_s_periodfind_ce; static PyObject *__pyx_n_u_periodogram; static PyObject *__pyx_n_s_periods; static PyObject *__pyx_n_s_phase_bin_extent; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_reduce; static PyObject *__pyx_n_s_reduce_cython; static PyObject *__pyx_n_s_reduce_ex; static PyObject *__pyx_n_s_send; static PyObject *__pyx_n_s_setstate; static PyObject *__pyx_n_s_setstate_cython; static PyObject *__pyx_n_s_significance_type; static PyObject *__pyx_n_s_statistics_from_data; static PyObject *__pyx_n_u_stats; static PyObject *__pyx_n_u_stdmean; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_throw; static PyObject *__pyx_n_s_times; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_n_s_zip; static int __pyx_pf_10periodfind_2ce_18ConditionalEntropy___cinit__(struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, PyObject *__pyx_v_n_phase, PyObject *__pyx_v_n_mag, PyObject *__pyx_v_phase_bin_extent, PyObject *__pyx_v_mag_bin_extent); /* proto */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_4calc_genexpr(PyObject *__pyx_self); /* proto */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_2calc(struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, PyObject *__pyx_v_times, PyObject *__pyx_v_mags, PyArrayObject *__pyx_v_periods, PyArrayObject *__pyx_v_period_dts, PyObject *__pyx_v_output, PyObject *__pyx_v_normalize, PyObject *__pyx_v_n_stats, PyObject *__pyx_v_significance_type); /* proto */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_tp_new_10periodfind_2ce_ConditionalEntropy(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_10periodfind_2ce___pyx_scope_struct__calc(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_10periodfind_2ce___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_float_5eneg_4; static PyObject *__pyx_float_0_999; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_10; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; /* Late includes */ /* "periodfind/ce.pyx":77 * cdef CppConditionalEntropy* ce * * def __cinit__(self, # <<<<<<<<<<<<<< * n_phase=10, * n_mag=10, */ /* Python wrapper */ static int __pyx_pw_10periodfind_2ce_18ConditionalEntropy_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_pw_10periodfind_2ce_18ConditionalEntropy_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_n_phase = 0; PyObject *__pyx_v_n_mag = 0; PyObject *__pyx_v_phase_bin_extent = 0; PyObject *__pyx_v_mag_bin_extent = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n_phase,&__pyx_n_s_n_mag,&__pyx_n_s_phase_bin_extent,&__pyx_n_s_mag_bin_extent,0}; PyObject* values[4] = {0,0,0,0}; values[0] = ((PyObject *)__pyx_int_10); values[1] = ((PyObject *)__pyx_int_10); values[2] = ((PyObject *)__pyx_int_1); values[3] = ((PyObject *)__pyx_int_1); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n_phase); if (value) { values[0] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 1: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n_mag); if (value) { values[1] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 2: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_phase_bin_extent); if (value) { values[2] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 3: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mag_bin_extent); if (value) { values[3] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(0, 77, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_n_phase = values[0]; __pyx_v_n_mag = values[1]; __pyx_v_phase_bin_extent = values[2]; __pyx_v_mag_bin_extent = values[3]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 0, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 77, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_10periodfind_2ce_18ConditionalEntropy___cinit__(((struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *)__pyx_v_self), __pyx_v_n_phase, __pyx_v_n_mag, __pyx_v_phase_bin_extent, __pyx_v_mag_bin_extent); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_10periodfind_2ce_18ConditionalEntropy___cinit__(struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, PyObject *__pyx_v_n_phase, PyObject *__pyx_v_n_mag, PyObject *__pyx_v_phase_bin_extent, PyObject *__pyx_v_mag_bin_extent) { int __pyx_r; __Pyx_RefNannyDeclarations size_t __pyx_t_1; size_t __pyx_t_2; size_t __pyx_t_3; size_t __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); /* "periodfind/ce.pyx":83 * mag_bin_extent=1): * self.ce = new CppConditionalEntropy( * n_phase, # <<<<<<<<<<<<<< * n_mag, * phase_bin_extent, */ __pyx_t_1 = __Pyx_PyInt_As_size_t(__pyx_v_n_phase); if (unlikely((__pyx_t_1 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 83, __pyx_L1_error) /* "periodfind/ce.pyx":84 * self.ce = new CppConditionalEntropy( * n_phase, * n_mag, # <<<<<<<<<<<<<< * phase_bin_extent, * mag_bin_extent) */ __pyx_t_2 = __Pyx_PyInt_As_size_t(__pyx_v_n_mag); if (unlikely((__pyx_t_2 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 84, __pyx_L1_error) /* "periodfind/ce.pyx":85 * n_phase, * n_mag, * phase_bin_extent, # <<<<<<<<<<<<<< * mag_bin_extent) * */ __pyx_t_3 = __Pyx_PyInt_As_size_t(__pyx_v_phase_bin_extent); if (unlikely((__pyx_t_3 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 85, __pyx_L1_error) /* "periodfind/ce.pyx":86 * n_mag, * phase_bin_extent, * mag_bin_extent) # <<<<<<<<<<<<<< * * def calc(self, */ __pyx_t_4 = __Pyx_PyInt_As_size_t(__pyx_v_mag_bin_extent); if (unlikely((__pyx_t_4 == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 86, __pyx_L1_error) /* "periodfind/ce.pyx":82 * phase_bin_extent=1, * mag_bin_extent=1): * self.ce = new CppConditionalEntropy( # <<<<<<<<<<<<<< * n_phase, * n_mag, */ __pyx_v_self->ce = new ConditionalEntropy(__pyx_t_1, __pyx_t_2, __pyx_t_3, __pyx_t_4); /* "periodfind/ce.pyx":77 * cdef CppConditionalEntropy* ce * * def __cinit__(self, # <<<<<<<<<<<<<< * n_phase=10, * n_mag=10, */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "periodfind/ce.pyx":88 * mag_bin_extent) * * def calc(self, # <<<<<<<<<<<<<< * list times, * list mags, */ /* Python wrapper */ static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_3calc(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10periodfind_2ce_18ConditionalEntropy_2calc[] = "Runs Conditional Entropy calculations on a list of light curves.\n\n Computes a Conditional Entropy periodogram for each of the input light\n curves, then returns either statistics or a full periodogram, depending\n on what is requested.\n\n Parameters\n ----------\n times : list of ndarray\n List of light curve times.\n \n mags : list of ndarray\n List of light curve magnitudes.\n \n periods : ndarray\n Array of trial periods\n \n period_dts : ndarray\n Array of trial period time derivatives\n \n output : {'stats', 'periodogram'}, default='stats'\n Type of output that should be returned\n \n normalize : bool, default=True\n Whether to normalize the light curve magnitudes\n\n n_stats : int, default=1\n Number of output `Statistics` to return if `output='stats'`\n \n significance_type : {'stdmean', 'madmedian'}, default='stdmean'\n Specifies the significance statistic that should be used. See the\n documentation for the `Statistics` class for more information.\n Used only if `output='stats'`.\n \n Returns\n -------\n data : list of Statistics or list of Periodogram\n If `output='stats'`, then returns a list of `Statistics` objects,\n one for each light curve.\n\n If `output='periodogram'`, then returns a list of `Periodogram`\n objects, one for each light curve.\n \n Notes\n -----\n The times and magnitudes arrays must be given such that the pair\n `(times[i], magnitudes[i])` gives the `i`th light curve. As such,\n `times[i]` and `magnitudes[i]` must have the same length for all `i`.\n \n Normalization is required for the underlying Conditional Entropy\n implementation to work, so if the data is ""not already in the interval\n (0, 1), then `normalize=True` should be used.\n "; static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_3calc(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_times = 0; PyObject *__pyx_v_mags = 0; PyArrayObject *__pyx_v_periods = 0; PyArrayObject *__pyx_v_period_dts = 0; PyObject *__pyx_v_output = 0; PyObject *__pyx_v_normalize = 0; PyObject *__pyx_v_n_stats = 0; PyObject *__pyx_v_significance_type = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("calc (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_times,&__pyx_n_s_mags,&__pyx_n_s_periods,&__pyx_n_s_period_dts,&__pyx_n_s_output,&__pyx_n_s_normalize,&__pyx_n_s_n_stats,&__pyx_n_s_significance_type,0}; PyObject* values[8] = {0,0,0,0,0,0,0,0}; values[4] = ((PyObject *)__pyx_n_u_stats); /* "periodfind/ce.pyx":94 * np.ndarray[ndim=1, dtype=np.float32_t] period_dts, * output="stats", * normalize=True, # <<<<<<<<<<<<<< * n_stats=1, * significance_type='stdmean'): */ values[5] = ((PyObject *)Py_True); values[6] = ((PyObject *)__pyx_int_1); values[7] = ((PyObject *)__pyx_n_u_stdmean); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); CYTHON_FALLTHROUGH; case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); CYTHON_FALLTHROUGH; case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); CYTHON_FALLTHROUGH; case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_times)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("calc", 0, 4, 8, 1); __PYX_ERR(0, 88, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_periods)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("calc", 0, 4, 8, 2); __PYX_ERR(0, 88, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_period_dts)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("calc", 0, 4, 8, 3); __PYX_ERR(0, 88, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_output); if (value) { values[4] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 5: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_normalize); if (value) { values[5] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 6: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_n_stats); if (value) { values[6] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 7: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_significance_type); if (value) { values[7] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "calc") < 0)) __PYX_ERR(0, 88, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); CYTHON_FALLTHROUGH; case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); CYTHON_FALLTHROUGH; case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); CYTHON_FALLTHROUGH; case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_times = ((PyObject*)values[0]); __pyx_v_mags = ((PyObject*)values[1]); __pyx_v_periods = ((PyArrayObject *)values[2]); __pyx_v_period_dts = ((PyArrayObject *)values[3]); __pyx_v_output = values[4]; __pyx_v_normalize = values[5]; __pyx_v_n_stats = values[6]; __pyx_v_significance_type = values[7]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("calc", 0, 4, 8, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 88, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.calc", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_times), (&PyList_Type), 1, "times", 1))) __PYX_ERR(0, 89, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mags), (&PyList_Type), 1, "mags", 1))) __PYX_ERR(0, 90, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_periods), __pyx_ptype_5numpy_ndarray, 1, "periods", 0))) __PYX_ERR(0, 91, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_period_dts), __pyx_ptype_5numpy_ndarray, 1, "period_dts", 0))) __PYX_ERR(0, 92, __pyx_L1_error) __pyx_r = __pyx_pf_10periodfind_2ce_18ConditionalEntropy_2calc(((struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *)__pyx_v_self), __pyx_v_times, __pyx_v_mags, __pyx_v_periods, __pyx_v_period_dts, __pyx_v_output, __pyx_v_normalize, __pyx_v_n_stats, __pyx_v_significance_type); /* "periodfind/ce.pyx":88 * mag_bin_extent) * * def calc(self, # <<<<<<<<<<<<<< * list times, * list mags, */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_gb_10periodfind_2ce_18ConditionalEntropy_4calc_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ /* "periodfind/ce.pyx":182 * * # Make sure the individual lengths match * if any(t != m for t, m in zip(times_lens, mags_lens)): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_4calc_genexpr(PyObject *__pyx_self) { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *__pyx_cur_scope; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("genexpr", 0); __pyx_cur_scope = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)__pyx_tp_new_10periodfind_2ce___pyx_scope_struct_1_genexpr(__pyx_ptype_10periodfind_2ce___pyx_scope_struct_1_genexpr, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_cur_scope)) { __pyx_cur_scope = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)Py_None); __Pyx_INCREF(Py_None); __PYX_ERR(0, 182, __pyx_L1_error) } else { __Pyx_GOTREF(__pyx_cur_scope); } __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *) __pyx_self; __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); { __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_10periodfind_2ce_18ConditionalEntropy_4calc_2generator, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_calc_locals_genexpr, __pyx_n_s_periodfind_ce); if (unlikely(!gen)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_DECREF(__pyx_cur_scope); __Pyx_RefNannyFinishContext(); return (PyObject *) gen; } /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.calc.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_gb_10periodfind_2ce_18ConditionalEntropy_4calc_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); PyObject *__pyx_r = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; Py_ssize_t __pyx_t_4; PyObject *(*__pyx_t_5)(PyObject *); PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *(*__pyx_t_8)(PyObject *); int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("genexpr", 0); switch (__pyx_generator->resume_label) { case 0: goto __pyx_L3_first_run; default: /* CPython raises the right error here */ __Pyx_RefNannyFinishContext(); return NULL; } __pyx_L3_first_run:; if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 182, __pyx_L1_error) __pyx_t_1 = __pyx_convert_vector_to_py_size_t(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_times_lens); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __pyx_convert_vector_to_py_size_t(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_mags_lens); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = NULL; } else { __pyx_t_4 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 182, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; for (;;) { if (likely(!__pyx_t_5)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_4 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 182, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif } else { if (__pyx_t_4 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_4); __Pyx_INCREF(__pyx_t_2); __pyx_t_4++; if (unlikely(0 < 0)) __PYX_ERR(0, 182, __pyx_L1_error) #else __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_4); __pyx_t_4++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); #endif } } else { __pyx_t_2 = __pyx_t_5(__pyx_t_3); if (unlikely(!__pyx_t_2)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 182, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_2); } if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { PyObject* sequence = __pyx_t_2; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 182, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_1 = PyList_GET_ITEM(sequence, 0); __pyx_t_6 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_1); __Pyx_INCREF(__pyx_t_6); #else __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); #endif __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else { Py_ssize_t index = -1; __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; index = 0; __pyx_t_1 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_1)) goto __pyx_L6_unpacking_failed; __Pyx_GOTREF(__pyx_t_1); index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L6_unpacking_failed; __Pyx_GOTREF(__pyx_t_6); if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 182, __pyx_L1_error) __pyx_t_8 = NULL; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L7_unpacking_done; __pyx_L6_unpacking_failed:; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_8 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 182, __pyx_L1_error) __pyx_L7_unpacking_done:; } __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_t); __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_t, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_m); __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_m, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_2 = PyObject_RichCompare(__pyx_cur_scope->__pyx_v_t, __pyx_cur_scope->__pyx_v_m, Py_NE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_9) { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_True); __pyx_r = Py_True; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } } /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_False); __pyx_r = Py_False; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); #if !CYTHON_USE_EXC_INFO_STACK __Pyx_Coroutine_ResetAndClearException(__pyx_generator); #endif __pyx_generator->resume_label = -1; __Pyx_Coroutine_clear((PyObject*)__pyx_generator); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "periodfind/ce.pyx":88 * mag_bin_extent) * * def calc(self, # <<<<<<<<<<<<<< * list times, * list mags, */ static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_2calc(struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, PyObject *__pyx_v_times, PyObject *__pyx_v_mags, PyArrayObject *__pyx_v_periods, PyArrayObject *__pyx_v_period_dts, PyObject *__pyx_v_output, PyObject *__pyx_v_normalize, PyObject *__pyx_v_n_stats, PyObject *__pyx_v_significance_type) { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *__pyx_cur_scope; PyArrayObject *__pyx_v_time_arr = 0; std::vector<float *> __pyx_v_times_ptrs; PyObject *__pyx_v_time_obj = NULL; PyObject *__pyx_v_mags_use = NULL; PyObject *__pyx_v_mag = NULL; PyObject *__pyx_v_min_v = NULL; PyObject *__pyx_v_max_v = NULL; PyObject *__pyx_v_scaled = NULL; PyArrayObject *__pyx_v_mag_arr = 0; std::vector<float *> __pyx_v_mags_ptrs; PyObject *__pyx_v_mag_obj = NULL; Py_ssize_t __pyx_v_n_per; Py_ssize_t __pyx_v_n_pdt; float *__pyx_v_ces; npy_intp __pyx_v_dim[3]; PyArrayObject *__pyx_v_ces_ndarr = 0; PyObject *__pyx_v_all_stats = NULL; Py_ssize_t __pyx_v_i; PyObject *__pyx_v_stats = NULL; PyObject *__pyx_8genexpr1__pyx_v_data = NULL; __Pyx_LocalBuf_ND __pyx_pybuffernd_ces_ndarr; __Pyx_Buffer __pyx_pybuffer_ces_ndarr; __Pyx_LocalBuf_ND __pyx_pybuffernd_mag_arr; __Pyx_Buffer __pyx_pybuffer_mag_arr; __Pyx_LocalBuf_ND __pyx_pybuffernd_period_dts; __Pyx_Buffer __pyx_pybuffer_period_dts; __Pyx_LocalBuf_ND __pyx_pybuffernd_periods; __Pyx_Buffer __pyx_pybuffer_periods; __Pyx_LocalBuf_ND __pyx_pybuffernd_time_arr; __Pyx_Buffer __pyx_pybuffer_time_arr; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; Py_ssize_t __pyx_t_13; int __pyx_t_14; Py_ssize_t __pyx_t_15; PyArrayObject *__pyx_t_16 = NULL; Py_ssize_t __pyx_t_17; PyObject *(*__pyx_t_18)(PyObject *); PyObject *__pyx_t_19 = NULL; PyObject *__pyx_t_20 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("calc", 0); __pyx_cur_scope = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *)__pyx_tp_new_10periodfind_2ce___pyx_scope_struct__calc(__pyx_ptype_10periodfind_2ce___pyx_scope_struct__calc, __pyx_empty_tuple, NULL); if (unlikely(!__pyx_cur_scope)) { __pyx_cur_scope = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *)Py_None); __Pyx_INCREF(Py_None); __PYX_ERR(0, 88, __pyx_L1_error) } else { __Pyx_GOTREF(__pyx_cur_scope); } __pyx_pybuffer_time_arr.pybuffer.buf = NULL; __pyx_pybuffer_time_arr.refcount = 0; __pyx_pybuffernd_time_arr.data = NULL; __pyx_pybuffernd_time_arr.rcbuffer = &__pyx_pybuffer_time_arr; __pyx_pybuffer_mag_arr.pybuffer.buf = NULL; __pyx_pybuffer_mag_arr.refcount = 0; __pyx_pybuffernd_mag_arr.data = NULL; __pyx_pybuffernd_mag_arr.rcbuffer = &__pyx_pybuffer_mag_arr; __pyx_pybuffer_ces_ndarr.pybuffer.buf = NULL; __pyx_pybuffer_ces_ndarr.refcount = 0; __pyx_pybuffernd_ces_ndarr.data = NULL; __pyx_pybuffernd_ces_ndarr.rcbuffer = &__pyx_pybuffer_ces_ndarr; __pyx_pybuffer_periods.pybuffer.buf = NULL; __pyx_pybuffer_periods.refcount = 0; __pyx_pybuffernd_periods.data = NULL; __pyx_pybuffernd_periods.rcbuffer = &__pyx_pybuffer_periods; __pyx_pybuffer_period_dts.pybuffer.buf = NULL; __pyx_pybuffer_period_dts.refcount = 0; __pyx_pybuffernd_period_dts.data = NULL; __pyx_pybuffernd_period_dts.rcbuffer = &__pyx_pybuffer_period_dts; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_periods.rcbuffer->pybuffer, (PyObject*)__pyx_v_periods, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 88, __pyx_L1_error) } __pyx_pybuffernd_periods.diminfo[0].strides = __pyx_pybuffernd_periods.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_periods.diminfo[0].shape = __pyx_pybuffernd_periods.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_period_dts.rcbuffer->pybuffer, (PyObject*)__pyx_v_period_dts, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 88, __pyx_L1_error) } __pyx_pybuffernd_period_dts.diminfo[0].strides = __pyx_pybuffernd_period_dts.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_period_dts.diminfo[0].shape = __pyx_pybuffernd_period_dts.rcbuffer->pybuffer.shape[0]; /* "periodfind/ce.pyx":152 * * # Make sure the number of times and mags matches * if len(times) != len(mags): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ if (unlikely(__pyx_v_times == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(0, 152, __pyx_L1_error) } __pyx_t_1 = PyList_GET_SIZE(__pyx_v_times); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 152, __pyx_L1_error) if (unlikely(__pyx_v_mags == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(0, 152, __pyx_L1_error) } __pyx_t_2 = PyList_GET_SIZE(__pyx_v_mags); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 152, __pyx_L1_error) __pyx_t_3 = ((__pyx_t_1 != __pyx_t_2) != 0); if (__pyx_t_3) { /* "periodfind/ce.pyx":153 * # Make sure the number of times and mags matches * if len(times) != len(mags): * return np.zeros([0, 0, 0], dtype=np.float32) # <<<<<<<<<<<<<< * * cdef np.ndarray[ndim=1, dtype=np.float32_t] time_arr */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_zeros); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyList_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_4, 0, __pyx_int_0); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_4, 1, __pyx_int_0); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_4, 2, __pyx_int_0); __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_np); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_float32); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_8) < 0) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_6, __pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_r = __pyx_t_8; __pyx_t_8 = 0; goto __pyx_L0; /* "periodfind/ce.pyx":152 * * # Make sure the number of times and mags matches * if len(times) != len(mags): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ } /* "periodfind/ce.pyx":158 * cdef vector[float*] times_ptrs * cdef vector[size_t] times_lens * for time_obj in times: # <<<<<<<<<<<<<< * time_arr = time_obj * times_ptrs.push_back(&time_arr[0]) */ if (unlikely(__pyx_v_times == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(0, 158, __pyx_L1_error) } __pyx_t_8 = __pyx_v_times; __Pyx_INCREF(__pyx_t_8); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_8)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 158, __pyx_L1_error) #else __pyx_t_4 = PySequence_ITEM(__pyx_t_8, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 158, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_XDECREF_SET(__pyx_v_time_obj, __pyx_t_4); __pyx_t_4 = 0; /* "periodfind/ce.pyx":159 * cdef vector[size_t] times_lens * for time_obj in times: * time_arr = time_obj # <<<<<<<<<<<<<< * times_ptrs.push_back(&time_arr[0]) * times_lens.push_back(len(time_arr)) */ if (!(likely(((__pyx_v_time_obj) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_time_obj, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 159, __pyx_L1_error) __pyx_t_4 = __pyx_v_time_obj; __Pyx_INCREF(__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_time_arr.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_time_arr.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_t_4), &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_time_arr.rcbuffer->pybuffer, (PyObject*)__pyx_v_time_arr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_12); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_10, __pyx_t_11, __pyx_t_12); } __pyx_t_10 = __pyx_t_11 = __pyx_t_12 = 0; } __pyx_pybuffernd_time_arr.diminfo[0].strides = __pyx_pybuffernd_time_arr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_time_arr.diminfo[0].shape = __pyx_pybuffernd_time_arr.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 159, __pyx_L1_error) } __Pyx_XDECREF_SET(__pyx_v_time_arr, ((PyArrayObject *)__pyx_t_4)); __pyx_t_4 = 0; /* "periodfind/ce.pyx":160 * for time_obj in times: * time_arr = time_obj * times_ptrs.push_back(&time_arr[0]) # <<<<<<<<<<<<<< * times_lens.push_back(len(time_arr)) * */ __pyx_t_13 = 0; __pyx_t_9 = -1; if (__pyx_t_13 < 0) { __pyx_t_13 += __pyx_pybuffernd_time_arr.diminfo[0].shape; if (unlikely(__pyx_t_13 < 0)) __pyx_t_9 = 0; } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_time_arr.diminfo[0].shape)) __pyx_t_9 = 0; if (unlikely(__pyx_t_9 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_9); __PYX_ERR(0, 160, __pyx_L1_error) } try { __pyx_v_times_ptrs.push_back((&(*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float32_t *, __pyx_pybuffernd_time_arr.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_time_arr.diminfo[0].strides)))); } catch(...) { __Pyx_CppExn2PyErr(); __PYX_ERR(0, 160, __pyx_L1_error) } /* "periodfind/ce.pyx":161 * time_arr = time_obj * times_ptrs.push_back(&time_arr[0]) * times_lens.push_back(len(time_arr)) # <<<<<<<<<<<<<< * * mags_use = [] */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_time_arr)); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 161, __pyx_L1_error) try { __pyx_cur_scope->__pyx_v_times_lens.push_back(__pyx_t_1); } catch(...) { __Pyx_CppExn2PyErr(); __PYX_ERR(0, 161, __pyx_L1_error) } /* "periodfind/ce.pyx":158 * cdef vector[float*] times_ptrs * cdef vector[size_t] times_lens * for time_obj in times: # <<<<<<<<<<<<<< * time_arr = time_obj * times_ptrs.push_back(&time_arr[0]) */ } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":163 * times_lens.push_back(len(time_arr)) * * mags_use = [] # <<<<<<<<<<<<<< * if normalize: * for mag in mags: */ __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 163, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_v_mags_use = ((PyObject*)__pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":164 * * mags_use = [] * if normalize: # <<<<<<<<<<<<<< * for mag in mags: * min_v = np.min(mag) */ __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_normalize); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) if (__pyx_t_3) { /* "periodfind/ce.pyx":165 * mags_use = [] * if normalize: * for mag in mags: # <<<<<<<<<<<<<< * min_v = np.min(mag) * max_v = np.max(mag) */ if (unlikely(__pyx_v_mags == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(0, 165, __pyx_L1_error) } __pyx_t_8 = __pyx_v_mags; __Pyx_INCREF(__pyx_t_8); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_8)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 165, __pyx_L1_error) #else __pyx_t_4 = PySequence_ITEM(__pyx_t_8, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 165, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_XDECREF_SET(__pyx_v_mag, __pyx_t_4); __pyx_t_4 = 0; /* "periodfind/ce.pyx":166 * if normalize: * for mag in mags: * min_v = np.min(mag) # <<<<<<<<<<<<<< * max_v = np.max(mag) * scaled = ((mag - min_v) / (max_v - min_v)) * 0.999 + 5e-4 */ __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_np); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 166, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_min); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 166, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_5))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); } } __pyx_t_4 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_v_mag) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_v_mag); __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 166, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF_SET(__pyx_v_min_v, __pyx_t_4); __pyx_t_4 = 0; /* "periodfind/ce.pyx":167 * for mag in mags: * min_v = np.min(mag) * max_v = np.max(mag) # <<<<<<<<<<<<<< * scaled = ((mag - min_v) / (max_v - min_v)) * 0.999 + 5e-4 * mags_use.append(scaled) */ __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 167, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_max); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 167, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); } } __pyx_t_4 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_6, __pyx_t_5, __pyx_v_mag) : __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_v_mag); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 167, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF_SET(__pyx_v_max_v, __pyx_t_4); __pyx_t_4 = 0; /* "periodfind/ce.pyx":168 * min_v = np.min(mag) * max_v = np.max(mag) * scaled = ((mag - min_v) / (max_v - min_v)) * 0.999 + 5e-4 # <<<<<<<<<<<<<< * mags_use.append(scaled) * else: */ __pyx_t_4 = PyNumber_Subtract(__pyx_v_mag, __pyx_v_min_v); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = PyNumber_Subtract(__pyx_v_max_v, __pyx_v_min_v); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = __Pyx_PyNumber_Divide(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = PyNumber_Multiply(__pyx_t_5, __pyx_float_0_999); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyFloat_AddObjC(__pyx_t_6, __pyx_float_5eneg_4, 5e-4, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF_SET(__pyx_v_scaled, __pyx_t_5); __pyx_t_5 = 0; /* "periodfind/ce.pyx":169 * max_v = np.max(mag) * scaled = ((mag - min_v) / (max_v - min_v)) * 0.999 + 5e-4 * mags_use.append(scaled) # <<<<<<<<<<<<<< * else: * mags_use = mags */ __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_mags_use, __pyx_v_scaled); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 169, __pyx_L1_error) /* "periodfind/ce.pyx":165 * mags_use = [] * if normalize: * for mag in mags: # <<<<<<<<<<<<<< * min_v = np.min(mag) * max_v = np.max(mag) */ } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":164 * * mags_use = [] * if normalize: # <<<<<<<<<<<<<< * for mag in mags: * min_v = np.min(mag) */ goto __pyx_L6; } /* "periodfind/ce.pyx":171 * mags_use.append(scaled) * else: * mags_use = mags # <<<<<<<<<<<<<< * * cdef np.ndarray[ndim=1, dtype=np.float32_t] mag_arr */ /*else*/ { __Pyx_INCREF(__pyx_v_mags); __Pyx_DECREF_SET(__pyx_v_mags_use, __pyx_v_mags); } __pyx_L6:; /* "periodfind/ce.pyx":176 * cdef vector[float*] mags_ptrs * cdef vector[size_t] mags_lens * for mag_obj in mags_use: # <<<<<<<<<<<<<< * mag_arr = mag_obj * mags_ptrs.push_back(&mag_arr[0]) */ if (unlikely(__pyx_v_mags_use == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(0, 176, __pyx_L1_error) } __pyx_t_8 = __pyx_v_mags_use; __Pyx_INCREF(__pyx_t_8); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_8)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_2); __Pyx_INCREF(__pyx_t_5); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 176, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_8, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_XDECREF_SET(__pyx_v_mag_obj, __pyx_t_5); __pyx_t_5 = 0; /* "periodfind/ce.pyx":177 * cdef vector[size_t] mags_lens * for mag_obj in mags_use: * mag_arr = mag_obj # <<<<<<<<<<<<<< * mags_ptrs.push_back(&mag_arr[0]) * mags_lens.push_back(len(mag_arr)) */ if (!(likely(((__pyx_v_mag_obj) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_mag_obj, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 177, __pyx_L1_error) __pyx_t_5 = __pyx_v_mag_obj; __Pyx_INCREF(__pyx_t_5); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mag_arr.rcbuffer->pybuffer); __pyx_t_9 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mag_arr.rcbuffer->pybuffer, (PyObject*)((PyArrayObject *)__pyx_t_5), &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack); if (unlikely(__pyx_t_9 < 0)) { PyErr_Fetch(&__pyx_t_12, &__pyx_t_11, &__pyx_t_10); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mag_arr.rcbuffer->pybuffer, (PyObject*)__pyx_v_mag_arr, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_12); Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_12, __pyx_t_11, __pyx_t_10); } __pyx_t_12 = __pyx_t_11 = __pyx_t_10 = 0; } __pyx_pybuffernd_mag_arr.diminfo[0].strides = __pyx_pybuffernd_mag_arr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mag_arr.diminfo[0].shape = __pyx_pybuffernd_mag_arr.rcbuffer->pybuffer.shape[0]; if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 177, __pyx_L1_error) } __Pyx_XDECREF_SET(__pyx_v_mag_arr, ((PyArrayObject *)__pyx_t_5)); __pyx_t_5 = 0; /* "periodfind/ce.pyx":178 * for mag_obj in mags_use: * mag_arr = mag_obj * mags_ptrs.push_back(&mag_arr[0]) # <<<<<<<<<<<<<< * mags_lens.push_back(len(mag_arr)) * */ __pyx_t_13 = 0; __pyx_t_9 = -1; if (__pyx_t_13 < 0) { __pyx_t_13 += __pyx_pybuffernd_mag_arr.diminfo[0].shape; if (unlikely(__pyx_t_13 < 0)) __pyx_t_9 = 0; } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_mag_arr.diminfo[0].shape)) __pyx_t_9 = 0; if (unlikely(__pyx_t_9 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_9); __PYX_ERR(0, 178, __pyx_L1_error) } try { __pyx_v_mags_ptrs.push_back((&(*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float32_t *, __pyx_pybuffernd_mag_arr.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_mag_arr.diminfo[0].strides)))); } catch(...) { __Pyx_CppExn2PyErr(); __PYX_ERR(0, 178, __pyx_L1_error) } /* "periodfind/ce.pyx":179 * mag_arr = mag_obj * mags_ptrs.push_back(&mag_arr[0]) * mags_lens.push_back(len(mag_arr)) # <<<<<<<<<<<<<< * * # Make sure the individual lengths match */ __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_mag_arr)); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 179, __pyx_L1_error) try { __pyx_cur_scope->__pyx_v_mags_lens.push_back(__pyx_t_1); } catch(...) { __Pyx_CppExn2PyErr(); __PYX_ERR(0, 179, __pyx_L1_error) } /* "periodfind/ce.pyx":176 * cdef vector[float*] mags_ptrs * cdef vector[size_t] mags_lens * for mag_obj in mags_use: # <<<<<<<<<<<<<< * mag_arr = mag_obj * mags_ptrs.push_back(&mag_arr[0]) */ } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":182 * * # Make sure the individual lengths match * if any(t != m for t, m in zip(times_lens, mags_lens)): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ __pyx_t_8 = __pyx_pf_10periodfind_2ce_18ConditionalEntropy_4calc_genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __pyx_t_5 = __Pyx_Generator_Next(__pyx_t_8); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_3) { /* "periodfind/ce.pyx":183 * # Make sure the individual lengths match * if any(t != m for t, m in zip(times_lens, mags_lens)): * return np.zeros([0, 0, 0], dtype=np.float32) # <<<<<<<<<<<<<< * * n_per = len(periods) */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_np); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s_zeros); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyList_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_5, 0, __pyx_int_0); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_5, 1, __pyx_int_0); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyList_SET_ITEM(__pyx_t_5, 2, __pyx_int_0); __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float32); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_7) < 0) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_6, __pyx_t_5); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_r = __pyx_t_7; __pyx_t_7 = 0; goto __pyx_L0; /* "periodfind/ce.pyx":182 * * # Make sure the individual lengths match * if any(t != m for t, m in zip(times_lens, mags_lens)): # <<<<<<<<<<<<<< * return np.zeros([0, 0, 0], dtype=np.float32) * */ } /* "periodfind/ce.pyx":185 * return np.zeros([0, 0, 0], dtype=np.float32) * * n_per = len(periods) # <<<<<<<<<<<<<< * n_pdt = len(period_dts) * */ __pyx_t_2 = PyObject_Length(((PyObject *)__pyx_v_periods)); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 185, __pyx_L1_error) __pyx_v_n_per = __pyx_t_2; /* "periodfind/ce.pyx":186 * * n_per = len(periods) * n_pdt = len(period_dts) # <<<<<<<<<<<<<< * * cdef float* ces = self.ce.CalcCEValsBatched( */ __pyx_t_2 = PyObject_Length(((PyObject *)__pyx_v_period_dts)); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 186, __pyx_L1_error) __pyx_v_n_pdt = __pyx_t_2; /* "periodfind/ce.pyx":190 * cdef float* ces = self.ce.CalcCEValsBatched( * times_ptrs, mags_ptrs, times_lens, * &periods[0], &period_dts[0], n_per, n_pdt, # <<<<<<<<<<<<<< * ) * */ __pyx_t_13 = 0; __pyx_t_9 = -1; if (__pyx_t_13 < 0) { __pyx_t_13 += __pyx_pybuffernd_periods.diminfo[0].shape; if (unlikely(__pyx_t_13 < 0)) __pyx_t_9 = 0; } else if (unlikely(__pyx_t_13 >= __pyx_pybuffernd_periods.diminfo[0].shape)) __pyx_t_9 = 0; if (unlikely(__pyx_t_9 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_9); __PYX_ERR(0, 190, __pyx_L1_error) } __pyx_t_15 = 0; __pyx_t_9 = -1; if (__pyx_t_15 < 0) { __pyx_t_15 += __pyx_pybuffernd_period_dts.diminfo[0].shape; if (unlikely(__pyx_t_15 < 0)) __pyx_t_9 = 0; } else if (unlikely(__pyx_t_15 >= __pyx_pybuffernd_period_dts.diminfo[0].shape)) __pyx_t_9 = 0; if (unlikely(__pyx_t_9 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_9); __PYX_ERR(0, 190, __pyx_L1_error) } /* "periodfind/ce.pyx":188 * n_pdt = len(period_dts) * * cdef float* ces = self.ce.CalcCEValsBatched( # <<<<<<<<<<<<<< * times_ptrs, mags_ptrs, times_lens, * &periods[0], &period_dts[0], n_per, n_pdt, */ __pyx_v_ces = __pyx_v_self->ce->CalcCEValsBatched(__pyx_v_times_ptrs, __pyx_v_mags_ptrs, __pyx_cur_scope->__pyx_v_times_lens, (&(*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float32_t *, __pyx_pybuffernd_periods.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_periods.diminfo[0].strides))), (&(*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float32_t *, __pyx_pybuffernd_period_dts.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_period_dts.diminfo[0].strides))), __pyx_v_n_per, __pyx_v_n_pdt); /* "periodfind/ce.pyx":194 * * cdef np.npy_intp dim[3] * dim[0] = len(times) # <<<<<<<<<<<<<< * dim[1] = n_per * dim[2] = n_pdt */ if (unlikely(__pyx_v_times == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(0, 194, __pyx_L1_error) } __pyx_t_2 = PyList_GET_SIZE(__pyx_v_times); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 194, __pyx_L1_error) (__pyx_v_dim[0]) = __pyx_t_2; /* "periodfind/ce.pyx":195 * cdef np.npy_intp dim[3] * dim[0] = len(times) * dim[1] = n_per # <<<<<<<<<<<<<< * dim[2] = n_pdt * */ (__pyx_v_dim[1]) = __pyx_v_n_per; /* "periodfind/ce.pyx":196 * dim[0] = len(times) * dim[1] = n_per * dim[2] = n_pdt # <<<<<<<<<<<<<< * * cdef np.ndarray[ndim=3, dtype=np.float32_t] ces_ndarr = \ */ (__pyx_v_dim[2]) = __pyx_v_n_pdt; /* "periodfind/ce.pyx":199 * * cdef np.ndarray[ndim=3, dtype=np.float32_t] ces_ndarr = \ * np.PyArray_SimpleNewFromData(3, dim, np.NPY_FLOAT, ces) # <<<<<<<<<<<<<< * * if output == 'stats': */ __pyx_t_7 = PyArray_SimpleNewFromData(3, __pyx_v_dim, NPY_FLOAT, __pyx_v_ces); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 199, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); if (!(likely(((__pyx_t_7) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_7, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 199, __pyx_L1_error) __pyx_t_16 = ((PyArrayObject *)__pyx_t_7); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer, (PyObject*)__pyx_t_16, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float32_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) { __pyx_v_ces_ndarr = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 198, __pyx_L1_error) } else {__pyx_pybuffernd_ces_ndarr.diminfo[0].strides = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_ces_ndarr.diminfo[0].shape = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_ces_ndarr.diminfo[1].strides = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_ces_ndarr.diminfo[1].shape = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_ces_ndarr.diminfo[2].strides = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_ces_ndarr.diminfo[2].shape = __pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer.shape[2]; } } __pyx_t_16 = 0; __pyx_v_ces_ndarr = ((PyArrayObject *)__pyx_t_7); __pyx_t_7 = 0; /* "periodfind/ce.pyx":201 * np.PyArray_SimpleNewFromData(3, dim, np.NPY_FLOAT, ces) * * if output == 'stats': # <<<<<<<<<<<<<< * all_stats = [] * for i in range(len(times)): */ __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_output, __pyx_n_u_stats, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 201, __pyx_L1_error) if (__pyx_t_3) { /* "periodfind/ce.pyx":202 * * if output == 'stats': * all_stats = [] # <<<<<<<<<<<<<< * for i in range(len(times)): * stats = Statistics.statistics_from_data( */ __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 202, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_v_all_stats = ((PyObject*)__pyx_t_7); __pyx_t_7 = 0; /* "periodfind/ce.pyx":203 * if output == 'stats': * all_stats = [] * for i in range(len(times)): # <<<<<<<<<<<<<< * stats = Statistics.statistics_from_data( * ces_ndarr[i], */ if (unlikely(__pyx_v_times == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(0, 203, __pyx_L1_error) } __pyx_t_2 = PyList_GET_SIZE(__pyx_v_times); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 203, __pyx_L1_error) __pyx_t_1 = __pyx_t_2; for (__pyx_t_17 = 0; __pyx_t_17 < __pyx_t_1; __pyx_t_17+=1) { __pyx_v_i = __pyx_t_17; /* "periodfind/ce.pyx":204 * all_stats = [] * for i in range(len(times)): * stats = Statistics.statistics_from_data( # <<<<<<<<<<<<<< * ces_ndarr[i], * [periods, period_dts], */ __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_Statistics); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 204, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_statistics_from_data); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 204, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "periodfind/ce.pyx":205 * for i in range(len(times)): * stats = Statistics.statistics_from_data( * ces_ndarr[i], # <<<<<<<<<<<<<< * [periods, period_dts], * False, */ __pyx_t_7 = __Pyx_GetItemInt(((PyObject *)__pyx_v_ces_ndarr), __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 0, 1, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 205, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); /* "periodfind/ce.pyx":206 * stats = Statistics.statistics_from_data( * ces_ndarr[i], * [periods, period_dts], # <<<<<<<<<<<<<< * False, * n=n_stats, */ __pyx_t_6 = PyList_New(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 206, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_INCREF(((PyObject *)__pyx_v_periods)); __Pyx_GIVEREF(((PyObject *)__pyx_v_periods)); PyList_SET_ITEM(__pyx_t_6, 0, ((PyObject *)__pyx_v_periods)); __Pyx_INCREF(((PyObject *)__pyx_v_period_dts)); __Pyx_GIVEREF(((PyObject *)__pyx_v_period_dts)); PyList_SET_ITEM(__pyx_t_6, 1, ((PyObject *)__pyx_v_period_dts)); /* "periodfind/ce.pyx":204 * all_stats = [] * for i in range(len(times)): * stats = Statistics.statistics_from_data( # <<<<<<<<<<<<<< * ces_ndarr[i], * [periods, period_dts], */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 204, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_INCREF(Py_False); __Pyx_GIVEREF(Py_False); PyTuple_SET_ITEM(__pyx_t_8, 2, Py_False); __pyx_t_7 = 0; __pyx_t_6 = 0; /* "periodfind/ce.pyx":208 * [periods, period_dts], * False, * n=n_stats, # <<<<<<<<<<<<<< * significance_type=significance_type, * ) */ __pyx_t_6 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 208, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_n, __pyx_v_n_stats) < 0) __PYX_ERR(0, 208, __pyx_L1_error) /* "periodfind/ce.pyx":209 * False, * n=n_stats, * significance_type=significance_type, # <<<<<<<<<<<<<< * ) * */ if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_significance_type, __pyx_v_significance_type) < 0) __PYX_ERR(0, 208, __pyx_L1_error) /* "periodfind/ce.pyx":204 * all_stats = [] * for i in range(len(times)): * stats = Statistics.statistics_from_data( # <<<<<<<<<<<<<< * ces_ndarr[i], * [periods, period_dts], */ __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_8, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 204, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF_SET(__pyx_v_stats, __pyx_t_7); __pyx_t_7 = 0; /* "periodfind/ce.pyx":212 * ) * * all_stats.append(stats) # <<<<<<<<<<<<<< * * return all_stats */ __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_all_stats, __pyx_v_stats); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 212, __pyx_L1_error) } /* "periodfind/ce.pyx":214 * all_stats.append(stats) * * return all_stats # <<<<<<<<<<<<<< * elif output == 'periodogram': * return [Periodogram(data, [periods, period_dts], False) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_all_stats); __pyx_r = __pyx_v_all_stats; goto __pyx_L0; /* "periodfind/ce.pyx":201 * np.PyArray_SimpleNewFromData(3, dim, np.NPY_FLOAT, ces) * * if output == 'stats': # <<<<<<<<<<<<<< * all_stats = [] * for i in range(len(times)): */ } /* "periodfind/ce.pyx":215 * * return all_stats * elif output == 'periodogram': # <<<<<<<<<<<<<< * return [Periodogram(data, [periods, period_dts], False) * for data in ces_ndarr] */ __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_output, __pyx_n_u_periodogram, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 215, __pyx_L1_error) if (likely(__pyx_t_3)) { /* "periodfind/ce.pyx":216 * return all_stats * elif output == 'periodogram': * return [Periodogram(data, [periods, period_dts], False) # <<<<<<<<<<<<<< * for data in ces_ndarr] * else: */ __Pyx_XDECREF(__pyx_r); { /* enter inner scope */ __pyx_t_7 = PyList_New(0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_7); /* "periodfind/ce.pyx":217 * elif output == 'periodogram': * return [Periodogram(data, [periods, period_dts], False) * for data in ces_ndarr] # <<<<<<<<<<<<<< * else: * raise NotImplementedError('Only "stats" output is implemented') */ if (likely(PyList_CheckExact(((PyObject *)__pyx_v_ces_ndarr))) || PyTuple_CheckExact(((PyObject *)__pyx_v_ces_ndarr))) { __pyx_t_6 = ((PyObject *)__pyx_v_ces_ndarr); __Pyx_INCREF(__pyx_t_6); __pyx_t_2 = 0; __pyx_t_18 = NULL; } else { __pyx_t_2 = -1; __pyx_t_6 = PyObject_GetIter(((PyObject *)__pyx_v_ces_ndarr)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 217, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_18 = Py_TYPE(__pyx_t_6)->tp_iternext; if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 217, __pyx_L17_error) } for (;;) { if (likely(!__pyx_t_18)) { if (likely(PyList_CheckExact(__pyx_t_6))) { if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_6)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_8 = PyList_GET_ITEM(__pyx_t_6, __pyx_t_2); __Pyx_INCREF(__pyx_t_8); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 217, __pyx_L17_error) #else __pyx_t_8 = PySequence_ITEM(__pyx_t_6, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 217, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_8); #endif } else { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_6)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_2); __Pyx_INCREF(__pyx_t_8); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 217, __pyx_L17_error) #else __pyx_t_8 = PySequence_ITEM(__pyx_t_6, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 217, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_8); #endif } } else { __pyx_t_8 = __pyx_t_18(__pyx_t_6); if (unlikely(!__pyx_t_8)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 217, __pyx_L17_error) } break; } __Pyx_GOTREF(__pyx_t_8); } __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_data, __pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":216 * return all_stats * elif output == 'periodogram': * return [Periodogram(data, [periods, period_dts], False) # <<<<<<<<<<<<<< * for data in ces_ndarr] * else: */ __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_Periodogram); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_4 = PyList_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(((PyObject *)__pyx_v_periods)); __Pyx_GIVEREF(((PyObject *)__pyx_v_periods)); PyList_SET_ITEM(__pyx_t_4, 0, ((PyObject *)__pyx_v_periods)); __Pyx_INCREF(((PyObject *)__pyx_v_period_dts)); __Pyx_GIVEREF(((PyObject *)__pyx_v_period_dts)); PyList_SET_ITEM(__pyx_t_4, 1, ((PyObject *)__pyx_v_period_dts)); __pyx_t_19 = NULL; __pyx_t_9 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_5))) { __pyx_t_19 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_19)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_19); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); __pyx_t_9 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[4] = {__pyx_t_19, __pyx_8genexpr1__pyx_v_data, __pyx_t_4, Py_False}; __pyx_t_8 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_9, 3+__pyx_t_9); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[4] = {__pyx_t_19, __pyx_8genexpr1__pyx_v_data, __pyx_t_4, Py_False}; __pyx_t_8 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_9, 3+__pyx_t_9); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else #endif { __pyx_t_20 = PyTuple_New(3+__pyx_t_9); if (unlikely(!__pyx_t_20)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_20); if (__pyx_t_19) { __Pyx_GIVEREF(__pyx_t_19); PyTuple_SET_ITEM(__pyx_t_20, 0, __pyx_t_19); __pyx_t_19 = NULL; } __Pyx_INCREF(__pyx_8genexpr1__pyx_v_data); __Pyx_GIVEREF(__pyx_8genexpr1__pyx_v_data); PyTuple_SET_ITEM(__pyx_t_20, 0+__pyx_t_9, __pyx_8genexpr1__pyx_v_data); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_20, 1+__pyx_t_9, __pyx_t_4); __Pyx_INCREF(Py_False); __Pyx_GIVEREF(Py_False); PyTuple_SET_ITEM(__pyx_t_20, 2+__pyx_t_9, Py_False); __pyx_t_4 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_20, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(__Pyx_ListComp_Append(__pyx_t_7, (PyObject*)__pyx_t_8))) __PYX_ERR(0, 216, __pyx_L17_error) __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; /* "periodfind/ce.pyx":217 * elif output == 'periodogram': * return [Periodogram(data, [periods, period_dts], False) * for data in ces_ndarr] # <<<<<<<<<<<<<< * else: * raise NotImplementedError('Only "stats" output is implemented') */ } __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_data); __pyx_8genexpr1__pyx_v_data = 0; goto __pyx_L20_exit_scope; __pyx_L17_error:; __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_data); __pyx_8genexpr1__pyx_v_data = 0; goto __pyx_L1_error; __pyx_L20_exit_scope:; } /* exit inner scope */ __pyx_r = __pyx_t_7; __pyx_t_7 = 0; goto __pyx_L0; /* "periodfind/ce.pyx":215 * * return all_stats * elif output == 'periodogram': # <<<<<<<<<<<<<< * return [Periodogram(data, [periods, period_dts], False) * for data in ces_ndarr] */ } /* "periodfind/ce.pyx":219 * for data in ces_ndarr] * else: * raise NotImplementedError('Only "stats" output is implemented') # <<<<<<<<<<<<<< */ /*else*/ { __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_NotImplementedError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 219, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __PYX_ERR(0, 219, __pyx_L1_error) } /* "periodfind/ce.pyx":88 * mag_bin_extent) * * def calc(self, # <<<<<<<<<<<<<< * list times, * list mags, */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_19); __Pyx_XDECREF(__pyx_t_20); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mag_arr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_period_dts.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_periods.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_time_arr.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.calc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_ces_ndarr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mag_arr.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_period_dts.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_periods.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_time_arr.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_time_arr); __Pyx_XDECREF(__pyx_v_time_obj); __Pyx_XDECREF(__pyx_v_mags_use); __Pyx_XDECREF(__pyx_v_mag); __Pyx_XDECREF(__pyx_v_min_v); __Pyx_XDECREF(__pyx_v_max_v); __Pyx_XDECREF(__pyx_v_scaled); __Pyx_XDECREF((PyObject *)__pyx_v_mag_arr); __Pyx_XDECREF(__pyx_v_mag_obj); __Pyx_XDECREF((PyObject *)__pyx_v_ces_ndarr); __Pyx_XDECREF(__pyx_v_all_stats); __Pyx_XDECREF(__pyx_v_stats); __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_data); __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_5__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_5__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf_10periodfind_2ce_18ConditionalEntropy_4__reduce_cython__(((struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_7__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw_10periodfind_2ce_18ConditionalEntropy_7__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf_10periodfind_2ce_18ConditionalEntropy_6__setstate_cython__(((struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10periodfind_2ce_18ConditionalEntropy_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_10periodfind_2ce_ConditionalEntropy *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("periodfind.ce.ConditionalEntropy.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":742 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":743 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 743, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":742 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":745 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":746 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":745 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":748 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":749 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 749, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":748 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":751 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":752 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 752, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":751 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":754 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":755 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline tuple PyDataType_SHAPE(dtype d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 755, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":754 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":757 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":758 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); if (__pyx_t_1) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":759 * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape # <<<<<<<<<<<<<< * else: * return () */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":758 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":761 * return <tuple>d.subarray.shape * else: * return () # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_empty_tuple); __pyx_r = __pyx_empty_tuple; goto __pyx_L0; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":757 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":763 * return () * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":768 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":769 * cdef dtype child * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":772 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(2, 772, __pyx_L1_error) } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(2, 772, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 772, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":773 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(2, 773, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 773, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(2, 773, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":774 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - <int>(new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(2, 774, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(2, 774, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(2, 774, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":776 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 776, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 776, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(2, 776, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (unlikely(__pyx_t_6)) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":777 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(2, 777, __pyx_L1_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":776 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":779 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":780 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":779 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (unlikely(__pyx_t_6)) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":781 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 781, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(2, 781, __pyx_L1_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":779 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":791 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 791, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 791, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 791, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":792 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":793 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":794 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":796 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":798 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":799 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":800 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (unlikely(__pyx_t_6)) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":801 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 801, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(2, 801, __pyx_L1_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":800 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":804 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 804, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 804, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":805 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 805, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 805, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":806 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 806, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 806, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 806, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":807 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 807, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 807, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 807, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":808 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 808, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 808, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 808, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":809 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 809, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 809, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 809, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":810 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 810, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 810, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 810, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":811 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 811, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 811, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 811, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":812 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 812, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 812, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 812, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":813 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 813, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":814 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 814, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 814, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 814, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":815 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 815, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 815, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 815, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":816 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 816, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 816, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 816, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":817 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 817, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 817, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 817, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":818 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 818, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 818, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 818, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":819 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 819, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 819, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 819, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":820 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 820, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 820, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(2, 820, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (likely(__pyx_t_6)) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":822 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(2, 822, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 822, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(2, 822, __pyx_L1_error) } __pyx_L15:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":823 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":798 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":827 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(2, 827, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":772 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":828 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":763 * return () * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":943 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_array_base", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":944 * * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< * PyArray_SetBaseObject(arr, base) * */ Py_INCREF(__pyx_v_base); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":945 * cdef inline void set_array_base(ndarray arr, object base): * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":943 * int _import_umath() except -1 * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * Py_INCREF(base) # important to do this before stealing the reference below! * PyArray_SetBaseObject(arr, base) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":947 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_v_base; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":948 * * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< * if base is NULL: * return None */ __pyx_v_base = PyArray_BASE(__pyx_v_arr); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":949 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ __pyx_t_1 = ((__pyx_v_base == NULL) != 0); if (__pyx_t_1) { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":950 * base = PyArray_BASE(arr) * if base is NULL: * return None # <<<<<<<<<<<<<< * return <object>base * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":949 * cdef inline object get_array_base(ndarray arr): * base = PyArray_BASE(arr) * if base is NULL: # <<<<<<<<<<<<<< * return None * return <object>base */ } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":951 * if base is NULL: * return None * return <object>base # <<<<<<<<<<<<<< * * # Versions of the import_* functions which are more suitable for */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_base)); __pyx_r = ((PyObject *)__pyx_v_base); goto __pyx_L0; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":947 * PyArray_SetBaseObject(arr, base) * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * base = PyArray_BASE(arr) * if base is NULL: */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":955 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * __pyx_import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_array", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":956 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":957 * cdef inline int import_array() except -1: * try: * __pyx_import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 957, __pyx_L3_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":956 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":958 * try: * __pyx_import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 958, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":959 * __pyx_import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 959, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 959, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":956 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * __pyx_import_array() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":955 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * __pyx_import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":961 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_umath", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":962 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":963 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 963, __pyx_L3_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":962 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":964 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 964, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":965 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 965, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 965, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":962 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":961 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":967 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":968 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":969 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(2, 969, __pyx_L3_error) /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":968 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":970 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(2, 970, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":971 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef extern from *: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(2, 971, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(2, 971, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":968 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":967 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "vector.to_py":60 * * @cname("__pyx_convert_vector_to_py_size_t") * cdef object __pyx_convert_vector_to_py_size_t(vector[X]& v): # <<<<<<<<<<<<<< * return [v[i] for i in range(v.size())] * */ static PyObject *__pyx_convert_vector_to_py_size_t(const std::vector<size_t> &__pyx_v_v) { size_t __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; size_t __pyx_t_2; size_t __pyx_t_3; size_t __pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_convert_vector_to_py_size_t", 0); /* "vector.to_py":61 * @cname("__pyx_convert_vector_to_py_size_t") * cdef object __pyx_convert_vector_to_py_size_t(vector[X]& v): * return [v[i] for i in range(v.size())] # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __pyx_v_v.size(); __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; __pyx_t_5 = __Pyx_PyInt_FromSize_t((__pyx_v_v[__pyx_v_i])); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "vector.to_py":60 * * @cname("__pyx_convert_vector_to_py_size_t") * cdef object __pyx_convert_vector_to_py_size_t(vector[X]& v): # <<<<<<<<<<<<<< * return [v[i] for i in range(v.size())] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("vector.to_py.__pyx_convert_vector_to_py_size_t", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_tp_new_10periodfind_2ce_ConditionalEntropy(PyTypeObject *t, PyObject *a, PyObject *k) { PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; if (unlikely(__pyx_pw_10periodfind_2ce_18ConditionalEntropy_1__cinit__(o, a, k) < 0)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_10periodfind_2ce_ConditionalEntropy(PyObject *o) { #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif (*Py_TYPE(o)->tp_free)(o); } static PyMethodDef __pyx_methods_10periodfind_2ce_ConditionalEntropy[] = { {"calc", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_10periodfind_2ce_18ConditionalEntropy_3calc, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10periodfind_2ce_18ConditionalEntropy_2calc}, {"__reduce_cython__", (PyCFunction)__pyx_pw_10periodfind_2ce_18ConditionalEntropy_5__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw_10periodfind_2ce_18ConditionalEntropy_7__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type_10periodfind_2ce_ConditionalEntropy = { PyVarObject_HEAD_INIT(0, 0) "periodfind.ce.ConditionalEntropy", /*tp_name*/ sizeof(struct __pyx_obj_10periodfind_2ce_ConditionalEntropy), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_10periodfind_2ce_ConditionalEntropy, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ "Conditional Entropy based light curve analysis.\n\n Attempts to determine the period of a light curve by folding the light\n curve sample times over each trial period, then binning the folded times\n and their corresponding magnitudes into a 2-D histogram. The output\n periodogram consists of the Conditional Entropy values of these 2-D\n histograms.\n\n Parameters\n ----------\n n_phase : int, default=10\n The number of phase bins in the histogram\n \n n_mag : int, default=10\n The number of magnitude bins in the histogram\n \n phase_bin_extent : int, default=1\n The effective width (in number of bins) of a given phase bin.\n Extends a bin by duplicating entries to adjacent bins, wrapping\n if necessary. Tends to smooth the periodogram curve.\n\n mag_bin_extent : int, default=1\n The effective width (in number of bins) of a given magnitude bin.\n Extends a bin by duplicating entries to adjacent bins, wrapping\n if necessary. Tends to smooth the periodogram curve.\n ", /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_10periodfind_2ce_ConditionalEntropy, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_10periodfind_2ce_ConditionalEntropy, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *__pyx_freelist_10periodfind_2ce___pyx_scope_struct__calc[8]; static int __pyx_freecount_10periodfind_2ce___pyx_scope_struct__calc = 0; static PyObject *__pyx_tp_new_10periodfind_2ce___pyx_scope_struct__calc(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *p; PyObject *o; if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_10periodfind_2ce___pyx_scope_struct__calc > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc)))) { o = (PyObject*)__pyx_freelist_10periodfind_2ce___pyx_scope_struct__calc[--__pyx_freecount_10periodfind_2ce___pyx_scope_struct__calc]; memset(o, 0, sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc)); (void) PyObject_INIT(o, t); } else { o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; } p = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *)o); new((void*)&(p->__pyx_v_mags_lens)) std::vector<size_t> (); new((void*)&(p->__pyx_v_times_lens)) std::vector<size_t> (); return o; } static void __pyx_tp_dealloc_10periodfind_2ce___pyx_scope_struct__calc(PyObject *o) { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *p = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *)o; __Pyx_call_destructor(p->__pyx_v_mags_lens); __Pyx_call_destructor(p->__pyx_v_times_lens); if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_10periodfind_2ce___pyx_scope_struct__calc < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc)))) { __pyx_freelist_10periodfind_2ce___pyx_scope_struct__calc[__pyx_freecount_10periodfind_2ce___pyx_scope_struct__calc++] = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc *)o); } else { (*Py_TYPE(o)->tp_free)(o); } } static PyTypeObject __pyx_type_10periodfind_2ce___pyx_scope_struct__calc = { PyVarObject_HEAD_INIT(0, 0) "periodfind.ce.__pyx_scope_struct__calc", /*tp_name*/ sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct__calc), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_10periodfind_2ce___pyx_scope_struct__calc, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_10periodfind_2ce___pyx_scope_struct__calc, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *__pyx_freelist_10periodfind_2ce___pyx_scope_struct_1_genexpr[8]; static int __pyx_freecount_10periodfind_2ce___pyx_scope_struct_1_genexpr = 0; static PyObject *__pyx_tp_new_10periodfind_2ce___pyx_scope_struct_1_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { PyObject *o; if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_10periodfind_2ce___pyx_scope_struct_1_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr)))) { o = (PyObject*)__pyx_freelist_10periodfind_2ce___pyx_scope_struct_1_genexpr[--__pyx_freecount_10periodfind_2ce___pyx_scope_struct_1_genexpr]; memset(o, 0, sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr)); (void) PyObject_INIT(o, t); PyObject_GC_Track(o); } else { o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; } return o; } static void __pyx_tp_dealloc_10periodfind_2ce___pyx_scope_struct_1_genexpr(PyObject *o) { struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)o; PyObject_GC_UnTrack(o); Py_CLEAR(p->__pyx_outer_scope); Py_CLEAR(p->__pyx_v_m); Py_CLEAR(p->__pyx_v_t); if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_10periodfind_2ce___pyx_scope_struct_1_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr)))) { __pyx_freelist_10periodfind_2ce___pyx_scope_struct_1_genexpr[__pyx_freecount_10periodfind_2ce___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)o); } else { (*Py_TYPE(o)->tp_free)(o); } } static int __pyx_tp_traverse_10periodfind_2ce___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr *)o; if (p->__pyx_outer_scope) { e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; } if (p->__pyx_v_m) { e = (*v)(p->__pyx_v_m, a); if (e) return e; } if (p->__pyx_v_t) { e = (*v)(p->__pyx_v_t, a); if (e) return e; } return 0; } static PyTypeObject __pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr = { PyVarObject_HEAD_INIT(0, 0) "periodfind.ce.__pyx_scope_struct_1_genexpr", /*tp_name*/ sizeof(struct __pyx_obj_10periodfind_2ce___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_10periodfind_2ce___pyx_scope_struct_1_genexpr, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_10periodfind_2ce___pyx_scope_struct_1_genexpr, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_10periodfind_2ce___pyx_scope_struct_1_genexpr, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_ce(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_ce}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "ce", __pyx_k_Provides_an_interface_for_analy, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_ConditionalEntropy, __pyx_k_ConditionalEntropy, sizeof(__pyx_k_ConditionalEntropy), 0, 0, 1, 1}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_s_NotImplementedError, __pyx_k_NotImplementedError, sizeof(__pyx_k_NotImplementedError), 0, 0, 1, 1}, {&__pyx_kp_u_Only_stats_output_is_implemented, __pyx_k_Only_stats_output_is_implemented, sizeof(__pyx_k_Only_stats_output_is_implemented), 0, 1, 0, 0}, {&__pyx_n_s_Periodogram, __pyx_k_Periodogram, sizeof(__pyx_k_Periodogram), 0, 0, 1, 1}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_Statistics, __pyx_k_Statistics, sizeof(__pyx_k_Statistics), 0, 0, 1, 1}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, {&__pyx_n_s_calc_locals_genexpr, __pyx_k_calc_locals_genexpr, sizeof(__pyx_k_calc_locals_genexpr), 0, 0, 1, 1}, {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_n_s_close, __pyx_k_close, sizeof(__pyx_k_close), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, {&__pyx_n_s_genexpr, __pyx_k_genexpr, sizeof(__pyx_k_genexpr), 0, 0, 1, 1}, {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_mag_bin_extent, __pyx_k_mag_bin_extent, sizeof(__pyx_k_mag_bin_extent), 0, 0, 1, 1}, {&__pyx_n_s_mags, __pyx_k_mags, sizeof(__pyx_k_mags), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_max, __pyx_k_max, sizeof(__pyx_k_max), 0, 0, 1, 1}, {&__pyx_n_s_min, __pyx_k_min, sizeof(__pyx_k_min), 0, 0, 1, 1}, {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, {&__pyx_n_s_n_mag, __pyx_k_n_mag, sizeof(__pyx_k_n_mag), 0, 0, 1, 1}, {&__pyx_n_s_n_phase, __pyx_k_n_phase, sizeof(__pyx_k_n_phase), 0, 0, 1, 1}, {&__pyx_n_s_n_stats, __pyx_k_n_stats, sizeof(__pyx_k_n_stats), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, {&__pyx_n_s_normalize, __pyx_k_normalize, sizeof(__pyx_k_normalize), 0, 0, 1, 1}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0}, {&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0}, {&__pyx_n_s_output, __pyx_k_output, sizeof(__pyx_k_output), 0, 0, 1, 1}, {&__pyx_n_s_period_dts, __pyx_k_period_dts, sizeof(__pyx_k_period_dts), 0, 0, 1, 1}, {&__pyx_n_s_periodfind, __pyx_k_periodfind, sizeof(__pyx_k_periodfind), 0, 0, 1, 1}, {&__pyx_n_s_periodfind_ce, __pyx_k_periodfind_ce, sizeof(__pyx_k_periodfind_ce), 0, 0, 1, 1}, {&__pyx_n_u_periodogram, __pyx_k_periodogram, sizeof(__pyx_k_periodogram), 0, 1, 0, 1}, {&__pyx_n_s_periods, __pyx_k_periods, sizeof(__pyx_k_periods), 0, 0, 1, 1}, {&__pyx_n_s_phase_bin_extent, __pyx_k_phase_bin_extent, sizeof(__pyx_k_phase_bin_extent), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, {&__pyx_n_s_send, __pyx_k_send, sizeof(__pyx_k_send), 0, 0, 1, 1}, {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, {&__pyx_n_s_significance_type, __pyx_k_significance_type, sizeof(__pyx_k_significance_type), 0, 0, 1, 1}, {&__pyx_n_s_statistics_from_data, __pyx_k_statistics_from_data, sizeof(__pyx_k_statistics_from_data), 0, 0, 1, 1}, {&__pyx_n_u_stats, __pyx_k_stats, sizeof(__pyx_k_stats), 0, 1, 0, 1}, {&__pyx_n_u_stdmean, __pyx_k_stdmean, sizeof(__pyx_k_stdmean), 0, 1, 0, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_throw, __pyx_k_throw, sizeof(__pyx_k_throw), 0, 0, 1, 1}, {&__pyx_n_s_times, __pyx_k_times, sizeof(__pyx_k_times), 0, 0, 1, 1}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 203, __pyx_L1_error) __pyx_builtin_NotImplementedError = __Pyx_GetBuiltinName(__pyx_n_s_NotImplementedError); if (!__pyx_builtin_NotImplementedError) __PYX_ERR(0, 219, __pyx_L1_error) __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 182, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(2, 777, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(2, 781, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(2, 959, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "periodfind/ce.pyx":219 * for data in ces_ndarr] * else: * raise NotImplementedError('Only "stats" output is implemented') # <<<<<<<<<<<<<< */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_Only_stats_output_is_implemented); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 219, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":777 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(2, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":781 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(2, 781, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":801 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(2, 801, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":959 * __pyx_import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(2, 959, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../testenv/lib/python3.8/site-packages/numpy/__init__.pxd":965 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(2, 965, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_float_5eneg_4 = PyFloat_FromDouble(5e-4); if (unlikely(!__pyx_float_5eneg_4)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_float_0_999 = PyFloat_FromDouble(0.999); if (unlikely(!__pyx_float_0_999)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_10 = PyInt_FromLong(10); if (unlikely(!__pyx_int_10)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ static int __Pyx_modinit_global_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- Global init code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(void) { __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ if (PyType_Ready(&__pyx_type_10periodfind_2ce_ConditionalEntropy) < 0) __PYX_ERR(0, 47, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type_10periodfind_2ce_ConditionalEntropy.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_10periodfind_2ce_ConditionalEntropy.tp_dictoffset && __pyx_type_10periodfind_2ce_ConditionalEntropy.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type_10periodfind_2ce_ConditionalEntropy.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (PyObject_SetAttr(__pyx_m, __pyx_n_s_ConditionalEntropy, (PyObject *)&__pyx_type_10periodfind_2ce_ConditionalEntropy) < 0) __PYX_ERR(0, 47, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type_10periodfind_2ce_ConditionalEntropy) < 0) __PYX_ERR(0, 47, __pyx_L1_error) __pyx_ptype_10periodfind_2ce_ConditionalEntropy = &__pyx_type_10periodfind_2ce_ConditionalEntropy; if (PyType_Ready(&__pyx_type_10periodfind_2ce___pyx_scope_struct__calc) < 0) __PYX_ERR(0, 88, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type_10periodfind_2ce___pyx_scope_struct__calc.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_10periodfind_2ce___pyx_scope_struct__calc.tp_dictoffset && __pyx_type_10periodfind_2ce___pyx_scope_struct__calc.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type_10periodfind_2ce___pyx_scope_struct__calc.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; } __pyx_ptype_10periodfind_2ce___pyx_scope_struct__calc = &__pyx_type_10periodfind_2ce___pyx_scope_struct__calc; if (PyType_Ready(&__pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr) < 0) __PYX_ERR(0, 182, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr.tp_dictoffset && __pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; } __pyx_ptype_10periodfind_2ce___pyx_scope_struct_1_genexpr = &__pyx_type_10periodfind_2ce___pyx_scope_struct_1_genexpr; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif __Pyx_ImportType_CheckSize_Warn); if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 207, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(2, 207, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(2, 230, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(2, 234, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(2, 246, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Ignore); if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(2, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_variable_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } #ifndef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #elif PY_MAJOR_VERSION < 3 #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" void #else #define __Pyx_PyMODINIT_FUNC void #endif #else #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * #else #define __Pyx_PyMODINIT_FUNC PyObject * #endif #endif #if PY_MAJOR_VERSION < 3 __Pyx_PyMODINIT_FUNC initce(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC initce(void) #else __Pyx_PyMODINIT_FUNC PyInit_ce(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_ce(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { #if PY_VERSION_HEX >= 0x030700A1 static PY_INT64_T main_interpreter_id = -1; PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); if (main_interpreter_id == -1) { main_interpreter_id = current_id; return (unlikely(current_id == -1)) ? -1 : 0; } else if (unlikely(main_interpreter_id != current_id)) #else static PyInterpreterState *main_interpreter = NULL; PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; if (!main_interpreter) { main_interpreter = current_interpreter; } else if (unlikely(main_interpreter != current_interpreter)) #endif { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__Pyx_check_single_interpreter()) return NULL; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_ce(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'ce' has already been imported. Re-initialisation is not supported."); return -1; } #elif PY_MAJOR_VERSION >= 3 if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_ce(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("ce", __pyx_methods, __pyx_k_Provides_an_interface_for_analy, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_b); __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_cython_runtime); if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_periodfind__ce) { if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "periodfind.ce")) { if (unlikely(PyDict_SetItemString(modules, "periodfind.ce", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); (void)__Pyx_modinit_function_export_code(); if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) (void)__Pyx_modinit_variable_import_code(); (void)__Pyx_modinit_function_import_code(); /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "periodfind/ce.pyx":13 * """ * * import numpy as np # <<<<<<<<<<<<<< * from periodfind import Statistics, Periodogram * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "periodfind/ce.pyx":14 * * import numpy as np * from periodfind import Statistics, Periodogram # <<<<<<<<<<<<<< * * cimport numpy as np */ __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_n_s_Statistics); __Pyx_GIVEREF(__pyx_n_s_Statistics); PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_Statistics); __Pyx_INCREF(__pyx_n_s_Periodogram); __Pyx_GIVEREF(__pyx_n_s_Periodogram); PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_Periodogram); __pyx_t_2 = __Pyx_Import(__pyx_n_s_periodfind, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_Statistics); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_Statistics, __pyx_t_1) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_Periodogram); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_Periodogram, __pyx_t_1) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "periodfind/ce.pyx":21 * * # Include numpy <-> c array interop * np.import_array() # <<<<<<<<<<<<<< * * # Define the C++ CE class so we can use it */ __pyx_t_3 = __pyx_f_5numpy_import_array(); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 21, __pyx_L1_error) /* "periodfind/ce.pyx":1 * #cython: language_level=3 # <<<<<<<<<<<<<< * * # Copyright 2020 California Institute of Technology. All rights reserved. */ __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "vector.to_py":60 * * @cname("__pyx_convert_vector_to_py_size_t") * cdef object __pyx_convert_vector_to_py_size_t(vector[X]& v): # <<<<<<<<<<<<<< * return [v[i] for i in range(v.size())] * */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init periodfind.ce", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init periodfind.ce"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (exact) { #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* IterFinish */ static CYTHON_INLINE int __Pyx_IterFinish(void) { #if CYTHON_FAST_THREAD_STATE PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* exc_type = tstate->curexc_type; if (unlikely(exc_type)) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { PyObject *exc_value, *exc_tb; exc_value = tstate->curexc_value; exc_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; Py_DECREF(exc_type); Py_XDECREF(exc_value); Py_XDECREF(exc_tb); return 0; } else { return -1; } } return 0; #else if (unlikely(PyErr_Occurred())) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { PyErr_Clear(); return 0; } else { return -1; } } return 0; #endif } /* UnpackItemEndCheck */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { if (unlikely(retval)) { Py_DECREF(retval); __Pyx_RaiseTooManyValuesError(expected); return -1; } else { return __Pyx_IterFinish(); } return 0; } /* IsLittleEndian */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { union { uint32_t u32; uint8_t u8[4]; } S; S.u32 = 0x01020304; return S.u8[0] == 4; } /* BufferFormatCheck */ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t <= '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case '?': return "'bool'"; case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number, ndim; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ndim = ctx->head->field->type->ndim; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } CYTHON_FALLTHROUGH; case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } CYTHON_FALLTHROUGH; case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } /* BufferGetAndValidate */ static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (unlikely(info->buf == NULL)) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } static void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static int __Pyx__GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { buf->buf = NULL; if (unlikely(__Pyx_GetBuffer(obj, buf, flags) == -1)) { __Pyx_ZeroBuffer(buf); return -1; } if (unlikely(buf->ndim != nd)) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if (unlikely((size_t)buf->itemsize != dtype->size)) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_SafeReleaseBuffer(buf); return -1; } /* PyDictVersioning */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { PyObject *dict = Py_TYPE(obj)->tp_dict; return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; } static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { PyObject **dictptr = NULL; Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; if (offset) { #if CYTHON_COMPILING_IN_CPYTHON dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); #else dictptr = _PyObject_GetDictPtr(obj); #endif } return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; } static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { PyObject *dict = Py_TYPE(obj)->tp_dict; if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) return 0; return obj_dict_version == __Pyx_get_object_dict_version(obj); } #endif /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { return NULL; } #else result = PyDict_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } #endif #else result = PyObject_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFallbackError */ static void __Pyx_RaiseBufferFallbackError(void) { PyErr_SetString(PyExc_ValueError, "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } /* BufferIndexError */ static void __Pyx_RaiseBufferIndexError(int axis) { PyErr_Format(PyExc_IndexError, "Out of bounds on buffer access (axis %d)", axis); } /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyObjectCall2Args */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { PyObject *args, *result = NULL; #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyFunction_FastCall(function, args, 2); } #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyCFunction_FastCall(function, args, 2); } #endif args = PyTuple_New(2); if (unlikely(!args)) goto done; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); Py_INCREF(function); result = __Pyx_PyObject_Call(function, args, NULL); Py_DECREF(args); Py_DECREF(function); done: return result; } /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallOneArg */ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* PyFloatBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyFloat_AddObjC(PyObject *op1, PyObject *op2, double floatval, int inplace, int zerodivision_check) { const double b = floatval; double a, result; (void)inplace; (void)zerodivision_check; if (likely(PyFloat_CheckExact(op1))) { a = PyFloat_AS_DOUBLE(op1); } else #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { a = (double) PyInt_AS_LONG(op1); } else #endif if (likely(PyLong_CheckExact(op1))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); switch (size) { case 0: a = 0.0; break; case -1: a = -(double) digits[0]; break; case 1: a = (double) digits[0]; break; case -2: case 2: if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (1 * PyLong_SHIFT < 53))) { a = (double) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); if ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { if (size == -2) a = -a; break; } } CYTHON_FALLTHROUGH; case -3: case 3: if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (2 * PyLong_SHIFT < 53))) { a = (double) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); if ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { if (size == -3) a = -a; break; } } CYTHON_FALLTHROUGH; case -4: case 4: if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT && ((8 * sizeof(unsigned long) < 53) || (3 * PyLong_SHIFT < 53))) { a = (double) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); if ((8 * sizeof(unsigned long) < 53) || (4 * PyLong_SHIFT < 53) || (a < (double) ((PY_LONG_LONG)1 << 53))) { if (size == -4) a = -a; break; } } CYTHON_FALLTHROUGH; default: #else { #endif a = PyLong_AsDouble(op1); if (unlikely(a == -1.0 && PyErr_Occurred())) return NULL; } } else { return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } PyFPE_START_PROTECT("add", return NULL) result = a + b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } #endif /* BytesEquals */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } /* UnicodeEquals */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; #if CYTHON_PEP393_ENABLED hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; #else hash1 = ((PyUnicodeObject*)s1)->hash; hash2 = ((PyUnicodeObject*)s2)->hash; #endif if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } /* GetItemInt */ static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) return NULL; PyErr_Clear(); } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* DictGetItem */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { if (unlikely(PyTuple_Check(key))) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) { PyErr_SetObject(PyExc_KeyError, args); Py_DECREF(args); } } else { PyErr_SetObject(PyExc_KeyError, key); } } return NULL; } Py_INCREF(value); return value; } #endif /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; } return 0; } static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; if (unlikely(PyTuple_Check(err))) return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; } #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* PyObject_GenericGetAttrNoDict */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, attr_name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(attr_name)); #endif return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { PyObject *descr; PyTypeObject *tp = Py_TYPE(obj); if (unlikely(!PyString_Check(attr_name))) { return PyObject_GenericGetAttr(obj, attr_name); } assert(!tp->tp_dictoffset); descr = _PyType_Lookup(tp, attr_name); if (unlikely(!descr)) { return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); } Py_INCREF(descr); #if PY_MAJOR_VERSION < 3 if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) #endif { descrgetfunc f = Py_TYPE(descr)->tp_descr_get; if (unlikely(f)) { PyObject *res = f(descr, obj, (PyObject *)tp); Py_DECREF(descr); return res; } } return descr; } #endif /* PyObject_GenericGetAttr */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { return PyObject_GenericGetAttr(obj, attr_name); } return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); } #endif /* PyObjectGetAttrStrNoError */ static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) __Pyx_PyErr_Clear(); } static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { PyObject *result; #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); } #endif result = __Pyx_PyObject_GetAttrStr(obj, attr_name); if (unlikely(!result)) { __Pyx_PyObject_GetAttrStr_ClearAttributeError(); } return result; } /* SetupReduce */ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { int ret; PyObject *name_attr; name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name); if (likely(name_attr)) { ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); } else { ret = -1; } if (unlikely(ret < 0)) { PyErr_Clear(); ret = 0; } Py_XDECREF(name_attr); return ret; } static int __Pyx_setup_reduce(PyObject* type_obj) { int ret = 0; PyObject *object_reduce = NULL; PyObject *object_reduce_ex = NULL; PyObject *reduce = NULL; PyObject *reduce_ex = NULL; PyObject *reduce_cython = NULL; PyObject *setstate = NULL; PyObject *setstate_cython = NULL; #if CYTHON_USE_PYTYPE_LOOKUP if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #else if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #endif #if CYTHON_USE_PYTYPE_LOOKUP object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #else object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #endif reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; if (reduce_ex == object_reduce_ex) { #if CYTHON_USE_PYTYPE_LOOKUP object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #else object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #endif reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); if (likely(reduce_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (reduce == object_reduce || PyErr_Occurred()) { goto __PYX_BAD; } setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); if (!setstate) PyErr_Clear(); if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); if (likely(setstate_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (!setstate || PyErr_Occurred()) { goto __PYX_BAD; } } PyType_Modified((PyTypeObject*)type_obj); } } goto __PYX_GOOD; __PYX_BAD: if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); ret = -1; __PYX_GOOD: #if !CYTHON_USE_PYTYPE_LOOKUP Py_XDECREF(object_reduce); Py_XDECREF(object_reduce_ex); #endif Py_XDECREF(reduce); Py_XDECREF(reduce_ex); Py_XDECREF(reduce_cython); Py_XDECREF(setstate); Py_XDECREF(setstate_cython); return ret; } /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size) { PyObject *result = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif result = PyObject_GetAttrString(module, class_name); if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if ((size_t)basicsize < size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); goto bad; } else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. " "Expected %zd from C header, got %zd from PyObject", module_name, class_name, size, basicsize); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(result); return NULL; } #endif /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_MAJOR_VERSION < 3 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif if (unlikely(!__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } py_code = __pyx_find_code_object(c_line ? -c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); } py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if ((0)) {} view->obj = NULL; Py_DECREF(obj); } #endif /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = (float)(1.0) / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = (float)(1.0) / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0.0, -1.0); } } else { r = __Pyx_c_abs_float(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = (double)(1.0) / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = (double)(1.0) / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0.0, -1.0); } } else { r = __Pyx_c_abs_double(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) ((enum NPY_TYPES) 0 - (enum NPY_TYPES) 1), const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { const size_t neg_one = (size_t) ((size_t) 0 - (size_t) 1), const_zero = (size_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(size_t) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(size_t, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (size_t) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, digits[0]) case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 2 * PyLong_SHIFT) { return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 3 * PyLong_SHIFT) { return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 4 * PyLong_SHIFT) { return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (size_t) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(size_t) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case -1: __PYX_VERIFY_RETURN_INT(size_t, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, +digits[0]) case -2: if (8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -3: if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -4: if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; } #endif if (sizeof(size_t) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else size_t val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (size_t) -1; } } else { size_t val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (size_t) -1; val = __Pyx_PyInt_As_size_t(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to size_t"); return (size_t) -1; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { PyObject *t = PyTuple_GET_ITEM(tuple, i); #if PY_MAJOR_VERSION < 3 if (likely(exc_type == t)) return 1; #endif if (likely(PyExceptionClass_Check(t))) { if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; } else { } } return 0; } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { if (likely(PyExceptionClass_Check(exc_type))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } else if (likely(PyTuple_Check(exc_type))) { return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); } else { } } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { assert(PyExceptionClass_Check(exc_type1)); assert(PyExceptionClass_Check(exc_type2)); if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* FetchCommonType */ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { PyObject* fake_module; PyTypeObject* cached_type = NULL; fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); if (!fake_module) return NULL; Py_INCREF(fake_module); cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); if (cached_type) { if (!PyType_Check((PyObject*)cached_type)) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s is not a type object", type->tp_name); goto bad; } if (cached_type->tp_basicsize != type->tp_basicsize) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s has the wrong size, try recompiling", type->tp_name); goto bad; } } else { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; PyErr_Clear(); if (PyType_Ready(type) < 0) goto bad; if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) goto bad; Py_INCREF(type); cached_type = type; } done: Py_DECREF(fake_module); return cached_type; bad: Py_XDECREF(cached_type); cached_type = NULL; goto done; } /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* PyObjectGetMethod */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { PyObject *attr; #if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP PyTypeObject *tp = Py_TYPE(obj); PyObject *descr; descrgetfunc f = NULL; PyObject **dictptr, *dict; int meth_found = 0; assert (*method == NULL); if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; } if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { return 0; } descr = _PyType_Lookup(tp, name); if (likely(descr != NULL)) { Py_INCREF(descr); #if PY_MAJOR_VERSION >= 3 #ifdef __Pyx_CyFunction_USED if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) #else if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type))) #endif #else #ifdef __Pyx_CyFunction_USED if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) #else if (likely(PyFunction_Check(descr))) #endif #endif { meth_found = 1; } else { f = Py_TYPE(descr)->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } } } dictptr = _PyObject_GetDictPtr(obj); if (dictptr != NULL && (dict = *dictptr) != NULL) { Py_INCREF(dict); attr = __Pyx_PyDict_GetItemStr(dict, name); if (attr != NULL) { Py_INCREF(attr); Py_DECREF(dict); Py_XDECREF(descr); goto try_unpack; } Py_DECREF(dict); } if (meth_found) { *method = descr; return 1; } if (f != NULL) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } if (descr != NULL) { *method = descr; return 0; } PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(name)); #endif return 0; #else attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; #endif try_unpack: #if CYTHON_UNPACK_METHODS if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { PyObject *function = PyMethod_GET_FUNCTION(attr); Py_INCREF(function); Py_DECREF(attr); *method = function; return 1; } #endif *method = attr; return 0; } /* PyObjectCallMethod1 */ static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); Py_DECREF(method); return result; } static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { PyObject *method = NULL, *result; int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); if (likely(is_method)) { result = __Pyx_PyObject_Call2Args(method, obj, arg); Py_DECREF(method); return result; } if (unlikely(!method)) return NULL; return __Pyx__PyObject_CallMethod1(method, arg); } /* CoroutineBase */ #include <structmember.h> #include <frameobject.h> #define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) static int __Pyx_PyGen__FetchStopIterationValue(CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject **pvalue) { PyObject *et, *ev, *tb; PyObject *value = NULL; __Pyx_ErrFetch(&et, &ev, &tb); if (!et) { Py_XDECREF(tb); Py_XDECREF(ev); Py_INCREF(Py_None); *pvalue = Py_None; return 0; } if (likely(et == PyExc_StopIteration)) { if (!ev) { Py_INCREF(Py_None); value = Py_None; } #if PY_VERSION_HEX >= 0x030300A0 else if (Py_TYPE(ev) == (PyTypeObject*)PyExc_StopIteration) { value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); } #endif else if (unlikely(PyTuple_Check(ev))) { if (PyTuple_GET_SIZE(ev) >= 1) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS value = PyTuple_GET_ITEM(ev, 0); Py_INCREF(value); #else value = PySequence_ITEM(ev, 0); #endif } else { Py_INCREF(Py_None); value = Py_None; } Py_DECREF(ev); } else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { value = ev; } if (likely(value)) { Py_XDECREF(tb); Py_DECREF(et); *pvalue = value; return 0; } } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { __Pyx_ErrRestore(et, ev, tb); return -1; } PyErr_NormalizeException(&et, &ev, &tb); if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { __Pyx_ErrRestore(et, ev, tb); return -1; } Py_XDECREF(tb); Py_DECREF(et); #if PY_VERSION_HEX >= 0x030300A0 value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); #else { PyObject* args = __Pyx_PyObject_GetAttrStr(ev, __pyx_n_s_args); Py_DECREF(ev); if (likely(args)) { value = PySequence_GetItem(args, 0); Py_DECREF(args); } if (unlikely(!value)) { __Pyx_ErrRestore(NULL, NULL, NULL); Py_INCREF(Py_None); value = Py_None; } } #endif *pvalue = value; return 0; } static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { PyObject *t, *v, *tb; t = exc_state->exc_type; v = exc_state->exc_value; tb = exc_state->exc_traceback; exc_state->exc_type = NULL; exc_state->exc_value = NULL; exc_state->exc_traceback = NULL; Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); } #define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) static void __Pyx__Coroutine_AlreadyRunningError(CYTHON_UNUSED __pyx_CoroutineObject *gen) { const char *msg; if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { msg = "coroutine already executing"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { msg = "async generator already executing"; #endif } else { msg = "generator already executing"; } PyErr_SetString(PyExc_ValueError, msg); } #define __Pyx_Coroutine_NotStartedError(gen) (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL) static void __Pyx__Coroutine_NotStartedError(CYTHON_UNUSED PyObject *gen) { const char *msg; if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check(gen)) { msg = "can't send non-None value to a just-started coroutine"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact(gen)) { msg = "can't send non-None value to a just-started async generator"; #endif } else { msg = "can't send non-None value to a just-started generator"; } PyErr_SetString(PyExc_TypeError, msg); } #define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing) (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL) static void __Pyx__Coroutine_AlreadyTerminatedError(CYTHON_UNUSED PyObject *gen, PyObject *value, CYTHON_UNUSED int closing) { #ifdef __Pyx_Coroutine_USED if (!closing && __Pyx_Coroutine_Check(gen)) { PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); } else #endif if (value) { #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(gen)) PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); else #endif PyErr_SetNone(PyExc_StopIteration); } } static PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) { __Pyx_PyThreadState_declare PyThreadState *tstate; __Pyx_ExcInfoStruct *exc_state; PyObject *retval; assert(!self->is_running); if (unlikely(self->resume_label == 0)) { if (unlikely(value && value != Py_None)) { return __Pyx_Coroutine_NotStartedError((PyObject*)self); } } if (unlikely(self->resume_label == -1)) { return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); } #if CYTHON_FAST_THREAD_STATE __Pyx_PyThreadState_assign tstate = __pyx_tstate; #else tstate = __Pyx_PyThreadState_Current; #endif exc_state = &self->gi_exc_state; if (exc_state->exc_type) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON #else if (exc_state->exc_traceback) { PyTracebackObject *tb = (PyTracebackObject *) exc_state->exc_traceback; PyFrameObject *f = tb->tb_frame; Py_XINCREF(tstate->frame); assert(f->f_back == NULL); f->f_back = tstate->frame; } #endif } #if CYTHON_USE_EXC_INFO_STACK exc_state->previous_item = tstate->exc_info; tstate->exc_info = exc_state; #else if (exc_state->exc_type) { __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); } else { __Pyx_Coroutine_ExceptionClear(exc_state); __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); } #endif self->is_running = 1; retval = self->body((PyObject *) self, tstate, value); self->is_running = 0; #if CYTHON_USE_EXC_INFO_STACK exc_state = &self->gi_exc_state; tstate->exc_info = exc_state->previous_item; exc_state->previous_item = NULL; __Pyx_Coroutine_ResetFrameBackpointer(exc_state); #endif return retval; } static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { PyObject *exc_tb = exc_state->exc_traceback; if (likely(exc_tb)) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON #else PyTracebackObject *tb = (PyTracebackObject *) exc_tb; PyFrameObject *f = tb->tb_frame; Py_CLEAR(f->f_back); #endif } } static CYTHON_INLINE PyObject *__Pyx_Coroutine_MethodReturn(CYTHON_UNUSED PyObject* gen, PyObject *retval) { if (unlikely(!retval)) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (!__Pyx_PyErr_Occurred()) { PyObject *exc = PyExc_StopIteration; #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(gen)) exc = __Pyx_PyExc_StopAsyncIteration; #endif __Pyx_PyErr_SetNone(exc); } } return retval; } static CYTHON_INLINE PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) { PyObject *ret; PyObject *val = NULL; __Pyx_Coroutine_Undelegate(gen); __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); ret = __Pyx_Coroutine_SendEx(gen, val, 0); Py_XDECREF(val); return ret; } static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { PyObject *retval; __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; gen->is_running = 1; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { ret = __Pyx_Coroutine_Send(yf, value); } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { ret = __Pyx_Coroutine_Send(yf, value); } else #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_PyAsyncGenASend_CheckExact(yf)) { ret = __Pyx_async_gen_asend_send(yf, value); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyGen_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact) && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyCoro_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); } else #endif { if (value == Py_None) ret = Py_TYPE(yf)->tp_iternext(yf); else ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s_send, value); } gen->is_running = 0; if (likely(ret)) { return ret; } retval = __Pyx_Coroutine_FinishDelegation(gen); } else { retval = __Pyx_Coroutine_SendEx(gen, value, 0); } return __Pyx_Coroutine_MethodReturn(self, retval); } static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { PyObject *retval = NULL; int err = 0; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { retval = __Pyx_Coroutine_Close(yf); if (!retval) return -1; } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { retval = __Pyx_Coroutine_Close(yf); if (!retval) return -1; } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf, NULL); if (!retval) return -1; } else #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_PyAsyncGenASend_CheckExact(yf)) { retval = __Pyx_async_gen_asend_close(yf, NULL); } else if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { retval = __Pyx_async_gen_athrow_close(yf, NULL); } else #endif { PyObject *meth; gen->is_running = 1; meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_close); if (unlikely(!meth)) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_WriteUnraisable(yf); } PyErr_Clear(); } else { retval = PyObject_CallFunction(meth, NULL); Py_DECREF(meth); if (!retval) err = -1; } gen->is_running = 0; } Py_XDECREF(retval); return err; } static PyObject *__Pyx_Generator_Next(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; gen->is_running = 1; #ifdef __Pyx_Generator_USED if (__Pyx_Generator_CheckExact(yf)) { ret = __Pyx_Generator_Next(yf); } else #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) if (PyGen_CheckExact(yf)) { ret = _PyGen_Send((PyGenObject*)yf, NULL); } else #endif #ifdef __Pyx_Coroutine_USED if (__Pyx_Coroutine_Check(yf)) { ret = __Pyx_Coroutine_Send(yf, Py_None); } else #endif ret = Py_TYPE(yf)->tp_iternext(yf); gen->is_running = 0; if (likely(ret)) { return ret; } return __Pyx_Coroutine_FinishDelegation(gen); } return __Pyx_Coroutine_SendEx(gen, Py_None, 0); } static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, CYTHON_UNUSED PyObject *arg) { return __Pyx_Coroutine_Close(self); } static PyObject *__Pyx_Coroutine_Close(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject *retval, *raised_exception; PyObject *yf = gen->yieldfrom; int err = 0; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { Py_INCREF(yf); err = __Pyx_Coroutine_CloseIter(gen, yf); __Pyx_Coroutine_Undelegate(gen); Py_DECREF(yf); } if (err == 0) PyErr_SetNone(PyExc_GeneratorExit); retval = __Pyx_Coroutine_SendEx(gen, NULL, 1); if (unlikely(retval)) { const char *msg; Py_DECREF(retval); if ((0)) { #ifdef __Pyx_Coroutine_USED } else if (__Pyx_Coroutine_Check(self)) { msg = "coroutine ignored GeneratorExit"; #endif #ifdef __Pyx_AsyncGen_USED } else if (__Pyx_AsyncGen_CheckExact(self)) { #if PY_VERSION_HEX < 0x03060000 msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)"; #else msg = "async generator ignored GeneratorExit"; #endif #endif } else { msg = "generator ignored GeneratorExit"; } PyErr_SetString(PyExc_RuntimeError, msg); return NULL; } raised_exception = PyErr_Occurred(); if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) { if (raised_exception) PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } return NULL; } static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, PyObject *args, int close_on_genexit) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject *yf = gen->yieldfrom; if (unlikely(gen->is_running)) return __Pyx_Coroutine_AlreadyRunningError(gen); if (yf) { PyObject *ret; Py_INCREF(yf); if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { int err = __Pyx_Coroutine_CloseIter(gen, yf); Py_DECREF(yf); __Pyx_Coroutine_Undelegate(gen); if (err < 0) return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); goto throw_here; } gen->is_running = 1; if (0 #ifdef __Pyx_Generator_USED || __Pyx_Generator_CheckExact(yf) #endif #ifdef __Pyx_Coroutine_USED || __Pyx_Coroutine_Check(yf) #endif ) { ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); #ifdef __Pyx_Coroutine_USED } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); #endif } else { PyObject *meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_throw); if (unlikely(!meth)) { Py_DECREF(yf); if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { gen->is_running = 0; return NULL; } PyErr_Clear(); __Pyx_Coroutine_Undelegate(gen); gen->is_running = 0; goto throw_here; } if (likely(args)) { ret = PyObject_CallObject(meth, args); } else { ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); } Py_DECREF(meth); } gen->is_running = 0; Py_DECREF(yf); if (!ret) { ret = __Pyx_Coroutine_FinishDelegation(gen); } return __Pyx_Coroutine_MethodReturn(self, ret); } throw_here: __Pyx_Raise(typ, val, tb, NULL); return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); } static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) { PyObject *typ; PyObject *val = NULL; PyObject *tb = NULL; if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb)) return NULL; return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1); } static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { Py_VISIT(exc_state->exc_type); Py_VISIT(exc_state->exc_value); Py_VISIT(exc_state->exc_traceback); return 0; } static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { Py_VISIT(gen->closure); Py_VISIT(gen->classobj); Py_VISIT(gen->yieldfrom); return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); } static int __Pyx_Coroutine_clear(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; Py_CLEAR(gen->closure); Py_CLEAR(gen->classobj); Py_CLEAR(gen->yieldfrom); __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); } #endif Py_CLEAR(gen->gi_code); Py_CLEAR(gen->gi_name); Py_CLEAR(gen->gi_qualname); Py_CLEAR(gen->gi_modulename); return 0; } static void __Pyx_Coroutine_dealloc(PyObject *self) { __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; PyObject_GC_UnTrack(gen); if (gen->gi_weakreflist != NULL) PyObject_ClearWeakRefs(self); if (gen->resume_label >= 0) { PyObject_GC_Track(self); #if PY_VERSION_HEX >= 0x030400a1 && CYTHON_USE_TP_FINALIZE if (PyObject_CallFinalizerFromDealloc(self)) #else Py_TYPE(gen)->tp_del(self); if (self->ob_refcnt > 0) #endif { return; } PyObject_GC_UnTrack(self); } #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { /* We have to handle this case for asynchronous generators right here, because this code has to be between UNTRACK and GC_Del. */ Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); } #endif __Pyx_Coroutine_clear(self); PyObject_GC_Del(gen); } static void __Pyx_Coroutine_del(PyObject *self) { PyObject *error_type, *error_value, *error_traceback; __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; __Pyx_PyThreadState_declare if (gen->resume_label < 0) { return; } #if !CYTHON_USE_TP_FINALIZE assert(self->ob_refcnt == 0); self->ob_refcnt = 1; #endif __Pyx_PyThreadState_assign __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); #ifdef __Pyx_AsyncGen_USED if (__Pyx_AsyncGen_CheckExact(self)) { __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; PyObject *finalizer = agen->ag_finalizer; if (finalizer && !agen->ag_closed) { PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); if (unlikely(!res)) { PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } __Pyx_ErrRestore(error_type, error_value, error_traceback); return; } } #endif if (unlikely(gen->resume_label == 0 && !error_value)) { #ifdef __Pyx_Coroutine_USED #ifdef __Pyx_Generator_USED if (!__Pyx_Generator_CheckExact(self)) #endif { PyObject_GC_UnTrack(self); #if PY_MAJOR_VERSION >= 3 || defined(PyErr_WarnFormat) if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) PyErr_WriteUnraisable(self); #else {PyObject *msg; char *cmsg; #if CYTHON_COMPILING_IN_PYPY msg = NULL; cmsg = (char*) "coroutine was never awaited"; #else char *cname; PyObject *qualname; qualname = gen->gi_qualname; cname = PyString_AS_STRING(qualname); msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname); if (unlikely(!msg)) { PyErr_Clear(); cmsg = (char*) "coroutine was never awaited"; } else { cmsg = PyString_AS_STRING(msg); } #endif if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0)) PyErr_WriteUnraisable(self); Py_XDECREF(msg);} #endif PyObject_GC_Track(self); } #endif } else { PyObject *res = __Pyx_Coroutine_Close(self); if (unlikely(!res)) { if (PyErr_Occurred()) PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } } __Pyx_ErrRestore(error_type, error_value, error_traceback); #if !CYTHON_USE_TP_FINALIZE assert(self->ob_refcnt > 0); if (--self->ob_refcnt == 0) { return; } { Py_ssize_t refcnt = self->ob_refcnt; _Py_NewReference(self); self->ob_refcnt = refcnt; } #if CYTHON_COMPILING_IN_CPYTHON assert(PyType_IS_GC(self->ob_type) && _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); _Py_DEC_REFTOTAL; #endif #ifdef COUNT_ALLOCS --Py_TYPE(self)->tp_frees; --Py_TYPE(self)->tp_allocs; #endif #endif } static PyObject * __Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) { PyObject *name = self->gi_name; if (unlikely(!name)) name = Py_None; Py_INCREF(name); return name; } static int __Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } tmp = self->gi_name; Py_INCREF(value); self->gi_name = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) { PyObject *name = self->gi_qualname; if (unlikely(!name)) name = Py_None; Py_INCREF(name); return name; } static int __Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) #else if (unlikely(value == NULL || !PyString_Check(value))) #endif { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } tmp = self->gi_qualname; Py_INCREF(value); self->gi_qualname = value; Py_XDECREF(tmp); return 0; } static __pyx_CoroutineObject *__Pyx__Coroutine_New( PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name) { __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); if (unlikely(!gen)) return NULL; return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); } static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, PyObject *name, PyObject *qualname, PyObject *module_name) { gen->body = body; gen->closure = closure; Py_XINCREF(closure); gen->is_running = 0; gen->resume_label = 0; gen->classobj = NULL; gen->yieldfrom = NULL; gen->gi_exc_state.exc_type = NULL; gen->gi_exc_state.exc_value = NULL; gen->gi_exc_state.exc_traceback = NULL; #if CYTHON_USE_EXC_INFO_STACK gen->gi_exc_state.previous_item = NULL; #endif gen->gi_weakreflist = NULL; Py_XINCREF(qualname); gen->gi_qualname = qualname; Py_XINCREF(name); gen->gi_name = name; Py_XINCREF(module_name); gen->gi_modulename = module_name; Py_XINCREF(code); gen->gi_code = code; PyObject_GC_Track(gen); return gen; } /* PatchModuleWithCoroutine */ static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) { #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) int result; PyObject *globals, *result_obj; globals = PyDict_New(); if (unlikely(!globals)) goto ignore; result = PyDict_SetItemString(globals, "_cython_coroutine_type", #ifdef __Pyx_Coroutine_USED (PyObject*)__pyx_CoroutineType); #else Py_None); #endif if (unlikely(result < 0)) goto ignore; result = PyDict_SetItemString(globals, "_cython_generator_type", #ifdef __Pyx_Generator_USED (PyObject*)__pyx_GeneratorType); #else Py_None); #endif if (unlikely(result < 0)) goto ignore; if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore; if (unlikely(PyDict_SetItemString(globals, "__builtins__", __pyx_b) < 0)) goto ignore; result_obj = PyRun_String(py_code, Py_file_input, globals, globals); if (unlikely(!result_obj)) goto ignore; Py_DECREF(result_obj); Py_DECREF(globals); return module; ignore: Py_XDECREF(globals); PyErr_WriteUnraisable(module); if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) { Py_DECREF(module); module = NULL; } #else py_code++; #endif return module; } /* PatchGeneratorABC */ #ifndef CYTHON_REGISTER_ABCS #define CYTHON_REGISTER_ABCS 1 #endif #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) static PyObject* __Pyx_patch_abc_module(PyObject *module); static PyObject* __Pyx_patch_abc_module(PyObject *module) { module = __Pyx_Coroutine_patch_module( module, "" "if _cython_generator_type is not None:\n" " try: Generator = _module.Generator\n" " except AttributeError: pass\n" " else: Generator.register(_cython_generator_type)\n" "if _cython_coroutine_type is not None:\n" " try: Coroutine = _module.Coroutine\n" " except AttributeError: pass\n" " else: Coroutine.register(_cython_coroutine_type)\n" ); return module; } #endif static int __Pyx_patch_abc(void) { #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) static int abc_patched = 0; if (CYTHON_REGISTER_ABCS && !abc_patched) { PyObject *module; module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections"); if (!module) { PyErr_WriteUnraisable(NULL); if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, ((PY_MAJOR_VERSION >= 3) ? "Cython module failed to register with collections.abc module" : "Cython module failed to register with collections module"), 1) < 0)) { return -1; } } else { module = __Pyx_patch_abc_module(module); abc_patched = 1; if (unlikely(!module)) return -1; Py_DECREF(module); } module = PyImport_ImportModule("backports_abc"); if (module) { module = __Pyx_patch_abc_module(module); Py_XDECREF(module); } if (!module) { PyErr_Clear(); } } #else if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL); #endif return 0; } /* Generator */ static PyMethodDef __pyx_Generator_methods[] = { {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS, (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, {0, 0, 0, 0} }; static PyMemberDef __pyx_Generator_memberlist[] = { {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL}, {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, (char*) PyDoc_STR("object being iterated by 'yield from', or None")}, {(char*) "gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, {0, 0, 0, 0, 0} }; static PyGetSetDef __pyx_Generator_getsets[] = { {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, (char*) PyDoc_STR("name of the generator"), 0}, {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, (char*) PyDoc_STR("qualified name of the generator"), 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_GeneratorType_type = { PyVarObject_HEAD_INIT(0, 0) "generator", sizeof(__pyx_CoroutineObject), 0, (destructor) __Pyx_Coroutine_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, 0, (traverseproc) __Pyx_Coroutine_traverse, 0, 0, offsetof(__pyx_CoroutineObject, gi_weakreflist), 0, (iternextfunc) __Pyx_Generator_Next, __pyx_Generator_methods, __pyx_Generator_memberlist, __pyx_Generator_getsets, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if CYTHON_USE_TP_FINALIZE 0, #else __Pyx_Coroutine_del, #endif 0, #if CYTHON_USE_TP_FINALIZE __Pyx_Coroutine_del, #elif PY_VERSION_HEX >= 0x030400a1 0, #endif #if PY_VERSION_HEX >= 0x030800b1 0, #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, #endif }; static int __pyx_Generator_init(void) { __pyx_GeneratorType_type.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type); if (unlikely(!__pyx_GeneratorType)) { return -1; } return 0; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; if (PyObject_Hash(*t->p) == -1) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; } #else static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif } #endif #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
[ "ethanjaszewski@yahoo.com" ]
ethanjaszewski@yahoo.com
daf2e566110b7b548df65275f8ba18ffccabf98a
653e5cd3724231bef882b419b1dc8fdc3502d807
/Misc/QEKF/QEKF.cpp
049c5546ce01aaeb8b5976455b2a9f1b7959f2b6
[ "MIT" ]
permissive
Hyeong-Yong/STM32-libraries
95299a3082fb5af6e286243b8762df39928a5b90
f0d05495acee83be8fbefe0bbbb0ec7fd236cef5
refs/heads/master
2023-06-21T18:37:57.950435
2020-12-06T07:43:09
2020-12-06T07:43:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,252
cpp
/* Copyright (C) 2018-2019 Thomas Jespersen, TKJ Electronics. All rights reserved. * * This program is free software: you can redistribute it and/or modify it * under the terms of the MIT License * * This program 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 MIT License for further details. * * Contact information * ------------------------------------------ * Thomas Jespersen, TKJ Electronics * Web : http://www.tkjelectronics.dk * e-mail : thomasj@tkjelectronics.dk * ------------------------------------------ */ #include "QEKF.h" #include "QEKF_coder.h" #include "QEKF_initialize.h" #include "MathLib.h" #include <math.h> #include <cmath> #include <string.h> // for memcpy #include "Quaternion.h" #include "MathLib.h" // for matrix symmetrization #include "arm_math.h" QEKF::QEKF(Parameters& params, Timer * microsTimer) : _params(params), _microsTimer(microsTimer) { Reset(); } QEKF::QEKF(Parameters& params) : _params(params), _microsTimer(0) { Reset(); } QEKF::~QEKF() { } void QEKF::Reset() { QEKF_initialize(_params.estimator.QEKF_P_init_diagonal, X, P); if (_microsTimer) _prevTimerValue = _microsTimer->Get(); else _prevTimerValue = 0; } /** * @brief Reset attitude estimator to an angle based on an accelerometer measurement * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] */ void QEKF::Reset(const float accelerometer[3]) { Reset(); /* Reset quaternion state into certain angle based on accelerometer measurement */ // Based on Freescale Application Note: https://www.nxp.com/files-static/sensors/doc/app_note/AN3461.pdf const float mu = 0.0001; // regularization factor float roll = atan2f(accelerometer[1], sqrtf(accelerometer[2]*accelerometer[2] + mu*accelerometer[0]*accelerometer[0])); float pitch = atan2f(-accelerometer[0], sqrtf(accelerometer[1]*accelerometer[1] + accelerometer[2]*accelerometer[2])); Quaternion_eul2quat_zyx(0, pitch, roll, &X[0]); } /** * @brief Reset attitude estimator to an angle based on an accelerometer measurement * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] */ void QEKF::Reset(const float accelerometer[3], const float heading) { Reset(); /* Reset quaternion state into certain angle based on accelerometer measurement */ // Based on Freescale Application Note: https://www.nxp.com/files-static/sensors/doc/app_note/AN3461.pdf const float mu = 0.0001; // regularization factor float roll = atan2f(accelerometer[1], sqrtf(accelerometer[2]*accelerometer[2] + mu*accelerometer[0]*accelerometer[0])); float pitch = atan2f(-accelerometer[0], sqrtf(accelerometer[1]*accelerometer[1] + accelerometer[2]*accelerometer[2])); Quaternion_eul2quat_zyx(heading, pitch, roll, &X[0]); } /** * @brief Estimate attitude quaternion given accelerometer and gyroscope measurements * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3]) { Step(accelerometer, gyroscope, _params.estimator.EstimateBias); } /** * @brief Estimate attitude quaternion given accelerometer and gyroscope measurements * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] * @param EstimateBias Input: flag to control if gyroscope bias should be estimated */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3], const bool EstimateBias) { float dt; if (!_microsTimer) return; // timer not defined dt = _microsTimer->GetDeltaTime(_prevTimerValue); _prevTimerValue = _microsTimer->Get(); Step(accelerometer, gyroscope, EstimateBias, dt); } /** * @brief Estimate attitude quaternion given accelerometer, gyroscope measurements, a heading input/estimate and passed time * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] * @param heading Input: heading angle in inertial frame [rad] * @param EstimateBias Input: flag to control if gyroscope bias should be estimated */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3], const float heading, const bool EstimateBias) { float dt; if (!_microsTimer) return; // timer not defined dt = _microsTimer->GetDeltaTime(_prevTimerValue); _prevTimerValue = _microsTimer->Get(); Step(accelerometer, gyroscope, heading, EstimateBias, dt); } /** * @brief Estimate attitude quaternion given accelerometer and gyroscope measurements and passed time * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] * @param EstimateBias Input: flag to control if gyroscope bias should be estimated * @param dt Input: time passed since last estimate */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3], const bool EstimateBias, const float dt) { if (_params.estimator.UseXsensIMU) // use MTI covariance Step(accelerometer, gyroscope, 0, false, _params.estimator.SensorDrivenQEKF, EstimateBias, false, _params.estimator.CreateQdotFromQDifference, _params.estimator.cov_acc_mti, _params.estimator.cov_gyro_mti, _params.estimator.GyroscopeTrustFactor, _params.estimator.sigma2_omega, _params.estimator.sigma2_heading, _params.estimator.sigma2_bias, _params.estimator.AccelerometerVibration_DetectionEnabled, _params.estimator.AccelerometerVibration_NormLPFtau, _params.estimator.AccelerometerVibration_CovarianceVaryFactor, _params.estimator.AccelerometerVibration_MaxVaryFactor, _params.model.g, dt); else Step(accelerometer, gyroscope, 0, false, _params.estimator.SensorDrivenQEKF, EstimateBias, false, _params.estimator.CreateQdotFromQDifference, _params.estimator.cov_acc_mpu, _params.estimator.cov_gyro_mpu, _params.estimator.GyroscopeTrustFactor, _params.estimator.sigma2_omega, _params.estimator.sigma2_heading, _params.estimator.sigma2_bias, _params.estimator.AccelerometerVibration_DetectionEnabled, _params.estimator.AccelerometerVibration_NormLPFtau, _params.estimator.AccelerometerVibration_CovarianceVaryFactor, _params.estimator.AccelerometerVibration_MaxVaryFactor, _params.model.g, dt); } /** * @brief Estimate attitude quaternion given accelerometer, gyroscope measurements, a heading input/estimate and passed time * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] * @param heading Input: heading angle in inertial frame [rad] * @param EstimateBias Input: flag to control if gyroscope bias should be estimated * @param dt Input: time passed since last estimate */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3], const float heading, const bool EstimateBias, const float dt) { if (_params.estimator.UseXsensIMU) // use MTI covariance Step(accelerometer, gyroscope, heading, true, _params.estimator.SensorDrivenQEKF, EstimateBias, EstimateBias, _params.estimator.CreateQdotFromQDifference, _params.estimator.cov_acc_mti, _params.estimator.cov_gyro_mti, _params.estimator.GyroscopeTrustFactor, _params.estimator.sigma2_omega, _params.estimator.sigma2_heading, _params.estimator.sigma2_bias, _params.estimator.AccelerometerVibration_DetectionEnabled, _params.estimator.AccelerometerVibration_NormLPFtau, _params.estimator.AccelerometerVibration_CovarianceVaryFactor, _params.estimator.AccelerometerVibration_MaxVaryFactor, _params.model.g, dt); else Step(accelerometer, gyroscope, heading, true, _params.estimator.SensorDrivenQEKF, EstimateBias, EstimateBias, _params.estimator.CreateQdotFromQDifference, _params.estimator.cov_acc_mpu, _params.estimator.cov_gyro_mpu, _params.estimator.GyroscopeTrustFactor, _params.estimator.sigma2_omega, _params.estimator.sigma2_heading, _params.estimator.sigma2_bias, _params.estimator.AccelerometerVibration_DetectionEnabled, _params.estimator.AccelerometerVibration_NormLPFtau, _params.estimator.AccelerometerVibration_CovarianceVaryFactor, _params.estimator.AccelerometerVibration_MaxVaryFactor, _params.model.g, dt); } /** * @brief Estimate attitude quaternion given accelerometer and gyroscope measurements and passed time * @param accelerometer[3] Input: acceleration measurement in body frame [m/s^2] * @param gyroscope[3] Input: angular velocity measurement in body frame [rad/s] * @param heading Input: heading angle measurement [rad] * @param UseHeadingForCorrection Input: flag to indicate if heading measurement is available * @param SensorDriven Input: flag to control if QEKF should run in sensor driven mode, disabling smoothing of angular velocity estimate * @param EstimateBias Input: flag to control if gyroscope x/y axis bias should be estimated * @param EstimateYawBias Input: flag to control if gyroscope z-axis bias should be estimated * @param CreateQdotFromDifference Input: flag to control if qdot estimate is generated by differentiating q estimate * @param cov_acc Input: accelerometer sensor covariance matrix * @param cov_gyro Input: gyroscope sensor covariance matrix * @param GyroscopeTrustFactor Input: tuning factor for accelerometer-gyroscope trust ratio - increase value to trust gyroscope measurements more * @param sigma2_omega Input: smoothing parameter for angular velocity * @param sigma2_heading Input: variance on heading input * @param sigma2_bias Input: bias variance (random walk) * @param AccelerometerVibrationDetectionEnabled Input: reduce trust in accelerometer measurements during periods with large vibrations * @param AccelerometerVibrationNormLPFtau Input: low-pass filter for vibration detector * @param AccelerometerVibrationCovarianceVaryFactor Input: exponentially scaled factor to decrease gyroscope covariance (to decrease trust in accelerometer measurement) with during vibration periods * @param AccelerometerCovarianceMaxVaryFactor Input: maximum ratio of decrease in gyroscope covariance * @param g Input: gravity constant [m/s^2] * @param dt Input: time passed since last estimate */ void QEKF::Step(const float accelerometer[3], const float gyroscope[3], const float heading, const bool UseHeadingForCorrection, const bool SensorDriven, const bool EstimateBias, const bool EstimateYawBias, const bool CreateQdotFromDifference, const float cov_acc[9], const float cov_gyro[9], const float GyroscopeTrustFactor, const float sigma2_omega, const float sigma2_heading, const float sigma2_bias, const bool AccelerometerVibrationDetectionEnabled, const float AccelerometerVibrationNormLPFtau, const float AccelerometerVibrationCovarianceVaryFactor, const float AccelerometerCovarianceMaxVaryFactor, const float g, const float dt) { if (dt == 0) return; // no time has passed float X_prev[10]; memcpy(X_prev, X, sizeof(X_prev)); float P_prev[10*10]; memcpy(P_prev, P, sizeof(P_prev)); _QEKF(X_prev, P_prev, gyroscope, accelerometer, heading, UseHeadingForCorrection, dt, SensorDriven, // true == sensor driven Kalman filter EstimateBias, EstimateYawBias, true, // true == normalize accelerometer cov_gyro, cov_acc, GyroscopeTrustFactor, sigma2_omega, sigma2_heading, sigma2_bias, AccelerometerVibrationDetectionEnabled, AccelerometerVibrationNormLPFtau, AccelerometerVibrationCovarianceVaryFactor, AccelerometerCovarianceMaxVaryFactor, g, X, P); Math_SymmetrizeSquareMatrix(P, sizeof(X)/sizeof(float)); if (CreateQdotFromDifference) { X[4] = (X[0] - X_prev[0]) / dt; // dq[0] X[5] = (X[1] - X_prev[1]) / dt; // dq[1] X[6] = (X[2] - X_prev[2]) / dt; // dq[2] X[7] = (X[3] - X_prev[3]) / dt; // dq[3] } } /** * @brief Get estimated attitude quaternion * @param q[4] Output: estimated attitude quaternion */ void QEKF::GetQuaternion(float q[4]) { q[0] = X[0]; q[1] = X[1]; q[2] = X[2]; q[3] = X[3]; } /** * @brief Get estimated attitude quaternion derivative * @param dq[4] Output: estimated attitude quaternion derivative */ void QEKF::GetQuaternionDerivative(float dq[4]) { /* Body angular velocity */ /* dq = 1/2 * Phi(q) * [0;omega]; */ float omega_q[4] = { 0, X[4], X[5], X[6] }; Quaternion_Phi(&X[0], omega_q, dq); // Phi(q) * [0;omega] arm_scale_f32(dq, 0.5f, dq, 4); /*dq[0] = X[4]; dq[1] = X[5]; dq[2] = X[6]; dq[3] = X[7];*/ } /** * @brief Get estimated gyroscope bias * @param bias[3] Output: estimated gyroscope bias */ void QEKF::GetGyroBias(float bias[3]) { bias[0] = X[7]; bias[1] = X[8]; bias[2] = X[9]; } /** * @brief Get covariance matrix of estimated quaternion * @param Cov_q[4*4] Output: quaternion estimate covariance */ void QEKF::GetQuaternionCovariance(float Cov_q[4*4]) { for (int m = 0; m < 4; m++) { for (int n = 0; n < 4; n++) { Cov_q[4*m + n] = P[10*m + n]; } } } /** * @brief Get covariance matrix of estimated quaternion derivative * @param Cov_dq[4*4] Output: quaternion derivative estimate covariance */ void QEKF::GetQuaternionDerivativeCovariance(float Cov_dq[4*4]) { /*for (int m = 0; m < 4; m++) { for (int n = 0; n < 4; n++) { Cov_dq[4*m + n] = P[10*m + n + (10*4 + 4)]; } }*/ // OBS. The covariance of the quaternion derivative estimate is not stored in the estimator covariance, since it is not part of the state vector // Hence we need to transform the covariance of the angular velocity estimate into a covariance of the quaternion derivative estimate /* Cov_dq = (1/2 * Phi(q) * vec) * Cov_omega * (1/2 * Phi(q) * vec)' */ /* Cov_dq = T(q) * Cov_omega * T(q)' */ float Cov_omega[3*3]; arm_matrix_instance_f32 Cov_omega_; arm_mat_init_f32(&Cov_omega_, 3, 3, Cov_omega); GetAngularVelocityCovariance(Cov_omega); // Compute transformation matrix, T(q) float T_q[4*3]; arm_matrix_instance_f32 T_q_; arm_mat_init_f32(&T_q_, 4, 3, T_q); Quaternion_mat_PhiVec(&X[0], T_q); arm_scale_f32(T_q, 0.5f, T_q, 4*3); // Compute transpose, T(q)' float T_q_T[3*4]; arm_matrix_instance_f32 T_q_T_; arm_mat_init_f32(&T_q_T_, 3, 4, T_q_T); arm_mat_trans_f32(&T_q_, &T_q_T_); // Compute right part of transformation --> tmp = Cov_omega * T(q)' float tmp[3*4]; arm_matrix_instance_f32 tmp_; arm_mat_init_f32(&tmp_, 3, 4, tmp); arm_mat_mult_f32(&Cov_omega_, &T_q_T_, &tmp_); // Compute output --> Cov_dq = T(q) * tmp arm_matrix_instance_f32 Cov_dq_; arm_mat_init_f32(&Cov_dq_, 4, 4, Cov_dq); arm_mat_mult_f32(&T_q_, &tmp_, &Cov_dq_); Math_SymmetrizeSquareMatrix(Cov_dq, 4); } /** * @brief Get covariance matrix of estimated angular velocity * @param Cov_omega[3*3] Output: angular velocity estimate covariance */ void QEKF::GetAngularVelocityCovariance(float Cov_omega[3*3]) { for (int m = 0; m < 3; m++) { for (int n = 0; n < 3; n++) { Cov_omega[3*m + n] = P[10*m + n + (10*4 + 4)]; } } } /** * @brief Get covariance matrix of estimated gyroscope bias * @param Cov_bias[3*3] Output: gyroscope bias estimate covariance */ void QEKF::GetBiasCovariance(float Cov_bias[3*3]) { for (int m = 0; m < 3; m++) { for (int n = 0; n < 3; n++) { Cov_bias[3*m + n] = P[10*m + n + (10*7 + 7)]; } } } bool QEKF::UnitTest(void) { const float g = 9.82f; const float cov_gyro_mpu[9] = {0.2529E-03, -0.0064E-03, 0.1981E-03, -0.0064E-03, 0.9379E-03, -0.0038E-03, 0.1981E-03, -0.0038E-03, 1.6828E-03}; const float cov_acc_mpu[9] = {0.4273E-03, 0.0072E-03, 0.0096E-03, 0.0072E-03, 0.4333E-03, 0.0041E-03, 0.0096E-03, 0.0041E-03, 1.0326E-03}; const bool SensorDriven = true; const float sigma2_bias = 1E-11; const float sigma2_omega = 1E-4; const float sigma2_heading = powf(deg2rad(1) / 3.0f, 2); const float GyroscopeTrustFactor = 1.0; const bool EstimateBias = true; const bool EstimateYawBias = true; const bool CreateQdotFromDifference = false; const bool UseHeadingForCorrection = true; const float VibrationDetectionAmount = 1.0; const bool VibrationDetectionEnabled = false; const float VibrationNormLPFtau = 0.5; const float VibrationCovarianceVaryFactor = 2.0; const float VibrationMaxVaryFactor = 10000; const float QEKF_P_init_diagonal[11] = {1E-5, 1E-5, 1E-5, 1E-7, 1E-7, 1E-7, 1E-7, 1E-7, 1E-5, 1E-5, 1E-5}; QEKF_initialize(QEKF_P_init_diagonal, X, P); // reset const float Accelerometer[3] = {0.05, 0, 9.82}; const float Gyroscope[3] = {1.0, 0.5, 0.09}; const float heading = 0.4; const float dt = 1.0 / 200.0; // 400 Hz Step(Accelerometer, Gyroscope, heading, UseHeadingForCorrection, SensorDriven, EstimateBias, EstimateYawBias, CreateQdotFromDifference, cov_acc_mpu, cov_gyro_mpu, GyroscopeTrustFactor, sigma2_omega, sigma2_heading, sigma2_bias, VibrationDetectionEnabled, VibrationNormLPFtau, VibrationCovarianceVaryFactor, VibrationMaxVaryFactor, g, dt); Step(Accelerometer, Gyroscope, heading, UseHeadingForCorrection, SensorDriven, EstimateBias, EstimateYawBias, CreateQdotFromDifference, cov_acc_mpu, cov_gyro_mpu, GyroscopeTrustFactor, sigma2_omega, sigma2_heading, sigma2_bias, VibrationDetectionEnabled, VibrationNormLPFtau, VibrationCovarianceVaryFactor, VibrationMaxVaryFactor, g, dt); float q[4]; GetQuaternion(q); float dq[4]; GetQuaternionDerivative(dq); float Cov_q[4*4]; GetQuaternionCovariance(Cov_q); float bias[3]; bias[0] = X[8]; bias[1] = X[9]; bias[2] = X[10]; const float q_expected[4] = {999.9893e-03, 0.8631e-03, 0.0246e-03, 4.5302e-03}; if (!(Math_Round(q[0], 3) == Math_Round(q_expected[0], 3) && Math_Round(q[1], 7) == Math_Round(q_expected[1], 7) && Math_Round(q[2], 7) == Math_Round(q_expected[2], 7) && Math_Round(q[3], 7) == Math_Round(q_expected[3], 7))) return false; const float dq_expected[4] = {0.0180e-03, 0.2838339, 0.0631545, -0.0189311}; if (!(Math_Round(dq[0], 7) == Math_Round(dq_expected[0], 7) && Math_Round(dq[1], 6) == Math_Round(dq_expected[1], 6) && Math_Round(dq[2], 6) == Math_Round(dq_expected[2], 6) && Math_Round(dq[3], 6) == Math_Round(dq_expected[3], 6))) return false; const float bias_expected[3] = {0.0401830, 0.0085002, -0.0032197}; if (!(Math_Round(bias[0], 5) == Math_Round(bias_expected[0], 5) && Math_Round(bias[1], 5) == Math_Round(bias_expected[1], 5) && Math_Round(bias[2], 5) == Math_Round(bias_expected[2], 5))) return false; const float Cov_q_diag_expected[4] = {0.9262118e-05, 0.8441292e-05, 0.8419634e-05, 0.0098245e-05}; if (!(Math_Round(Cov_q[0], 9) == Math_Round(Cov_q_diag_expected[0], 9) && Math_Round(Cov_q[1+4], 9) == Math_Round(Cov_q_diag_expected[1], 9) && Math_Round(Cov_q[2+8], 9) == Math_Round(Cov_q_diag_expected[2], 9) && Math_Round(Cov_q[3+12], 9) == Math_Round(Cov_q_diag_expected[3], 9))) return false; return true; }
[ "thomasj@tkjelectronics.dk" ]
thomasj@tkjelectronics.dk
e99cd3d69bcea3d819983b11b091788c86d2afc6
64c5d0a41a109df7f49a75e9c8ee9ca98dfbba24
/libcef/renderer/render_frame_observer.h
2601b603e1c30b068e900beb5e8a0918e507f3fe
[ "BSD-3-Clause" ]
permissive
alexcross11248/cef
0d8fde5fc34dd667d7d1d6a87fd0c4f3f672e9dc
732a307c751c2670a35fd9e0e4a491cdfc6bcc6b
refs/heads/master
2020-06-07T13:28:05.610313
2019-06-19T14:53:31
2019-06-19T14:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
h
// Copyright 2014 The Chromium Embedded Framework 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 LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_ #define LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_ #include "content/public/renderer/render_frame_observer.h" #include "services/service_manager/public/cpp/binder_registry.h" namespace content { class RenderFrame; } class CefFrameImpl; class CefRenderFrameObserver : public content::RenderFrameObserver { public: explicit CefRenderFrameObserver(content::RenderFrame* render_frame); ~CefRenderFrameObserver() override; // RenderFrameObserver methods: void OnInterfaceRequestForFrame( const std::string& interface_name, mojo::ScopedMessagePipeHandle* interface_pipe) override; void DidFinishLoad() override; void FrameDetached() override; void FrameFocused() override; void FocusedNodeChanged(const blink::WebNode& node) override; void DraggableRegionsChanged() override; void DidCreateScriptContext(v8::Handle<v8::Context> context, int world_id) override; void WillReleaseScriptContext(v8::Handle<v8::Context> context, int world_id) override; void OnDestruct() override; bool OnMessageReceived(const IPC::Message& message) override; service_manager::BinderRegistry* registry() { return &registry_; } void AttachFrame(CefFrameImpl* frame); private: service_manager::BinderRegistry registry_; CefFrameImpl* frame_ = nullptr; DISALLOW_COPY_AND_ASSIGN(CefRenderFrameObserver); }; #endif // LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_
[ "magreenblatt@gmail.com" ]
magreenblatt@gmail.com
5d2f40d69eb1aa890b98d040971ba7e7f2861d46
f0458e378c0b86d07a90699ffcfe4b621b570395
/src/processors/MemTestProcessor.hh
dc56e753dea43d8a5ba7f96345c95e46a22f4bb3
[]
no_license
thomasms/lbno-nd
c8d9468a9b598bbae242e7698d538216f7745c4a
699ec919c4980e066e302de864ccfeee7de393a8
refs/heads/master
2021-01-12T08:54:39.309814
2016-12-17T09:29:57
2016-12-17T09:29:57
76,714,980
0
0
null
null
null
null
UTF-8
C++
false
false
895
hh
//____________________________________________________________________________ /*! \class MemTestProcessor \brief Processor class to check for memory leaks \author Yordan Karadzhov <Yordan.Karadzhov \at cern.ch> University of Geneva \created Sep 2013 \last update Sep 2013 */ //____________________________________________________________________________ #ifndef PROCESSORS_MEM_TEST_H #define PROCESSORS_MEM_TEST_H 1 #include <string> #include <iostream> #include <TSystem.h> #include <TRandom.h> #include "LbnoProcessor.hh" #include "PiDecayAlgorithm.hh" class MemTestProcessor : public LbnoProcessor { public: MemTestProcessor(); virtual ~MemTestProcessor() {} bool process(); void initOutDataTree(); void loadInDataTree() {} void loadDataCards(); private: void initDataCards(); MemTestRecord *event_; TRandom rand_; ProcInfo_t info_; }; #endif
[ "stainer.tom@gmail.com" ]
stainer.tom@gmail.com
f25dbe4846bf71ef357b5ba75014debca1298792
5838cf8f133a62df151ed12a5f928a43c11772ed
/NT/inetsrv/msmq/src/lib/msm/lib/msmlisten.cpp
50f53793b17fa26a02dd0e7516c6558c3c6d6be8
[]
no_license
proaholic/Win2K3
e5e17b2262f8a2e9590d3fd7a201da19771eb132
572f0250d5825e7b80920b6610c22c5b9baaa3aa
refs/heads/master
2023-07-09T06:15:54.474432
2021-08-11T09:09:14
2021-08-11T09:09:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,568
cpp
/*++ Copyright (c) 1995-97 Microsoft Corporation Module Name: MsmListen.cpp Abstract: Multicast Listener implementation Author: Shai Kariv (shaik) 05-Sep-00 Environment: Platform-independent --*/ #include <libpch.h> #include <winsock.h> #include <Mswsock.h> #include <WsRm.h> #include <Cm.h> #include "MsmListen.h" #include "MsmReceive.h" #include "Msmp.h" #include <strsafe.h> #include "msmlisten.tmh" static void MsmpDumpPGMReceiverStats(const SOCKET s); static CTimeDuration s_AcceptRetryTimeout( 10 * 1000 * CTimeDuration::OneMilliSecond().Ticks() ); static CTimeDuration s_ReceiverCleanupTimeout( 120 * 1000 * CTimeDuration::OneMilliSecond().Ticks() ); void MsmpInitConfiguration(void) { CmQueryValue( RegEntry(NULL, L"MulticastAcceptRetryTimeout", 10 * 1000), // 10 seconds &s_AcceptRetryTimeout ); CmQueryValue( RegEntry(NULL, L"MulticastReceiversCleanupTimeout", 120 * 1000), // 2 minutes &s_ReceiverCleanupTimeout ); } CMulticastListener::CMulticastListener( MULTICAST_ID id ): m_MulticastId(id), m_ov(AcceptSucceeded, AcceptFailed), m_retryAcceptTimer(TimeToRetryAccept), m_cleanupTimer(TimeToCleanupUnusedReceiever), m_fCleanupScheduled(FALSE) /*++ Routine Description: Bind to multicast group. Schedule async accept on the socket. Arguments: id - The multicast group IP address and port. Returned Value: None. --*/ { TrTRACE(NETWORKING, "Create multicast listener for %d:%d", id.m_address, id.m_port); DWORD flags = WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF | WSA_FLAG_OVERLAPPED; *&m_ListenSocket = WSASocket(AF_INET, SOCK_RDM, IPPROTO_RM, NULL, 0, flags); if (m_ListenSocket == INVALID_SOCKET) { DWORD ec = WSAGetLastError(); TrERROR(NETWORKING, "Failed to create PGM listen socket, error %d", ec); throw bad_win32_error(ec); } SOCKADDR_IN address; address.sin_family = AF_INET; address.sin_port = htons(numeric_cast<u_short>(m_MulticastId.m_port)); address.sin_addr.s_addr = m_MulticastId.m_address; BOOL reuse = TRUE; int rc = setsockopt(m_ListenSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)); if (rc == SOCKET_ERROR) { DWORD ec = WSAGetLastError(); TrERROR(NETWORKING, "Failed to setsockopt to PGM socket. %!winerr!", ec); throw bad_win32_error(ec); } rc = bind(m_ListenSocket, (SOCKADDR *)&address, sizeof(address)); if (rc == SOCKET_ERROR) { DWORD ec = WSAGetLastError(); TrERROR(NETWORKING, "Failed to bind to PGM socket, error %d", ec); throw bad_win32_error(ec); } rc = listen(m_ListenSocket, 1); if (rc == SOCKET_ERROR) { DWORD ec = WSAGetLastError(); TrERROR(NETWORKING, "Failed to listen to PGM socket, error %d", ec); throw bad_win32_error(ec); } ExAttachHandle(reinterpret_cast<HANDLE>(*&m_ListenSocket)); // // Begin aynchronous accept, to insure failure overcome // AddRef(); ExSetTimer(&m_retryAcceptTimer, CTimeDuration(0)); } void CMulticastListener::IssueAccept( void ) /*++ Routine Description: Issue async accept request. Arguments: None. Returned Value: None. --*/ { ASSERT(m_ReceiveSocket == INVALID_SOCKET); DWORD flags = WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF | WSA_FLAG_OVERLAPPED; *&m_ReceiveSocket = WSASocket(AF_INET, SOCK_RDM, IPPROTO_RM, NULL, 0, flags); if (m_ReceiveSocket == INVALID_SOCKET) { DWORD rc = WSAGetLastError(); TrERROR(NETWORKING, "Failed to create PGM receive socket, error %d", rc); throw bad_win32_error(rc); } // // Get the CS so no one will close the listner while we try to accept // CS lock(m_cs); if(m_ListenSocket == INVALID_SOCKET) { m_ReceiveSocket.free(); return; } // // Increment ref count on this object. // The completion routines decrement the ref count. // R<CMulticastListener> ref = SafeAddRef(this); DWORD BytesReceived; BOOL f = AcceptEx( m_ListenSocket, m_ReceiveSocket, m_AcceptExBuffer, 0, 40, 40, &BytesReceived, &m_ov ); DWORD rc = WSAGetLastError(); if (!f && rc != ERROR_IO_PENDING) { TrERROR(NETWORKING, "Failed to issue AcceptEx on socket, error %d", rc); m_ReceiveSocket.free(); throw bad_win32_error(rc); } // // All went well. Completion routines will complete the work. // ref.detach(); } void CMulticastListener::AcceptSucceeded( void ) { // // These pointers don't leak since they are assigned by GetAcceptExSockaddrs to point into the // buffer m_AcceptExBuffer // SOCKADDR* localSockAddr; SOCKADDR* remoteSockAddr; int localSockaddrLength, remoteSockaddrLength; GetAcceptExSockaddrs( m_AcceptExBuffer, 0, 40, 40, &localSockAddr, &localSockaddrLength, &remoteSockAddr, &remoteSockaddrLength ); WCHAR storeRemoteAddr[256] = L""; LPSTR remoteAddr = inet_ntoa((reinterpret_cast<sockaddr_in*>(remoteSockAddr))->sin_addr); if (remoteAddr != NULL) { HRESULT hr = StringCchPrintf(storeRemoteAddr, TABLE_SIZE(storeRemoteAddr), L"%hs", remoteAddr); ASSERT(("Address buffer is too small", SUCCEEDED(hr))); UNREFERENCED_PARAMETER(hr); } // // Get the receive socket to local variable. // The member receive socket is detached so that we can reissue async accept. // CSocketHandle socket(m_ReceiveSocket.detach()); try { IssueAccept(); } catch (const bad_win32_error& ) { AddRef(); ExSetTimer(&m_retryAcceptTimer, s_AcceptRetryTimeout); } // // Pass responsibility on Auto socket to the receiver. Don't call detach. // CreateReceiver(socket, storeRemoteAddr); } void WINAPI CMulticastListener::AcceptSucceeded( EXOVERLAPPED* pov ) { ASSERT(SUCCEEDED(pov->GetStatus())); R<CMulticastListener> pms = CONTAINING_RECORD(pov, CMulticastListener, m_ov); pms->AcceptSucceeded(); } void CMulticastListener::AcceptFailed( void ) { MsmpDumpPGMReceiverStats(m_ListenSocket); // // Failed to issue an accept. secudel accept retry // AddRef(); ExSetTimer(&m_retryAcceptTimer, s_AcceptRetryTimeout); } void WINAPI CMulticastListener::AcceptFailed( EXOVERLAPPED* pov ) { ASSERT(FAILED(pov->GetStatus())); TrERROR(NETWORKING, "Accept failed, error %d", pov->GetStatus()); R<CMulticastListener> pms = CONTAINING_RECORD(pov, CMulticastListener, m_ov); pms->AcceptFailed(); } void CMulticastListener::RetryAccept( void ) { // // Check listner validity. If the listener already closed, don't try to issue a new accept. // if (m_ListenSocket == INVALID_SOCKET) return; m_ReceiveSocket.free(); try { IssueAccept(); } catch (const bad_win32_error& ) { AddRef(); ExSetTimer(&m_retryAcceptTimer, s_AcceptRetryTimeout); } } void WINAPI CMulticastListener::TimeToRetryAccept( CTimer* pTimer ) { R<CMulticastListener> pms = CONTAINING_RECORD(pTimer, CMulticastListener, m_retryAcceptTimer); pms->RetryAccept(); } void CMulticastListener::CleanupUnusedReceiver( void ) /*++ Routine Description: Cleanup unused receivers. The routine scans the receivers and checkes if it was used in the last cleanup interval. If the receiver was in ideal state, the routine shutdown the receiver and remove it from the active receiver list Arguments: None. Returned Value: None. Note: The routine rearm the cleanup timer if still has an active receivers. --*/ { // // Get the critical secction, so no other thread will chnage the receiver list // while the routine scans the list // CS lock(m_cs); // // Check listner validity. If the listener already closed exit // if (m_ListenSocket == INVALID_SOCKET) return; // // Scan the receiver list // ReceiversList::iterator it = m_Receivers.begin(); while(it != m_Receivers.end()) { R<CMulticastReceiver> pReceiver = *it; if(pReceiver->IsUsed()) { // // Mark the receiver as unused. // pReceiver->SetIsUsed(false); ++it; continue; } // // The receiver isn't used. Shut it down and remove the receiver from the list // TrTRACE(NETWORKING, "Shutdown unused receiver. pr = 0x%p", pReceiver.get()); pReceiver->Shutdown(); it = m_Receivers.erase(it); } // // If not exist an active receiver, clear the flag that indicates if // cleanup was scheduled or not // if (m_Receivers.empty()) { InterlockedExchange(&m_fCleanupScheduled, FALSE); return; } // // still has an active receivers, rearm the cleanup timer // AddRef(); ExSetTimer(&m_cleanupTimer, s_ReceiverCleanupTimeout); } void WINAPI CMulticastListener::TimeToCleanupUnusedReceiever( CTimer* pTimer ) { R<CMulticastListener> pms = CONTAINING_RECORD(pTimer, CMulticastListener, m_cleanupTimer); TrTRACE(NETWORKING, "Call cleanup unused receiever on listener 0x%p", pms.get()); pms->CleanupUnusedReceiver(); } void CMulticastListener::CreateReceiver( CSocketHandle& socket, LPCWSTR remoteAddr ) /*++ Routine Description: Create a new receiver object and start receive. Arguments: None. Returned Value: None. --*/ { R<CMulticastReceiver> pReceiver = new CMulticastReceiver(socket, m_MulticastId, remoteAddr); try { CS lock(m_cs); m_Receivers.push_back(pReceiver); } catch (const bad_alloc&) { TrERROR(NETWORKING, "Failed to insert to list of receivers"); pReceiver->Shutdown(); throw; } if (InterlockedExchange(&m_fCleanupScheduled, TRUE) == FALSE) { AddRef(); ExSetTimer(&m_cleanupTimer, s_ReceiverCleanupTimeout); } } void CMulticastListener::Close( void ) throw() /*++ Routine Description: Stop listen on the multicast group address. Close all receivers. Arguments: None. Returned Value: None. --*/ { CS lock(m_cs); if (m_ListenSocket == INVALID_SOCKET) { // // The receiver already closed // ASSERT(m_Receivers.empty()); return; } // // Try to cancel the accept retry. If succeeded decrement the reference count // if (ExCancelTimer(&m_retryAcceptTimer)) { Release(); } // // Try to cancel cleanup timer // if (ExCancelTimer(&m_cleanupTimer)) { Release(); } MsmpDumpPGMReceiverStats(m_ListenSocket); // // Stop listening // closesocket(m_ListenSocket.detach()); // // Close receivers // ReceiversList::iterator it; for (it = m_Receivers.begin(); it != m_Receivers.end(); ) { (*it)->Shutdown(); it = m_Receivers.erase(it); } } void MsmpDumpPGMReceiverStats(const SOCKET s) /*++ Routine Description: Get statistic information from the PGM sockets. Arguments: socket - PGM socket. Returned Value: None. --*/ { if(!WPP_LEVEL_COMPID_ENABLED(rsTrace, NETWORKING)) { return; } RM_RECEIVER_STATS RmReceiverStats; INT BufferLength = sizeof(RM_RECEIVER_STATS); memset(&RmReceiverStats,0,BufferLength); ULONG ret = getsockopt( s, IPPROTO_RM, RM_RECEIVER_STATISTICS,(char *)&RmReceiverStats,&BufferLength); if ( ERROR_SUCCESS != ret ) { TrERROR(NETWORKING, "GetReceiverStats: Failed to retrieve receiver stats! error = %d",WSAGetLastError()); return; } TrTRACE(NETWORKING,"NumODataPacketsReceived = <%I64d>",RmReceiverStats.NumODataPacketsReceived); TrTRACE(NETWORKING,"NumRDataPacketsReceived = <%I64d>",RmReceiverStats.NumRDataPacketsReceived); TrTRACE(NETWORKING,"NumDuplicateDataPackets = <%I64d>",RmReceiverStats.NumDuplicateDataPackets); TrTRACE(NETWORKING,"DataBytesReceived = <%I64d>",RmReceiverStats.DataBytesReceived); TrTRACE(NETWORKING,"TotalBytesReceived = <%I64d>",RmReceiverStats.TotalBytesReceived); TrTRACE(NETWORKING,"RateKBitsPerSecOverall = <%I64d>",RmReceiverStats.RateKBitsPerSecOverall); TrTRACE(NETWORKING,"RateKBitsPerSecLast = <%I64d>",RmReceiverStats.RateKBitsPerSecLast); TrTRACE(NETWORKING,"TrailingEdgeSeqId = <%I64d>",RmReceiverStats.TrailingEdgeSeqId); TrTRACE(NETWORKING,"LeadingEdgeSeqId = <%I64d>",RmReceiverStats.LeadingEdgeSeqId); TrTRACE(NETWORKING,"AverageSequencesInWindow= <%I64d>",RmReceiverStats.AverageSequencesInWindow); TrTRACE(NETWORKING,"MinSequencesInWindow = <%I64d>",RmReceiverStats.MinSequencesInWindow); TrTRACE(NETWORKING,"MaxSequencesInWindow = <%I64d>",RmReceiverStats.MaxSequencesInWindow); TrTRACE(NETWORKING,"FirstNakSequenceNumber = <%I64d>",RmReceiverStats.FirstNakSequenceNumber); TrTRACE(NETWORKING,"NumPendingNaks = <%I64d>",RmReceiverStats.NumPendingNaks); TrTRACE(NETWORKING,"NumOutstandingNaks = <%I64d>",RmReceiverStats.NumOutstandingNaks); TrTRACE(NETWORKING,"NumDataPacketsBuffered = <%I64d>",RmReceiverStats.NumDataPacketsBuffered); TrTRACE(NETWORKING,"TotalSelectiveNaksSent = <%I64d>",RmReceiverStats.TotalSelectiveNaksSent); TrTRACE(NETWORKING,"TotalParityNaksSent = <%I64d>",RmReceiverStats.TotalParityNaksSent); }
[ "blindtiger@foxmail.com" ]
blindtiger@foxmail.com
85029e713f56770002d55609dc614840eca2ff03
3f5fbaeaaf62da1e4f9bfb7b349cf7a3a6e4efcb
/LeetCode Submissions/Remove Nth Node From End of List.cpp
ec49ed61c7718837ddfa28ba2eaf17b0e268f149
[]
no_license
dipesh-m/Data-Structures-and-Algorithms
f91cd3e3a71c46dc6ffe22dac6be22d454d01ec3
f3dfd6f1e0f9c0124d589ecdb60e7e0e26eb28fc
refs/heads/master
2023-05-26T05:14:19.258994
2021-05-26T16:41:11
2021-05-26T16:41:11
276,396,488
1
1
null
null
null
null
UTF-8
C++
false
false
897
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(head==NULL) return NULL; ListNode* first=head; ListNode* second=head; for(int i=0; i<n; i++) { second=second->next; } if(second==NULL) { head=head->next; return head; } while(second->next!=NULL) { first=first->next; second=second->next; } ListNode* temp=first->next; first->next=first->next->next; delete temp; return head; } };
[ "62656237+dipesh-m@users.noreply.github.com" ]
62656237+dipesh-m@users.noreply.github.com
a8584bc19678d8c0290aa9d3ee3bf423afdc5a7d
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/StorageSettingsGeneratedFromCapabilities/UNIX_StorageSettingsGeneratedFromCapabilities_ZOS.hxx
cfc73ef3273c54a9d944b007b71cea48fc7b06a3
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,863
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_ZOS #ifndef __UNIX_STORAGESETTINGSGENERATEDFROMCAPABILITIES_PRIVATE_H #define __UNIX_STORAGESETTINGSGENERATEDFROMCAPABILITIES_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
9d447fc2dccbd169dfc51181a14efbd5fe589ec7
63ead0e6eeed62fbe6b4e88680c6a351610abfda
/Dev/Cpp/Effekseer/Effekseer/Effekseer.Socket.cpp
ea5d1f6e98632874f9fe96e44a3c519b0e70bd42
[ "IJG", "MS-PL", "GD", "MIT" ]
permissive
AndrewFM/Effekseer
216aff21568814bad5abe95fd9870b78ed89ce60
77c5521ae288adbb43e071e368c6e2eb418f39da
refs/heads/master
2020-04-11T04:42:40.383611
2017-03-26T02:00:40
2017-03-26T02:00:40
62,411,370
0
0
null
2016-07-01T18:10:06
2016-07-01T18:10:06
null
UTF-8
C++
false
false
2,668
cpp
 //---------------------------------------------------------------------------------- // Include //---------------------------------------------------------------------------------- #ifdef _WIN32 #include <winsock2.h> #pragma comment( lib, "ws2_32.lib" ) #else #include <sys/types.h> #include <sys/socket.h> #endif #include "Effekseer.Socket.h" //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- namespace Effekseer { //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Socket::Initialize() { #ifdef _WIN32 /* Winsock初期化 */ WSADATA m_WsaData; ::WSAStartup( MAKEWORD(2,0), &m_WsaData ); #endif } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Socket::Finalize() { #ifdef _WIN32 /* Winsock参照カウンタ減少+破棄 */ WSACleanup(); #endif } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- EfkSocket Socket::GenSocket() { return ::socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Socket::Close( EfkSocket s ) { #ifdef _WIN32 ::closesocket( s ); #else ::close( s ); #endif } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Socket::Shutsown( EfkSocket s ) { #ifdef _WIN32 ::shutdown( s, SD_BOTH ); #else ::shutdown( s, SHUT_RDWR ); #endif } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- bool Socket::Listen( EfkSocket s, int32_t backlog ) { #ifdef _WIN32 return ::listen( s, backlog ) != SocketError; #else return listen( s, backlog ) >= 0; #endif } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- } //---------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------
[ "effekseer@gmail.com" ]
effekseer@gmail.com
ffa13ed506a3c2f210b94edc8df02fb7667d7c79
34e8f4016f29d8d15caa1d3e8ad9bc4451d5dcd2
/lab2/hw2-starterCode/hw2-starterCode/hw2.cpp
fb74140542500ffd452357053cc1474891f60b83
[]
no_license
liuzijing2014/Computer-Graphics
5791b32c84d98796a611c8a105d68146158d4658
780137a82f16367b66a33cad34c9f211b4e71993
refs/heads/master
2021-01-13T15:31:53.797168
2017-01-12T21:26:24
2017-01-12T21:26:24
72,472,464
1
0
null
null
null
null
UTF-8
C++
false
false
40,321
cpp
/* CSCI 420 Computer Graphics, USC Assignment 2: Roller Coaster C++ starter code Student username: Zijing Liu */ #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <math.h> #include <limits> #include "openGLHeader.h" #include "glutHeader.h" #include "imageIO.h" #include "openGLMatrix.h" #include "basicPipelineProgram.h" #include <glm/glm.hpp> #define DEBUG true #ifdef WIN #ifdef _DEBUG #pragma comment(lib, "glew32d.lib") #else #pragma comment(lib, "glew32.lib") #endif #endif #ifdef WIN32 char shaderBasePath[1024] = SHADER_BASE_PATH; #else char shaderBasePath[1024] = "../openGLHelper-starterCode"; #endif using namespace std; // Represent a vertex typedef struct { float XYZ[3]; float RGBA[4]; float TEX[2]; } Vertex; // Data structure that stores all information that camera needs // to simulate spline movement. typedef struct { glm::vec3 position; glm::vec3 tangent; glm::vec3 normal; glm::vec3 binormal; } AnimationPoint; // represents one control point along the spline struct Point { double x; double y; double z; }; // spline struct // contains how many control points the spline has, and an array of control points struct Spline { int numControlPoints; Point *points; }; int mousePos[2]; // x,y coordinate of the mouse position int leftMouseButton = 0; // 1 if pressed, 0 if not int middleMouseButton = 0; // 1 if pressed, 0 if not int rightMouseButton = 0; // 1 if pressed, 0 if not typedef enum { ROTATE, TRANSLATE, SCALE } CONTROL_STATE; CONTROL_STATE controlState = ROTATE; // state of the world float landRotate[3] = {0.0f, 0.0f, 0.0f}; float landTranslate[3] = {0.0f, 0.0f, 0.0f}; float landScale[3] = {1.0f, 1.0f, 1.0f}; float cameraForward[3] = {0.0f, 0.0f, 0.0f}; float cameraUp[3] = {0.0f, 1.0f, 0.0f}; int windowWidth = 1280; int windowHeight = 720; char windowTitle[512] = "CSCI 420 homework I"; // Screenshot flag bool screenshot = false; int screenshotCount = 0; // Texture handler const char *mainImageFilename = "./textures/empty.jpg"; GLuint mTextureHandler; const char *gdImageFilename = "./textures/sand.jpg"; GLuint gdTextureHandler; const char *cbImageFilename = "./textures/wood.jpg"; GLuint cbTextureHandler; const GLchar *faces[6] = { "./textures/right.jpg", "./textures/left.jpg", "./textures/bottom.jpg", "./textures/top.jpg", "./textures/back.jpg", "./textures/front.jpg"}; GLuint skyboxHandler; // Vertiex array for the rails vector<Vertex> verticesVector; // Index array for the rails vector<GLuint> indicesVector; // Vertex array for the cross bars vector<Vertex> crossbarVertices; // Index array for the cross bars vector<GLuint> crossbarIndices; // AnimationPoint vector vector<AnimationPoint> aniArray; // Index counter for aniArray; GLint aniCounter = 0; // Ground vertice Vertex groundVertices[4] = { {{-64.0, 0.0, -64.0}, {1.0, 1.0, 1.0, 1.0}, {0.0, 0.0}}, {{-64.0, 0.0, 64.0}, {1.0, 1.0, 1.0, 1.0}, {0.0, 32.0}}, {{64.0, 0.0, 64.0}, {1.0, 1.0, 1.0, 1.0}, {32.0, 32.0}}, {{64.0, 0.0, -64.0}, {1.0, 1.0, 1.0, 1.0}, {32.0, 0.0}}, }; // Ground indices GLuint groundIndices[6] = { 0, 1, 2, 2, 3, 0}; // Skybox vertice Vertex skyVertices[8] = { {{-128.0, 128.0, 128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{-128.0, -128.0, 128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{128.0, -128.0, 128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{128.0, 128.0, 128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{128.0, 128.0, -128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{-128.0, 128.0, -128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{-128.0, -128.0, -128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, {{128.0, -128.0, -128.0}, {1.0, 1.0, 1.0, -1.0}, {0.0, 0.0}}, }; // Skybox indices GLuint skyboxIndices[36] = { 5, 0, 3, 3, 4, 5, 0, 1, 2, 2, 3, 0, 6, 1, 2, 2, 7, 6, 5, 6, 1, 1, 0, 5, 5, 6, 7, 4, 7, 2, 7, 4, 5, 2, 3, 4, }; GLuint IndexRail; // rail index buffer handler GLuint IndexGd; // ground index buffer handler GLuint IndexSky; // sky index buffer handler GLuint IndexCb; // cross bar index buffer handler GLuint programId; GLuint VaoId; GLuint VaoGd; // ground VAO GLuint VaoSky; // skybox VAO GLuint VaoCb; // cross bar VAO GLuint BufferId; GLuint BufferGd; // ground buffer GLuint BufferSky; // skybox buffer GLuint BufferCb; // cross bar buffer float sFactor = 1.0f; float splineScale = 1.5f; float railScale = 0.1f; // Helper lib pointers BasicPipelineProgram *pipelineProgram; OpenGLMatrix *openGLMatrix; // the spline array Spline *splines; // total number of splines int numSplines; // Base Matrix glm::mat4x4 basisMatrix = glm::mat4x4(-0.5, 1.0, -0.5, 0.0, 1.5, -2.5, 0.0, 1.0, -1.5, 2.0, 0.5, 0.0, 0.5, -0.5, 0.0, 0.0); // Max distance float maxDistance = 0.05f; // lowest/highest spline altitude float lowest = FLT_MAX; float highest = -FLT_MAX; // physics related variables float vi = 1.25f; float a = 0.0f; float t = 0.1f; glm::vec3 g = glm::vec3(0.0f, -0.075f, 0.0f); // pause control flag bool pause = false; // Functions decleared void initBuffer(); void initVertex(); void initPerspective(int, int); void setupMatrex(); void subDivideSegment(float, float, glm::mat4x4&); GLuint loadSkybox(const GLchar); void addAnimationPoint(float, glm::vec3&, glm::mat4x4&); void addRailVertices(glm::vec3&, glm::vec3&, glm::vec3&); void addRailIndices(GLuint); void addCrossbarVertices(glm::vec3&, glm::vec3&, glm::vec3&, glm::vec3&); void updateGroundHeight(); // write a screenshot to the specified filename void saveScreenshot(const char *filename) { unsigned char *screenshotData = new unsigned char[windowWidth * windowHeight * 4]; glReadPixels(0, 0, windowWidth, windowHeight, GL_RGBA, GL_UNSIGNED_BYTE, screenshotData); ImageIO screenshotImg(windowWidth, windowHeight, 4, screenshotData); if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK) cout << "File " << filename << " saved successfully." << endl; else cout << "Failed to save file " << filename << '.' << endl; delete[] screenshotData; } void displayFunc() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Draw skybox pipelineProgram->Bind(); setupMatrex(); glDepthMask(GL_FALSE); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_CUBE_MAP, skyboxHandler); glBindVertexArray(VaoSky); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, (GLvoid *)0); glBindVertexArray(0); glDepthMask(GL_TRUE); // Draw rails glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, mTextureHandler); glBindVertexArray(VaoId); glDrawElements(GL_TRIANGLES, indicesVector.size(), GL_UNSIGNED_INT, (GLvoid *)0); glBindVertexArray(0); // Draw cross bar glBindTexture(GL_TEXTURE_2D, cbTextureHandler); glBindVertexArray(VaoCb); glDrawElements(GL_TRIANGLES, crossbarIndices.size(), GL_UNSIGNED_INT, (GLvoid *)0); glBindVertexArray(0); /* Render Ground Begin */ // glBindTexture(GL_TEXTURE_2D, gdTextureHandler); // glBindVertexArray(VaoGd); // glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (GLvoid*)0); // glBindVertexArray(0); /* Render Ground End */ glFlush(); glutSwapBuffers(); } // Setup modelview and upload the matrix to GPU void setupMatrex() { glm::vec3 &position = aniArray[aniCounter].position; glm::vec3 &tangent = aniArray[aniCounter].tangent; glm::vec3 &normal = aniArray[aniCounter].normal; // determine the real speed if(aniCounter + 2 < aniArray.size() && !pause) { a = glm::dot(g, tangent); a = a < -1.5f ? -1.5f : a; a = a > 1.5f ? 1.5f : a; float vf = vi + a * t; vf = vf <= 0.5f ? 0.5f : vf; vf = vf > 2.0f ? 2.0f : vf; float p = (vi + vf) * t / 2.0f; aniCounter += floor(p / maxDistance); vi = vf; } //change mode to modelview openGLMatrix->SetMatrixMode(OpenGLMatrix::ModelView); openGLMatrix->LoadIdentity(); openGLMatrix->LookAt(position, position + tangent, normal); //openGLMatrix->LookAt(0.0f, 2.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); openGLMatrix->Rotate(landRotate[0], 1.0, 0.0, 0.0); openGLMatrix->Rotate(landRotate[1], 0.0, 1.0, 0.0); openGLMatrix->Rotate(landRotate[2], 0.0, 0.0, 1.0); openGLMatrix->Translate(landTranslate[0], landTranslate[1], landTranslate[2]); openGLMatrix->Scale(landScale[0] * sFactor, landScale[1] * sFactor, landScale[2] * sFactor); // Setup modelview matrix float m[16]; openGLMatrix->GetMatrix(m); pipelineProgram->SetModelViewMatrix(m); } void idleFunc() { // do some stuff... // for example, here, you can save the screenshots to disk (to make the animation) if (screenshot) { std::string fname = "frame" + std::to_string(screenshotCount++) + ".jpg"; saveScreenshot(fname.c_str()); } // make the screen update glutPostRedisplay(); } void reshapeFunc(int w, int h) { glViewport(0, 0, w, h); // setup perspective matrix... initPerspective(w, h); } void initPerspective(int w, int h) { openGLMatrix->SetMatrixMode(OpenGLMatrix::Projection); openGLMatrix->LoadIdentity(); float aspect = (float)w / (float)h; openGLMatrix->Perspective(60.0f, aspect, 0.01, 1000.0); // Setup projection matrix float p[16]; openGLMatrix->GetMatrix(p); pipelineProgram->SetProjectionMatrix(p); openGLMatrix->SetMatrixMode(OpenGLMatrix::ModelView); // Reset aniCounter aniCounter = 0; } void mouseMotionDragFunc(int x, int y) { // mouse has moved and one of the mouse buttons is pressed (dragging) // the change in mouse position since the last invocation of this function int mousePosDelta[2] = {x - mousePos[0], y - mousePos[1]}; switch (controlState) { // translate the landscape case TRANSLATE: if (leftMouseButton) { // control x,y translation via the left mouse button landTranslate[0] += mousePosDelta[0] * 0.01f; landTranslate[1] -= mousePosDelta[1] * 0.01f; } if (middleMouseButton) { // control z translation via the middle mouse button landTranslate[2] += mousePosDelta[1] * 0.01f; } break; // rotate the landscape case ROTATE: if (leftMouseButton) { // control x,y rotation via the left mouse button landRotate[0] += mousePosDelta[1]; landRotate[1] += mousePosDelta[0]; } if (middleMouseButton) { // control z rotation via the middle mouse button landRotate[2] += mousePosDelta[1]; } break; // scale the landscape case SCALE: if (leftMouseButton) { // control x,y scaling via the left mouse button landScale[0] *= 1.0f + mousePosDelta[0] * 0.01f; landScale[1] *= 1.0f - mousePosDelta[1] * 0.01f; } if (middleMouseButton) { // control z scaling via the middle mouse button landScale[2] *= 1.0f - mousePosDelta[1] * 0.01f; } break; } // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void mouseMotionFunc(int x, int y) { // mouse has moved // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void mouseButtonFunc(int button, int state, int x, int y) { // a mouse button has has been pressed or depressed // keep track of the mouse button state, in leftMouseButton, middleMouseButton, rightMouseButton variables switch (button) { case GLUT_LEFT_BUTTON: leftMouseButton = (state == GLUT_DOWN); break; case GLUT_MIDDLE_BUTTON: middleMouseButton = (state == GLUT_DOWN); break; case GLUT_RIGHT_BUTTON: rightMouseButton = (state == GLUT_DOWN); break; } // keep track of whether CTRL and SHIFT keys are pressed switch (glutGetModifiers()) { case GLUT_ACTIVE_CTRL: controlState = TRANSLATE; break; case GLUT_ACTIVE_SHIFT: controlState = SCALE; break; // if CTRL and SHIFT are not pressed, we are in rotate mode default: controlState = ROTATE; break; } // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void keyboardFunc(unsigned char key, int x, int y) { switch (key) { case 27: // ESC key exit(0); // exit the program break; case ' ': break; case 'x': // take a screenshot saveScreenshot("screenshot.jpg"); break; case 'r': aniCounter = 0; vi = 1.25f; a = 0.0f; t = 0.1f; case 's': pause = pause ? false : true; } } // Initilize the vertices void initVertex() { for (int i = 0; i < numSplines; i++) { int splineLength = splines[i].numControlPoints; Spline &segment = splines[i]; for (int j = 0; j < splineLength - 3; j++) { glm::mat4x4 controlMatrix = glm::mat4x4(segment.points[j].x, segment.points[j + 1].x, segment.points[j + 2].x, segment.points[j + 3].x, segment.points[j].y, segment.points[j + 1].y, segment.points[j + 2].y, segment.points[j + 3].y, segment.points[j].z, segment.points[j + 1].z, segment.points[j + 2].z, segment.points[j + 3].z, 0.0, 0.0, 0.0, 0.0); glm::mat4x4 combinedMatrix = basisMatrix * controlMatrix; subDivideSegment(0.0, 1.0, combinedMatrix); } } } /* * Based on u and given combined matrix of control matrix and basis matrix, * calculate the current AnimationPoint at u. */ void addAnimationPoint(float u, glm::vec3& v, glm::mat4x4 &matrix) { static bool firstPoint = true; // The first time calling this function, we need to generate the first point // and its associated tangent, normal, and binormal. if(firstPoint) { #ifdef DEBUG printf("Generate the first point\n"); #endif AnimationPoint p; p.tangent = glm::normalize(glm::vec3(glm::vec4(0.0, 0.0, 1, 0) * matrix)); p.normal = glm::normalize(glm::cross(p.tangent, glm::vec3(1.0, 0.0, 0.0))); p.binormal = glm::normalize(glm::cross(p.tangent, p.normal)); p.position = glm::vec3(glm::vec4(0.0, 0.0, 0.0, 1.0) * matrix) * splineScale; aniArray.push_back(p); firstPoint = false; } #ifdef DEBUG //printf("Added Animation Point at U = %f\n", u); #endif AnimationPoint p; // Calculate the Tangent t(u) = p'(u) = [3u^2 2u 1 0] M C p.tangent = glm::normalize(glm::vec3(glm::vec4(3 * pow(u, 2.0), 2 * u, 1, 0) * matrix)); // Calculate normal, N = cross(T, B) p.normal = glm::normalize(glm::cross(aniArray[aniCounter].binormal, p.tangent)); // Now calculate binormal by crossing tangent and normal p.binormal = glm::normalize(glm::cross(p.tangent, p.normal)); // Set position p.position = v; aniArray.push_back(p); aniCounter++; } // Subdivide the spline segment to generate vertices void subDivideSegment(float u0, float u1, glm::mat4x4 &matrix) { static bool firstPoint = true; static GLuint drawCrossbar = 0; static GLuint crossbarDis = 35; float uMid = (u0 + u1) / 2.0; glm::vec3 v0 = glm::vec3(glm::vec4(pow(u0, 3.0), pow(u0, 2.0), u0, 1.0) * matrix); glm::vec3 v1 = glm::vec3(glm::vec4(pow(u1, 3.0), pow(u1, 2.0), u1, 1.0) * matrix); if (glm::distance(v1, v0) > maxDistance) { subDivideSegment(u0, uMid, matrix); subDivideSegment(uMid, u1, matrix); } else { v1 *= splineScale; // update lowest/highest if(v1.z < lowest) { lowest = v1.z; } else if(v1.z > highest) { highest = v1.z; } addAnimationPoint(u1, v1, matrix); if(firstPoint) { #ifdef DEBUG printf("first point to add position, u = %f\n", u0); #endif v0 *= splineScale; if(v0.z < lowest) { lowest = v0.z; } else if(v0.z > highest) { highest = v0.z; } addRailVertices(v0, aniArray[0].normal, aniArray[0].binormal); firstPoint = false; } GLuint index0 = verticesVector.size(); addRailVertices(v1, aniArray[aniCounter].normal, aniArray[aniCounter].binormal); addRailIndices(index0); // Check if we need to add a cross bar if(drawCrossbar >= crossbarDis) { addCrossbarVertices(v1, aniArray[aniCounter].normal, aniArray[aniCounter].binormal, aniArray[aniCounter].tangent); drawCrossbar = 0; } else { drawCrossbar++; } } } void addCrossbarVertices(glm::vec3 &position, glm::vec3 &normal, glm::vec3 &binormal, glm::vec3& tangent) { glm::vec3 curPos; GLuint index0 = crossbarVertices.size(); Vertex v; v.RGBA[0] = v.RGBA[1] = v.RGBA[2] = v.RGBA[3] = 1.0; // top four vertices curPos = position - 3 * railScale * binormal - 2.0f * railScale * normal - 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 0.0f; v.TEX[1] = 0.0f; crossbarVertices.push_back(v); curPos = position - 3 * railScale * binormal - 2.0f * railScale * normal + 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 0.0f; v.TEX[1] = 1.0f; crossbarVertices.push_back(v); curPos = position + 3 * railScale * binormal - 2.0f * railScale * normal + 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 1.0f; v.TEX[1] = 1.0f; crossbarVertices.push_back(v); curPos = position + 3 * railScale * binormal - 2.0f * railScale * normal - 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 1.0f; v.TEX[1] = 0.0f; crossbarVertices.push_back(v); // bottom four vertices curPos = position - 3 * railScale * binormal - 2.5f * railScale * normal - 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 1.0f; v.TEX[1] = 1.0f; crossbarVertices.push_back(v); curPos = position - 3 * railScale * binormal - 2.5f * railScale * normal + 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 1.0f; v.TEX[1] = 0.0f; crossbarVertices.push_back(v); curPos = position + 3 * railScale * binormal - 2.5f * railScale * normal + 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 0.0f; v.TEX[1] = 0.0f; crossbarVertices.push_back(v); curPos = position + 3 * railScale * binormal - 2.5f * railScale * normal - 0.75f * railScale * tangent; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; v.TEX[0] = 0.0f; v.TEX[1] = 1.0f; crossbarVertices.push_back(v); // Add indices crossbarIndices.push_back(index0); crossbarIndices.push_back(index0+1); crossbarIndices.push_back(index0+5); crossbarIndices.push_back(index0+5); crossbarIndices.push_back(index0+4); crossbarIndices.push_back(index0); crossbarIndices.push_back(index0); crossbarIndices.push_back(index0+1); crossbarIndices.push_back(index0+2); crossbarIndices.push_back(index0+2); crossbarIndices.push_back(index0+3); crossbarIndices.push_back(index0); crossbarIndices.push_back(index0+3); crossbarIndices.push_back(index0+2); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+7); crossbarIndices.push_back(index0+3); crossbarIndices.push_back(index0+4); crossbarIndices.push_back(index0+5); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+7); crossbarIndices.push_back(index0+4); crossbarIndices.push_back(index0); crossbarIndices.push_back(index0+3); crossbarIndices.push_back(index0+7); crossbarIndices.push_back(index0+7); crossbarIndices.push_back(index0+4); crossbarIndices.push_back(index0); crossbarIndices.push_back(index0+1); crossbarIndices.push_back(index0+2); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+6); crossbarIndices.push_back(index0+5); crossbarIndices.push_back(index0+1); } /* * Calculate the indices for triangles */ void addRailIndices(GLuint index0) { // Add indices // leftmost face indicesVector.push_back(index0 - 8); indicesVector.push_back(index0); indicesVector.push_back(index0 + 4); indicesVector.push_back(index0 + 4); indicesVector.push_back(index0 - 4); indicesVector.push_back(index0 - 8); // left top face indicesVector.push_back(index0 - 8); indicesVector.push_back(index0); indicesVector.push_back(index0 + 1); indicesVector.push_back(index0 + 1); indicesVector.push_back(index0 - 7); indicesVector.push_back(index0 - 8); // 2nd leftmost face indicesVector.push_back(index0 - 7); indicesVector.push_back(index0 + 1); indicesVector.push_back(index0 + 5); indicesVector.push_back(index0 + 5); indicesVector.push_back(index0 - 3); indicesVector.push_back(index0 - 7); // left bottom face indicesVector.push_back(index0 - 4); indicesVector.push_back(index0 + 4); indicesVector.push_back(index0 + 5); indicesVector.push_back(index0 + 5); indicesVector.push_back(index0 - 3); indicesVector.push_back(index0 - 4); // 2nd rightmost face indicesVector.push_back(index0 - 6); indicesVector.push_back(index0 + 2); indicesVector.push_back(index0 + 6); indicesVector.push_back(index0 + 6); indicesVector.push_back(index0 - 2); indicesVector.push_back(index0 - 6); // right top face indicesVector.push_back(index0 - 6); indicesVector.push_back(index0 + 2); indicesVector.push_back(index0 + 3); indicesVector.push_back(index0 + 3); indicesVector.push_back(index0 - 5); indicesVector.push_back(index0 - 6); // rightmost face indicesVector.push_back(index0 - 5); indicesVector.push_back(index0 + 3); indicesVector.push_back(index0 + 7); indicesVector.push_back(index0 + 7); indicesVector.push_back(index0 - 1); indicesVector.push_back(index0 - 5); // right bottom face indicesVector.push_back(index0 - 2); indicesVector.push_back(index0 + 6); indicesVector.push_back(index0 + 7); indicesVector.push_back(index0 + 7); indicesVector.push_back(index0 - 1); indicesVector.push_back(index0 - 2); } /* * Given a point on the spline, generate 8 vertices around * this point to form double rail. * top left 2nd top left 2nd top right top right * bottom left 2nd bottom left 2nd bottom right bottom right */ void addRailVertices(glm::vec3 &position, glm::vec3 &normal, glm::vec3 &binormal) { glm::vec3 curPos; Vertex v; v.RGBA[0] = v.RGBA[1] = v.RGBA[2] = v.RGBA[3] = 1.0; v.TEX[0] = 0.1f; v.TEX[1] = 0.8f; // top left curPos = position - 2 * railScale * binormal - 1.5f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // 2nd top left curPos = position - 1 * railScale * binormal - 1.5f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // 2nd top right curPos = position + 1 * railScale * binormal - 1.5f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // top right curPos = position + 2 * railScale * binormal - 1.5f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // bottom left curPos = position - 2 * railScale * binormal - 2.0f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // 2nd bottom left curPos = position - 1 * railScale * binormal - 2.0f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // 2nd bottom right curPos = position + 1 * railScale * binormal - 2.0f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); // bottom right curPos = position + 2 * railScale * binormal - 2.0f * railScale * normal; v.XYZ[0] = curPos.x; v.XYZ[1] = curPos.y; v.XYZ[2] = curPos.z; verticesVector.push_back(v); } void initBuffer() { const size_t BufferSize = sizeof(Vertex) * verticesVector.size(); const size_t VertexSize = sizeof(verticesVector[0]); const size_t RgbOffset = sizeof(verticesVector[0].XYZ); const size_t TexOffset = sizeof(verticesVector[0].XYZ) + sizeof(verticesVector[0].RGBA); GLuint pos = glGetAttribLocation(programId, "position"); GLuint col = glGetAttribLocation(programId, "color"); GLuint tex = glGetAttribLocation(programId, "texcoord"); // Generate rail VBO and VAO glGenVertexArrays(1, &VaoId); glBindVertexArray(VaoId); glGenBuffers(1, &BufferId); glBindBuffer(GL_ARRAY_BUFFER, BufferId); glBufferData(GL_ARRAY_BUFFER, BufferSize, verticesVector.data(), GL_STATIC_DRAW); glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VertexSize, 0); glEnableVertexAttribArray(pos); glVertexAttribPointer(col, 4, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)RgbOffset); glEnableVertexAttribArray(col); glVertexAttribPointer(tex, 2, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)TexOffset); glEnableVertexAttribArray(tex); glGenBuffers(1, &IndexRail); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexRail); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indicesVector.size(), indicesVector.data(), GL_STATIC_DRAW); glBindVertexArray(0); // Generate the crossbar VAO and VBO glGenVertexArrays(1, &VaoCb); glBindVertexArray(VaoCb); glGenBuffers(1, &BufferCb); glBindBuffer(GL_ARRAY_BUFFER, BufferCb); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * crossbarVertices.size(), crossbarVertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VertexSize, 0); glEnableVertexAttribArray(pos); glVertexAttribPointer(col, 4, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)RgbOffset); glEnableVertexAttribArray(col); glVertexAttribPointer(tex, 2, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)TexOffset); glEnableVertexAttribArray(tex); glGenBuffers(1, &IndexCb); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexCb); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * crossbarIndices.size(), crossbarIndices.data(), GL_STATIC_DRAW); glBindVertexArray(0); //Generate the ground VAO glGenVertexArrays(1, &VaoGd); glBindVertexArray(VaoGd); glGenBuffers(1, &BufferGd); glBindBuffer(GL_ARRAY_BUFFER, BufferGd); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 4, groundVertices, GL_STATIC_DRAW); glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VertexSize, 0); glEnableVertexAttribArray(pos); glVertexAttribPointer(col, 4, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)RgbOffset); glEnableVertexAttribArray(col); glVertexAttribPointer(tex, 2, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)TexOffset); glEnableVertexAttribArray(tex); glGenBuffers(1, &IndexGd); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexGd); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * 6, groundIndices, GL_STATIC_DRAW); glBindVertexArray(0); // Initiliaize skybox glGenVertexArrays(1, &VaoSky); glBindVertexArray(VaoSky); glGenBuffers(1, &BufferSky); glBindBuffer(GL_ARRAY_BUFFER, BufferSky); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 8, skyVertices, GL_STATIC_DRAW); glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VertexSize, 0); glEnableVertexAttribArray(pos); glVertexAttribPointer(col, 4, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)RgbOffset); glEnableVertexAttribArray(col); glVertexAttribPointer(tex, 2, GL_FLOAT, GL_FALSE, VertexSize, (GLvoid *)TexOffset); glEnableVertexAttribArray(tex); glGenBuffers(1, &IndexSky); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexSky); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * 36, skyboxIndices, GL_STATIC_DRAW); glBindVertexArray(0); } GLuint loadSkybox() { GLuint textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); for (GLuint i = 0; i < 6; i++) { // read the texture image ImageIO img; ImageIO::fileFormatType imgFormat; ImageIO::errorType err = img.load(faces[i], &imgFormat); if (err != ImageIO::OK) { printf("Loading texture from %s failed.\n", faces[i]); return -1; } // check that the number of bytes is a multiple of 4 if (img.getWidth() * img.getBytesPerPixel() % 4) { printf("Error (%s): The width*numChannels in the loaded image must be a multiple of 4.\n", faces[i]); return -1; } // allocate space for an array of pixels int width = img.getWidth(); int height = img.getHeight(); unsigned char *pixelsRGBA = new unsigned char[4 * width * height]; // we will use 4 bytes per pixel, i.e., RGBA // fill the pixelsRGBA array with the image pixels memset(pixelsRGBA, 0, 4 * width * height); // set all bytes to 0 for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { // assign some default byte values (for the case where img.getBytesPerPixel() < 4) pixelsRGBA[4 * (h * width + w) + 0] = 0; // red pixelsRGBA[4 * (h * width + w) + 1] = 0; // green pixelsRGBA[4 * (h * width + w) + 2] = 0; // blue pixelsRGBA[4 * (h * width + w) + 3] = 255; // alpha channel; fully opaque // set the RGBA channels, based on the loaded image int numChannels = img.getBytesPerPixel(); for (int c = 0; c < numChannels; c++) // only set as many channels as are available in the loaded image; the rest get the default value pixelsRGBA[4 * (h * width + w) + c] = img.getPixel(w, h, c); } } glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelsRGBA); delete[] pixelsRGBA; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); return textureID; } void updateGroundHeight() { for (int i = 0; i < 4; i++) { groundVertices[i].XYZ[1] = lowest - 10.0f; } } int initTexture(const char *imageFilename, GLuint textureHandle) { // read the texture image ImageIO img; ImageIO::fileFormatType imgFormat; ImageIO::errorType err = img.load(imageFilename, &imgFormat); if (err != ImageIO::OK) { printf("Loading texture from %s failed.\n", imageFilename); return -1; } // check that the number of bytes is a multiple of 4 if (img.getWidth() * img.getBytesPerPixel() % 4) { printf("Error (%s): The width*numChannels in the loaded image must be a multiple of 4.\n", imageFilename); return -1; } // allocate space for an array of pixels int width = img.getWidth(); int height = img.getHeight(); unsigned char *pixelsRGBA = new unsigned char[4 * width * height]; // we will use 4 bytes per pixel, i.e., RGBA // fill the pixelsRGBA array with the image pixels memset(pixelsRGBA, 0, 4 * width * height); // set all bytes to 0 for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { // assign some default byte values (for the case where img.getBytesPerPixel() < 4) pixelsRGBA[4 * (h * width + w) + 0] = 0; // red pixelsRGBA[4 * (h * width + w) + 1] = 0; // green pixelsRGBA[4 * (h * width + w) + 2] = 0; // blue pixelsRGBA[4 * (h * width + w) + 3] = 255; // alpha channel; fully opaque // set the RGBA channels, based on the loaded image int numChannels = img.getBytesPerPixel(); for (int c = 0; c < numChannels; c++) // only set as many channels as are available in the loaded image; the rest get the default value pixelsRGBA[4 * (h * width + w) + c] = img.getPixel(w, h, c); } // bind the texture glBindTexture(GL_TEXTURE_2D, textureHandle); // initialize the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelsRGBA); // generate the mipmaps for this texture glGenerateMipmap(GL_TEXTURE_2D); // set the texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // query support for anisotropic texture filtering GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); printf("Max available anisotropic samples: %f\n", fLargest); // set anisotropic texture filtering glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0.5f * fLargest); // query for any errors GLenum errCode = glGetError(); if (errCode != 0) { printf("Texture initialization error. Error code: %d.\n", errCode); return -1; } glBindTexture(GL_TEXTURE_2D, 0); // de-allocate the pixel array -- it is no longer needed delete[] pixelsRGBA; return 0; } int loadSplines(char *argv) { char *cName = (char *)malloc(128 * sizeof(char)); FILE *fileList; FILE *fileSpline; int iType, i = 0, j, iLength; // load the track file fileList = fopen(argv, "r"); if (fileList == NULL) { printf("can't open file\n"); exit(1); } // stores the number of splines in a global variable fscanf(fileList, "%d", &numSplines); splines = (Spline *)malloc(numSplines * sizeof(Spline)); // reads through the spline files for (j = 0; j < numSplines; j++) { i = 0; fscanf(fileList, "%s", cName); fileSpline = fopen(cName, "r"); if (fileSpline == NULL) { printf("can't open file\n"); exit(1); } // gets length for spline file fscanf(fileSpline, "%d %d", &iLength, &iType); // allocate memory for all the points splines[j].points = (Point *)malloc(iLength * sizeof(Point)); splines[j].numControlPoints = iLength; // saves the data to the struct while (fscanf(fileSpline, "%lf %lf %lf", &splines[j].points[i].x, &splines[j].points[i].y, &splines[j].points[i].z) != EOF) { i++; } } free(cName); return 0; } void initScene() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Initialize openGLMatrix openGLMatrix = new OpenGLMatrix(); // Initialize pipeline program pipelineProgram = new BasicPipelineProgram(); pipelineProgram->Init("../openGLHelper-starterCode"); programId = pipelineProgram->GetProgramHandle(); pipelineProgram->Bind(); // Initialize skybox skyboxHandler = loadSkybox(); // Initialize textures glGenTextures(1, &mTextureHandler); if (initTexture(mainImageFilename, mTextureHandler) != 0) { cout << "Error reading main image texture." << endl; exit(EXIT_FAILURE); } glGenTextures(1, &gdTextureHandler); if (initTexture(gdImageFilename, gdTextureHandler) != 0) { cout << "Error reading ground image texture." << endl; exit(EXIT_FAILURE); } glGenTextures(1, &cbTextureHandler); if (initTexture(cbImageFilename, cbTextureHandler) != 0) { cout << "Error reading cross bar image texture." << endl; exit(EXIT_FAILURE); } // Initialize initVertex(); updateGroundHeight(); initBuffer(); initPerspective(windowWidth, windowHeight); glLinkProgram(programId); //Initial link GLint textureLoc = glGetUniformLocation(programId, "textureImage"); GLint skyboxLoc = glGetUniformLocation(programId, "skyboxMap"); glUseProgram(programId); glUniform1i(textureLoc, 0); //Texture unit 0 is for base images. glUniform1i(skyboxLoc, 1); //Texture unit 2 is for normal maps. } int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: %s <trackfile>\n", argv[0]); exit(0); } // load the splines from the provided filename loadSplines(argv[1]); printf("Loaded %d spline(s).\n", numSplines); for (int i = 0; i < numSplines; i++) { printf("Num control points in spline %d: %d.\n", i, splines[i].numControlPoints); } // OpenGL initilization cout << "Initializing GLUT..." << endl; glutInit(&argc, argv); cout << "Initializing OpenGL..." << endl; #ifdef __APPLE__ glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); #else glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL); #endif glutInitWindowSize(windowWidth, windowHeight); glutInitWindowPosition(0, 0); glutCreateWindow(windowTitle); cout << "OpenGL Version: " << glGetString(GL_VERSION) << endl; cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << endl; cout << "Shading Language Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; // tells glut to use a particular display function to redraw glutDisplayFunc(displayFunc); // perform animation inside idleFunc glutIdleFunc(idleFunc); // callback for mouse drags glutMotionFunc(mouseMotionDragFunc); // callback for idle mouse movement glutPassiveMotionFunc(mouseMotionFunc); // callback for mouse button changes glutMouseFunc(mouseButtonFunc); // callback for resizing the window glutReshapeFunc(reshapeFunc); // callback for pressing the keys on the keyboard glutKeyboardFunc(keyboardFunc); // init glew #ifdef __APPLE__ // nothing is needed on Apple #else // Windows, Linux GLint result = glewInit(); if (result != GLEW_OK) { cout << "error: " << glewGetErrorString(result) << endl; exit(EXIT_FAILURE); } #endif // Enable Z-buffer glEnable(GL_DEPTH_TEST); // do initialization initScene(); // sink forever into the glut loop glutMainLoop(); }
[ "zijingli@usc.edu" ]
zijingli@usc.edu
f84046a25ec4ec6245ec1ab86d68530b55afafce
612f8a3a3a7f319d9d47eaed84880bf7a21a4e70
/SPOJ/PALIN-TheNextPalindrome/inpGen.cpp
ef2882652e48de9378afe44e9bd70e7bc123e6cf
[]
no_license
albertin0/coding
ab7b82e4e27c1f9eab94d66eeb2d0b614494b0f8
e4ced3127596958c6b233772097f101ec6093d84
refs/heads/master
2021-01-10T14:27:22.672157
2016-04-09T15:25:28
2016-04-09T15:25:28
49,198,001
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include <iostream> #include <fstream> using namespace std; int main() { ofstream fPtr; fPtr.open("./input.in"); int t,i=1; cin>>t; fPtr<<t<<endl; while(i<=t) fPtr<<i++<<endl; fPtr.close(); return 0; }
[ "albertino1903@gmail.com" ]
albertino1903@gmail.com
8db59322a5bacac2108ac800a06643800a14dd79
729a6e2fcc8c25f53c448aa75cd2a03a6282631e
/stratified_wave_tank_with_internal_wave_generator/0.orig/U
ad7a27dc54391e90ec351ad346c9b8bade4c5367
[]
no_license
liqun1981/iceberg_drift
1803d881d52662a68fa57119f152dabf9563dffc
d57de3ceceea1116141a64a733ae1cc76214a798
refs/heads/master
2020-03-16T13:56:30.241043
2016-08-31T18:23:56
2016-08-31T18:23:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 3.0.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "0"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField uniform (0 0 0); boundaryField { atmosphere { type pressureInletOutletVelocity; value uniform (0 0 0); } ".*Wall" { type noSlip; } "floatingObject.*" { type movingWallVelocity; value uniform (0 0 0); } frontAndBack { type noSlip; } } // ************************************************************************* //
[ "evankielley@gmail.com" ]
evankielley@gmail.com
74cf05da39073e27c76a76f5f5849df380c0e0a8
098de7d77b877755f3acf0153356d8af0467836e
/LightOj/IP Checking.cpp
633bc2fa84caa8ee333da08c91d0a8a76b20e802
[]
no_license
tariqul2814/ACMProblemSolves
58594deb51bd1d810e1efcf11257d56dc61da285
d23054508061812cc877237358c32eea5e9616c0
refs/heads/master
2020-05-19T11:30:11.848996
2019-05-05T06:59:30
2019-05-05T06:59:30
184,992,045
0
0
null
null
null
null
UTF-8
C++
false
false
1,743
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; for(int i=0;i<n;i++) { string x=""; string y=""; cin.ignore(); cin>>x; cin>>y; int size1=x.size(); int size2=y.size(); int b=0; int number = 0; int arr[]={128,64,32,16,8,4,2,1}; int track = 0; for(int j=0;j<=size1;j++) { int checkmate=0; if(x[j]=='.' || j==(size1)) { checkmate=1; number = number / 10; int number2 = 0; int check12 = 0; for(;b<size2;b++) { if(y[b]=='.' || b==(size2-1)) { if(y[b]=='1') { number2+=arr[check12] ; } b++; break; } if(y[b]=='1') { number2+=arr[check12] ; } check12++; } check12=0; if(number2==number) { track++; } else break; number=0; } if(checkmate==0) { int n1 = x[j]; n1 = n1 - 48; number += n1; number = number * 10; } } if(track==4) { cout<<"Case "<<i+1<<": Yes"<<endl; } else cout<<"Case "<<i+1<<": No"<<endl; } }
[ "tariqul2814@gmail.com" ]
tariqul2814@gmail.com
73a5a61b155f528afbb96c48326ddd196b02ec72
a0b0d3e00f838d780b2b231a7668e4a3a360be64
/item/13.media/3.ARM/4.advertisement_system/mainwindow.cpp
7c024cd0fac7d7c7d4d5b82adebcb07117edddca
[]
no_license
hewei-bit/QT-Learing
d5ba754b2f6dec4fb18e085766a6b1e2b394111f
d5c1c4cb8d15237b1c21eda4385bd661068b545e
refs/heads/master
2022-11-26T05:06:18.491108
2020-08-02T07:20:37
2020-08-02T07:20:37
275,719,032
0
0
null
null
null
null
UTF-8
C++
false
false
4,923
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" int runningTimer::count = 0; void runningTimer::ad_vedio() { if(ad_video_Process.state() == QProcess::Running) { ad_video_Process.kill(); ad_video_Process.waitForFinished(); } QString cmd = QString("mplayer -slave -quiet " "-geometry 0:0 -zoom -x %1 -y %2 " "/zero/qttest.mp4") .arg(ui->ad_vediolabel->width()) .arg(ui->ad_vediolabel->height()); qDebug() << "cmd = " << cmd; ad_video_Process.start(cmd); } void runningTimer::show_time() { QTime time = QTime::currentTime(); ui->time_label->setText(time.toString("hh:mm:ss")); QDate date = QDate::currentDate(); ui->date_label->setText(date.toString("yyyy-MM-dd")); } void runningTimer::show_ad_text() { // update(); // m_curIndex++; // if (m_curIndex*m_charWidth > width()) // m_curIndex = 0; // 当截取的位置比字符串长时,从头开始 if (count > sl.length()) count = 0; ui->ad_text_label->setText(sl.mid(count)); // 闪动文字 // ui->ad_text_label->setText(sl[count%3]); count++; } void runningTimer::read_data(QNetworkReply* reply) { QByteArray array = reply->readAll(); qDebug() << array; QJsonDocument doc = QJsonDocument::fromJson(array); // QJsonObject object = doc.object(); QString reason = object.value("reason").toString(); qDebug() << reason; QJsonObject resultObject = object.value("result").toObject(); // QJsonObject todayObject = resultObject.value("today").toObject(); QString mcity = resultObject.value("city").toString(); qDebug() << mcity; QJsonObject realtimeObject = resultObject.value("realtime").toObject(); QString mtemperature = realtimeObject.value("temperature").toString(); QString minfo = realtimeObject.value("info").toString(); qDebug() << minfo; qDebug() << mtemperature; /* { "reason":"查询成功!", "result":{ "city":"广州", "realtime":{ "temperature":"29", "humidity":"75", "info":"多云", "wid":"01", "direct":"东南风", "power":"2级", "aqi":"15" }} */ ui->address_label->setText(mcity); ui->weather_label->setText(minfo); ui->tempreaturelabel->setText(mtemperature); } QString runningTimer::showText() const { return m_showText; } void runningTimer::run_time() { mtimer = new QTimer(this); connect(mtimer,&QTimer::timeout,this,&runningTimer::show_time); mtimer->setInterval(1000); mtimer->start(1000); } void runningTimer::ad_text() { m_curIndex = 0;//当前文字下标值 m_showText = tr("Welcome to the image processing software of Star Dragon Company");//显示的文字 m_charWidth = fontMetrics().width("a");//每个字符的宽度 mtimer = new QTimer(this); connect(mtimer,&QTimer::timeout,this,&runningTimer::show_ad_text); mtimer->setInterval(1000); mtimer->start(1000); } void runningTimer::paintEvent(QPaintEvent *) { QPen pen; pen.setColor(QColor(255,0,255)); pen.setStyle(Qt::DashDotDotLine); QFont font("楷体",14,QFont::Bold); QPainter painter(this); painter.setPen(pen); painter.setFont(font); painter.drawText(0, 15, m_showText.mid(m_curIndex)); painter.drawText(width() - m_charWidth*m_curIndex, 15, m_showText.left(m_curIndex)); } void runningTimer::http_weather() { manager = new QNetworkAccessManager(); connect(manager,&QNetworkAccessManager::finished,this,&runningTimer::read_data); QUrl url("http://apis.juhe.cn/simpleWeather/query?" "city=%E5%B9%BF%E5%B7%9E" "&key=6eaaa433d136ff59653d126c67270943"); QNetworkRequest request(url); manager->get(request); } runningTimer::runningTimer(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //播放视频广告 ad_vedio(); //显示时间 // run_time(); // //创建线程池 // QThreadPool *manager = QThreadPool::globalInstance(); // //创建任务一 // MyClock* mc = new MyClock(); // //加入线程池并启动 // manager->start(mc); // connect(mc,&MyClock::run,this,&MainWindow::show_time); MyClock* mc = new MyClock(); mc->setObjectName("mc"); connect(mc,&MyClock::send,this,&runningTimer::show_time); mc->start(); //显示广告标语 ad_text(); // 天气API已连接成功 http_weather(); QImage img; img.load(":/new/prefix1/weather/sunny.png"); QPixmap originalPixmap = QPixmap::fromImage(img); ui->label->setPixmap(originalPixmap.scaled(ui->label->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } runningTimer::~runningTimer() { delete ui; }
[ "1003826976@qq.com" ]
1003826976@qq.com
ded95773b99a87a9cdfba07fc25534624919a046
136ef215ae05f74d31dab2336979a94dfe960992
/407-grove-beginner-kit-p1/Grove-Beginner-Kit-for-Arduino-SCH-PCB/Grove_Starter_Kit/Grove_BMP280-master/Seeed_BMP280.h
3336df019d427843c33bcf1f0a50ba47170c7940
[ "MIT" ]
permissive
zmaker/arduino_cookbook
5ff4791ebce916e35060f2e9a7c26a014adeb26c
a972470c10f2c283d66aad8f389acf117a25f01e
refs/heads/master
2023-08-30T21:08:28.290973
2023-08-28T11:14:41
2023-08-28T11:14:41
135,202,699
196
134
null
2020-05-27T17:53:02
2018-05-28T19:46:44
C++
UTF-8
C++
false
false
1,658
h
#ifndef _SEEED_BMP280_H_ #define _SEEED_BMP280_H_ #include <Arduino.h> #include <Wire.h> #define BMP280_ADDRESS 0x77 #define BMP280_REG_DIG_T1 0x88 #define BMP280_REG_DIG_T2 0x8A #define BMP280_REG_DIG_T3 0x8C #define BMP280_REG_DIG_P1 0x8E #define BMP280_REG_DIG_P2 0x90 #define BMP280_REG_DIG_P3 0x92 #define BMP280_REG_DIG_P4 0x94 #define BMP280_REG_DIG_P5 0x96 #define BMP280_REG_DIG_P6 0x98 #define BMP280_REG_DIG_P7 0x9A #define BMP280_REG_DIG_P8 0x9C #define BMP280_REG_DIG_P9 0x9E #define BMP280_REG_CHIPID 0xD0 #define BMP280_REG_VERSION 0xD1 #define BMP280_REG_SOFTRESET 0xE0 #define BMP280_REG_CONTROL 0xF4 #define BMP280_REG_CONFIG 0xF5 #define BMP280_REG_PRESSUREDATA 0xF7 #define BMP280_REG_TEMPDATA 0xFA class BMP280 { public: bool init(int i2c_addr = BMP280_ADDRESS); float getTemperature(void); uint32_t getPressure(void); float calcAltitude(float pressure); private: bool isTransport_OK; int _devAddr; // Calibratino data uint16_t dig_T1; int16_t dig_T2; int16_t dig_T3; uint16_t dig_P1; int16_t dig_P2; int16_t dig_P3; int16_t dig_P4; int16_t dig_P5; int16_t dig_P6; int16_t dig_P7; int16_t dig_P8; int16_t dig_P9; int32_t t_fine; // private functoins uint8_t bmp280Read8(uint8_t reg); uint16_t bmp280Read16(uint8_t reg); uint16_t bmp280Read16LE(uint8_t reg); int16_t bmp280ReadS16(uint8_t reg); int16_t bmp280ReadS16LE(uint8_t reg); uint32_t bmp280Read24(uint8_t reg); void writeRegister(uint8_t reg, uint8_t val); }; #endif
[ "paolo.aliverti@gmail.com" ]
paolo.aliverti@gmail.com
1be46b31ad05bfd78d66c34bc3b475ec9daa823d
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/libs/spirit/test/qi/utree1.cpp
f76155bd910a1c6ef0fbfa25b340523558718176
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,923
cpp
// Copyright (c) 2001-2011 Hartmut Kaiser // Copyright (c) 2001-2011 Joel de Guzman // Copyright (c) 2010 Bryce Lelbach // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <sstd/boost/config/warning_disable.hpp> #include <sstd/boost/detail/lightweight_test.hpp> #include <sstd/boost/mpl/print.hpp> #include <sstd/boost/spirit/include/qi.hpp> #include <sstd/boost/spirit/include/support_utree.hpp> #include <sstream> #include "test.hpp" inline bool check(boost::spirit::utree const& val, std::string expected) { std::stringstream s; s << val; if (s.str() == expected + " ") return true; std::cerr << "got result: " << s.str() << ", expected: " << expected << std::endl; return false; } int main() { using spirit_test::test_attr; using boost::spirit::utree; using boost::spirit::utree_type; using boost::spirit::utf8_string_range_type; using boost::spirit::utf8_symbol_type; using boost::spirit::utf8_string_type; using boost::spirit::qi::real_parser; using boost::spirit::qi::strict_real_policies; using boost::spirit::qi::digit; using boost::spirit::qi::char_; using boost::spirit::qi::string; using boost::spirit::qi::int_; using boost::spirit::qi::double_; using boost::spirit::qi::space; using boost::spirit::qi::space_type; using boost::spirit::qi::rule; using boost::spirit::qi::as; using boost::spirit::qi::lexeme; // primitive data types { utree ut; BOOST_TEST(test_attr("x", char_, ut) && ut.which() == utree_type::string_type && check(ut, "\"x\"")); ut.clear(); BOOST_TEST(test_attr("123", int_, ut) && ut.which() == utree_type::int_type && check(ut, "123")); ut.clear(); BOOST_TEST(test_attr("123.45", double_, ut) && ut.which() == utree_type::double_type && check(ut, "123.45")); ut.clear(); rule<char const*, utf8_string_type()> r1 = lexeme[*char_]; BOOST_TEST(test_attr("foo", r1, ut) && ut.which() == utree_type::string_type && check(ut, "\"foo\"")); ut.clear(); rule<char const*, utf8_symbol_type()> r2 = lexeme[*char_]; BOOST_TEST(test_attr("xyz", r2, ut) && ut.which() == utree_type::symbol_type && check(ut, "xyz")); } // single character parsers { utree ut; // this rule returns a utree string rule<char const*, utree()> r1 = char_("abc"); // this rule forces a utree list to be returned rule<char const*, utree::list_type()> r2 = char_("abc"); BOOST_TEST(test_attr("a", r1, ut) && ut.which() == utree_type::string_type && check(ut, "\"a\"")); ut.clear(); BOOST_TEST(test_attr("a", r2, ut) && ut.which() == utree_type::list_type && check(ut, "( \"a\" )")); } // sequences { using boost::spirit::qi::as_string; utree ut; BOOST_TEST(test_attr("xy", char_ >> char_, ut) && ut.which() == utree_type::list_type && check(ut, "( \"x\" \"y\" )")); ut.clear(); BOOST_TEST(test_attr("123 456", int_ >> int_, ut, space) && ut.which() == utree_type::list_type && check(ut, "( 123 456 )")); ut.clear(); BOOST_TEST(test_attr("1.23 4.56", double_ >> double_, ut, space) && ut.which() == utree_type::list_type && check(ut, "( 1.23 4.56 )")); ut.clear(); BOOST_TEST(test_attr("1.2ab", double_ >> *char_, ut) && ut.which() == utree_type::list_type && check(ut, "( 1.2 \"a\" \"b\" )")); ut.clear(); BOOST_TEST(test_attr("ab1.2", *~digit >> double_, ut) && ut.which() == utree_type::list_type && check(ut, "( \"a\" \"b\" 1.2 )")); // forces a utree list rule<char const*, utree::list_type()> r1 = double_; ut.clear(); BOOST_TEST(test_attr("1.2ab", r1 >> *char_, ut) && ut.which() == utree_type::list_type && check(ut, "( ( 1.2 ) \"a\" \"b\" )")); ut.clear(); BOOST_TEST(test_attr("ab1.2", *~digit >> r1, ut) && ut.which() == utree_type::list_type && check(ut, "( \"a\" \"b\" ( 1.2 ) )")); ut.clear(); // implicitly a utree list, because of sequence attribute rules rule<char const*, utree()> r2 = int_ >> char_("!") >> double_; BOOST_TEST(test_attr("17!3.14", r2, ut) && ut.which() == utree_type::list_type && check(ut, "( 17 \"!\" 3.14 )")); ut.clear(); rule<char const*, utree()> r3 = double_ >> as_string[string("foo")] >> int_; BOOST_TEST(test_attr("0.5foo5", r3, ut) && ut.which() == utree_type::list_type && check(ut, "( 0.5 \"foo\" 5 )")); } { utree ut; rule<char const*, utree()> r1 = char_; rule<char const*, utree::list_type()> r2 = double_; rule<char const*, utree::list_type()> r3 = char_; BOOST_TEST(test_attr("a25.5b", r1 >> r2 >> r3, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( \"a\" ( 25.5 ) ( \"b\" ) )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", r3 >> r2 >> r1, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( ( \"a\" ) ( 25.5 ) \"b\" )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", char_ >> r2 >> r3, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( \"a\" ( 25.5 ) ( \"b\" ) )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", r3 >> r2 >> char_, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( ( \"a\" ) ( 25.5 ) \"b\" )")); ut.clear(); #if defined(BOOST_CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" #endif BOOST_TEST(test_attr("a25.5b", r1 > r2 >> r3, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( \"a\" ( 25.5 ) ( \"b\" ) )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", r3 >> r2 > r1, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( ( \"a\" ) ( 25.5 ) \"b\" )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", char_ > r2 >> r3, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( \"a\" ( 25.5 ) ( \"b\" ) )")); ut.clear(); BOOST_TEST(test_attr("a25.5b", r3 >> r2 > char_, ut)); BOOST_TEST(ut.which() == utree_type::list_type); BOOST_TEST(check(ut, "( ( \"a\" ) ( 25.5 ) \"b\" )")); #if defined(BOOST_CLANG) #pragma clang diagnostic pop #endif } return boost::report_errors(); }
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
4f7dbc68899d3f0f078f92e50d8484035297e6ac
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/IPNetworkIdentity/UNIX_IPNetworkIdentity_FREEBSD.hxx
f3a0c6b44ed60800f7dec764270758d5f11bb438
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,821
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_IPNETWORKIDENTITY_PRIVATE_H #define __UNIX_IPNETWORKIDENTITY_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
1da26e68ae44feb621352a2c8f5221aec1ef87c7
61deafb2dcf4820d46f2500d12497a89ff66e445
/1863.cpp
e5f75003c259b183de0009e8fc061e580d23fdff
[]
no_license
Otrebus/timus
3495f314587beade3de67890e65b6f72d53b3954
3a1dca43dc61b27c8f903a522743afeb69d38df2
refs/heads/master
2023-04-08T16:54:07.973863
2023-04-06T19:59:07
2023-04-06T19:59:07
38,758,841
72
40
null
null
null
null
UTF-8
C++
false
false
2,300
cpp
/* 1863. Peaceful Atom - http://acm.timus.ru/problem.aspx?num=1863 * * Strategy: * Meet-in-the-middle. First, enumerate all the possible insertion depths for half of the input * by brute-force, then do the same for the second half, but for each value also associate the * maximum and minimum insertion depth for the sequence that produced the depth. For each of the * depths produced in the second half, use the associated min (max) depth to do a binary * search over the first half of the data to find the least (greatest) insertion depth we can * append to, and update the answer accordingly. * * Performance: * O(2^(k/2)k), runs the tests in 0.156s using 36,576KB memory. */ #include <iostream> #include <vector> #include <algorithm> #include <functional> struct lr { int n, l, r; }; // Depth, max and min depths int main() { int n, s, k, x; std::cin >> n >> s >> k; std::vector<int> A = { s }; // Produce all possible depths for the first half for(int i = 0; i < k/2; i++) { std::cin >> x; std::vector<int> v; for(auto a : A) { for(auto y : { a - x, a + x }) if(y >= 0 && y <= n) v.push_back(y); } A = v; } std::sort(A.begin(), A.end()); // Sort for the binary search A.erase(std::unique(A.begin(), A.end()), A.end()); // Remove duplicates // Produce the possible depths for the second half along with the max and min depths std::vector<lr> B = {{ 0, 0, 0 }}; for(int i = k/2; i < k; i++) { std::cin >> x; std::vector<lr> v; for(auto p : B) for(auto y : { p.n - x, p.n + x }) if(y >= -n && y <= n) v.push_back({ y, std::min(p.l, y), std::max(p.r, y) }); B = v; } // Do binary search over the first half to find what depth we can append to int min = n, max = 0; for(auto p : B) { auto it = std::lower_bound(A.begin(), A.end(), -p.l); if(it != A.end() && *it + p.r <= n) min = std::min(min, *it + p.n); auto iu = std::lower_bound(A.rbegin(), A.rend(), n-p.r, std::greater<int>()); if(iu != A.rend() && *iu + p.l >= 0) max = std::max(max, *iu + p.n); } std::cout << min << " " << max; }
[ "otrebus@gmail.com" ]
otrebus@gmail.com
b2c124b8d204269aa0393af5c6f3c76fa4f95606
c254b84340be475b5513dbf5aa15dab7c316b886
/range-sum-query-immutable/range_sum_query_immutable.cpp
1f8d0a035f4059a52f8a0b3d4cdc341747bc21a1
[]
no_license
guoyu07/oj-leetcode
8cd794738a2d95862e8b2b3b2927f60ab3dd8506
3e80c210e71e2e3e52144b5c6839207effb6683c
refs/heads/master
2021-06-05T01:57:18.220446
2016-09-23T05:39:26
2016-09-23T05:39:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
733
cpp
#include <iostream> #include <vector> using namespace std; class NumArray { public: NumArray(vector<int> &nums) { partial_sums.resize(nums.size()); int sum = 0; for(size_t i = 0; i < nums.size(); ++i ) { sum += nums[i]; partial_sums[i] = sum; } } // NOTE: do not validate the i, j int sumRange(int i, int j) { return partial_sums[j] - (i <= 0 ? 0 : partial_sums[i-1]); } private: vector<int> partial_sums; }; int main() { vector<int> nums = {-2, 0, 3,-5, 2, -1}; NumArray num_arr(nums); cout<<num_arr.sumRange(0,2)<<endl; cout<<num_arr.sumRange(2,2)<<endl; cout<<num_arr.sumRange(2,5)<<endl; cout<<num_arr.sumRange(0,5)<<endl; return 0; }
[ "justinj656@live.cn" ]
justinj656@live.cn
5d9b5ab7662684088cf50fed8bfeeef53e3d459e
996a50566173f3500dfe18aec3efb13437ca93b5
/iota-net/include/iota-tcpsocket.h
fa06cff4b908c4fa71cbaaf8a60eb5a7cc9c286f
[ "MIT" ]
permissive
cleversoap/iota-net
c1b95af493c1faf3f71e631783130ea86e520323
6dc43d7e7cfd6aff2d2d816ec6099c5bf24ad9e1
refs/heads/master
2020-05-17T19:16:24.267920
2014-04-17T06:41:08
2014-04-17T06:41:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef __IOTA_TCPSOCKET_H__ #define __IOTA_TCPSOCKET_H__ #include "iota-socket.h" namespace iota { namespace net { class TcpSocket : public Socket { public: TcpSocket(); }; } } #endif // __IOTA_TCPSOCKET_H__
[ "clever@cleversoap.com" ]
clever@cleversoap.com
67f9e40ab90de55cc30a629ac1f663dbac7c2df2
d6258ae3c0fd9f36efdd859a2c93ab489da2aa9b
/fulldocset/add/codesnippet/CPP/t-system.web.services.de_10_1.cpp
fd4ed3d24445a582b3ca47779c41e16368c11ccd
[ "CC-BY-4.0", "MIT" ]
permissive
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
ca4d3821767bba558336b2ef2d2a40aa100d67f6
9a577bbd8ead778fd4723fbdbce691e69b3b14d4
refs/heads/master
2020-05-26T22:12:47.034527
2017-03-07T07:07:15
2017-03-07T07:07:15
82,508,764
1
0
null
2017-02-28T02:14:26
2017-02-20T02:36:59
Visual Basic
UTF-8
C++
false
false
2,961
cpp
#using <System.Xml.dll> #using <System.Web.Services.dll> #using <System.dll> using namespace System; using namespace System::Web::Services::Description; using namespace System::Xml; Port^ CreatePort( String^ PortName, String^ BindingName, String^ targetNamespace ) { Port^ myPort = gcnew Port; myPort->Name = PortName; myPort->Binding = gcnew XmlQualifiedName( BindingName,targetNamespace ); // Create a SoapAddress extensibility element to add to the port. SoapAddressBinding^ mySoapAddressBinding = gcnew SoapAddressBinding; mySoapAddressBinding->Location = "http://localhost/ServiceClass/MathService_CS.asmx"; myPort->Extensions->Add( mySoapAddressBinding ); return myPort; } int main() { try { // Read a WSDL document. ServiceDescription^ myServiceDescription = ServiceDescription::Read( "MathService_CS.wsdl" ); ServiceCollection^ myServiceCollection = myServiceDescription->Services; int noOfServices = myServiceCollection->Count; Console::WriteLine( "\nTotal number of services: {0}", noOfServices ); // Gets a reference to the service. Service^ myOldService = myServiceCollection[ 0 ]; Console::WriteLine( "No. of ports in the service: {0}", myServiceCollection[ 0 ]->Ports->Count ); Console::WriteLine( "These are the ports in the service:" ); for ( int i = 0; i < myOldService->Ports->Count; i++ ) Console::WriteLine( "Port name: {0}", myOldService->Ports[ i ]->Name ); Console::WriteLine( "Service name: {0}", myOldService->Name ); Service^ myService = gcnew Service; myService->Name = "MathService"; // Add the Ports to the newly created Service. for ( int i = 0; i < myOldService->Ports->Count; i++ ) { String^ PortName = myServiceCollection[ 0 ]->Ports[ i ]->Name; String^ BindingName = myServiceCollection[ 0 ]->Ports[ i ]->Binding->Name; myService->Ports->Add( CreatePort( PortName, BindingName, myServiceDescription->TargetNamespace ) ); } Console::WriteLine( "Newly created ports -" ); for ( int i = 0; i < myService->Ports->Count; i++ ) Console::WriteLine( "Port name: {0}", myOldService->Ports[ i ]->Name ); // Add the extensions to the newly created Service. int noOfExtensions = myOldService->Extensions->Count; Console::WriteLine( "No. of extensions: {0}", noOfExtensions ); if ( noOfExtensions > 0 ) { for ( int i = 0; i < myOldService->Ports->Count; i++ ) myService->Extensions->Add( myServiceCollection[ 0 ]->Extensions[ i ] ); } // Remove the service from the collection. myServiceCollection->Remove( myOldService ); // Add the newly created service. myServiceCollection->Add( myService ); myServiceDescription->Write( "MathService_New.wsdl" ); } catch ( Exception^ e ) { Console::WriteLine( "Exception: {0}", e->Message ); } }
[ "tianzh@microsoft.com" ]
tianzh@microsoft.com
1fd45e4d062c4d1125ed63f2cf7f0fc186315f6e
ac6fe2065caf41f6792b2cec0f22797f1f8badce
/Engine/ZenCore/Resource/Graphic/zcResGfxTexture_DX11.h
592550dec3de98d4c217fc9ca7bb41e2c8506c7a
[ "MIT" ]
permissive
ZenEngine3D/ZenEngine
02e93ed46defa8e431d12dc2d8380e381c357ce3
42bcd06f743eb1381a587c9671de67e24cf72316
refs/heads/master
2021-04-30T00:35:19.578736
2021-04-03T06:45:09
2021-04-03T06:45:09
121,461,927
1
1
null
null
null
null
UTF-8
C++
false
false
340
h
#pragma once namespace zcRes { class GfxTexture2D_DX11 : public zcExp::ExportGfxTexture2D { public: virtual ~GfxTexture2D_DX11(); bool Initialize(); ID3D11Texture2D* mpTextureBuffer; ID3D11ShaderResourceView* mpTextureView; typedef zcExp::ExporterGfxTexture2DDX11_DX11 RuntimeExporter; }; }
[ "ZenEngine3D@gmail.com" ]
ZenEngine3D@gmail.com
1c45cbcd9d800a3ea080e39ac77db13f1e4c1aa0
b6607ecc11e389cc56ee4966293de9e2e0aca491
/informatics.mccme.ru/Menshikov/1/B/B.cpp
467b678007824c38b00c7a903cc2de112b60a0c9
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
#include <iostream> #include <cstdio> #include <cmath> #include <vector> using namespace std; vector <int> a; int main() { int n; cin >> n; a.resize(n); for (int i = 0; i < n; i++) cin >> a[i]; int tmp = n / 2; set <int> set1; for (int mask = 0; mask < (1 << tmp); mask++) { int x = 0; int i = mask; while (i) { if (i & 1) x += a[i]; else x -= a[i]; i >>= 1; } set1.insert(x); } }
[ "bekzhan.kassenov@nu.edu.kz" ]
bekzhan.kassenov@nu.edu.kz
7fb6e30387107a5f63732cef3b18ee99624446d9
032013d17b506b2eb732a535b9e42df148d9a75d
/src/plugins/lmp/engine/output.cpp
4b4eda403db45a393f03a10d2b3c358b6d09a036
[ "BSL-1.0" ]
permissive
zhao07/leechcraft
55bb64d6eab590a69d92585150ae1af3d32ee342
4100c5bf3a260b8bc041c14902e2f7b74da638a3
refs/heads/master
2021-01-22T11:59:18.782462
2014-04-01T14:04:10
2014-04-01T14:04:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,452
cpp
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "output.h" #include <cmath> #include <QtDebug> #include <QTimer> #include "../gstfix.h" #include "path.h" #include "../xmlsettingsmanager.h" namespace LeechCraft { namespace LMP { namespace { /* Signature found on * http://cgit.freedesktop.org/gstreamer/gst-plugins-base/commit/?id=de1db5ccbdc10a835a2dfdd5984892f3b0c9bcf4 * * I love C language, it's freaking compile-time-safe and sane. */ gboolean CbVolumeChanged (GObject*, GParamSpec*, gpointer data) { auto output = static_cast<Output*> (data); const auto volume = output->GetVolume (); QMetaObject::invokeMethod (output, "volumeChanged", Q_ARG (qreal, volume)); QMetaObject::invokeMethod (output, "volumeChanged", Q_ARG (int, volume * 100)); return true; } gboolean CbMuteChanged (GObject*, GParamSpec*, gpointer data) { auto output = static_cast<Output*> (data); const auto isMuted = output->IsMuted (); QMetaObject::invokeMethod (output, "mutedChanged", Q_ARG (bool, isMuted)); return true; } } Output::Output (QObject *parent) : QObject (parent) , Bin_ (gst_bin_new ("audio_sink_bin")) , Equalizer_ (gst_element_factory_make ("equalizer-3bands", "equalizer")) , Volume_ (gst_element_factory_make ("volume", "volume")) , Converter_ (gst_element_factory_make ("audioconvert", "convert")) , Sink_ (gst_element_factory_make ("autoaudiosink", "audio_sink")) , SaveVolumeScheduled_ (false) { gst_bin_add_many (GST_BIN (Bin_), Equalizer_, Volume_, Converter_, Sink_, nullptr); gst_element_link_many (Equalizer_, Volume_, Converter_, Sink_, nullptr); auto pad = gst_element_get_static_pad (Equalizer_, "sink"); auto ghostPad = gst_ghost_pad_new ("sink", pad); gst_pad_set_active (ghostPad, TRUE); gst_element_add_pad (Bin_, ghostPad); gst_object_unref (pad); g_signal_connect (Volume_, "notify::volume", G_CALLBACK (CbVolumeChanged), this); g_signal_connect (Volume_, "notify::mute", G_CALLBACK (CbMuteChanged), this); const auto volume = XmlSettingsManager::Instance () .Property ("AudioVolume", 1).toDouble (); setVolume (volume); const auto isMuted = XmlSettingsManager::Instance () .Property ("AudioMuted", false).toBool (); g_object_set (G_OBJECT (Volume_), "mute", static_cast<gboolean> (isMuted), nullptr); } void Output::AddToPath (Path *path) { path->SetOutputBin (Bin_); } void Output::PostAdd (Path*) { } double Output::GetVolume () const { gdouble value = 1; g_object_get (G_OBJECT (Volume_), "volume", &value, nullptr); const auto exp = XmlSettingsManager::Instance ().property ("VolumeExponent").toDouble (); if (exp != 1) value = std::pow (value, 1 / exp); return value; } bool Output::IsMuted () const { gboolean value = false; g_object_get (G_OBJECT (Volume_), "mute", &value, nullptr); return value; } void Output::ScheduleSaveVolume () { if (SaveVolumeScheduled_) return; SaveVolumeScheduled_ = true; QTimer::singleShot (1000, this, SLOT (saveVolume ())); } void Output::setVolume (double volume) { const auto exp = XmlSettingsManager::Instance ().property ("VolumeExponent").toDouble (); if (exp != 1) volume = std::pow (volume, exp); g_object_set (G_OBJECT (Volume_), "volume", static_cast<gdouble> (volume), nullptr); ScheduleSaveVolume (); } void Output::setVolume (int volume) { setVolume (volume / 100.); } void Output::toggleMuted () { g_object_set (G_OBJECT (Volume_), "mute", static_cast<gboolean> (!IsMuted ()), nullptr); ScheduleSaveVolume (); } void Output::saveVolume () { SaveVolumeScheduled_ = false; XmlSettingsManager::Instance ().setProperty ("AudioVolume", GetVolume ()); XmlSettingsManager::Instance ().setProperty ("AudioMuted", IsMuted ()); } } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
d3b7763565894dd5e705cf6a4c5a08484289823f
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/core/include/Animation.h
a362bb66a02a00187d20f6debe0cce1ad675a2c3
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,145
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __rlAnimation_H__ #define __rlAnimation_H__ #include "CorePrerequisites.h" #include <set> #include <map> #include "AnimationListener.h" namespace rl { class MeshObject; /** Diese Klasse ermöglicht eine einfache Steuerung von Animationseinstellungen und ist die Basisklasse erweiterter Animationen. @remarks Instanzen werden über den AnimationManager erzeugt @see AnimationManager */ class _RlCoreExport Animation : public virtual EventSource { public: /** Der Basiskonstruktor, für MeshObject, die einen AnimationState mitbringen @param animState AnimationState, intern @param speed Geschwindigkeit, auch negativ @param timesToPlay Abspielanzahl, 0 = unendlich @mesh mesh The MeshObjekt whose Animation is played @remarks Die Animation beginnt sofort zu spielen, bei negativer Geschwindigkeit beginnt sie mit dem letzten Frame. Konstruktor sollte nicht direkt aufgerufen werden, sondern vom AnimationManager. */ Animation(Ogre::AnimationState* animState, MeshObject* mesh, Ogre::Real speed=1.0, unsigned int timesToPlay=0); /** Ein Konstruktor, für eine später festlegbare Animation @remarks Dieser Konstruktor ist für Unterklassen. Konstruktor sollte nicht direkt aufgerufen werden, sondern vom AnimationManager. */ Animation(); /// Virtueller Destruktor virtual ~Animation( ); /// Gibt zurück ob die Animation pausiert ist bool isPaused() const; /** Pausieren/Fortsetzen der Animation @param isPaused Zukünftiger Status @remarks Löst einen AnimationPaused/Unpaused Event aus */ void setPaused( bool isPaused ); /// Gibt zurück ob die globale Beschleunigung ignoriert wird bool isIgnoringGlobalSpeed() const; /** Setzt die Ignoranz @param isIgnoringGlobalSpeed Die zukünftige Ignoranz der globalen Geschwindigkeit @remarks Möglichkeit die globale SlowMotion zu umgehen Nützlich für Statusanzeigen, oder ähnliche konstante Animationen @todo TODO Eventuell das ganze auf Flags erweitern */ void setIgnoringGlobalSpeed( bool isIgnoringGlobalSpeed ); /// Gibt die aktuelle Geschwindigkeit zurück Ogre::Real getSpeed() const; /** Setzt die aktuelle Geschwindigkeit der Animation @param speed die Geschwindigkeit @remarks 1.0 ist die normale Geschwindigkeit der Animation (mLength in Sekunden), negative Werte spielen die Animation rückwärts ab. Bei 0 herrscht Stillstand. */ void setSpeed( Ogre::Real speed ); /// Negiert die aktuelle Geschwindigkeit void reverseAnimation(); /** Setzt die maximalen Wiederholungszahl der Animation @param timesToPlay Die nicht negative Anzahl der Wiederholungen @remarks Bei 0 wird die Animation beliebig oft wiederholt */ void setTimesToPlay(unsigned int timesToPlay); /// Gibt die Anzahl der bereits vollständig abgespielten Wiederholungen zurück unsigned int getTimesPlayed() const; /** Setzt die Abspielzeit zurück Löst dabei auch eine mögliche Pause auf, und spult die Animation zurück */ void resetTimesPlayed(); /// Gibt zurück wieviel Wiederholungen insgesamt abzuspielen sind unsigned int getTimesToPlay() const; /// Gibt zurück wieviele Wiederholungen noch durchzuführen sind unsigned int getTimesToPlayLeft() const; /// Gibt die Abspieldauer zurück (intern) Ogre::Real getTimePlayed() const; /// Gibt das Gewicht der Animation zurück Ogre::Real getWeight(void) const; /** Setzt das Gewicht (Einfluss) der Animation @param weigt Das Gewicht der Animation */ void setWeight( Ogre::Real weight ); /// Gibt das MeshObject MeshObject* getMeshObject(); /// Zeit hinzufügen - wird vom AnimationManager aufgerufen void addTime( Ogre::Real timePassed ); /** Fügt einen AnimationListener hinzu @param listener Der hinzuzufügende Listener @remarks Der Listener wird benachrichtigt, wenn * die Animation pausiert/fortgesetzt wird * die Animation ihr gesamten Wiederholungen vollendet hat */ void addAnimationListener( AnimationListener *listener); /// Entfernt einen AnimationListener void removeAnimationListener( AnimationListener *listener); /// Gibt den erstbesten Listener wieder (nur ne Testmethode) AnimationListener* getAnimationListener( ); /** Fügt einen AnimationFrameListener hinzu @param listener Der hinzuzufügende Listener @param frameNumber Die zu überwachende Zeitindex @remarks Der Listener wird benachrichtigt, wenn der Zeitindex erreicht oder übersprungen wird. Dabei wird, falls der Fortschritt größer als die Länge der Animation korrekt geprüft, so dass keine Events verloren gehen */ void addAnimationFrameListener( AnimationFrameListener *listener, Ogre::Real frameNumber ); /// Entfernt einen AnimationListener an allen Zeitindizes void removeAnimationFrameListener( AnimationFrameListener *listener ); /// Entfernt einen AnimationListener an einem bestimmtem Zeitindex void removeAnimationFrameListener( AnimationFrameListener *listener, Ogre::Real frameNumber ); /// Gibt den AnimationState zurück (intern) Ogre::AnimationState* getAnimationState() const { return mAnimState; }; protected: /// Der AnimationState Ogre::AnimationState* mAnimState; /// Das MeshObject MeshObject* mMeshObject; /// Pause bool mPaused; /// Ignoriert die globale Geschwindigkeit bool mIgnoringGlobalSpeed; /// Eigene Geschwindigkeit Ogre::Real mSpeed; /// Gesamte Abspielwiederholungen unsigned int mTimesToPlay; /// Bisherige Abspielzeit Ogre::Real mTimePlayed; /// Setzt den AnimationState void setAnimationState( Ogre::AnimationState* animState ); /// EventCaster EventCaster<AnimationEvent> mAnimationCaster; typedef std::multimap<Ogre::Real,AnimationFrameListener*> AnimationFrameListenerMap; /// Die Multimap mit den FrameNummern und den dazugehörigen Listenern AnimationFrameListenerMap mAnimationFrameListener; private: /// Überwacht das erreichen der einzelnen Frames für die Listener void checkAnimationFrameListeners( Ogre::Real timePassed ); void removeAllListeners(); }; } #endif
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013