hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
09c3e07c4b75adcd347bd16b2dc8db98dafef82d | 2,295 | hpp | C++ | parent_selector.hpp | mortalisk/xtpath | e643fa4a215d35af9f0e57cfd38f2e219156b81f | [
"BSL-1.0"
] | 2 | 2015-04-14T19:34:27.000Z | 2019-09-18T18:35:12.000Z | parent_selector.hpp | mortalisk/xtpath | e643fa4a215d35af9f0e57cfd38f2e219156b81f | [
"BSL-1.0"
] | null | null | null | parent_selector.hpp | mortalisk/xtpath | e643fa4a215d35af9f0e57cfd38f2e219156b81f | [
"BSL-1.0"
] | null | null | null |
// Copyright Morten Bendiksen 2014 - 2016.
// 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)
#ifndef MEDIASEQUENCER_PLUGIN_UTIL_XPATH_PARENT_SELECTOR_HPP
#define MEDIASEQUENCER_PLUGIN_UTIL_XPATH_PARENT_SELECTOR_HPP
#include "selector_common.hpp"
#include "parent_iterator.hpp"
namespace mediasequencer { namespace plugin { namespace util { namespace xpath {
// represents the parent selector filtered on the name of
// the parent
struct filtered_parent {
explicit filtered_parent(std::string s): name(std::move(s)) {
}
filtered_parent(filtered_parent const& other)
: name(other.name) {
}
std::string name;
};
// the type of the parent selector object
class _parent {
public:
filtered_parent operator()(std::string name) const {
return filtered_parent(name);
}
};
namespace {
/// The parent selctor object gives the parents of each node
/// in the input range if used on its own, i.e. 'range | parent'
/// If given a targen parent name as argument, will give only the
/// parents with that name, i.e. 'range | parent("foo")'
const _parent parent;
}
// Implements the pipe operator for the parent selector. E.g.
// 'range | parent'
template <typename Range>
boost::iterator_range<parent_iterator<typename Range::iterator> >
operator|(Range const& range,
_parent const&)
{
return make_parent(range);
}
// Implements the pipe operator for the parent selector filtered on
// name. E.g. 'range | parent("foo")'
template <typename Range>
boost::range_detail::filtered_range
<name_predicate<typename Range::iterator::reference>,
const boost::iterator_range<parent_iterator<typename Range::iterator> > >
operator|(Range const& range,
filtered_parent f)
{
return make_parent(range)
| filtered(name_predicate<typename Range::iterator::reference>(f.name));
}
// enables the parent selector in sub expressions
template <>
struct is_expr<_parent>: std::true_type {
};
// enables the filtered parent selector in sub expressions
template <>
struct is_expr<filtered_parent>: std::true_type {
};
}}}}
#endif // MEDIASEQUENCER_PLUGIN_UTIL_XPATH_PARENT_SELECTOR_HPP
| 27.987805 | 84 | 0.722004 | [
"object"
] |
09d519a43a187988c1c9d8c911e7bda61925f677 | 11,591 | cc | C++ | test/test_RadixTreeFunctions.cc | neufeldm/akamai-radix-tree | 008c15d8d41b24a8aff9a230e52e56e3fb5c3de8 | [
"MIT"
] | 19 | 2019-03-16T03:20:18.000Z | 2022-02-26T14:12:27.000Z | test/test_RadixTreeFunctions.cc | neufeldm/akamai-radix-tree | 008c15d8d41b24a8aff9a230e52e56e3fb5c3de8 | [
"MIT"
] | 15 | 2019-03-22T17:53:15.000Z | 2020-11-13T19:59:29.000Z | test/test_RadixTreeFunctions.cc | neufeldm/akamai-radix-tree | 008c15d8d41b24a8aff9a230e52e56e3fb5c3de8 | [
"MIT"
] | 7 | 2019-06-20T14:39:44.000Z | 2022-03-15T09:56:11.000Z | /*
Copyright (c) 2019 Akamai Technologies, Inc
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 "gtest/gtest.h"
#include "BinaryTreeTestUtils.h"
#include "BinaryTestPath.h"
#include "SimplePath.h"
#include "CursorTraversal.h"
#include "CompoundCursor.h"
#include "TreeTestUtils.h"
using namespace Akamai::Mapper::RadixTree;
TEST(RadixTreeFunctions, CursorTraversalFollow) {
Tree6_3 tree1;
Tree6_3 tree2;
Tree6_3 tree3;
auto leader1 = tree1.cursor();
auto follower = tree2.cursor();
auto leader2 = tree3.cursor();
// Fully populate two, identical binary trees with path depth 2
SimplePath<2,6> pv1{0,0}, pv2{0,1}, pv3{1,0}, pv4{1,1};
std::vector<SimplePath<2,6>>tree_paths {pv1, pv2, pv3, pv4};
for (int i = 0; i < tree_paths.size(); i++) {
while (leader1.canGoParent()) { leader1.goParent(); }
while (leader2.canGoParent()) { leader2.goParent(); }
while (follower.canGoParent()) { follower.goParent(); }
for (int j = 0; j < pv1.size(); j++) {
leader1.goChild(tree_paths[i].at(j));
leader2.goChild(tree_paths[i].at(j));
follower.goChild(tree_paths[i].at(j));
leader1.addNode();
leader2.addNode();
follower.addNode();
leader1.nodeValue().set(i);
leader2.nodeValue().set(i);
follower.nodeValue().set(i);
}
}
// Return both cursors to the root
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
// Check that follower can follow one leader, and then two leaders in pre-order
preOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
preOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
// Check that follower can follow one leader, and then two leaders in post-order
postOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
postOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
// Check that follower can follow one leader, and then two leaders in in-order
inOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
inOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
}
TEST(RadixTreeFunctions, CursorTraversalFollowDiff) {
Tree6_3 tree1;
Tree6_3 tree2;
auto leader1 = tree1.cursor();
auto follower = tree2.cursor();
SimplePath<2,6> pv1{0,0,0}, pv2{0,0,1}, pv3{0,1,0}, pv4{0,1,1},
pv5{1,1,1}, pv6{1,1,0}, pv7{1,0,0}, pv8{1,0,1};
SimplePath<2,6> p1{0,0,0}, p2{0,1,1}, p3{1,0,1};
std::vector<SimplePath<2,6>> tree1_paths {pv1, pv2, pv3, pv4, pv5, pv6, pv7, pv8};
std::vector<SimplePath<2,6>> tree2_paths {p1, p2, p3};
// Make fully populated binary tree of depth 3
for (size_t i = 0; i < tree1_paths.size(); i++) {
while (leader1.canGoParent()) { leader1.goParent(); }
for (size_t j = 0; j < pv1.size(); j++) {
leader1.goChild(tree1_paths[i].at(j));
}
leader1.addNode();
leader1.nodeValue().set(i);
}
// Populate sparse tree, a subset of the full depth 3 tree
// with different values at each node
for (size_t i = 0; i < tree2_paths.size(); i++) {
while(follower.canGoParent()) { follower.goParent(); }
for (size_t j = 0; j < p1.size(); j++) {
if (follower.canGoChild(tree2_paths[i].at(j))) {
follower.goChild(tree2_paths[i].at(j));
}
follower.addNode();
follower.nodeValue().set(i*2);
}
}
while(leader1.canGoParent() || follower.canGoParent()) {
leader1.goParent();
follower.goParent();
}
// Check that leader1 and follower show different values at same path locations
postOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
if (*(L1.nodeValueRO().getPtrRO()) == 3) {
ASSERT_EQ(*(f.nodeValueRO().getPtrRO()), 2);}}, follower, leader1);
}
TEST(RadixTreeFunctions, CursorTraversalFollowOver) {
Tree6_3 tree1;
Tree6_3 tree2;
auto leader1 = tree1.cursor();
auto follower = tree2.cursor();
int callCount = 0;
// Fully populate the two binary trees with path depth 2
SimplePath<2,6> p1{0,0}, p2{0,1}, p3{1,0}, p4{1,1};
std::vector<SimplePath<2,6>> tree_paths {p1,p2,p3,p4};
// Set values at leaves of both trees
for (size_t i = 0; i < tree_paths.size(); i++) {
while (leader1.canGoParent()) { leader1.goParent(); }
while (follower.canGoParent()) { follower.goParent(); }
for (size_t j = 0; j < p1.size(); j++) {
leader1.goChild(tree_paths[i].at(j));
follower.goChild(tree_paths[i].at(j));
}
leader1.addNode();
follower.addNode();
follower.nodeValue().set(i);
}
// Add extra value to tree2; follower triggers callback when at value
while(follower.canGoParent()) { follower.goParent(); }
follower.goChild(0);
ASSERT_TRUE(follower.atNode());
follower.nodeValue().set(700);
// Return both cursors to the root
while (leader1.canGoParent() || follower.canGoParent()) {
leader1.goParent();
follower.goParent();
}
preOrderFollowOver<false,2>([&callCount](const decltype(follower)& f, const decltype(leader1)& L1) {
callCount++;}, follower, leader1);
ASSERT_EQ(callCount, 5);
// Reset callCount for postOrder check
callCount = 0;
postOrderFollowOver<false,2>(
[&callCount](const decltype(follower)& f, const decltype(leader1)& L1){callCount++;},
follower, leader1);
ASSERT_EQ(callCount, 5);
callCount = 0;
inOrderFollowOver<false,2>(
[&callCount](const decltype(follower)& f, const decltype(leader1)& L1){callCount++;},
follower, leader1);
ASSERT_EQ(callCount, 5);
}
#if 0
TEST(RadixTreeFunctions, Depth16Traversal) {
using PathVal32 = IntPathValue<IntPath32, uint32_t>;
std::vector<PathVal32> vals;
uint32_t v{0};
addAllThroughDepth<PathVal32>(16, v, std::back_inserter(vals));
uint32_t expectedEndVal = countAtAllThroughDepth(16);
std::vector<uint32_t> shallowToDeep = makeIdentityMap<uint32_t>(expectedEndVal);
std::vector<uint32_t> preOrder(shallowToDeep);
std::sort(preOrder.begin(),preOrder.end(),[&vals](size_t a, size_t b) -> bool { return IntPathSortPreOrder<uint32_t>{}(vals[a],vals[b]); });
Tree16_3 tree1;
Tree16_3 tree2;
Tree16_3 tree3;
addToTreeMove(tree1, vals, preOrder);
addToTreeMove(tree2, vals, preOrder);
addToTreeMove(tree3, vals, preOrder);
auto leader1 = tree1.cursor();
auto follower = tree2.cursor();
auto leader2 = tree3.cursor();
// Check that follower can follow one leader, and then two leaders in pre-order
preOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
preOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
// Check that follower can follow one leader, and then two leaders in post-order
postOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
postOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
// Check that follower can follow one leader, and then two leaders in in-order
inOrderFollow<false, 2>([](const decltype(follower)& f, const decltype(leader1)& L1) {
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1);
while (leader1.canGoParent() || leader2.canGoParent() || follower.canGoParent()) {
leader1.goParent();
leader2.goParent();
follower.goParent();
}
inOrderFollow<false,2>([](const decltype(follower)& f, const decltype(leader1)& L1,
const decltype(leader2)& L2) {
ASSERT_EQ(*(L2.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
ASSERT_EQ(*(L1.nodeValueRO().getPtrRO()), *(f.nodeValueRO().getPtrRO()));
}, follower, leader1, leader2);
}
#endif
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.446483 | 142 | 0.663791 | [
"vector"
] |
09e4f8890c663a0bb243e85e3a8388e10380ec0c | 3,339 | cpp | C++ | VNCpp/jni/src/model/Vnc.cpp | ocrespo/VNCpp | 6efdf40e53ae4a0cf3c0345b66d789ac93ad62d0 | [
"CC-BY-3.0",
"Apache-2.0"
] | 27 | 2015-06-16T12:22:47.000Z | 2021-04-18T07:03:42.000Z | VNCpp/jni/src/model/Vnc.cpp | ocrespo/VNCpp | 6efdf40e53ae4a0cf3c0345b66d789ac93ad62d0 | [
"CC-BY-3.0",
"Apache-2.0"
] | 5 | 2015-09-25T01:27:18.000Z | 2017-01-05T01:09:05.000Z | VNCpp/jni/src/model/Vnc.cpp | ocrespo/VNCpp | 6efdf40e53ae4a0cf3c0345b66d789ac93ad62d0 | [
"CC-BY-3.0",
"Apache-2.0"
] | 23 | 2015-01-04T07:09:04.000Z | 2021-01-01T14:59:30.000Z | /*
Copyright 2013 Oscar Crespo Salazar
Copyright 2013 Gorka Jimeno Garrachon
Copyright 2013 Luis Valero Martin
This file is part of VNCpp.
VNCpp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
VNCpp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VNCpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Vnc.h"
#include <model/screen/ClientScreen.h>
#include <model/comunication/ClientConnectionRFB.h>
#include <model/comunication/HandlerRFB.h>
/**
* @brief The default constructor
* @details The default constructor. Creates the ClientConnectionRFB and ClientScreen objects,
* also sets the screen and the update as true in HandlerRFB
*/
Vnc::Vnc() {
rfb = new ClientConnectionRFB;
screen = new ClientScreen;
HandlerRFB::setScreen(screen);
HandlerRFB::setUpdate(true);
}
/**
* @brief The default destroyer
* @details The default destroyer. Free the password form HandlerRFB and also destroys the ClientConnectionRFB and
* ClientScreen objects
*/
Vnc::~Vnc() {
if(DEBUG){
LOGE("Limpiando vnc");
}
HandlerRFB::freePass();
delete rfb;
delete screen;
}
/**
* @brief Starts the connection
* @param host The IP
* @param port The port
* @param pass The password
* @param quality The image quality
* @param compress the image has to be compress or not
* @param hide_mouse the maouse has to be hide or not
* @return ALLOK if everything ok, or an error
* @details Calls the ClientConnectionRFB method iniConnect to start the connection
*/
ConnectionError Vnc::iniConnection(char *host,int port,char *pass,int quality,int compress,bool hide_mouse){
ConnectionError error = rfb->iniConnection(host,port,pass,quality,compress,hide_mouse);
if(DEBUG)
LOGE("Return inicio de conexion");
return error;
//rfb->eventLoop();
}
/**
* @brief Stops the connection
* @details Calls the ClientConnectionRFB method stopConnection to close the connection
*/
void Vnc::closeConnection(){
rfb->stopConnection();
}
/**
* @brief Adds the observers to screen
* @param observer The Java observer
* @param env The JNI environment at this point
* @details Adds the observer to screen. This allows screen to communicate with Java
*/
void Vnc::addObserver(jobject observer,JNIEnv *env){
screen->addObserver(observer,env);
}
/**
* @brief Sends a mouse event
* @param x The x coordinate
* @param y The y coordinate
* @param event The event
* @return if everything is ok or not
*/
bool Vnc::sendMouseEvent(int x,int y,MouseEvent event){
return rfb->sendMouseEvent(x,y,event);
}
/**
* @brief Sends a key event
* @param key The key
* @param down The key is down or not
* @return If everything is ok or not
*/
bool Vnc::sendKeyEvent(int key,bool down){
return rfb->sendKeyEvent(key,down);
}
/**
* @brief Sets the update
* @param update update or not
* @details Sets the update to HandlerRFB
*/
void Vnc::setUpdate(bool update){
HandlerRFB::setUpdate(update);
}
| 27.368852 | 114 | 0.739443 | [
"model"
] |
09ee90040aecf672f92d8a8b77d6afb067594c08 | 1,260 | cpp | C++ | competition/fuzhou3.2.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | competition/fuzhou3.2.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | competition/fuzhou3.2.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
#include <cctype>
#include <vector>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
const double eps = 1e-8;
const int maxn = 100000 + 100;
const int MOD = 1e9 + 7;
int N, K;
ll cuo[10010];
ll C[10010];
void quancuo()
{
int i, j;
cuo[0] = 1;
cuo[1] = 0;
cuo[2] = 1;
for (i = 3; i <= 10000; i++)
{
cuo[i] = ((cuo[i - 1] + cuo[i - 2]) % MOD) * (i - 1) % MOD;
}
}
ll Extend_Euclid(ll a, ll b, ll&x, ll& y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
ll d = Extend_Euclid(b, a%b, x, y);
ll t = x;
x = y;
y = t - a / b*y;
return d;
}
//a在模n乘法下的逆元,没有则返回-1
ll inv(ll a, ll n)
{
ll x, y;
ll t = Extend_Euclid(a, n, x, y);
if (t != 1)
return -1;
return (x%n + n) % n;
}
void getC(ll n)
{
ll i, j, k;
C[0] = 1;
C[1] = n;
for (i = 2; i <= n; i++)
{
C[i] = C[i - 1] * (n - i + 1) % MOD * inv(i, MOD) % MOD;
}
}
int main()
{
int i, j, k, u, n, m, a, b;
quancuo();
while (scanf("%d", &n) != EOF)
{
for (m = 1; m <= n; m++)
{
scanf("%d %d", &N, &K);
ll res = 0;
getC((ll)N);
for (i = K; i <= N; i++)
{
res = (res + C[i] * cuo[N - i] % MOD) % MOD;
}
printf("%lld\n", res);
}
}
return 0;
} | 15.555556 | 61 | 0.483333 | [
"vector"
] |
09f6edfad87c87da8f3ee2d916692827a97438d7 | 1,168 | cpp | C++ | 2019/0609_ABC129/past/C.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2019/0609_ABC129/past/C.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2019/0609_ABC129/past/C.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | #define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/9/2019, 9:04:45 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
const ll MOD = 1000000007;
int N, M;
bool ok[100010];
ll dp[100010];
int main()
{
cin >> N >> M;
fill(ok, ok + 100010, true);
for (auto i = 0; i < M; i++)
{
int a;
cin >> a;
ok[a] = false;
}
dp[0] = 1;
for (auto i = 0; i < N; i++)
{
if (ok[i + 1])
{
dp[i + 1] += dp[i];
dp[i + 1] %= MOD;
}
if (ok[i + 2])
{
dp[i + 2] += dp[i];
dp[i + 2] %= MOD;
}
}
cout << dp[N] << endl;
} | 14.072289 | 33 | 0.527397 | [
"vector"
] |
e2503f4cb4866ef3dbd35a228f24e03ea9604f6b | 982 | cpp | C++ | test/util/shift_to_value_test.cpp | jkomyno/jkds | 94ffdf3e1f1cf7a413756a7096c749e675ca7b0a | [
"MIT"
] | 3 | 2022-02-12T18:47:51.000Z | 2022-02-15T08:59:21.000Z | test/util/shift_to_value_test.cpp | jkomyno/jkds | 94ffdf3e1f1cf7a413756a7096c749e675ca7b0a | [
"MIT"
] | null | null | null | test/util/shift_to_value_test.cpp | jkomyno/jkds | 94ffdf3e1f1cf7a413756a7096c749e675ca7b0a | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <jkds/util/shift_to_value.h>
#include <cstdint>
#include <vector>
using namespace std;
namespace {
class ShiftToValueTest : public ::testing::Test {
};
} // namespace
TEST_F(ShiftToValueTest, distinct) {
std::vector<uint8_t> vec{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
EXPECT_EQ(vec.size(), 10);
jkds::util::shift_to_value(vec, 5);
EXPECT_EQ(vec.size(), 10);
EXPECT_EQ(vec, std::vector<uint8_t>({5, 6, 7, 8, 9, 0, 1, 2, 3, 4}));
}
TEST_F(ShiftToValueTest, repeated_selects_first) {
std::vector<uint8_t> vec{0, 10, 10, 10, 20};
EXPECT_EQ(vec.size(), 5);
jkds::util::shift_to_value(vec, 10);
EXPECT_EQ(vec.size(), 5);
EXPECT_EQ(vec, std::vector<uint8_t>({10, 10, 10, 20, 0}));
}
TEST_F(ShiftToValueTest, not_found) {
std::vector<uint8_t> vec{0, 10, 10, 10, 20};
EXPECT_EQ(vec.size(), 5);
jkds::util::shift_to_value(vec, 1);
EXPECT_EQ(vec.size(), 5);
EXPECT_EQ(vec, std::vector<uint8_t>({0, 10, 10, 10, 20}));
}
| 22.318182 | 71 | 0.644603 | [
"vector"
] |
e26616428be2fc5db27671954a86b6e8adf7972c | 1,245 | cc | C++ | stapl_release/test/containers/graph/out_of_core.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/graph/out_of_core.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/graph/out_of_core.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#include <stapl/runtime.hpp>
#include <stapl/utility/do_once.hpp>
#include <stapl/containers/graph/out_of_core_graph.hpp>
#include <stapl/containers/graph/views/graph_view.hpp>
#include <stapl/containers/graph/algorithms/graph_io.hpp>
#include <stapl/containers/graph/generators/mesh.hpp>
#include <stapl/algorithms/algorithm.hpp>
#include <stapl/containers/array/array.hpp>
#include <boost/lexical_cast.hpp>
#include <stapl/runtime/counter/default_counters.hpp>
#include <vector>
#include <algorithm>
#include "test_util.h"
using namespace stapl;
stapl::exit_code stapl_main(int argc, char* argv[])
{
size_t n = 128;
size_t blk_sz = 32;
if (argc > 1) {
n = atoi(argv[1]);
}
one_print("Testing Out-of-Core Graph Construction...\t\t");
out_of_core_graph<DIRECTED, MULTIEDGES, int, int> g(n, blk_sz);
one_print(g.size() == n);
return EXIT_SUCCESS;
}
| 27.666667 | 74 | 0.742972 | [
"mesh",
"vector"
] |
e26ac46e1029a2da573d16bcc382f8a6465ed2d2 | 518 | cpp | C++ | 4/src/ReadFileAction.cpp | AlinaNenasheva/operating-systems | 9f04381945aa7870dff9616b45c6d07e96701bd7 | [
"MIT"
] | null | null | null | 4/src/ReadFileAction.cpp | AlinaNenasheva/operating-systems | 9f04381945aa7870dff9616b45c6d07e96701bd7 | [
"MIT"
] | null | null | null | 4/src/ReadFileAction.cpp | AlinaNenasheva/operating-systems | 9f04381945aa7870dff9616b45c6d07e96701bd7 | [
"MIT"
] | null | null | null | #pragma once
#include "Action.cpp"
#include "ActionResult.cpp"
using namespace std;
#define READ_FILE_ARGUMENTS_NUMBER 1
class ReadFileAction : public Action {
public:
ReadFileAction(const vector<string> &arguments, const FileSystemService &service) : Action(arguments, service) {}
ActionResult *execute() override {
string path = getArguments().front();
return getService().readFile(path);
}
int getArgumentsNumber() override {
return READ_FILE_ARGUMENTS_NUMBER;
}
}; | 23.545455 | 117 | 0.712355 | [
"vector"
] |
e26fff477c036fba478734da27352503f607424a | 2,524 | cpp | C++ | projects/PolyhedralModel/projects/spmd-generator/compute-systems/array-system.cpp | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 4 | 2017-12-19T17:15:00.000Z | 2021-02-05T12:25:50.000Z | projects/PolyhedralModel/projects/spmd-generator/compute-systems/array-system.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | null | null | null | projects/PolyhedralModel/projects/spmd-generator/compute-systems/array-system.cpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 2 | 2019-02-19T01:27:51.000Z | 2019-02-19T12:29:49.000Z |
#include "compute-systems/array-system.hpp"
#include <cassert>>
ArraySystem::ArraySystem(
std::vector<unsigned> dimensions_,
ComputeSystem * element,
Memory * shared_,
Link * interconnect_,
ComputeSystem * parent
) :
ComputeSystem(parent),
dimensions(dimensions_),
array(NULL),
shared(shared_),
interconnect(interconnect_)
{
assert(element != NULL); // FIXME may be authorize later
unsigned long nbr_elem = 1;
for (int i = 0; i < dimensions.size(); i++) nbr_elem *= dimensions[i];
array = new ComputeSystem*[nbr_elem];
array[0] = element;
array[0]->setParent(this);
for (unsigned long i = 1; i < nbr_elem; i++) {
if (element != NULL) {
array[i] = element->copy();
array[i]->setParent(this);
}
else
array[i] = NULL;
}
}
ArraySystem::ArraySystem(const ArraySystem & arg) :
ComputeSystem(arg.parent),
dimensions(arg.dimensions),
array(NULL),
shared(arg.shared == NULL ? NULL : arg.shared->copy()),
interconnect(arg.interconnect == NULL ? NULL : arg.interconnect->copy())
{
unsigned long nbr_elem = 1;
for (unsigned i = 0; i < dimensions.size(); i++) nbr_elem *= dimensions[i];
array = new ComputeSystem*[nbr_elem];
for (unsigned long i = 0; i < nbr_elem; i++) {
assert(arg.array[i] != NULL); // FIXME may be authorized later
if (arg.array[i] == NULL) {
array[i] = arg.array[i]->copy();
array[i]->setParent(this);
}
else
array[i] = NULL;
}
}
ArraySystem::~ArraySystem() {
if (shared != NULL) delete shared;
if (interconnect != NULL) delete interconnect;
if (array != NULL) {
unsigned long nbr_elem = 1;
for (unsigned i = 0; i < dimensions.size(); i++) nbr_elem *= dimensions[i];
for (unsigned long i = 0; i < nbr_elem; i++)
if (array[i] != NULL)
delete array[i];
delete array;
}
}
std::vector<unsigned> ArraySystem::getPosition(ComputeSystem * element) const {
unsigned long nbr_elem = 1;
for (unsigned i = 0; i < dimensions.size(); i++) nbr_elem *= dimensions[i];
unsigned long pos = 0;
for (pos = 0; pos < nbr_elem; pos++)
if (array[pos] == element)
break;
assert(pos < nbr_elem);
std::vector<unsigned> res(dimensions.size(), 0);
assert(false); // TODO
return res;
}
Link * ArraySystem::getLink(ComputeSystem * cs1, ComputeSystem * cs2) const {
assert(false); // TODO
return NULL;
}
Memory * ArraySystem::getSharedMemory() const { return shared; }
Link * ArraySystem::getInterconnect() const { return interconnect; }
| 24.745098 | 79 | 0.637876 | [
"vector"
] |
e2811aa824afb961081f088002000a533f0eb36d | 1,533 | cpp | C++ | main.cpp | AceCoooool/MiniSTL | 786421ad81d7d0a5acaf0f753c5993287f6f83ca | [
"MIT"
] | null | null | null | main.cpp | AceCoooool/MiniSTL | 786421ad81d7d0a5acaf0f753c5993287f6f83ca | [
"MIT"
] | null | null | null | main.cpp | AceCoooool/MiniSTL | 786421ad81d7d0a5acaf0f753c5993287f6f83ca | [
"MIT"
] | null | null | null | #include <iostream>
#include "Allocator/test_allocator.h"
#include "Sequence/Vector/test_vector.h"
#include "Sequence/List/test_list.h"
#include "Sequence/Deque/test_deque.h"
#include "Sequence/Stack/test_stack.h"
#include "Sequence/Queue/test_queue.h"
#include "Sequence/Slist/test_slist.h"
#include "Sequence/Priority_Queue/test_priority_queue.h"
#include "Algorithm/Numeric/test_numeric.h"
#include "Algorithm/Algobase/test_algobase.h"
#include "Algorithm/Heap/test_heap.h"
#include "Algorithm/Algo/test_algo.h"
#include "Functor/test_function.h"
#include "Iterator/test_iterator.h"
#include "Associative/Set/test_set.h"
#include "Associative/Map/test_map.h"
#include "Associative/Multiset/test_multiset.h"
#include "Associative/Multimap/test_multimap.h"
#include "Associative/Hashtable/test_hash.h"
#include "Associative/Hashset/test_hash_set.h"
#include "Associative/Hashmap/test_hash_map.h"
using namespace MiniSTL;
int main() {
// test_allocator();
// test_uninitialized();
// test_vector();
// test_list();
// test_deque();
// test_stack();
// test_queue();
// test_priority_queue();
// test_slist();
// test_algo1();
// test_algo2();
// test_numeric();
// test_algobase();
// test_heap();
// test_functor();
// test_iterator_adapters();
// test_function_adapters();
// test_set();
// test_map();
// test_multiset();
// test_multimap();
// test_hash();
// test_hast_set();
// test_hast_multiset();
// test_hash_map();
test_hash_multimap();
} | 27.375 | 56 | 0.710372 | [
"vector"
] |
e292309a1bca3da2ea75f00c4c3ba708c686a472 | 16,829 | hxx | C++ | main/sc/source/filter/inc/xcl97rec.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/filter/inc/xcl97rec.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/filter/inc/xcl97rec.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
#ifndef SC_XCL97REC_HXX
#define SC_XCL97REC_HXX
#include "excrecds.hxx"
#include "xcl97esc.hxx"
#include "xlstyle.hxx"
// ============================================================================
class XclObj;
class XclExpMsoDrawing;
class XclExpObjList : public List, public ExcEmptyRec, protected XclExpRoot
{
public:
explicit XclExpObjList( const XclExpRoot& rRoot, XclEscherEx& rEscherEx );
virtual ~XclExpObjList();
XclObj* First() { return (XclObj*) List::First(); }
XclObj* Next() { return (XclObj*) List::Next(); }
/// return: 1-based ObjId
///! count>=0xFFFF: Obj will be deleted, return 0
sal_uInt16 Add( XclObj* );
inline XclExpMsoDrawing* GetMsodrawingPerSheet() { return pMsodrawingPerSheet; }
/// close groups and DgContainer opened in ctor
void EndSheet();
virtual void Save( XclExpStream& rStrm );
private:
XclEscherEx& mrEscherEx;
XclExpMsoDrawing* pMsodrawingPerSheet;
XclExpMsoDrawing* pSolverContainer;
};
// --- class XclObj --------------------------------------------------
class XclTxo;
class SdrTextObj;
class XclObj : public XclExpRecord
{
protected:
XclEscherEx& mrEscherEx;
XclExpMsoDrawing* pMsodrawing;
XclExpMsoDrawing* pClientTextbox;
XclTxo* pTxo;
sal_uInt16 mnObjType;
sal_uInt16 nObjId;
sal_uInt16 nGrbit;
sal_Bool bFirstOnSheet;
bool mbOwnEscher; /// true = Escher part created on the fly.
/** @param bOwnEscher If set to true, this object will create its escher data.
See SetOwnEscher() for details. */
explicit XclObj( XclExpObjectManager& rObjMgr, sal_uInt16 nObjType, bool bOwnEscher = false );
void ImplWriteAnchor( const XclExpRoot& rRoot, const SdrObject* pSdrObj, const Rectangle* pChildAnchor );
// overwritten for writing MSODRAWING record
virtual void WriteBody( XclExpStream& rStrm );
virtual void WriteSubRecs( XclExpStream& rStrm );
void SaveTextRecs( XclExpStream& rStrm );
public:
virtual ~XclObj();
inline sal_uInt16 GetObjType() const { return mnObjType; }
inline void SetId( sal_uInt16 nId ) { nObjId = nId; }
inline void SetLocked( sal_Bool b )
{ b ? nGrbit |= 0x0001 : nGrbit &= ~0x0001; }
inline void SetPrintable( sal_Bool b )
{ b ? nGrbit |= 0x0010 : nGrbit &= ~0x0010; }
inline void SetAutoFill( sal_Bool b )
{ b ? nGrbit |= 0x2000 : nGrbit &= ~0x2000; }
inline void SetAutoLine( sal_Bool b )
{ b ? nGrbit |= 0x4000 : nGrbit &= ~0x4000; }
// set corresponding Excel object type in OBJ/ftCmo
void SetEscherShapeType( sal_uInt16 nType );
inline void SetEscherShapeTypeGroup() { mnObjType = EXC_OBJTYPE_GROUP; }
/** If set to true, this object has created its own escher data.
@descr This causes the function EscherEx::EndShape() to not post process
this object. This is used i.e. for form controls. They are not handled in
the svx base code, so the XclExpEscherOcxCtrl c'tor creates the escher data
itself. The svx base code does not receive the correct shape ID after the
EscherEx::StartShape() call, which would result in deleting the object in
EscherEx::EndShape(). */
inline void SetOwnEscher( bool bOwnEscher = true ) { mbOwnEscher = bOwnEscher; }
/** Returns true, if the object has created the escher data itself.
@descr See SetOwnEscher() for details. */
inline bool IsOwnEscher() const { return mbOwnEscher; }
//! actually writes ESCHER_ClientTextbox
void SetText( const XclExpRoot& rRoot, const SdrTextObj& rObj );
virtual void Save( XclExpStream& rStrm );
};
// --- class XclObjComment -------------------------------------------
class XclObjComment : public XclObj
{
public:
XclObjComment( XclExpObjectManager& rObjMgr,
const Rectangle& rRect, const EditTextObject& rEditObj, SdrObject* pCaption, bool bVisible );
virtual ~XclObjComment();
/** c'tor process for formatted text objects above .
@descr used to construct the MSODRAWING Escher object properties. */
void ProcessEscherObj( const XclExpRoot& rRoot,
const Rectangle& rRect, SdrObject* pCaption, bool bVisible );
virtual void Save( XclExpStream& rStrm );
};
// --- class XclObjDropDown ------------------------------------------
class XclObjDropDown : public XclObj
{
private:
sal_Bool bIsFiltered;
virtual void WriteSubRecs( XclExpStream& rStrm );
protected:
public:
XclObjDropDown( XclExpObjectManager& rObjMgr, const ScAddress& rPos, sal_Bool bFilt );
virtual ~XclObjDropDown();
};
// --- class XclTxo --------------------------------------------------
class SdrTextObj;
class XclTxo : public ExcRecord
{
public:
XclTxo( const String& rString, sal_uInt16 nFontIx = EXC_FONT_APP );
XclTxo( const XclExpRoot& rRoot, const SdrTextObj& rEditObj );
XclTxo( const XclExpRoot& rRoot, const EditTextObject& rEditObj, SdrObject* pCaption );
inline void SetHorAlign( sal_uInt8 nHorAlign ) { mnHorAlign = nHorAlign; }
inline void SetVerAlign( sal_uInt8 nVerAlign ) { mnVerAlign = nVerAlign; }
virtual void Save( XclExpStream& rStrm );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
private:
virtual void SaveCont( XclExpStream& rStrm );
private:
XclExpStringRef mpString; /// Text and formatting data.
sal_uInt16 mnRotation; /// Text rotation.
sal_uInt8 mnHorAlign; /// Horizontal alignment.
sal_uInt8 mnVerAlign; /// Vertical alignment.
};
// --- class XclObjOle -----------------------------------------------
class XclObjOle : public XclObj
{
private:
const SdrObject& rOleObj;
SotStorage* pRootStorage;
virtual void WriteSubRecs( XclExpStream& rStrm );
public:
XclObjOle( XclExpObjectManager& rObjMgr, const SdrObject& rObj );
virtual ~XclObjOle();
virtual void Save( XclExpStream& rStrm );
};
// --- class XclObjAny -----------------------------------------------
class XclObjAny : public XclObj
{
private:
virtual void WriteSubRecs( XclExpStream& rStrm );
public:
XclObjAny( XclExpObjectManager& rObjMgr );
virtual ~XclObjAny();
virtual void Save( XclExpStream& rStrm );
};
// --- class ExcBof8_Base --------------------------------------------
class ExcBof8_Base : public ExcBof_Base
{
protected:
sal_uInt32 nFileHistory; // bfh
sal_uInt32 nLowestBiffVer; // sfo
virtual void SaveCont( XclExpStream& rStrm );
public:
ExcBof8_Base();
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
};
// --- class ExcBofW8 ------------------------------------------------
// Header Record fuer WORKBOOKS
class ExcBofW8 : public ExcBof8_Base
{
public:
ExcBofW8();
};
// --- class ExcBof8 -------------------------------------------------
// Header Record fuer WORKSHEETS
class ExcBof8 : public ExcBof8_Base
{
public:
ExcBof8();
};
// --- class ExcBundlesheet8 -----------------------------------------
class ExcBundlesheet8 : public ExcBundlesheetBase
{
private:
String sUnicodeName;
XclExpString GetName() const;
virtual void SaveCont( XclExpStream& rStrm );
public:
ExcBundlesheet8( RootData& rRootData, SCTAB nTab );
ExcBundlesheet8( const String& rString );
virtual sal_Size GetLen() const;
virtual void SaveXml( XclExpXmlStream& rStrm );
};
// --- class XclObproj -----------------------------------------------
class XclObproj : public ExcRecord
{
public:
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
};
// ---- class XclCodename --------------------------------------------
class XclCodename : public ExcRecord
{
private:
XclExpString aName;
virtual void SaveCont( XclExpStream& rStrm );
public:
XclCodename( const String& );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
};
// ---- Scenarios ----------------------------------------------------
// - ExcEScenarioCell a cell of a scenario range
// - ExcEScenario all ranges of a scenario table
// - ExcEScenarioManager list of scenario tables
class ExcEScenarioCell
{
private:
sal_uInt16 nCol;
sal_uInt16 nRow;
XclExpString sText;
protected:
public:
ExcEScenarioCell( sal_uInt16 nC, sal_uInt16 nR, const String& rTxt );
inline sal_Size GetStringBytes()
{ return sText.GetSize(); }
void WriteAddress( XclExpStream& rStrm );
void WriteText( XclExpStream& rStrm );
void SaveXml( XclExpXmlStream& rStrm );
};
class ExcEScenario : public ExcRecord, private List
{
private:
sal_Size nRecLen;
XclExpString sName;
XclExpString sComment;
XclExpString sUserName;
sal_uInt8 nProtected;
inline ExcEScenarioCell* _First() { return (ExcEScenarioCell*) List::First(); }
inline ExcEScenarioCell* _Next() { return (ExcEScenarioCell*) List::Next(); }
sal_Bool Append( sal_uInt16 nCol, sal_uInt16 nRow, const String& rTxt );
virtual void SaveCont( XclExpStream& rStrm );
protected:
public:
ExcEScenario( const XclExpRoot& rRoot, SCTAB nTab );
virtual ~ExcEScenario();
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
virtual void SaveXml( XclExpXmlStream& rStrm );
};
class ExcEScenarioManager : public ExcRecord, private List
{
private:
sal_uInt16 nActive;
inline ExcEScenario* _First() { return (ExcEScenario*) List::First(); }
inline ExcEScenario* _Next() { return (ExcEScenario*) List::Next(); }
inline void Append( ExcEScenario* pScen )
{ List::Insert( pScen, LIST_APPEND ); }
virtual void SaveCont( XclExpStream& rStrm );
protected:
public:
ExcEScenarioManager( const XclExpRoot& rRoot, SCTAB nTab );
virtual ~ExcEScenarioManager();
virtual void Save( XclExpStream& rStrm );
virtual void SaveXml( XclExpXmlStream& rStrm );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
};
// ============================================================================
/** Represents a SHEETPROTECTION record that stores sheet protection
options. Note that a sheet still needs to save its sheet protection
options even when it's not protected. */
class XclExpSheetProtectOptions : public XclExpRecord
{
public:
explicit XclExpSheetProtectOptions( const XclExpRoot& rRoot, SCTAB nTab );
private:
virtual void WriteBody( XclExpStream& rStrm );
private:
sal_uInt16 mnOptions; /// Encoded sheet protection options.
};
// ============================================================================
class XclCalccount : public ExcRecord
{
private:
sal_uInt16 nCount;
protected:
virtual void SaveCont( XclExpStream& rStrm );
public:
XclCalccount( const ScDocument& );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
virtual void SaveXml( XclExpXmlStream& rStrm );
};
class XclIteration : public ExcRecord
{
private:
sal_uInt16 nIter;
protected:
virtual void SaveCont( XclExpStream& rStrm );
public:
XclIteration( const ScDocument& );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
virtual void SaveXml( XclExpXmlStream& rStrm );
};
class XclDelta : public ExcRecord
{
private:
double fDelta;
protected:
virtual void SaveCont( XclExpStream& rStrm );
public:
XclDelta( const ScDocument& );
virtual sal_uInt16 GetNum() const;
virtual sal_Size GetLen() const;
virtual void SaveXml( XclExpXmlStream& rStrm );
};
class XclRefmode : public XclExpBoolRecord
{
public:
XclRefmode( const ScDocument& );
virtual void SaveXml( XclExpXmlStream& rStrm );
};
// ============================================================================
class XclExpFileEncryption : public XclExpRecord
{
public:
explicit XclExpFileEncryption( const XclExpRoot& rRoot );
virtual ~XclExpFileEncryption();
private:
virtual void WriteBody( XclExpStream& rStrm );
private:
const XclExpRoot& mrRoot;
};
// ============================================================================
/** Beginning of User Interface Records */
class XclExpInterfaceHdr : public XclExpUInt16Record
{
public:
explicit XclExpInterfaceHdr( sal_uInt16 nCodePage );
private:
virtual void WriteBody( XclExpStream& rStrm );
};
// ============================================================================
/** End of User Interface Records */
class XclExpInterfaceEnd : public XclExpRecord
{
public:
explicit XclExpInterfaceEnd();
virtual ~XclExpInterfaceEnd();
private:
virtual void WriteBody( XclExpStream& rStrm );
};
// ============================================================================
/** Write Access User Name - This record contains the user name, which is
the name you type when you install Excel. */
class XclExpWriteAccess : public XclExpRecord
{
public:
explicit XclExpWriteAccess();
virtual ~XclExpWriteAccess();
private:
virtual void WriteBody( XclExpStream& rStrm );
};
// ============================================================================
class XclExpFileSharing : public XclExpRecord
{
public:
explicit XclExpFileSharing( const XclExpRoot& rRoot, sal_uInt16 nPasswordHash, bool bRecommendReadOnly );
virtual void Save( XclExpStream& rStrm );
private:
virtual void WriteBody( XclExpStream& rStrm );
private:
XclExpString maUserName;
sal_uInt16 mnPasswordHash;
bool mbRecommendReadOnly;
};
// ============================================================================
class XclExpProt4Rev : public XclExpRecord
{
public:
explicit XclExpProt4Rev();
virtual ~XclExpProt4Rev();
private:
virtual void WriteBody( XclExpStream& rStrm );
};
// ============================================================================
class XclExpProt4RevPass : public XclExpRecord
{
public:
explicit XclExpProt4RevPass();
virtual ~XclExpProt4RevPass();
private:
virtual void WriteBody( XclExpStream& rStrm );
};
// ============================================================================
class XclExpRecalcId : public XclExpDummyRecord
{
public:
explicit XclExpRecalcId();
};
// ============================================================================
class XclExpBookExt : public XclExpDummyRecord
{
public:
explicit XclExpBookExt();
};
#endif // _XCL97REC_HXX
| 28.572156 | 132 | 0.576267 | [
"object",
"shape"
] |
e29f00b6bf692301174baade0b573995ea9fa71b | 296 | cc | C++ | primer-answer/chapter10/10.37.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | 1 | 2018-02-23T11:12:17.000Z | 2018-02-23T11:12:17.000Z | primer-answer/chapter10/10.37.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | primer-answer/chapter10/10.37.cc | Becavalier/playground-cpp | 0fce453f769111698f813852238f933e326ed441 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main (int argc, char **argv) {
vector<int> l{0, 1, 2, 3, 4, 0, 1, 3, 4, 5}, r(5);
copy(l.rbegin() + 3, l.rend() - 2, r.begin());
for (auto e : r) {
cout << e << endl;
}
return 0;
} | 18.5 | 54 | 0.52027 | [
"vector"
] |
e2aa80c9687aa1f8ed8b1718166c99587904d22f | 2,182 | cpp | C++ | UVA/ProjectScheduling.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 1 | 2018-08-28T19:58:40.000Z | 2018-08-28T19:58:40.000Z | UVA/ProjectScheduling.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 2 | 2017-04-16T00:48:05.000Z | 2017-08-03T20:12:26.000Z | UVA/ProjectScheduling.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 4 | 2016-03-04T19:42:00.000Z | 2018-01-08T11:42:00.000Z | #include <bits/stdc++.h>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }
using namespace std;
typedef long long Int;
typedef unsigned uint;
const int INF = INT_MAX / 3;
int T;
string S;
bool vis[30], seen[30];
int cost[30];
vector<int> graph[30];
vector<int> order;
vector<string> split(string st) {
vector<string> ans;
istringstream ss(st);
string buff;
for ( ; ss >> buff; ) {
ans.push_back(buff);
}
return ans;
}
void dfs(int x) {
vis[x] = true;
for (auto& i: graph[x]) {
if (!vis[i]) {
dfs(i);
}
}
order.push_back(x);
}
int dp[30];
int func(int id) {
if (graph[id].empty()) {
return cost[id];
} else {
int& ans = dp[id];
if (ans == -1) {
ans = cost[id];
for (auto& i: graph[id]) {
chmax(ans, cost[id] + func(i));
}
}
return ans;
}
}
int main(void) {
cin >> T;
getline(cin, S);
getline(cin, S);
for ( ; T--; ) {
order.clear();
for (int i = 0; i < 30; i++) {
cost[i] = 0;
dp[i] = -INF;
vis[i] = seen[i] = false;
graph[i].clear();
}
while (getline(cin, S) && S != "") {
vector<string> vs = split(S);
if (vs.empty()) break;
int id = vs[0][0] - 'A';
seen[id] = true;
cost[id] = stoi(vs[1]);
if (vs.size() > 2) {
for (auto& i: vs[2]) {
graph[i - 'A'].push_back(id);
}
}
}
for (int i = 0; i < 26; i++) {
if (!vis[i] && seen[i]) {
dfs(i);
}
}
reverse(order.begin(), order.end());
memset(dp, -1, sizeof(dp));
for (auto& i: order) {
dp[i] = cost[i];
}
dp[order[0]] = cost[order[0]];
for (int i = 0; i < order.size(); i++) {
int u = order[i];
for (int j = 0; j < (int) graph[u].size(); j++) {
int v = graph[u][j];
if (dp[v] < dp[u] + cost[v]) {
dp[v] = dp[u] + cost[v];
}
}
}
int ans = *max_element(dp, dp + 30);
cout << ans << "\n";
if (T != 0) cout << "\n";
}
return 0;
}
| 15.811594 | 67 | 0.491292 | [
"vector"
] |
e2aef761c454771e4ee9bf87077b4e4c55774c94 | 5,217 | cpp | C++ | alienfx-haptics/kiss_fft/tools/kiss_fftr.cpp | Hellohi3654/alienfx-tools | 46a2918aa07a5c2362be2ec06547d3f2c16798bb | [
"MIT"
] | 55 | 2020-07-24T13:50:59.000Z | 2022-03-31T02:15:09.000Z | alienfx-haptics/kiss_fft/tools/kiss_fftr.cpp | Hellohi3654/alienfx-tools | 46a2918aa07a5c2362be2ec06547d3f2c16798bb | [
"MIT"
] | 41 | 2020-07-25T14:37:25.000Z | 2022-03-28T02:36:15.000Z | alienfx-haptics/kiss_fft/tools/kiss_fftr.cpp | Hellohi3654/alienfx-tools | 46a2918aa07a5c2362be2ec06547d3f2c16798bb | [
"MIT"
] | 9 | 2020-12-24T05:19:35.000Z | 2022-03-30T01:52:32.000Z | /*
Copyright (c) 2003, Mark Borgerding
All rights reserved.
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.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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.
*/
#include "../_kiss_fft_guts.h"
typedef struct {
int minus3; /*magic to signify a 1-d real transform*/
kiss_fft_state * substate;
kiss_fft_cpx * tmpbuf;
kiss_fft_cpx * super_twiddles;
}kiss_fftr_state;
void * kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem)
{
int i;
kiss_fftr_state *st = NULL;
size_t subsize, memneeded;
if (nfft & 1) {
fprintf(stderr,"Real FFT optimization must be even.\n");
return NULL;
}
nfft >>= 1;
kiss_fft_alloc (nfft, inverse_fft, NULL, &subsize);
memneeded = sizeof(kiss_fftr_state) + subsize + sizeof(kiss_fft_cpx) * ( nfft * 2);
if (lenmem == NULL) {
st = (kiss_fftr_state *) malloc (memneeded);
} else {
if (*lenmem >= memneeded)
st = (kiss_fftr_state *) mem;
*lenmem = memneeded;
}
if (!st)
return NULL;
st->minus3 = -3;
st->substate = (kiss_fft_state *) (st + 1); /*just beyond kiss_fftr_state struct */
st->tmpbuf = (kiss_fft_cpx *) (((char *) st->substate) + subsize);
st->super_twiddles = st->tmpbuf + nfft;
kiss_fft_alloc(nfft, inverse_fft, st->substate, &subsize);
for (i = 0; i < nfft; ++i) {
double phase =
-3.14159265358979323846264338327 * ((double) i / nfft + .5);
if (inverse_fft)
phase *= -1;
st->super_twiddles[i] = kf_cexp (phase);
}
return st;
}
void kiss_fftr(const void * cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata)
{
/* input buffer timedata is stored row-wise */
kiss_fftr_state *st = ( kiss_fftr_state *)cfg;
int k,N;
if ( st->minus3 != -3 || st->substate->inverse) {
fprintf(stderr,"kiss fft usage error: improper alloc\n");
exit(1);
}
N = st->substate->nfft;
/*perform the parallel fft of two real signals packed in real,imag*/
kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, st->tmpbuf );
freqdata[0].r = st->tmpbuf[0].r + st->tmpbuf[0].i;
freqdata[0].i = 0;
C_FIXDIV(freqdata[0],2);
for (k=1;k <= N/2 ; ++k ) {
kiss_fft_cpx fpnk,fpk,f1k,f2k,tw;
fpk = st->tmpbuf[k];
fpnk.r = st->tmpbuf[N-k].r;
fpnk.i = -st->tmpbuf[N-k].i;
C_FIXDIV(fpk,2);
C_FIXDIV(fpnk,2);
C_ADD( f1k, fpk , fpnk );
C_SUB( f2k, fpk , fpnk );
C_MUL( tw , f2k , st->super_twiddles[k]);
C_ADD( freqdata[k] , f1k ,tw);
freqdata[k].r = (f1k.r + tw.r) / 2;
freqdata[k].i = (f1k.i + tw.i) / 2;
freqdata[N-k].r = (f1k.r - tw.r)/2;
freqdata[N-k].i = - (f1k.i - tw.i)/2;
}
freqdata[N].r = st->tmpbuf[0].r - st->tmpbuf[0].i;
freqdata[N].i = 0;
C_FIXDIV(freqdata[N],2);
}
void kiss_fftri(const void * cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata)
{
/* input buffer timedata is stored row-wise */
kiss_fftr_state *st = (kiss_fftr_state *) cfg;
int k, N;
if (st->minus3 != -3 || st->substate->inverse == 0) {
fprintf (stderr, "kiss fft usage error: improper alloc\n");
exit (1);
}
N = st->substate->nfft;
st->tmpbuf[0].r = freqdata[0].r + freqdata[N].r;
st->tmpbuf[0].i = freqdata[0].r - freqdata[N].r;
for (k = 1; k <= N / 2; ++k) {
kiss_fft_cpx fk, fnkc, fek, fok, tmpbuf;
fk = freqdata[k];
fnkc.r = freqdata[N - k].r;
fnkc.i = -freqdata[N - k].i;
C_ADD (fek, fk, fnkc);
C_SUB (tmpbuf, fk, fnkc);
C_MUL (fok, tmpbuf, st->super_twiddles[k]);
C_ADD (st->tmpbuf[k], fek, fok);
C_SUB (st->tmpbuf[N - k], fek, fok);
st->tmpbuf[N - k].i *= -1;
}
kiss_fft (st->substate, st->tmpbuf, (kiss_fft_cpx *) timedata);
}
| 37 | 754 | 0.631589 | [
"transform"
] |
e2af729dc11ec879f7357452b7e632a81ce3277e | 1,329 | hh | C++ | src/plugin/graphics/nullrender/include/nullrenderer.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/nullrender/include/nullrenderer.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/nullrender/include/nullrenderer.hh | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | /* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#ifndef MOTOR_NULLRENDER_RENDERER_HH_
#define MOTOR_NULLRENDER_RENDERER_HH_
/**************************************************************************************************/
#include <stdafx.h>
#include <motor/filesystem/folder.meta.hh>
#include <motor/plugin.graphics.3d/renderer/irenderer.hh>
#include <motor/plugin/plugin.hh>
namespace Motor { namespace Null {
class NullRenderer : public IRenderer
{
MOTOR_NOCOPY(NullRenderer);
public:
NullRenderer(const Plugin::Context& context);
~NullRenderer();
u32 getMaxSimultaneousRenderTargets() const override
{
return 1;
}
void flush() override;
uint2 getScreenSize() const override
{
return make_uint2(1920, 1080);
}
private:
ref< IGPUResource >
create(weak< const RenderSurfaceDescription > renderSurfaceDescription) const override;
ref< IGPUResource >
create(weak< const RenderWindowDescription > renderWindowDescription) const override;
ref< IGPUResource >
create(weak< const ShaderProgramDescription > shaderDescription) const override;
};
}} // namespace Motor::Null
/**************************************************************************************************/
#endif
| 28.891304 | 101 | 0.595184 | [
"3d"
] |
e2af7ae095901563499428404279d4c33c7e165c | 1,041 | hpp | C++ | libs/core/include/fcppt/math/vector/null.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/math/vector/null.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/math/vector/null.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#ifndef FCPPT_MATH_VECTOR_NULL_HPP_INCLUDED
#define FCPPT_MATH_VECTOR_NULL_HPP_INCLUDED
#include <fcppt/math/detail/null_storage.hpp>
#include <fcppt/math/vector/is_vector.hpp>
#include <fcppt/math/vector/static.hpp>
#include <fcppt/type_traits/value_type.hpp>
namespace fcppt::math::vector
{
/**
\brief Returns the null vector
\ingroup fcpptmathvector
*/
template <typename Vector>
fcppt::math::vector::static_<fcppt::type_traits::value_type<Vector>, Vector::static_size::value>
null()
{
static_assert(fcppt::math::vector::is_vector<Vector>::value, "Vector must be a vector");
using result_type = fcppt::math::vector::
static_<fcppt::type_traits::value_type<Vector>, Vector::static_size::value>;
return result_type(fcppt::math::detail::null_storage<typename result_type::storage_type>());
}
}
#endif
| 28.916667 | 96 | 0.75024 | [
"vector"
] |
e2b5e1ff3e4d84f82577b37b9e800c68eb90ac08 | 5,564 | cpp | C++ | cpp/tree.cpp | ianyfan/depccg | dda01a72ad09ee36fb5d626a473cc2a0d267c57b | [
"MIT"
] | null | null | null | cpp/tree.cpp | ianyfan/depccg | dda01a72ad09ee36fb5d626a473cc2a0d267c57b | [
"MIT"
] | null | null | null | cpp/tree.cpp | ianyfan/depccg | dda01a72ad09ee36fb5d626a473cc2a0d267c57b | [
"MIT"
] | null | null | null |
#include "tree.h"
#include "cat.h"
#include "utils.h"
#include <stack>
#include <algorithm>
#include <string>
namespace myccg {
RuleType GetUnaryRuleType(Cat cat) {
return cat->IsForwardTypeRaised() ? FWD_TYPERAISE :
(cat->IsBackwardTypeRaised() ? BWD_TYPERAISE : UNARY);
}
class PrologCatStr: public CatVisitor {
public:
PrologCatStr(Cat cat) { cat->Accept(*this); }
friend std::ostream& operator<<(std::ostream& ost, const PrologCatStr& p) {
ost << p.stack.top();
return ost;
}
std::string Get() { return stack.top(); }
int Visit(const AtomicCategory* cat) {
std::string cstr = cat->ToStrWithoutFeat();
std::transform(cstr.begin(), cstr.end(), cstr.begin(), ::tolower);
if (false) {
} else if (*cat == *CCategory::Parse(".")) {
stack.push("period");
} else if (*cat == *CCategory::Parse(",")) {
stack.push("comma");
} else if (*cat == *CCategory::Parse(":")) {
stack.push("colon");
} else if (*cat == *CCategory::Parse(";")) {
stack.push("semicolon");
} else if (cat->GetFeat()->IsEmpty()) {
stack.push(cstr);
} else {
std::string feat = cat->GetFeat()->ToStr();
stack.push(
cstr + ":" + feat.substr(1, feat.size() - 2));
}
return 0;
}
int Visit(const Functor* cat) {
std::string left, right;
cat->GetLeft()->Accept(*this);
cat->GetRight()->Accept(*this);
right = stack.top();
stack.pop();
left = stack.top();
stack.pop();
stack.push(
"(" + left + cat->GetSlash().ToStr() + right + ")");
return 0;
}
std::stack<std::string> stack;
};
std::string escapeProlog(std::string in) {
if (in.find("'") != std::string::npos)
utils::ReplaceAll(&in, "'", "\\'");
return in;
}
int Prolog::Visit(const Leaf* leaf) {
Cat c = leaf->GetCategory();
Indent();
out_ << "t(" << PrologCatStr(c)
<< ", \'" << escapeProlog(leaf->GetWord())
<< "\', \'{" << position << ".lemma}"
<< "\', \'{" << position << ".pos}"
<< "\', \'{" << position << ".chunk}"
<< "\', \'{" << position << ".entity}\')";
position++;
return 0;
}
// TODO: Fix this
int Prolog::Visit(const CTree* tree) {
bool child = false, arg = false, noise = false, conj2 = false;
Indent();
if (tree->IsUnary()) {
out_ << "lx(";
child = true;
} else {
switch (tree->GetRule()->GetRuleType()) {
case FA: out_ << "fa("; break;
case COORD:
case BA: out_ << "ba("; break;
case FX:
case FC: out_ << "fc("; break;
case BX:
case BC: out_ << "bxc("; break;
case GFC: out_ << "gfc("; break;
case GBC: out_ << "gbx("; break;
case RP: out_ << "rp("; break;
case LP:
case NOISE: out_ << "lx(";
noise = true;
break;
case CONJ: out_ << "conj(";
arg = true;
break;
case CONJ2: out_ << "lx(";
conj2 = true;
break;
default:
out_ << "other(";
}
}
out_ << PrologCatStr(tree->GetCategory()) << ", ";
if (conj2) {
std::string c = PrologCatStr(tree->GetRightChild()->GetCategory()).Get();
out_ << c << "\\" << c << ", ";
out_ << std::endl;
depth++;
Indent();
out_ << "conj(" << c << "\\" << c << ", " << c << ", ";
}
if (noise) {
out_ << PrologCatStr(tree->GetRightChild()->GetCategory()) << ", ";
out_ << std::endl;
depth++;
Indent();
out_ << "lp("
<< PrologCatStr(tree->GetRightChild()->GetCategory()) << ", ";
}
if (child)
out_ << PrologCatStr(tree->GetLeftChild()->GetCategory()) << ", ";
if (arg)
out_ << PrologCatStr(tree->GetCategory()->GetLeft()) << ", ";
out_ << std::endl;
depth++;
tree->GetLeftChild()->Accept(*this);
if (! tree->IsUnary()) {
out_ << "," << std::endl;
tree->GetRightChild()->Accept(*this);
}
out_ << ")";
depth--;
if (conj2 || noise) {
out_ << ")";
depth--;
}
return 0;
}
std::string EnResolveCombinatorName(const Node* parse) {
const CTree* tree;
if ( (tree = dynamic_cast<const CTree*>(parse)) == nullptr )
throw std::runtime_error("This node is leaf and does not have combinator!");
if (tree->IsUnary()) {
Cat init = tree->GetLeftChild()->GetCategory();
if ((init->Matches(CCategory::Parse("NP")) ||
init->Matches(CCategory::Parse("PP")))
&& tree->GetCategory()->IsTypeRaised())
return "tr";
else
return "lex";
}
switch (tree->GetRule()->GetRuleType()) {
case FA: return "fa";
case BA: return "ba";
case FC: return "fc";
case BC: return "bx";
case GFC: return "gfc";
case GBC: return "gbx";
case FX: return "fx";
case BX: return "bx";
case CONJ: return "conj";
case CONJ2: return "conj";
case COORD: return "ba";
case RP: return "rp";
case LP: return "lp";
case NOISE: return "lp";
default:
return "other";
}
}
} // namespace myccg
| 29.284211 | 84 | 0.472502 | [
"transform"
] |
e2c19a36e264e4fbe8e4eebf981c791404cade42 | 655 | cpp | C++ | Physics/Phantom/phantomSphereSimple.cpp | XZelnar/GameEngine | cb28f6046249e77e30d5e3526f9f0a1fe7f3ef8f | [
"MIT"
] | 1 | 2016-10-05T13:58:54.000Z | 2016-10-05T13:58:54.000Z | Physics/Phantom/phantomSphereSimple.cpp | XZelnar/GameEngine | cb28f6046249e77e30d5e3526f9f0a1fe7f3ef8f | [
"MIT"
] | null | null | null | Physics/Phantom/phantomSphereSimple.cpp | XZelnar/GameEngine | cb28f6046249e77e30d5e3526f9f0a1fe7f3ef8f | [
"MIT"
] | null | null | null | #include "phantomSphereSimple.h"
#ifndef NO_HAVOK_PHYSICS
PhantomSphereSimple::PhantomSphereSimple()
{
phantom = null;
radius = 1;
shape = null;
transform.setIdentity();
}
void PhantomSphereSimple::Initialize()
{
shape = new hkpSphereShape(radius);
PhantomShapeSimple::Initialize();
}
void PhantomSphereSimple::Dispose()
{
PhantomShapeSimple::Dispose();
shape->removeReference();
shape = null;
}
void PhantomSphereSimple::SetShape(hkpShape* s)
{
}
void PhantomSphereSimple::SetRadius(float r)
{
radius = r;
if (shape)
{
((hkpSphereShape*)shape)->setRadius(r);
phantom->setShape(shape);
}
}
#endif | 17.236842 | 48 | 0.691603 | [
"shape",
"transform"
] |
e2c301d6e8e03c39c7c89a32518e3e5f36efe59f | 5,185 | cpp | C++ | http_opencv.cpp | phoenixqm/OpenCV-Server | a9cc6900207f064f51c0cfad7e37494e76619090 | [
"MIT"
] | null | null | null | http_opencv.cpp | phoenixqm/OpenCV-Server | a9cc6900207f064f51c0cfad7e37494e76619090 | [
"MIT"
] | null | null | null | http_opencv.cpp | phoenixqm/OpenCV-Server | a9cc6900207f064f51c0cfad7e37494e76619090 | [
"MIT"
] | null | null | null | #include "server_http.hpp"
#include "client_http.hpp"
//Added for the json-example
#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//Added for the default_resource example
#include <fstream>
#include <boost/filesystem.hpp>
#include <vector>
#include <algorithm>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include"opencv_solutions.hpp"
using namespace std;
const int PORT = 8080;
//Added for the json-example:
using namespace boost::property_tree;
typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
//Added for the default_resource example
void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
const shared_ptr<ifstream> &ifs);
int main() {
FloodFillSolution solution;
solution.initOpenCVImage("web/floorplan2.png");
//solution.initOpenCVWindow();
HttpServer server(PORT, 1);
cout << "listening port " << PORT << endl;
server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response,
shared_ptr<HttpServer::Request> request) {
auto content=request->content.string();
//request->content.string() is a convenience function for:
//stringstream ss;
//ss << request->content.rdbuf();
//string content=ss.str();
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
server.resource["^/opencv-floodfill/([0-9]+)/([0-9]+)$"]["GET"]
= [&server, &solution](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
int x = stoi(request->path_match[1]);
int y = stoi(request->path_match[2]);
string ret = solution.getContoursFromPoint(x, y);
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << ret.length() << "\r\n\r\n" << ret;
};
//Get example simulating heavy work in a separate thread
server.resource["^/work$"]["GET"]
= [&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
thread work_thread([response] {
this_thread::sleep_for(chrono::seconds(5));
string message="Work done";
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << message.length() << "\r\n\r\n" << message;
});
work_thread.detach();
};
server.default_resource["GET"] = [&server](shared_ptr<HttpServer::Response> response,
shared_ptr<HttpServer::Request> request) {
try {
auto web_root_path = boost::filesystem::canonical("web");
auto path=boost::filesystem::canonical(web_root_path/request->path);
//Check if path is within web_root_path
if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) ||
!equal(web_root_path.begin(), web_root_path.end(), path.begin()))
throw invalid_argument("path must be within root path");
if(boost::filesystem::is_directory(path))
path/="index.html";
if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
throw invalid_argument("file does not exist");
auto ifs = make_shared<ifstream>();
ifs->open(path.string(), ifstream::in | ios::binary);
if (*ifs) {
ifs->seekg(0, ios::end);
auto length=ifs->tellg();
ifs->seekg(0, ios::beg);
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << length << "\r\n\r\n";
default_resource_send(server, response, ifs);
}
else
throw invalid_argument("could not read file");
}
catch(const exception &e) {
string content = "Could not open path "+request->path+": "+e.what();
*response << "HTTP/1.1 400 Bad Request\r\nContent-Length: "
<< content.length() << "\r\n\r\n" << content;
}
};
thread server_thread([&server](){
//Start server
server.start();
});
server_thread.join();
return 0;
}
void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
const shared_ptr<ifstream> &ifs) {
//read and send 128 KB at a time
static vector<char> buffer(131072); // Safe when server is running on one thread
streamsize read_length;
if((read_length=ifs->read(&buffer[0], buffer.size()).gcount())>0) {
response->write(&buffer[0], read_length);
if(read_length==static_cast<streamsize>(buffer.size())) {
server.send(response, [&server, response, ifs](const boost::system::error_code &ec) {
if(!ec)
default_resource_send(server, response, ifs);
else
cerr << "Connection interrupted" << endl;
});
}
}
}
| 35.758621 | 110 | 0.601157 | [
"vector"
] |
e2c504e19c4bb0df161b4f3a96537ca9cc7edab1 | 4,814 | cpp | C++ | SDK/Database/TransactionCoinbase.cpp | fakecoinbase/elastosslashElastos.ELA.SPV.Cpp | b18eaeaa96e6c9049e3527c6e8b22a571aba35f6 | [
"MIT"
] | 11 | 2018-08-01T02:01:34.000Z | 2019-09-15T23:31:40.000Z | SDK/Database/TransactionCoinbase.cpp | chenyukaola/Elastos.ELA.SPV.Cpp | 57b5264d4eb259439dd85aefc0455389551ee3cf | [
"MIT"
] | 51 | 2018-07-16T09:41:14.000Z | 2020-01-08T03:40:34.000Z | SDK/Database/TransactionCoinbase.cpp | yiyaowen/ela-spvwallet-desktop | 475095ee3c1f49bc7e23c5c341e959568d4f72b9 | [
"MIT"
] | 26 | 2018-07-12T02:34:46.000Z | 2022-02-07T07:08:54.000Z | /*
* Copyright (c) 2019 Elastos Foundation
*
* 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 "TransactionCoinbase.h"
#include <Common/Log.h>
#include <WalletCore/Address.h>
#include <Plugin/Transaction/TransactionOutput.h>
#include <Plugin/Transaction/Transaction.h>
#include <Plugin/Transaction/Payload/CoinBase.h>
#include <Plugin/Registry.h>
#include <cstdint>
#include <Plugin/Transaction/IDTransaction.h>
namespace Elastos {
namespace ElaWallet {
TransactionCoinbase::TransactionCoinbase(Sqlite *sqlite, SqliteTransactionType type) :
TransactionNormal(sqlite, type) {
_tableNameOld = "coinBaseUTXOTable";
_txHashOld = "txHash";
_blockHeightOld = "blockHeight";
_timestampOld = "timestamp";
_indexOld = "outputIndex";
_programHashOld = "programHash";
_assetIDOld = "assetID";
_outputLockOld = "outputLock";
_amountOld = "amount";
_payloadOld = "payload";
_spentOld = "spent";
// new table
_tableName = "transactionCoinbase";
}
TransactionCoinbase::~TransactionCoinbase() {
}
void TransactionCoinbase::InitializeTable() {
if (!ContainOldData()) {
TransactionNormal::InitializeTable();
}
}
std::vector<TransactionPtr> TransactionCoinbase::GetAll(const std::string &chainID) const {
if (!ContainOldData()) {
return TransactionNormal::GetAll(chainID);
}
return GetAllOld(chainID);
}
void TransactionCoinbase::RemoveOld() {
if (ContainOldData()) {
TransactionNormal::InitializeTable();
TableBase::InitializeTable("drop table if exists " + _tableNameOld + ";");
}
}
std::vector<TransactionPtr> TransactionCoinbase::GetAllOld(const std::string &chainID) const {
std::string sql;
std::vector<TransactionPtr> txns;
sql = "SELECT " + _txHashOld + ", " + _blockHeightOld + ", " + _timestampOld + ", " + _indexOld + ", " +
_programHashOld + ", " + _assetIDOld + ", " + _outputLockOld + ", " + _amountOld + ", " +
_payloadOld + ", " + _spentOld + " FROM " + _tableNameOld + ";";
sqlite3_stmt *stmt;
if (!_sqlite->Prepare(sql, &stmt, nullptr)) {
Log::error("prepare sql: {}", sql);
return {};
}
while (SQLITE_ROW == _sqlite->Step(stmt)) {
uint256 txHash(_sqlite->ColumnText(stmt, 0));
uint32_t blockHeight = _sqlite->ColumnInt(stmt, 1);
time_t timestamp = _sqlite->ColumnInt64(stmt, 2);
uint16_t index = (uint16_t) _sqlite->ColumnInt(stmt, 3);
uint168 programHash(*_sqlite->ColumnBlobBytes(stmt, 4));
uint256 assetID(*_sqlite->ColumnBlobBytes(stmt, 5));
uint32_t outputLock = _sqlite->ColumnInt(stmt, 6);
BigInt amount;
amount.setDec(_sqlite->ColumnText(stmt, 7));
_sqlite->ColumnBlobBytes(stmt, 8);
bool spent = _sqlite->ColumnInt(stmt, 9) != 0;
OutputPtr o(new TransactionOutput(amount, Address(programHash), assetID));
o->SetOutputLock(outputLock);
o->SetFixedIndex(index);
TransactionPtr tx;
if (chainID == CHAINID_MAINCHAIN) {
tx = TransactionPtr(new Transaction(Transaction::coinBase, PayloadPtr(new CoinBase())));
} else if (chainID == CHAINID_IDCHAIN || chainID == CHAINID_TOKENCHAIN) {
tx = TransactionPtr(new IDTransaction(Transaction::coinBase, PayloadPtr(new CoinBase())));
}
tx->SetHash(txHash);
tx->SetBlockHeight(blockHeight);
tx->SetTimestamp(timestamp);
tx->AddOutput(o);
txns.push_back(tx);
}
if (!_sqlite->Finalize(stmt)) {
Log::error("Coinbase get all finalize");
return {};
}
return txns;
}
bool TransactionCoinbase::ContainOldData() const {
return TableBase::ContainTable(_tableNameOld);
}
void TransactionCoinbase::ConvertFromOldData() {
if (ContainOldData()) {
std::vector<TransactionPtr> txns = GetAllOld(CHAINID_MAINCHAIN);
Puts(txns);
}
}
}
} | 33.2 | 107 | 0.700665 | [
"vector"
] |
e2c9bdb7d90ac771616f1979fd86f2bc5391d936 | 6,672 | cpp | C++ | Source/Readers/HTKDeserializers/MLFIndexBuilder.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | 17,702 | 2016-01-25T14:03:01.000Z | 2019-05-06T09:23:41.000Z | Source/Readers/HTKDeserializers/MLFIndexBuilder.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | 3,489 | 2016-01-25T13:32:09.000Z | 2019-05-03T11:29:15.000Z | Source/Readers/HTKDeserializers/MLFIndexBuilder.cpp | burhandodhy/CNTK | fcdeef63d0192c7b4b7428b14c1f9750d6c1de2e | [
"MIT"
] | 5,180 | 2016-01-25T14:02:12.000Z | 2019-05-06T04:24:28.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#include "MLFIndexBuilder.h"
#include "MLFUtils.h"
#include "ReaderUtil.h"
namespace CNTK {
using namespace std;
MLFIndexBuilder::MLFIndexBuilder(const FileWrapper& input, CorpusDescriptorPtr corpus)
: IndexBuilder(input)
{
IndexBuilder::SetCorpus(corpus);
IndexBuilder::SetChunkSize(g_64MB);
if (m_corpus == nullptr)
InvalidArgument("MLFIndexBuilder: corpus descriptor was not specified.");
// MLF index builder does not need to map sequence keys to locations,
// deserializer will do that instead, set primary to true to skip that step.
m_primary = true;
}
/*virtual*/ wstring MLFIndexBuilder::GetCacheFilename() /*override*/
{
if (m_isCacheEnabled && !m_corpus->IsNumericSequenceKeys() && !m_corpus->IsHashingEnabled())
InvalidArgument("Index caching is not supported for non-numeric sequence keys "
"using in a corpus with disabled hashing.");
wstringstream wss;
wss << m_input.Filename() << "."
<< (m_corpus->IsNumericSequenceKeys() ? "1" : "0") << "."
<< (m_corpus->IsHashingEnabled() ? std::to_wstring(CorpusDescriptor::s_hashVersion) : L"0") << "."
<< L"v" << IndexBuilder::s_version << "."
<< L"cache";
return wss.str();
}
// Building an index of the MLF file:
// MLF file -> MLF Header [MLF Utterance]+
// MLF Utterance -> Key EOL [Frame Range EOL]+ "." EOL
// MLF file should start with the MLF header (State::Header -> State:UtteranceKey).
// Each utterance starts with an utterance key (State::UtteranceKey -> State::UtteranceFrames).
// End of utterance is indicated by a single dot on a line (State::UtteranceFrames -> State::UtteranceKey)
/*virtual*/ void MLFIndexBuilder::Populate(shared_ptr<Index>& index) /*override*/
{
m_input.CheckIsOpenOrDie();
index->Reserve(filesize(m_input.File()));
BufferedFileReader reader(m_bufferSize, m_input);
if (reader.Empty())
RuntimeError("Input file is empty");
if (!m_corpus)
RuntimeError("MLFIndexBuilder: corpus descriptor was not specified.");
size_t id = 0;
State currentState = State::Header;
vector<boost::iterator_range<char*>> tokens;
bool isValid = true; // Flag indicating whether the current sequence is valid.
size_t sequenceStartOffset = 0; // Offset in file where current sequence starts.
string lastNonEmptyLine; // Needed to parse information about last frame
IndexedSequence sequence;
string line;
while (true)
{
auto offset = reader.GetFileOffset();
if (!reader.TryReadLine(line))
break;
if (!line.empty() && line.back() == '\r')
line.pop_back();
if (line.empty())
continue;
switch (currentState)
{
case State::Header:
{
if (line != "#!MLF!#")
RuntimeError("Expected MLF header was not found.");
currentState = State::UtteranceKey;
}
break;
case State::UtteranceKey:
{
// When several files are appended to a big mlf, there can be
// an MLF header between the utterances.
if (line == "#!MLF!#")
continue;
lastNonEmptyLine.clear();
sequenceStartOffset = offset;
isValid = TryParseSequenceKey(line, id, m_corpus->KeyToId);
currentState = State::UtteranceFrames;
}
break;
case State::UtteranceFrames:
{
if (line != ".")
{
// Remembering last non empty string to be able to retrieve time frame information
// when the dot is just at the beginning of the next buffer.
lastNonEmptyLine = line;
continue; // Still current utterance.
}
// Ok, a single . on a line means we found the end of the utterance.
auto sequenceEndOffset = reader.GetFileOffset();
uint32_t numberOfSamples = 0;
if (lastNonEmptyLine.empty())
isValid = false;
else
{
tokens.clear();
const static vector<bool> delim = DelimiterHash({ ' ' });
Split(&lastNonEmptyLine[0], &lastNonEmptyLine[0] + lastNonEmptyLine.size(), delim, tokens);
auto range = MLFFrameRange::ParseFrameRange(tokens, sequenceEndOffset);
numberOfSamples = static_cast<uint32_t>(range.second);
}
if (isValid)
{
sequence.SetKey(id)
.SetNumberOfSamples(numberOfSamples)
.SetOffset(sequenceStartOffset)
.SetSize(sequenceEndOffset - sequenceStartOffset);
index->AddSequence(sequence);
}
else
fprintf(stderr, "WARNING: Cannot parse the utterance '%s' at offset (%" PRIu64 ")\n", m_corpus->IdToKey(id).c_str(), sequenceStartOffset);
currentState = State::UtteranceKey; // Let's try the next one.
}
break;
default:
LogicError("Unexpected MLF state.");
}
}
}
// Tries to parse sequence key
// In MLF a sequence key should be in quotes. During parsing the extension should be removed.
bool MLFIndexBuilder::TryParseSequenceKey(const string& line, size_t& id, function<size_t(const string&)> keyToId)
{
id = 0;
string key(line);
boost::trim_right(key);
if (key.size() <= 2 || key.front() != '"' || key.back() != '"')
return false;
key = key.substr(1, key.size() - 2);
if (key.size() > 2 && key[0] == '*' && key[1] == '/') // Preserving the old behavior
key = key.substr(2);
// Remove extension if specified.
key = key.substr(0, key.find_last_of("."));
id = keyToId(key);
return true;
}
}
| 36.659341 | 158 | 0.553357 | [
"vector"
] |
e2ca89ac1b82640121d7ddae0a5eae327bb4ab9f | 1,764 | hh | C++ | day06/common/solver.hh | ovove/aoc21 | 6abcf1e898700826290f35e40bb4514dbcd8d8ef | [
"Unlicense"
] | null | null | null | day06/common/solver.hh | ovove/aoc21 | 6abcf1e898700826290f35e40bb4514dbcd8d8ef | [
"Unlicense"
] | null | null | null | day06/common/solver.hh | ovove/aoc21 | 6abcf1e898700826290f35e40bb4514dbcd8d8ef | [
"Unlicense"
] | null | null | null | #pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <vector>
void fish_grow_simulation(std::vector<int>& population, unsigned days) {
while (days--) {
unsigned new_fish {0};
std::for_each(std::begin(population),
std::end(population),
[&new_fish](int& days_until_reproduce) {
if (days_until_reproduce == 0) {
++new_fish;
days_until_reproduce = 6;
}
else {
--days_until_reproduce;
}
});
population.insert(std::end(population), new_fish, 8);
}
}
std::array<uint64_t, 9> fish_population_distribution(const std::vector<int>& population) {
std::array<uint64_t, 9> result {};
for (unsigned days_until_reproduce = 0; days_until_reproduce <= 8; ++days_until_reproduce) {
result[days_until_reproduce]
= std::count(std::begin(population), std::end(population), days_until_reproduce);
}
return result;
}
void fish_grow_simulation(std::array<uint64_t, 9>& population, unsigned days) {
while (days--) {
const uint64_t new_fish = population[0];
for (std::size_t days_until_reproduce = 0; days_until_reproduce < 8;
++days_until_reproduce) {
population[days_until_reproduce] = population[days_until_reproduce + 1];
}
population[6] += new_fish;
population[8] = new_fish;
}
}
uint64_t fish_population_size(const std::array<uint64_t, 9>& population) {
return std::accumulate(std::begin(population), std::end(population), 0LLU);
}
| 34.588235 | 96 | 0.577098 | [
"vector"
] |
e2cb2a5b485139b68f5cec61b6c2c5e3db86cddf | 5,557 | cpp | C++ | trt_l2norm_helper/l2norm_helper.cpp | r7vme/tensorrt_l2norm_helper | bc2c0651ca450db4661cbd22530a014feda523c4 | [
"MIT"
] | 30 | 2019-07-08T22:24:40.000Z | 2021-08-12T08:50:54.000Z | eagle2_perception/vendor/trt_l2norm_helper/l2norm_helper.cpp | r7vme/eagle2 | 6b079e5849e401f17730c520c45a5d43421eddc2 | [
"MIT"
] | 3 | 2019-10-08T11:47:28.000Z | 2021-10-04T12:39:58.000Z | trt_l2norm_helper/l2norm_helper.cpp | r7vme/tensorrt_l2norm_helper | bc2c0651ca450db4661cbd22530a014feda523c4 | [
"MIT"
] | 2 | 2019-12-20T14:54:51.000Z | 2020-05-14T13:26:17.000Z | #include <cstring>
#include <iostream>
#include <sstream>
#include "l2norm_helper.h"
using namespace std;
using namespace nvinfer1;
namespace
{
const char* L2NORM_HELPER_PLUGIN_VERSION{"1"};
const char* L2NORM_HELPER_PLUGIN_NAME{"L2Norm_Helper_TRT"};
} // namespace
PluginFieldCollection L2NormHelperPluginCreator::mFC{};
vector<PluginField> L2NormHelperPluginCreator::mPluginAttributes;
L2NormHelper::L2NormHelper(int op_type, float eps): op_type(op_type), eps(eps) {}
L2NormHelper::L2NormHelper(int op_type, float eps, int C, int H, int W):
op_type(op_type), eps(eps), C(C), H(H), W(W) {}
L2NormHelper::L2NormHelper(const void* buffer, size_t length)
{
const char *d = reinterpret_cast<const char*>(buffer), *a = d;
op_type = read<int>(d);
eps = read<float>(d);
C = read<int>(d);
H = read<int>(d);
W = read<int>(d);
mDataType = read<DataType>(d);
ASSERT(d == a + length);
}
int L2NormHelper::getNbOutputs() const
{
// Plugin layer has 1 output
return 1;
}
Dims L2NormHelper::getOutputDimensions(int index, const Dims* inputs, int nbInputDims)
{
ASSERT(nbInputDims == 1);
ASSERT(index == 0);
ASSERT(inputs[0].nbDims == 3);
return Dims3(inputs[0].d[0], inputs[0].d[1], inputs[0].d[2]);
}
int L2NormHelper::initialize()
{
return 0;
}
void L2NormHelper::terminate() {}
size_t L2NormHelper::getWorkspaceSize(int maxBatchSize) const
{
return 0;
}
size_t L2NormHelper::getSerializationSize() const
{
// C, H, W, eps, op_type, mDataType
return sizeof(int) * 3 + sizeof(float) + sizeof(int) + sizeof(mDataType);
}
void L2NormHelper::serialize(void* buffer) const
{
char *d = reinterpret_cast<char*>(buffer), *a = d;
write(d, op_type);
write(d, eps);
write(d, C);
write(d, H);
write(d, W);
write(d, mDataType);
ASSERT(d == a + getSerializationSize());
}
bool L2NormHelper::supportsFormat(DataType type, PluginFormat format) const
{
return ((type == DataType::kFLOAT || type == DataType::kHALF) &&
(format == PluginFormat::kNCHW));
}
// Set plugin namespace
void L2NormHelper::setPluginNamespace(const char* pluginNamespace)
{
mPluginNamespace = pluginNamespace;
}
const char* L2NormHelper::getPluginNamespace() const
{
return mPluginNamespace;
}
// Configure the layer with input and output data types.
void L2NormHelper::configureWithFormat(
const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs,
DataType type, PluginFormat format, int maxBatchSize)
{
ASSERT(format == PluginFormat::kNCHW);
ASSERT(type == DataType::kFLOAT || type == DataType::kHALF);
mDataType = type;
C = inputDims[0].d[0];
H = inputDims[0].d[1];
W = inputDims[0].d[2];
ASSERT(nbInputs == 1);
ASSERT(nbOutputs == 1);
ASSERT(inputDims[0].nbDims >= 1); // number of dimensions of the input tensor must be >=1
ASSERT(inputDims[0].d[0] == outputDims[0].d[0] &&
inputDims[0].d[1] == outputDims[0].d[1] &&
inputDims[0].d[2] == outputDims[0].d[2]);
}
const char* L2NormHelper::getPluginType() const
{
return L2NORM_HELPER_PLUGIN_NAME;
}
const char* L2NormHelper::getPluginVersion() const
{
return L2NORM_HELPER_PLUGIN_VERSION;
}
void L2NormHelper::destroy()
{
delete this;
}
// Clone the plugin
IPluginV2* L2NormHelper::clone() const
{
// Create a new instance
IPluginV2* plugin = new L2NormHelper(op_type, eps);
// Set the namespace
plugin->setPluginNamespace(mPluginNamespace);
return plugin;
}
// PluginCreator
L2NormHelperPluginCreator::L2NormHelperPluginCreator()
{
mPluginAttributes.emplace_back(PluginField("op_type", nullptr, PluginFieldType::kINT32, 1));
mPluginAttributes.emplace_back(PluginField("eps", nullptr, PluginFieldType::kFLOAT32, 1));
mFC.nbFields = mPluginAttributes.size();
mFC.fields = mPluginAttributes.data();
}
const char* L2NormHelperPluginCreator::getPluginName() const
{
return L2NORM_HELPER_PLUGIN_NAME;
}
const char* L2NormHelperPluginCreator::getPluginVersion() const
{
return L2NORM_HELPER_PLUGIN_VERSION;
}
void L2NormHelperPluginCreator::setPluginNamespace(const char* ns)
{
mNamespace = ns;
}
const char* L2NormHelperPluginCreator::getPluginNamespace() const
{
return mNamespace.c_str();
}
const PluginFieldCollection* L2NormHelperPluginCreator::getFieldNames()
{
return &mFC;
}
IPluginV2* L2NormHelperPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc)
{
const PluginField* fields = fc->fields;
for (int i = 0; i < fc->nbFields; ++i)
{
const char* attrName = fields[i].name;
if (!strcmp(attrName, "op_type"))
{
ASSERT(fields[i].type == PluginFieldType::kINT32);
mOpType = static_cast<int>(*(static_cast<const int*>(fields[i].data)));
}
if (!strcmp(attrName, "eps"))
{
ASSERT(fields[i].type == PluginFieldType::kFLOAT32);
mEps = static_cast<float>(*(static_cast<const float*>(fields[i].data)));
}
}
L2NormHelper* obj = new L2NormHelper(mOpType, mEps);
obj->setPluginNamespace(mNamespace.c_str());
return obj;
}
IPluginV2* L2NormHelperPluginCreator::deserializePlugin(
const char* name, const void* serialData, size_t serialLength)
{
// This object will be deleted when the network is destroyed, which will
// call L2NormHelper::destroy()
L2NormHelper* obj = new L2NormHelper(serialData, serialLength);
obj->setPluginNamespace(mNamespace.c_str());
return obj;
}
| 26.588517 | 101 | 0.685802 | [
"object",
"vector"
] |
e2dbe78ac59129111522f3a132cfd6a7e3716761 | 954 | cpp | C++ | book/CH06/S01_Specifying_attachments_descriptions.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | book/CH06/S01_Specifying_attachments_descriptions.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | book/CH06/S01_Specifying_attachments_descriptions.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by aicdg on 2017/6/21.
//
//
// Chapter: 06 Render Passes and Framebuffers
// Recipe: 01 Specifying attachments descriptions
#include "S01_Specifying_attachments_descriptions.h"
namespace VKCookbook {
void SpecifyAttachmentsDescriptions( std::vector<VkAttachmentDescription> const & attachments_descriptions ) {
// typedef struct VkAttachmentDescription {
// VkAttachmentDescriptionFlags flags;
// VkFormat format;
// VkSampleCountFlagBits samples;
// VkAttachmentLoadOp loadOp;
// VkAttachmentStoreOp storeOp;
// VkAttachmentLoadOp stencilLoadOp;
// VkAttachmentStoreOp stencilStoreOp;
// VkImageLayout initialLayout;
// VkImageLayout finalLayout;
// } VkAttachmentDescription;
return;
}
} | 34.071429 | 114 | 0.592243 | [
"render",
"vector"
] |
e2eb685972dd3c75f2012f6b8c6af0d6ec9bea83 | 4,414 | cpp | C++ | audio_algorithms/fft.cpp | mumtozee/MIPT_algos | dc7834bea73cde716f2da4c2ac6771572f44b9d5 | [
"MIT"
] | 4 | 2020-05-13T22:32:29.000Z | 2021-01-11T13:21:41.000Z | audio_algorithms/fft.cpp | mumtozee/MSTL_custom | dc7834bea73cde716f2da4c2ac6771572f44b9d5 | [
"MIT"
] | null | null | null | audio_algorithms/fft.cpp | mumtozee/MSTL_custom | dc7834bea73cde716f2da4c2ac6771572f44b9d5 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <complex>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <valarray>
#include <vector>
struct WavHeader {
char chunk_id[4];
uint32_t chunk_size;
char format[4];
char subchunk1_id[4];
uint32_t subchunk1_size;
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
char subchunk2_id[4];
uint32_t subchunk2_size;
};
template <typename T>
void PrintArray(const T* arr, size_t size) {
for (size_t i = 0; i < size; ++i) {
std::cout << arr[i];
}
}
void PrintHeader(const WavHeader& header) {
std::cout << "RIFF: ";
PrintArray(header.chunk_id, 4);
std::cout << '\n';
std::cout << "Overall Size: " << header.chunk_size << '\n';
std::cout << "WAVE: ";
PrintArray(header.format, 4);
std::cout << '\n';
std::cout << "FMT: ";
PrintArray(header.subchunk1_id, 4);
std::cout << '\n';
std::cout << "Length of FMT: " << header.subchunk1_size << '\n';
std::cout << "Format Type: " << header.audio_format << '\n';
std::cout << "Channels: " << header.num_channels << '\n';
std::cout << "Sample rate: " << header.sample_rate << '\n';
std::cout << "Byte rate: " << header.byte_rate << '\n';
std::cout << "Block align: " << header.block_align << '\n';
std::cout << "Bits per sample: " << header.bits_per_sample << '\n';
std::cout << "Data chunk reader: ";
PrintArray(header.subchunk2_id, 4);
std::cout << '\n';
std::cout << "Data size: " << header.subchunk2_size << '\n';
}
using Complex = std::complex<double>;
uint32_t RoundUpToPowerofTwo(uint32_t input) {
--input;
input |= input >> 1;
input |= input >> 2;
input |= input >> 4;
input |= input >> 8;
input |= input >> 16;
++input;
return input;
}
void FFT(std::valarray<Complex>& data) {
if (data.size() <= 1) {
return;
}
std::valarray<Complex> even = data[std::slice(0, data.size() / 2, 2)];
std::valarray<Complex> odd = data[std::slice(1, data.size() / 2, 2)];
FFT(even);
FFT(odd);
for (uint32_t i = 0; i < data.size() / 2; ++i) {
Complex temp = std::polar(1.0, -2 * M_PI * i / data.size()) * odd[i];
data[i] = even[i] + temp;
data[i + data.size() / 2] = even[i] - temp;
}
}
void FFTReverse(std::valarray<Complex>& data) {
data = data.apply(std::conj);
FFT(data);
data = data.apply(std::conj);
data /= data.size();
}
void AnnihilateLastCoeffs(std::valarray<Complex>& data, size_t pure_size) {
uint32_t percent = static_cast<double>(pure_size) * 0.2;
std::fill(std::begin(data) + percent, std::end(data), Complex{0.0, 0.0});
}
template <typename T>
void ResizeValarray(std::valarray<T>& varr, size_t new_size, T value = T()) {
if (new_size == varr.size()) {
return;
}
std::vector<T> buffer(std::begin(varr), std::end(varr));
buffer.resize(new_size, T());
varr.resize(new_size);
std::copy(buffer.begin(), buffer.end(), std::begin(varr));
}
int main() {
std::ifstream in{"speech.wav", std::ios::in | std::ios::binary};
WavHeader head{};
in.read(reinterpret_cast<char*>(&head), sizeof(WavHeader));
PrintHeader(head);
std::cout << sizeof(head) << '\n';
const size_t data_size = head.subchunk2_size / 2;
auto* data = new int16_t[data_size];
in.read(reinterpret_cast<char*>(data), data_size * sizeof(uint16_t));
in.close();
auto* complex_data = new Complex[data_size];
std::copy(data, data + data_size, complex_data);
std::valarray<Complex> carray(complex_data, data_size);
delete[] complex_data;
delete[] data;
auto original_size = carray.size();
ResizeValarray(carray, RoundUpToPowerofTwo(original_size), Complex{0.0, 0.0});
FFTReverse(carray);
AnnihilateLastCoeffs(carray, original_size);
FFT(carray);
ResizeValarray(carray, original_size);
std::ofstream out{"out.wav", std::ios::out | std::ios::binary};
auto* out_data = new int16_t[original_size];
uint32_t i = 0;
std::for_each(
out_data, out_data + original_size,
[&i, &carray](int16_t& number) { number = round(carray[i++].real()); });
out.write(reinterpret_cast<char*>(&head), sizeof(WavHeader));
out.write(reinterpret_cast<char*>(out_data), head.subchunk2_size);
delete[] out_data;
out.close();
return 0;
}
| 30.652778 | 81 | 0.620752 | [
"vector"
] |
e2f619222b7a685230a6b1897604189cc40a6eff | 1,216 | cpp | C++ | Kattis/fridge.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | 3 | 2021-02-19T17:01:11.000Z | 2021-03-11T16:50:19.000Z | Kattis/fridge.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | Kattis/fridge.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | // iteration
// https://open.kattis.com/problems/fridge
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <cmath>
#include <map>
#include <utility>
#include <queue>
#include <iomanip>
#include <deque>
#include <set>
#define Forcase int __t;cin>>__t;getchar();for(int ___t=1;___t<=__t;___t++)
#define For(i, n) for(int i=0;i<n;i++)
#define Fore(e, arr) for(auto e:arr)
#define INF 1e9
#define EPS 1e-9
using ull = unsigned long long;
using ll = long long;
using namespace std;
int num[10];
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
string s;
getline(cin, s);
For (i, s.length()) {
num[s[i] - '0']++;
}
int mn = -1;
for (int i = 1; i < 10; i++) {
if (mn == -1 || num[i] < num[mn]) {
mn = i;
}
}
if (num[mn] == 0) {
cout << mn << '\n';
} else if (num[0] <= num[mn] - 1) {
cout << 1;
For (i, num[0] + 1) {
cout << 0;
}
cout << '\n';
} else {
For (i, num[mn] + 1) {
cout << mn;
}
cout << '\n';
}
return 0;
} | 19 | 75 | 0.501645 | [
"vector"
] |
e2f734cd0d6b6c029a32f3f0807724d9d920bb1b | 1,539 | cpp | C++ | src/main.cpp | HostedDinner/ServiceStarter | 07a9a683564b756565edfce2788bc0edeba42855 | [
"MIT"
] | 1 | 2018-11-06T08:33:30.000Z | 2018-11-06T08:33:30.000Z | src/main.cpp | HostedDinner/ServiceStarter | 07a9a683564b756565edfce2788bc0edeba42855 | [
"MIT"
] | 1 | 2017-08-26T17:48:26.000Z | 2017-08-26T17:48:26.000Z | src/main.cpp | HostedDinner/ServiceStarter | 07a9a683564b756565edfce2788bc0edeba42855 | [
"MIT"
] | null | null | null | /*
* File: main.cpp
* Author: Fabian
*
* Created on 8. Februar 2017, 17:06
*/
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include "main.h"
#include <windows.h>
#include "Window.h"
#include "ServiceGUI.h"
#include "ConfigParser.h"
#include "ScrollBarController.h"
//int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
int main(int argc, char* argv[]){
int width = 350;
int height = 130;
HINSTANCE hInstance = GetModuleHandle(NULL);
Window window = Window(L"Service Starter", width, height, hInstance);
if(!window.isInitSuccess()){
return 0;
}
ConfigParser configP(L"config.xml");
auto *confs = configP.pGetServiceConfigs();
auto length = confs->size();
std::vector<std::unique_ptr<ServiceGUI>> services;
services.reserve(length);
for (auto &elem : *confs) {
std::unique_ptr<ServiceGUI> p(new ServiceGUI(&window, elem.first, elem.second));
services.push_back(std::move(p));
}
//Adjust the Scrollbar (height of 1 element is 30, top margin is 10)
ScrollBarController *scrBC = window.getpScrollBarController();
scrBC->setRange(1, (length*30+10) / 10);
window.showWindow();
WPARAM exitCode = window.handleMessages();
//cleaning the serviceGUI/Services is done by our smart pointer
return exitCode;
}
| 23.318182 | 100 | 0.619883 | [
"vector"
] |
e2f7d97b4257826c4fc66b3ce2aed835fbd6af01 | 731 | cpp | C++ | 2020/day1/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | 2020/day1/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | 2020/day1/main.cpp | bielskij/AOC-2019 | e98d660412037b3fdac4a6b49adcb9230f518c99 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include "utils/file.h"
#include "utils/utils.h"
#include "common/debug.h"
static int _solve(const std::vector<int> &samples, int num) {
std::vector<std::vector<int>> combinations;
utils::genCombinations(combinations, samples.size(), num);
for (auto v : combinations) {
int sum = 0;
for (auto idx : v) {
sum += samples[idx];
}
if (sum == 2020) {
int mul = 1;
for (auto idx : v) {
mul *= samples[idx];
}
return mul;
}
}
}
int main(int argc, char *argv[]) {
auto numbers = utils::toIntV(File::readAllLines(argv[1]));
PRINTF(("PART_A: %d", _solve(numbers, 2)));
PRINTF(("PART_B: %d", _solve(numbers, 3)));
}
| 16.244444 | 61 | 0.615595 | [
"vector"
] |
e2fa78871273c2fcd7bb3ae3b94fe5c91a0df00a | 1,946 | cpp | C++ | data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUM_IARRI_AMONG_ROTATIONS_GIVEN_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUM_IARRI_AMONG_ROTATIONS_GIVEN_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/cpp/MAXIMUM_SUM_IARRI_AMONG_ROTATIONS_GIVEN_ARRAY.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
int f_gold ( int arr [ ], int n ) {
int res = INT_MIN;
for ( int i = 0;
i < n;
i ++ ) {
int curr_sum = 0;
for ( int j = 0;
j < n;
j ++ ) {
int index = ( i + j ) % n;
curr_sum += j * arr [ index ];
}
res = max ( res, curr_sum );
}
return res;
}
//TOFILL
int main() {
int n_success = 0;
vector<vector<int>> param0 {{11,12,16,26,29,40,54,59,65,70,71,73,78,81,87,87,88,90,95,97},{-46,-32,54,96,-72,-58,-36,-44,26,-2,-68,42,90,26,-92,-96,88,-42,-18,46,-70,24,0,24,34,34,-52,50,94,-60,64,58},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{48,2,79,98,28,17,41,47,61,76,82,5,74,4,80,51,22,45,91,75,91,93,42,45,69,98,76,74,83,17,30,88,53,25,35,19,26},{-88,-84,-82,-74,-44,-34,-32,-20,-20,-14,6,6,10,12,16,24,32,34,38,46,54,54,56,60,82,88,90,94,98},{0,1,1,1,1,0,1,1,1,1,1,1,1},{10,14,14,14,19,20,22,26,35,36,40,53,54,55,55,57,57,67,72,72,77,78,83,84,95,96},{-80,18,-76,48,-52,-38,52,-82,40,-44,-90,86,-86,-36,-32,-2,56,-12,-88,14,-16,8,52,24,46,56,84,-36,84,-60,72,-46,32,-16,-20,68,-86,-62,58,8,78,-52,22,-28,-22,-42,12,-48},{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},{20,94,36,2,50,62,84,50,66,75,1,18,41,48,72,61,86,22,54,6,71,46,92,68,59,51,89,31,58,78,82,84}};
vector<int> param1 {11,22,33,20,24,7,16,30,14,25};
for(int i = 0; i < param0.size(); ++i)
{
if(f_filled(¶m0[i].front(),param1[i]) == f_gold(¶m0[i].front(),param1[i]))
{
n_success+=1;
}
}
cout << "#Results:" << " " << n_success << ", " << param0.size();
return 0;
} | 39.714286 | 915 | 0.561151 | [
"vector"
] |
c3bc3808298f4971560d4daa552bd92f542f4c5a | 24,225 | cpp | C++ | Engine/Entities/Components.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | null | null | null | Engine/Entities/Components.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | null | null | null | Engine/Entities/Components.cpp | Higami69/Leviathan | 90f68f9f6e5506d6133bcefcf35c8e84f158483b | [
"BSL-1.0"
] | null | null | null | // ------------------------------------ //
#include "Components.h"
#include "CommonStateObjects.h"
#include "GameWorld.h"
#include "Handlers/IDFactory.h"
#include "Networking/Connection.h"
#include "Networking/SentNetworkThing.h"
#include "Newton/NewtonConversions.h"
#include "Utility/Convert.h"
#include "OgreBillboardChain.h"
#include "OgreItem.h"
#include "OgreMesh2.h"
#include "OgreMeshManager.h"
#include "OgreMeshManager2.h"
#include "OgreRibbonTrail.h"
#include "OgreSceneManager.h"
#include <limits>
using namespace Leviathan;
// ------------------------------------ //
// ------------------ RenderNode ------------------ //
DLLEXPORT RenderNode::RenderNode(Ogre::SceneManager* scene) : Component(TYPE)
{
Marked = false;
// TODO: allow for static render nodes
Node = scene->getRootSceneNode(Ogre::SCENE_DYNAMIC)
->createChildSceneNode(Ogre::SCENE_DYNAMIC);
// Node = scene->createSceneNode();
}
DLLEXPORT void RenderNode::Release(Ogre::SceneManager* worldsscene)
{
worldsscene->destroySceneNode(Node);
Node = nullptr;
}
// ------------------------------------ //
DLLEXPORT RenderNode::RenderNode(const Test::TestComponentCreation& test) : Component(TYPE)
{
Marked = false;
Node = nullptr;
}
// ------------------------------------ //
// Plane
DLLEXPORT Plane::Plane(Ogre::SceneManager* scene, Ogre::SceneNode* parent,
const std::string& material, const Ogre::Plane& plane, const Float2& size) :
Component(TYPE),
GeneratedMeshName("Plane_Component_Mesh_" + std::to_string(IDFactory::GetID()))
{
const auto mesh = Ogre::v1::MeshManager::getSingleton().createPlane(
GeneratedMeshName + "_v1", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
plane, size.X, size.Y, 1, 1,
// Normals
true, 1, 1.0f, 1.0f, Ogre::Vector3::UNIT_Y,
Ogre::v1::HardwareBuffer::HBU_STATIC_WRITE_ONLY,
Ogre::v1::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false, false);
const auto mesh2 = Ogre::MeshManager::getSingleton().createManual(
GeneratedMeshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
// Fourth true is qtangent encoding which is not needed if we don't do normal mapping
mesh2->importV1(mesh.get(), true, true, true);
Ogre::v1::MeshManager::getSingleton().remove(mesh);
GraphicalObject = scene->createItem(mesh2);
parent->attachObject(GraphicalObject);
// This DOESN'T seem to throw if material is invalid
GraphicalObject->setMaterialName(material);
}
DLLEXPORT void Plane::Release(Ogre::SceneManager* scene)
{
scene->destroyItem(GraphicalObject);
Ogre::MeshManager::getSingleton().remove(GeneratedMeshName);
}
// ------------------ Physics ------------------ //
DLLEXPORT Physics::~Physics()
{
if(Body) {
LOG_ERROR("Physics: Release not called before destructor!");
Release();
}
}
DLLEXPORT void Physics::Release()
{
if(Body)
NewtonDestroyBody(Body);
if(Collision)
NewtonDestroyCollision(Collision);
Body = NULL;
Collision = NULL;
}
// ------------------------------------ //
DLLEXPORT void Physics::JumpTo(Position& target)
{
SetPosition(target.Members._Position, target.Members._Orientation);
}
DLLEXPORT bool Physics::SetPosition(const Float3& pos, const Float4& orientation)
{
if(!Body)
return false;
// Safety check. Can be disabled in release builds if this is a performance issue
if(pos.HasInvalidValues() || orientation.HasInvalidValues()) {
std::stringstream msg;
msg << "SetPosition call had at least one value with non-finite value, pos: "
<< Convert::ToString(pos) << " orientation: " << Convert::ToString(orientation);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
Ogre::Matrix4 matrix;
Ogre::Vector3 ogrepos = pos;
Ogre::Quaternion ogrerot = orientation;
matrix.makeTransform(ogrepos, Float3(1, 1, 1), ogrerot);
Ogre::Matrix4 tmatrix = PrepareOgreMatrixForNewton(matrix);
// Update body //
NewtonBodySetMatrix(Body, &tmatrix[0][0]);
return true;
}
DLLEXPORT bool Physics::SetOnlyOrientation(const Float4& orientation)
{
if(!Body)
return false;
// Safety check. Can be disabled in release builds if this is a performance issue
if(orientation.HasInvalidValues()) {
std::stringstream msg;
msg << "SetOnlyOrientation call had at least one value with non-finite value, "
"orientation: "
<< Convert::ToString(orientation);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
float newtonMatrix[16];
NewtonBodyGetMatrix(Body, &newtonMatrix[0]);
const auto pos = ExtractNewtonMatrixTranslation(newtonMatrix);
Ogre::Matrix4 matrix;
Ogre::Vector3 ogrepos = pos;
Ogre::Quaternion ogrerot = orientation;
matrix.makeTransform(ogrepos, Float3(1, 1, 1), ogrerot);
Ogre::Matrix4 tmatrix = PrepareOgreMatrixForNewton(matrix);
// Update body //
NewtonBodySetMatrix(Body, &tmatrix[0][0]);
return true;
}
DLLEXPORT Ogre::Matrix4 Physics::GetFullMatrix() const
{
if(!Body)
return Ogre::Matrix4::IDENTITY;
float matrix[16];
NewtonBodyGetMatrix(Body, &matrix[0]);
return NewtonMatrixToOgre(matrix);
}
// ------------------------------------ //
void Physics::PhysicsMovedEvent(
const NewtonBody* const body, const dFloat* const matrix, int threadIndex)
{
// first create Ogre 4x4 matrix from the matrix //
Ogre::Matrix4 mat = NewtonMatrixToOgre(matrix);
Physics* tmp = static_cast<Physics*>(NewtonBodyGetUserData(body));
const auto pos = mat.getTrans();
// #ifdef CHECK_FOR_NANS
if(!std::isfinite(pos.x)) {
LOG_ERROR("Physics::PhysicsMovedEvent: physics body has NaN translation");
// Would really like to find a fix instead of this hack
if(std::isnan(tmp->_Position.Members._Position.X)) {
LOG_ERROR("Even Position.X is NaN");
tmp->SetPosition(Float3(0, 0, 0), Ogre::Quaternion::IDENTITY);
} else {
// Doesn't seem to work
// tmp->JumpTo(tmp->_Position);
// This doesn't work either
tmp->SetPosition(Float3(0, 0, 0), Ogre::Quaternion::IDENTITY);
}
return;
}
// #endif // CHECK_FOR_NANS
tmp->_Position.Members._Position = pos;
tmp->_Position.Members._Orientation = mat.extractQuaternion();
tmp->_Position.Marked = true;
if(tmp->UpdateSendable) {
tmp->UpdateSendable->Marked = true;
}
tmp->Marked = true;
}
void Physics::ApplyForceAndTorqueEvent(
const NewtonBody* const body, dFloat timestep, int threadIndex)
{
// Get object from body //
Physics* tmp = static_cast<Physics*>(NewtonBodyGetUserData(body));
// Check if physics can't apply //
// Newton won't call this if the mass is 0
Float3 Torque = tmp->SumQueuedTorque;
// Get properties from newton //
float mass;
float Ixx;
float Iyy;
float Izz;
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
Float3 Force = tmp->SumQueuedForce;
// get gravity force and apply mass to it //
if(tmp->ApplyGravity)
Force += tmp->World->GetGravityAtPosition(tmp->_Position.Members._Position) * mass;
// add other forces //
if(!tmp->ApplyForceList.empty()) {
Force += tmp->_GatherApplyForces(mass);
}
#ifdef CHECK_FOR_NANS
if(Force.HasInvalidValues()) {
LOG_ERROR("Physics::ApplyForceAndTorqueEvent: Force was calculated to have a "
"non-finite value in it. Skipping applying");
return;
}
#endif // CHECK_FOR_NANS
NewtonBodyAddForce(body, &Force.X);
tmp->SumQueuedForce = Float3(0, 0, 0);
// Torque applying //
Float3 torque;
if(tmp->TorqueOverride) {
torque = tmp->SumQueuedTorque;
tmp->TorqueOverride = false;
tmp->SumQueuedTorque = Float3(0, 0, 0);
} else {
torque = Torque;
}
#ifdef CHECK_FOR_NANS
if(Force.HasInvalidValues()) {
LOG_ERROR("Physics::ApplyForceAndTorqueEvent: Torque was calculated to have a "
"non-finite value in it. Skipping applying");
return;
}
#endif // CHECK_FOR_NANS
NewtonBodyAddTorque(body, &torque.X);
}
void Physics::DestroyBodyCallback(const NewtonBody* body)
{
// This shouldn't be required as the newton world won't be cleared while running
// Physics* tmp = reinterpret_cast<Physics*>(NewtonBodyGetUserData(body));
// LOG_INFO("Destroy body callback");
// GUARD_LOCK_OTHER(tmp);
// tmp->Body = nullptr;
// tmp->Collision = nullptr;
}
// ------------------------------------ //
DLLEXPORT void Physics::GiveImpulse(const Float3& deltaspeed, const Float3& point
/*= Float3(0)*/)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
// Safety check. Can be disabled in release builds if this is a performance issue
if(deltaspeed.HasInvalidValues() || point.HasInvalidValues()) {
std::stringstream msg;
msg << "GiveImpulse call had at least one value with non-finite value, deltaspeed: "
<< Convert::ToString(deltaspeed) << " point: " << Convert::ToString(point);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
// No clue what the delta step should be
NewtonBodyAddImpulse(Body, &deltaspeed.X, &point.X, 0.1f);
}
DLLEXPORT void Physics::AddForce(const Float3& force)
{
// Safety check. Can be disabled in release builds if this is a performance issue
if(force.HasInvalidValues()) {
std::stringstream msg;
msg << "AddForce call had at least one value with non-finite value, force: "
<< Convert::ToString(force);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
SumQueuedForce += force;
}
DLLEXPORT void Physics::SetVelocity(const Float3& velocities)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
// Safety check. Can be disabled in release builds if this is a performance issue
if(velocities.HasInvalidValues()) {
std::stringstream msg;
msg << "SetVelocity call had at least one value with non-finite value, velocities: "
<< Convert::ToString(velocities);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
NewtonBodySetVelocity(Body, &velocities.X);
}
DLLEXPORT void Physics::ClearVelocity()
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
Float3 zeroVector(0, 0, 0);
NewtonBodySetVelocity(Body, &zeroVector.X);
// Forces are recalculated each physics update so we can't set them here
SetTorque(Float3(0, 0, 0));
}
DLLEXPORT Float3 Physics::GetVelocity() const
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
Float3 vel(0);
NewtonBodyGetVelocity(Body, &vel.X);
return vel;
}
// ------------------------------------ //
DLLEXPORT Float3 Physics::GetOmega() const
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
Float3 vel(0);
NewtonBodyGetOmega(Body, &vel.X);
return vel;
}
DLLEXPORT void Physics::SetOmega(const Float3& velocities)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
// Safety check. Can be disabled in release builds if this is a performance issue
if(velocities.HasInvalidValues()) {
std::stringstream msg;
msg << "SetOmega call had at least one value with non-finite value, velocities: "
<< Convert::ToString(velocities);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
NewtonBodySetOmega(Body, &velocities.X);
}
DLLEXPORT void Physics::AddOmega(const Float3& velocities)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
// Safety check. Can be disabled in release builds if this is a performance issue
if(velocities.HasInvalidValues()) {
std::stringstream msg;
msg << "AddOmega call had at least one value with non-finite value, velocities: "
<< Convert::ToString(velocities);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
Float3 temp;
NewtonBodyGetOmega(Body, &temp.X);
temp += velocities;
NewtonBodySetOmega(Body, &temp.X);
}
// ------------------------------------ //
DLLEXPORT Float3 Physics::GetTorque() const
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
Float3 torq(0);
NewtonBodyGetTorque(Body, &torq.X);
return torq;
}
DLLEXPORT void Physics::AddTorque(const Float3& torque)
{
// Safety check. Can be disabled in release builds if this is a performance issue
if(torque.HasInvalidValues()) {
std::stringstream msg;
msg << "AddTorque call had at least one value with non-finite value, torque: "
<< Convert::ToString(torque);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
if(TorqueOverride) {
SumQueuedTorque = Float3(0, 0, 0);
TorqueOverride = false;
}
SumQueuedTorque += torque;
}
DLLEXPORT void Physics::SetTorque(const Float3& torque)
{
// Safety check. Can be disabled in release builds if this is a performance issue
if(torque.HasInvalidValues()) {
std::stringstream msg;
msg << "SetTorque call had at least one value with non-finite value, torque: "
<< Convert::ToString(torque);
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
SumQueuedTorque = torque;
TorqueOverride = true;
}
DLLEXPORT void Physics::SetLinearDamping(float factor /*= 0.1f*/)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
NewtonBodySetLinearDamping(Body, factor);
}
DLLEXPORT void Physics::SetAngularDamping(const Float3& factor /*= Float3(0.1f)*/)
{
if(!Body)
throw InvalidState("Physics object doesn't have a body");
NewtonBodySetAngularDamping(Body, &factor.X);
}
// ------------------------------------ //
Float3 Physics::_GatherApplyForces(const float& mass)
{
// Return if just an empty list //
if(ApplyForceList.empty())
return Float3(0);
Float3 total(0);
for(auto iter = ApplyForceList.begin(); iter != ApplyForceList.end(); ++iter) {
// Add to total, and multiply by mass if wanted //
const Float3 force = (*iter)->Callback((*iter).get(), *this);
total += (*iter)->MultiplyByMass ? force * mass : force;
// We might assert/crash here if the force was removed //
}
return total;
}
// ------------------------------------ //
DLLEXPORT void Physics::ApplyForce(ApplyForceInfo* pointertohandle)
{
// Overwrite old if found //
for(auto iter = ApplyForceList.begin(); iter != ApplyForceList.end(); ++iter) {
// Check do the names match //
if((bool)(*iter)->OptionalName == (bool)pointertohandle->OptionalName) {
if(!pointertohandle->OptionalName ||
*pointertohandle->OptionalName == *(*iter)->OptionalName) {
// it's the default, overwrite //
**iter = *pointertohandle;
SAFE_DELETE(pointertohandle);
return;
}
}
}
// got here, so add a new one //
ApplyForceList.push_back(std::shared_ptr<ApplyForceInfo>(pointertohandle));
}
DLLEXPORT bool Physics::RemoveApplyForce(const std::string& name)
{
// Search for a matching name //
auto end = ApplyForceList.end();
for(auto iter = ApplyForceList.begin(); iter != end; ++iter) {
// Check do the names match //
if((!((*iter)->OptionalName) && name.size() == 0) ||
((*iter)->OptionalName && *(*iter)->OptionalName == name)) {
ApplyForceList.erase(iter);
return true;
}
}
return false;
}
// ------------------------------------ //
DLLEXPORT void Physics::SetPhysicalMaterialID(int ID)
{
if(!Body) {
throw InvalidState("Calling set material ID without having physical Body");
}
NewtonBodySetMaterialGroupID(Body, ID);
}
// ------------------------------------ //
DLLEXPORT NewtonBody* Physics::CreatePhysicsBody(
PhysicalWorld* world, int physicsmaterialid /*= -1*/)
{
if(!world || !Collision)
return nullptr;
// Destroy old if there is one //
if(Body)
NewtonDestroyBody(Body);
Body = world->CreateBodyFromCollision(Collision);
if(!Body)
return nullptr;
// Add this as user data //
NewtonBodySetUserData(Body, this);
// Callbacks //
NewtonBodySetTransformCallback(Body, Physics::PhysicsMovedEvent);
NewtonBodySetForceAndTorqueCallback(Body, Physics::ApplyForceAndTorqueEvent);
NewtonBodySetDestructorCallback(Body, Physics::DestroyBodyCallback);
// And material //
if(physicsmaterialid != -1)
NewtonBodySetMaterialGroupID(Body, physicsmaterialid);
return Body;
}
DLLEXPORT void Physics::SetMass(float mass)
{
if(!Body)
return;
// Safety check. Shouldn't be disabled
if(!std::isfinite(mass)) {
std::stringstream msg;
msg << "SetMass mass is invalid value: " << Convert::ToString(mass)
<< " (use 0 for immovable)";
LOG_ERROR("Physics: " + msg.str());
throw InvalidArgument(msg.str());
}
Mass = mass;
// First calculate inertia and center of mass points //
Float3 inertia;
Float3 centerofmass;
// TODO: cache this per Collision object
NewtonConvexCollisionCalculateInertialMatrix(Collision, &inertia.X, ¢erofmass.X);
// Apply mass to inertia
inertia *= Mass;
#ifdef CHECK_FOR_NANS
// Doesn't work. Apparently there is a chance to screw up the collision object permanently
// if(std::isnan(inertia.X) || std::isnan(inertia.Y) || std::isnan(inertia.Z) ||
// std::isnan(centerofmass.X) || std::isnan(centerofmass.Y) ||
// std::isnan(centerofmass.Z)) {
// LOG_ERROR("Physics: SetMass: failed to calculate collision inertial matrix, "
// "trying again");
// SetMass(mass);
// return;
// }
inertia.CheckForNans();
centerofmass.CheckForNans();
#endif // CHECK_FOR_NANS
NewtonBodySetMassMatrix(Body, Mass, inertia.X, inertia.Y, inertia.Z);
NewtonBodySetCentreOfMass(Body, ¢erofmass.X);
}
DLLEXPORT bool Physics::SetCollision(NewtonCollision* collision)
{
if(Body)
return false;
if(Collision)
Release();
Collision = collision;
return true;
}
// ------------------------------------ //
DLLEXPORT bool Physics::CreatePlaneConstraint(
PhysicalWorld* world, const Float3& planenormal /*= Float3(0, 1, 0)*/)
{
if(!Body || !world)
return false;
world->Create2DJoint(Body, planenormal);
return true;
}
// ------------------ Received ------------------ //
DLLEXPORT void Received::GetServerSentStates(
StoredState const** first, StoredState const** second, int tick, float& progress) const
{
// Used to find the first tick before or on tick //
int firstinpast = std::numeric_limits<int>::max();
int secondfound = 0;
for(auto& obj : ClientStateBuffer) {
if(tick - obj.Tick < firstinpast && tick - obj.Tick >= 0) {
// This is (potentially) the first state //
firstinpast = tick - obj.Tick;
*first = &obj;
}
// For this to be found the client should be around 50-100 milliseconds in the past
if(obj.Tick > tick && (secondfound == 0 || obj.Tick - tick < secondfound)) {
// The second state //
*second = &obj;
secondfound = obj.Tick - tick;
continue;
}
}
if(firstinpast == std::numeric_limits<int>::max() || secondfound == 0) {
throw InvalidState("No stored server states around tick");
}
// If the range is not 1, meaning firstinpast != 0 || secondfound > 1 we need to adjust
// progress
int range = firstinpast + secondfound;
if(range == 1)
return;
progress = ((tick + progress) - (*first)->Tick) / range;
}
// // ------------------ Trail ------------------ //
// DLLEXPORT bool Trail::SetTrailProperties(const Properties &variables, bool force /*=
// false*/){
//
// if(!TrailEntity || !_RenderNode)
// return false;
// // Set if we unconnected the node and we should reconnect it afterwards //
// bool ConnectAgain = false;
// // Determine if we need to unconnect the node //
// if(force || variables.MaxChainElements != CurrentSettings.MaxChainElements){
// // This to avoid Ogre bug //
// TrailEntity->removeNode(_RenderNode->Node);
// ConnectAgain = true;
// // Apply the properties //
// TrailEntity->setUseVertexColours(true);
// TrailEntity->setRenderingDistance(variables.MaxDistance);
// TrailEntity->setMaxChainElements(variables.MaxChainElements);
// TrailEntity->setCastShadows(variables.CastShadows);
// TrailEntity->setTrailLength(variables.TrailLenght);
// }
// // Update cached settings //
// CurrentSettings = variables;
// // Apply per element properties //
// for(size_t i = 0; i < variables.Elements.size(); i++){
// // Apply settings //
// const ElementProperties& tmp = variables.Elements[i];
// TrailEntity->setInitialColour(i, tmp.InitialColour);
// TrailEntity->setInitialWidth(i, tmp.InitialSize);
// TrailEntity->setColourChange(i, tmp.ColourChange);
// TrailEntity->setWidthChange(i, tmp.SizeChange);
// }
// // More bug avoiding //
// if(ConnectAgain)
// TrailEntity->addNode(_RenderNode->Node);
// return true;
// }
// // ------------------------------------ //
// DLLEXPORT void Trail::Release(Ogre::SceneManager* scene){
// if(TrailEntity){
// scene->destroyRibbonTrail(TrailEntity);
// TrailEntity = nullptr;
// }
// }
// ------------------ Sendable ------------------ //
DLLEXPORT void Sendable::ActiveConnection::CheckReceivedPackets()
{
if(SentPackets.empty())
return;
// Looped in reverse to hopefully remove only last elements //
for(int i = static_cast<int>(SentPackets.size() - 1); i >= 0;) {
const auto& tuple = SentPackets[i];
if(std::get<2>(tuple)->IsFinalized()) {
if(std::get<2>(tuple)->GetStatus()) {
// Succeeded //
if(std::get<0>(tuple) > LastConfirmedTickNumber) {
LastConfirmedTickNumber = std::get<0>(tuple);
LastConfirmedData = std::get<1>(tuple);
}
}
SentPackets.erase(SentPackets.begin() + i);
if(SentPackets.empty())
break;
} else {
i--;
}
}
if(SentPackets.capacity() > 10) {
Logger::Get()->Warning("Sendable::ActiveConnection: SentPackets has space for over 10 "
"sent packets");
SentPackets.shrink_to_fit();
}
}
// ------------------------------------ //
DLLEXPORT Model::Model(
Ogre::SceneManager* scene, Ogre::SceneNode* parent, const std::string& meshname) :
Component(TYPE)
{
GraphicalObject = scene->createItem(meshname);
GraphicalObject->setRenderQueueGroup(DEFAULT_RENDER_QUEUE);
parent->attachObject(GraphicalObject);
}
DLLEXPORT void Model::Release(Ogre::SceneManager* scene)
{
scene->destroyItem(GraphicalObject);
}
// ------------------ ManualObject ------------------ //
DLLEXPORT ManualObject::ManualObject(Ogre::SceneManager* scene) : Component(TYPE)
{
Object = scene->createManualObject();
Object->setRenderQueueGroup(DEFAULT_RENDER_QUEUE);
}
DLLEXPORT void ManualObject::Release(Ogre::SceneManager* scene)
{
if(Object) {
scene->destroyManualObject(Object);
Object = nullptr;
}
CreatedMesh.clear();
}
| 28.702607 | 95 | 0.621094 | [
"mesh",
"render",
"object",
"model"
] |
c3bcd9aaea695ffd2bde8951e55c636768ec1b28 | 37,362 | cc | C++ | src/third_party/mozc/session/internal/keymap.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/third_party/mozc/session/internal/keymap.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/third_party/mozc/session/internal/keymap.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright 2010-2011, Google Inc.
// All rights reserved.
//
// 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// 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.
// Keymap utils of Mozc interface.
#include "session/internal/keymap.h"
#include <string>
#include <vector>
#include <sstream>
#include "base/file_stream.h"
#include "base/config_file_stream.h"
#include "base/util.h"
#include "config/config.pb.h"
#include "config/config_handler.h"
#include "session/commands.pb.h"
#include "session/internal/keymap-inl.h"
#include "session/key_event_normalizer.h"
#include "session/key_parser.h"
namespace mozc {
namespace keymap {
namespace {
static const char kMSIMEKeyMapFile[] = "system://ms-ime.tsv";
static const char kATOKKeyMapFile[] = "system://atok.tsv";
static const char kKotoeriKeyMapFile[] = "system://kotoeri.tsv";
static const char kCustomKeyMapFile[] = "user://keymap.tsv";
uint32 GetModifiers(const commands::KeyEvent &key_event) {
uint32 modifiers = 0;
if (key_event.has_modifiers()) {
modifiers = key_event.modifiers();
} else {
for (int i = 0; i < key_event.modifier_keys_size(); ++i) {
modifiers |= key_event.modifier_keys(i);
}
}
return modifiers;
}
} // anonymous namespace
void NormalizeKeyEvent(const commands::KeyEvent &key_event,
commands::KeyEvent *new_key_event) {
DCHECK(new_key_event);
new_key_event->CopyFrom(key_event);
if ((GetModifiers(key_event) & (commands::KeyEvent::CAPS)) == 0) {
// No caps lock. Nothing to do.
return;
}
// Remove caps lock from |new_key_event->modifier_keys()|.
new_key_event->clear_modifier_keys();
for (size_t i = 0; i < key_event.modifier_keys_size(); ++i) {
if (key_event.modifier_keys(i) != commands::KeyEvent::CAPS) {
new_key_event->add_modifier_keys(key_event.modifier_keys(i));
}
}
if (!key_event.has_key_code()) {
return;
}
// Revert the flip of alphabetical key events caused by CapsLock.
const int key_code = key_event.key_code();
if ('A' <= key_code && key_code <= 'Z') {
new_key_event->set_key_code(key_code - 'A' + 'a');
} else if ('a' <= key_code && key_code <= 'z') {
new_key_event->set_key_code(key_code - 'a' + 'A');
}
}
bool GetKey(const commands::KeyEvent &key_event, Key *key) {
// Key is an alias of uint64.
Key modifier_keys = GetModifiers(key_event);
Key special_key = key_event.has_special_key() ?
key_event.special_key() : commands::KeyEvent::NO_SPECIALKEY;
Key key_code = key_event.has_key_code() ? key_event.key_code() : 0;
// Make sure the translation from the obsolete spesification.
// key_code should no longer contain control characters.
if (0 < key_code && key_code <= 32) {
return false;
}
// Key = |Modifiers(16bit)|SpecialKey(16bit)|Unicode(32bit)|.
*key = (modifier_keys << 48) + (special_key << 32) + key_code;
return true;
}
// Return a fallback keyevent generated from key_event. In the
// current implementation, if the input key_event does not contains
// any special keys or modifier keys, that printable key will be replaced
// with the ASCII special key.
bool MaybeGetKeyStub(const commands::KeyEvent &key_event, Key *key) {
// If any modifier keys were pressed, this function does nothing.
if (GetModifiers(key_event) != 0) {
return false;
}
// No stub rule is supported for special keys yet.
if (key_event.has_special_key()) {
return false;
}
if (!key_event.has_key_code() || key_event.key_code() <= 32) {
return false;
}
commands::KeyEvent stub_key_event;
stub_key_event.set_special_key(commands::KeyEvent::ASCII);
if (!GetKey(stub_key_event, key)) {
return false;
}
return true;
}
KeyMapManager::KeyMapManager()
: keymap_(config::Config::NONE) {
InitCommandData();
ReloadWithKeymap(GET_CONFIG(session_keymap));
}
KeyMapManager::~KeyMapManager() {}
void KeyMapManager::CheckIMEOnOffKeymap() {
uint64 key_on = 0, key_off = 0, key_eisu = 0;
{
commands::KeyEvent key_event;
KeyParser::ParseKey("ON", &key_event);
KeyEventNormalizer::ToUint64(key_event, &key_on);
}
{
commands::KeyEvent key_event;
KeyParser::ParseKey("OFF", &key_event);
KeyEventNormalizer::ToUint64(key_event, &key_off);
}
{
commands::KeyEvent key_event;
KeyParser::ParseKey("EISU", &key_event);
KeyEventNormalizer::ToUint64(key_event, &key_eisu);
}
if (key_on == 0 || key_off == 0 || key_eisu == 0) {
// One of KeyEventNormalizer fails: do nothing to avoid unexpected errors.
return;
}
bool need_to_be_migrated = true;
for (set<uint64>::const_iterator iter = ime_on_off_keys_.begin();
iter != ime_on_off_keys_.end(); ++iter) {
if (*iter != key_on && *iter != key_off && *iter != key_eisu) {
// This seems to have own settings.
need_to_be_migrated = false;
break;
}
}
if (need_to_be_migrated) {
// Add rules
commands::KeyEvent key_event_hankaku;
commands::KeyEvent key_event_kanji;
KeyParser::ParseKey("Hankaku/Zenkaku", &key_event_hankaku);
KeyParser::ParseKey("Kanji", &key_event_kanji);
keymap_direct_.AddRule(key_event_hankaku, DirectInputState::IME_ON);
keymap_precomposition_.AddRule(key_event_hankaku,
PrecompositionState::IME_OFF);
keymap_composition_.AddRule(key_event_hankaku, CompositionState::IME_OFF);
keymap_conversion_.AddRule(key_event_hankaku, ConversionState::IME_OFF);
keymap_direct_.AddRule(key_event_kanji, DirectInputState::IME_ON);
keymap_precomposition_.AddRule(key_event_kanji,
PrecompositionState::IME_OFF);
keymap_composition_.AddRule(key_event_kanji, CompositionState::IME_OFF);
keymap_conversion_.AddRule(key_event_kanji, ConversionState::IME_OFF);
// Write settings
config::Config config;
config.CopyFrom(config::ConfigHandler::GetConfig());
ostringstream oss(config.custom_keymap_table());
oss << endl;
oss << "DirectInput\tHankaku/Zenkaku\tIMEOn" << endl;
oss << "DirectInput\tKanji\tIMEOn" << endl;
oss << "Conversion\tHankaku/Zenkaku\tIMEOff" << endl;
oss << "Conversion\tKanji\tIMEOff" << endl;
oss << "Precomposition\tHankaku/Zenkaku\tIMEOff" << endl;
oss << "Precomposition\tKanji\tIMEOff" << endl;
oss << "Composition\tHankaku/Zenkaku\tIMEOff" << endl;
oss << "Composition\tKanji\tIMEOff" << endl;
config.set_custom_keymap_table(oss.str());
config::ConfigHandler::SetConfig(config);
}
}
bool KeyMapManager::ReloadWithKeymap(
const config::Config::SessionKeymap new_keymap) {
// If the current keymap is the same with the new keymap and not
// CUSTOM, do nothing.
if (new_keymap == keymap_ && new_keymap != config::Config::CUSTOM) {
return true;
}
keymap_ = new_keymap;
const char *keymap_file = GetKeyMapFileName(new_keymap);
// Clear the previous keymaps.
keymap_direct_.Clear();
keymap_precomposition_.Clear();
keymap_composition_.Clear();
keymap_conversion_.Clear();
keymap_zero_query_suggestion_.Clear();
keymap_suggestion_.Clear();
keymap_prediction_.Clear();
ime_on_off_keys_.clear();
if (new_keymap == config::Config::CUSTOM) {
const string &custom_keymap_table = GET_CONFIG(custom_keymap_table);
if (custom_keymap_table.empty()) {
LOG(WARNING) << "custom_keymap_table is empty. use default setting";
const char *default_keymapfile = GetKeyMapFileName(GetDefaultKeyMap());
return LoadFile(default_keymapfile);
}
#ifndef NO_LOGGING
// make a copy of keymap file just for debugging
const string filename = ConfigFileStream::GetFileName(keymap_file);
OutputFileStream ofs(filename.c_str());
if (ofs) {
ofs << "# This is a copy of keymap table for debugging." << endl;
ofs << "# Nothing happens when you edit this file manually." << endl;
ofs << custom_keymap_table;
}
#endif
istringstream ifs(custom_keymap_table);
const bool result = LoadStream(&ifs);
CheckIMEOnOffKeymap();
return result;
}
if (keymap_file != NULL && LoadFile(keymap_file)) {
return true;
}
const char *default_keymapfile = GetKeyMapFileName(GetDefaultKeyMap());
return LoadFile(default_keymapfile);
}
// static
const char *KeyMapManager::GetKeyMapFileName(
const config::Config::SessionKeymap keymap) {
switch(keymap) {
case config::Config::ATOK:
return kATOKKeyMapFile;
case config::Config::MSIME:
return kMSIMEKeyMapFile;
case config::Config::KOTOERI:
return kKotoeriKeyMapFile;
case config::Config::CUSTOM:
return kCustomKeyMapFile;
case config::Config::NONE:
default:
// should not appear here.
LOG(ERROR) << "Keymap type: " << keymap
<< " appeared at key map initialization.";
const config::Config::SessionKeymap default_keymap = GetDefaultKeyMap();
DCHECK(default_keymap == config::Config::ATOK ||
default_keymap == config::Config::MSIME ||
default_keymap == config::Config::KOTOERI ||
default_keymap == config::Config::CUSTOM);
// should never make loop.
return GetKeyMapFileName(default_keymap);
}
}
// static
config::Config::SessionKeymap KeyMapManager::GetDefaultKeyMap() {
#ifdef OS_MACOSX
return config::Config::KOTOERI;
#else // OS_MACOSX
return config::Config::MSIME;
#endif // OS_MACOSX
}
bool KeyMapManager::LoadFile(const char *filename) {
scoped_ptr<istream> ifs(ConfigFileStream::Open(filename));
if (ifs.get() == NULL) {
LOG(WARNING) << "cannot load keymap table: " << filename;
return false;
}
return LoadStream(ifs.get());
}
bool KeyMapManager::LoadStream(istream *ifs) {
vector<string> errors;
return LoadStreamWithErrors(ifs, &errors);
}
bool KeyMapManager::LoadStreamWithErrors(istream *ifs, vector<string> *errors) {
string line;
getline(*ifs, line); // Skip the first line.
while (!ifs->eof()) {
getline(*ifs, line);
Util::ChopReturns(&line);
if (line.empty() || line[0] == '#') { // Skip empty or comment line.
continue;
}
vector<string> rules;
Util::SplitStringUsing(line, "\t", &rules);
if (rules.size() != 3) {
LOG(ERROR) << "Invalid format: " << line;
continue;
}
if (!AddCommand(rules[0], rules[1], rules[2])) {
errors->push_back(line);
LOG(ERROR) << "Unknown command: " << line;
}
}
commands::KeyEvent key_event;
KeyParser::ParseKey("ASCII", &key_event);
keymap_precomposition_.AddRule(key_event,
PrecompositionState::INSERT_CHARACTER);
keymap_composition_.AddRule(key_event, CompositionState::INSERT_CHARACTER);
keymap_conversion_.AddRule(key_event, ConversionState::INSERT_CHARACTER);
key_event.Clear();
KeyParser::ParseKey("Shift", &key_event);
keymap_composition_.AddRule(key_event, CompositionState::INSERT_CHARACTER);
return true;
}
bool KeyMapManager::AddCommand(const string &state_name,
const string &key_event_name,
const string &command_name) {
#ifdef NO_LOGGING // means RELEASE BUILD
// On the release build, we do not support the Abort and ReportBug
// commands. Note, true is returned as the arguments are
// interpreted properly.
if (command_name == "Abort" || command_name == "ReportBug") {
return true;
}
#endif // NO_LOGGING
#ifndef _DEBUG
// Only debug build supports the Abort command. Note, true is
// returned as the arguments are interpreted properly.
if (command_name == "Abort") {
return true;
}
#endif // NO_LOGGING
commands::KeyEvent key_event;
if (!KeyParser::ParseKey(key_event_name, &key_event)) {
return false;
}
// Migration code:
// check key events for IME ON/OFF
{
if (command_name == "IMEOn" ||
command_name == "IMEOff") {
uint64 key;
if (KeyEventNormalizer::ToUint64(key_event, &key)) {
ime_on_off_keys_.insert(key);
}
}
}
if (state_name == "DirectInput" || state_name == "Direct") {
DirectInputState::Commands command;
if (!ParseCommandDirect(command_name, &command)) {
return false;
}
keymap_direct_.AddRule(key_event, command);
return true;
}
if (state_name == "Precomposition") {
PrecompositionState::Commands command;
if (!ParseCommandPrecomposition(command_name, &command)) {
return false;
}
keymap_precomposition_.AddRule(key_event, command);
return true;
}
if (state_name == "Composition") {
CompositionState::Commands command;
if (!ParseCommandComposition(command_name, &command)) {
return false;
}
keymap_composition_.AddRule(key_event, command);
return true;
}
if (state_name == "Conversion") {
ConversionState::Commands command;
if (!ParseCommandConversion(command_name, &command)) {
return false;
}
keymap_conversion_.AddRule(key_event, command);
return true;
}
if (state_name == "ZeroQuerySuggestion") {
PrecompositionState::Commands command;
if (!ParseCommandPrecomposition(command_name, &command)) {
return false;
}
keymap_zero_query_suggestion_.AddRule(key_event, command);
return true;
}
if (state_name == "Suggestion") {
CompositionState::Commands command;
if (!ParseCommandComposition(command_name, &command)) {
return false;
}
keymap_suggestion_.AddRule(key_event, command);
return true;
}
if (state_name == "Prediction") {
ConversionState::Commands command;
if (!ParseCommandConversion(command_name, &command)) {
return false;
}
keymap_prediction_.AddRule(key_event, command);
return true;
}
return false;
}
namespace {
template<typename T> bool GetNameInternal(
const map<T, string> &reverse_command_map, T command, string *name) {
DCHECK(name);
typename map<T, string>::const_iterator iter =
reverse_command_map.find(command);
if (iter == reverse_command_map.end()) {
return false;
} else {
*name = iter->second;
return true;
}
}
} // namespace
bool KeyMapManager::GetNameFromCommandDirect(
DirectInputState::Commands command, string *name) const {
return GetNameInternal<DirectInputState::Commands>(
reverse_command_direct_map_, command, name);
}
bool KeyMapManager::GetNameFromCommandPrecomposition(
PrecompositionState::Commands command, string *name) const {
return GetNameInternal<PrecompositionState::Commands>(
reverse_command_precomposition_map_, command, name);
}
bool KeyMapManager::GetNameFromCommandComposition(
CompositionState::Commands command, string *name) const {
return GetNameInternal<CompositionState::Commands>(
reverse_command_composition_map_, command, name);
}
bool KeyMapManager::GetNameFromCommandConversion(
ConversionState::Commands command, string *name) const {
return GetNameInternal<ConversionState::Commands>(
reverse_command_conversion_map_, command, name);
}
void KeyMapManager::RegisterDirectCommand(
const string &command_string, DirectInputState::Commands command) {
command_direct_map_[command_string] = command;
reverse_command_direct_map_[command] = command_string;
}
void KeyMapManager::RegisterPrecompositionCommand(
const string &command_string, PrecompositionState::Commands command) {
command_precomposition_map_[command_string] = command;
reverse_command_precomposition_map_[command] = command_string;
}
void KeyMapManager::RegisterCompositionCommand(
const string &command_string, CompositionState::Commands command) {
command_composition_map_[command_string] = command;
reverse_command_composition_map_[command] = command_string;
}
void KeyMapManager::RegisterConversionCommand(
const string &command_string, ConversionState::Commands command) {
command_conversion_map_[command_string] = command;
reverse_command_conversion_map_[command] = command_string;
}
void KeyMapManager::InitCommandData() {
RegisterDirectCommand("IMEOn", DirectInputState::IME_ON);
// Support InputMode command only on Windows for now.
// TODO(toshiyuki): delete #ifdef when we support them on Mac, and
// activate SessionTest.InputModeConsumedForTestSendKey.
#ifdef OS_WINDOWS
RegisterDirectCommand("InputModeHiragana",
DirectInputState::INPUT_MODE_HIRAGANA);
RegisterDirectCommand("InputModeFullKatakana",
DirectInputState::INPUT_MODE_FULL_KATAKANA);
RegisterDirectCommand("InputModeHalfKatakana",
DirectInputState::INPUT_MODE_HALF_KATAKANA);
RegisterDirectCommand("InputModeFullAlphanumeric",
DirectInputState::INPUT_MODE_FULL_ALPHANUMERIC);
RegisterDirectCommand("InputModeHalfAlphanumeric",
DirectInputState::INPUT_MODE_HALF_ALPHANUMERIC);
#else
RegisterDirectCommand("InputModeHiragana",
DirectInputState::NONE);
RegisterDirectCommand("InputModeFullKatakana",
DirectInputState::NONE);
RegisterDirectCommand("InputModeHalfKatakana",
DirectInputState::NONE);
RegisterDirectCommand("InputModeFullAlphanumeric",
DirectInputState::NONE);
RegisterDirectCommand("InputModeHalfAlphanumeric",
DirectInputState::NONE);
#endif // OS_WINDOWS
RegisterDirectCommand("Reconvert",
DirectInputState::RECONVERT);
// Precomposition
RegisterPrecompositionCommand("IMEOff", PrecompositionState::IME_OFF);
RegisterPrecompositionCommand("IMEOn", PrecompositionState::IME_ON);
RegisterPrecompositionCommand("InsertCharacter",
PrecompositionState::INSERT_CHARACTER);
RegisterPrecompositionCommand("InsertSpace",
PrecompositionState::INSERT_SPACE);
RegisterPrecompositionCommand("InsertAlternateSpace",
PrecompositionState::INSERT_ALTERNATE_SPACE);
RegisterPrecompositionCommand("InsertHalfSpace",
PrecompositionState::INSERT_HALF_SPACE);
RegisterPrecompositionCommand("InsertFullSpace",
PrecompositionState::INSERT_FULL_SPACE);
RegisterPrecompositionCommand("ToggleAlphanumericMode",
PrecompositionState::TOGGLE_ALPHANUMERIC_MODE);
#ifdef OS_WINDOWS
RegisterPrecompositionCommand("InputModeHiragana",
PrecompositionState::INPUT_MODE_HIRAGANA);
RegisterPrecompositionCommand("InputModeFullKatakana",
PrecompositionState::INPUT_MODE_FULL_KATAKANA);
RegisterPrecompositionCommand("InputModeHalfKatakana",
PrecompositionState::INPUT_MODE_HALF_KATAKANA);
RegisterPrecompositionCommand(
"InputModeFullAlphanumeric",
PrecompositionState::INPUT_MODE_FULL_ALPHANUMERIC);
RegisterPrecompositionCommand(
"InputModeHalfAlphanumeric",
PrecompositionState::INPUT_MODE_HALF_ALPHANUMERIC);
RegisterPrecompositionCommand(
"InputModeSwitchKanaType",
PrecompositionState::INPUT_MODE_SWITCH_KANA_TYPE);
#else
RegisterPrecompositionCommand("InputModeHiragana",
PrecompositionState::NONE);
RegisterPrecompositionCommand("InputModeFullKatakana",
PrecompositionState::NONE);
RegisterPrecompositionCommand("InputModeHalfKatakana",
PrecompositionState::NONE);
RegisterPrecompositionCommand("InputModeFullAlphanumeric",
PrecompositionState::NONE);
RegisterPrecompositionCommand("InputModeHalfAlphanumeric",
PrecompositionState::NONE);
RegisterPrecompositionCommand("InputModeSwitchKanaType",
PrecompositionState::NONE);
#endif // OS_WINDOWS
RegisterPrecompositionCommand("LaunchConfigDialog",
PrecompositionState::LAUNCH_CONFIG_DIALOG);
RegisterPrecompositionCommand("LaunchDictionaryTool",
PrecompositionState::LAUNCH_DICTIONARY_TOOL);
RegisterPrecompositionCommand(
"LaunchWordRegisterDialog",
PrecompositionState::LAUNCH_WORD_REGISTER_DIALOG);
RegisterPrecompositionCommand("Revert", PrecompositionState::REVERT);
RegisterPrecompositionCommand("Undo", PrecompositionState::UNDO);
RegisterPrecompositionCommand("Reconvert", PrecompositionState::RECONVERT);
RegisterPrecompositionCommand("Cancel", PrecompositionState::CANCEL);
RegisterPrecompositionCommand("CommitFirstSuggestion",
PrecompositionState::COMMIT_FIRST_SUGGESTION);
RegisterPrecompositionCommand("PredictAndConvert",
PrecompositionState::PREDICT_AND_CONVERT);
#ifdef _DEBUG // only for debugging
RegisterPrecompositionCommand("Abort", PrecompositionState::ABORT);
#endif // _DEBUG
// Composition
RegisterCompositionCommand("IMEOff", CompositionState::IME_OFF);
RegisterCompositionCommand("IMEOn", CompositionState::IME_ON);
RegisterCompositionCommand("InsertCharacter",
CompositionState::INSERT_CHARACTER);
RegisterCompositionCommand("Delete", CompositionState::DEL);
RegisterCompositionCommand("Backspace", CompositionState::BACKSPACE);
RegisterCompositionCommand("InsertHalfSpace",
CompositionState::INSERT_HALF_SPACE);
RegisterCompositionCommand("InsertFullSpace",
CompositionState::INSERT_FULL_SPACE);
RegisterCompositionCommand("Cancel", CompositionState::CANCEL);
RegisterCompositionCommand("Undo", CompositionState::UNDO);
RegisterCompositionCommand("MoveCursorLeft",
CompositionState::MOVE_CURSOR_LEFT);
RegisterCompositionCommand("MoveCursorRight",
CompositionState::MOVE_CURSOR_RIGHT);
RegisterCompositionCommand("MoveCursorToBeginning",
CompositionState::MOVE_CURSOR_TO_BEGINNING);
RegisterCompositionCommand("MoveCursorToEnd",
CompositionState::MOVE_MOVE_CURSOR_TO_END);
RegisterCompositionCommand("Commit", CompositionState::COMMIT);
RegisterCompositionCommand("CommitFirstSuggestion",
CompositionState::COMMIT_FIRST_SUGGESTION);
RegisterCompositionCommand("Convert", CompositionState::CONVERT);
RegisterCompositionCommand("ConvertWithoutHistory",
CompositionState::CONVERT_WITHOUT_HISTORY);
RegisterCompositionCommand("PredictAndConvert",
CompositionState::PREDICT_AND_CONVERT);
RegisterCompositionCommand("ConvertToHiragana",
CompositionState::CONVERT_TO_HIRAGANA);
RegisterCompositionCommand("ConvertToFullKatakana",
CompositionState::CONVERT_TO_FULL_KATAKANA);
RegisterCompositionCommand("ConvertToHalfKatakana",
CompositionState::CONVERT_TO_HALF_KATAKANA);
RegisterCompositionCommand("ConvertToHalfWidth",
CompositionState::CONVERT_TO_HALF_WIDTH);
RegisterCompositionCommand("ConvertToFullAlphanumeric",
CompositionState::CONVERT_TO_FULL_ALPHANUMERIC);
RegisterCompositionCommand("ConvertToHalfAlphanumeric",
CompositionState::CONVERT_TO_HALF_ALPHANUMERIC);
RegisterCompositionCommand("SwitchKanaType",
CompositionState::SWITCH_KANA_TYPE);
RegisterCompositionCommand("DisplayAsHiragana",
CompositionState::DISPLAY_AS_HIRAGANA);
RegisterCompositionCommand("DisplayAsFullKatakana",
CompositionState::DISPLAY_AS_FULL_KATAKANA);
RegisterCompositionCommand("DisplayAsHalfKatakana",
CompositionState::DISPLAY_AS_HALF_KATAKANA);
RegisterCompositionCommand("DisplayAsHalfWidth",
CompositionState::TRANSLATE_HALF_WIDTH);
RegisterCompositionCommand("DisplayAsFullAlphanumeric",
CompositionState::TRANSLATE_FULL_ASCII);
RegisterCompositionCommand("DisplayAsHalfAlphanumeric",
CompositionState::TRANSLATE_HALF_ASCII);
RegisterCompositionCommand("ToggleAlphanumericMode",
CompositionState::TOGGLE_ALPHANUMERIC_MODE);
#ifdef OS_WINDOWS
RegisterCompositionCommand("InputModeHiragana",
CompositionState::INPUT_MODE_HIRAGANA);
RegisterCompositionCommand("InputModeFullKatakana",
CompositionState::INPUT_MODE_FULL_KATAKANA);
RegisterCompositionCommand("InputModeHalfKatakana",
CompositionState::INPUT_MODE_HALF_KATAKANA);
RegisterCompositionCommand("InputModeFullAlphanumeric",
CompositionState::INPUT_MODE_FULL_ALPHANUMERIC);
RegisterCompositionCommand("InputModeHalfAlphanumeric",
CompositionState::INPUT_MODE_HALF_ALPHANUMERIC);
#else
RegisterCompositionCommand("InputModeHiragana",
CompositionState::NONE);
RegisterCompositionCommand("InputModeFullKatakana",
CompositionState::NONE);
RegisterCompositionCommand("InputModeHalfKatakana",
CompositionState::NONE);
RegisterCompositionCommand("InputModeFullAlphanumeric",
CompositionState::NONE);
RegisterCompositionCommand("InputModeHalfAlphanumeric",
CompositionState::NONE);
#endif // OS_WINDOWS
#ifdef _DEBUG // only for debugging
RegisterCompositionCommand("Abort", CompositionState::ABORT);
#endif // _DEBUG
// Conversion
RegisterConversionCommand("IMEOff", ConversionState::IME_OFF);
RegisterConversionCommand("IMEOn", ConversionState::IME_ON);
RegisterConversionCommand("InsertCharacter",
ConversionState::INSERT_CHARACTER);
RegisterConversionCommand("InsertHalfSpace",
ConversionState::INSERT_HALF_SPACE);
RegisterConversionCommand("InsertFullSpace",
ConversionState::INSERT_FULL_SPACE);
RegisterConversionCommand("Cancel", ConversionState::CANCEL);
RegisterConversionCommand("Undo", ConversionState::UNDO);
RegisterConversionCommand("SegmentFocusLeft",
ConversionState::SEGMENT_FOCUS_LEFT);
RegisterConversionCommand("SegmentFocusRight",
ConversionState::SEGMENT_FOCUS_RIGHT);
RegisterConversionCommand("SegmentFocusFirst",
ConversionState::SEGMENT_FOCUS_FIRST);
RegisterConversionCommand("SegmentFocusLast",
ConversionState::SEGMENT_FOCUS_LAST);
RegisterConversionCommand("SegmentWidthExpand",
ConversionState::SEGMENT_WIDTH_EXPAND);
RegisterConversionCommand("SegmentWidthShrink",
ConversionState::SEGMENT_WIDTH_SHRINK);
RegisterConversionCommand("ConvertNext", ConversionState::CONVERT_NEXT);
RegisterConversionCommand("ConvertPrev", ConversionState::CONVERT_PREV);
RegisterConversionCommand("ConvertNextPage",
ConversionState::CONVERT_NEXT_PAGE);
RegisterConversionCommand("ConvertPrevPage",
ConversionState::CONVERT_PREV_PAGE);
RegisterConversionCommand("PredictAndConvert",
ConversionState::PREDICT_AND_CONVERT);
RegisterConversionCommand("Commit", ConversionState::COMMIT);
RegisterConversionCommand("CommitOnlyFirstSegment",
ConversionState::COMMIT_SEGMENT);
RegisterConversionCommand("ConvertToHiragana",
ConversionState::CONVERT_TO_HIRAGANA);
RegisterConversionCommand("ConvertToFullKatakana",
ConversionState::CONVERT_TO_FULL_KATAKANA);
RegisterConversionCommand("ConvertToHalfKatakana",
ConversionState::CONVERT_TO_HALF_KATAKANA);
RegisterConversionCommand("ConvertToHalfWidth",
ConversionState::CONVERT_TO_HALF_WIDTH);
RegisterConversionCommand("ConvertToFullAlphanumeric",
ConversionState::CONVERT_TO_FULL_ALPHANUMERIC);
RegisterConversionCommand("ConvertToHalfAlphanumeric",
ConversionState::CONVERT_TO_HALF_ALPHANUMERIC);
RegisterConversionCommand("SwitchKanaType",
ConversionState::SWITCH_KANA_TYPE);
RegisterConversionCommand("ToggleAlphanumericMode",
ConversionState::TOGGLE_ALPHANUMERIC_MODE);
RegisterConversionCommand("DisplayAsHiragana",
ConversionState::DISPLAY_AS_HIRAGANA);
RegisterConversionCommand("DisplayAsFullKatakana",
ConversionState::DISPLAY_AS_FULL_KATAKANA);
RegisterConversionCommand("DisplayAsHalfKatakana",
ConversionState::DISPLAY_AS_HALF_KATAKANA);
RegisterConversionCommand("DisplayAsHalfWidth",
ConversionState::TRANSLATE_HALF_WIDTH);
RegisterConversionCommand("DisplayAsFullAlphanumeric",
ConversionState::TRANSLATE_FULL_ASCII);
RegisterConversionCommand("DisplayAsHalfAlphanumeric",
ConversionState::TRANSLATE_HALF_ASCII);
#ifdef OS_WINDOWS
RegisterConversionCommand("InputModeHiragana",
ConversionState::INPUT_MODE_HIRAGANA);
RegisterConversionCommand("InputModeFullKatakana",
ConversionState::INPUT_MODE_FULL_KATAKANA);
RegisterConversionCommand("InputModeHalfKatakana",
ConversionState::INPUT_MODE_HALF_KATAKANA);
RegisterConversionCommand("InputModeFullAlphanumeric",
ConversionState::INPUT_MODE_FULL_ALPHANUMERIC);
RegisterConversionCommand("InputModeHalfAlphanumeric",
ConversionState::INPUT_MODE_HALF_ALPHANUMERIC);
#else
RegisterConversionCommand("InputModeHiragana",
ConversionState::NONE);
RegisterConversionCommand("InputModeFullKatakana",
ConversionState::NONE);
RegisterConversionCommand("InputModeHalfKatakana",
ConversionState::NONE);
RegisterConversionCommand("InputModeFullAlphanumeric",
ConversionState::NONE);
RegisterConversionCommand("InputModeHalfAlphanumeric",
ConversionState::NONE);
#endif // OS_WINDOWS
#ifndef NO_LOGGING // means NOT RELEASE build
RegisterConversionCommand("ReportBug", ConversionState::REPORT_BUG);
#endif // NO_LOGGING
#ifdef _DEBUG // only for dubugging
RegisterConversionCommand("Abort", ConversionState::ABORT);
#endif // _DEBUG
}
#undef ADD_TO_COMMAND_MAP
bool KeyMapManager::GetCommandDirect(
const commands::KeyEvent &key_event,
DirectInputState::Commands *command) const {
return keymap_direct_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandPrecomposition(
const commands::KeyEvent &key_event,
PrecompositionState::Commands *command) const {
return keymap_precomposition_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandComposition(
const commands::KeyEvent &key_event,
CompositionState::Commands *command) const {
return keymap_composition_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandZeroQuerySuggestion(
const commands::KeyEvent &key_event,
PrecompositionState::Commands *command) const {
// try zero query suggestion rule first
if (keymap_zero_query_suggestion_.GetCommand(key_event, command)) {
return true;
}
// use precomposition rule
return keymap_precomposition_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandSuggestion(
const commands::KeyEvent &key_event,
CompositionState::Commands *command) const {
// try suggestion rule first
if (keymap_suggestion_.GetCommand(key_event, command)) {
return true;
}
// use composition rule
return keymap_composition_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandConversion(
const commands::KeyEvent &key_event,
ConversionState::Commands *command) const {
return keymap_conversion_.GetCommand(key_event, command);
}
bool KeyMapManager::GetCommandPrediction(
const commands::KeyEvent &key_event,
ConversionState::Commands *command) const {
// try prediction rule first
if (keymap_prediction_.GetCommand(key_event, command)) {
return true;
}
// use conversion rule
return keymap_conversion_.GetCommand(key_event, command);
}
bool KeyMapManager::ParseCommandDirect(
const string &command_string,
DirectInputState::Commands *command) const {
if (command_direct_map_.count(command_string) == 0) {
return false;
}
*command = command_direct_map_.find(command_string)->second;
return true;
}
// This should be in KeyMap instead of KeyMapManager.
bool KeyMapManager::ParseCommandPrecomposition(
const string &command_string,
PrecompositionState::Commands *command) const {
if (command_precomposition_map_.count(command_string) == 0) {
return false;
}
*command = command_precomposition_map_.find(command_string)->second;
return true;
}
bool KeyMapManager::ParseCommandComposition(
const string &command_string,
CompositionState::Commands *command) const {
if (command_composition_map_.count(command_string) == 0) {
return false;
}
*command = command_composition_map_.find(command_string)->second;
return true;
}
bool KeyMapManager::ParseCommandConversion(
const string &command_string,
ConversionState::Commands *command) const {
if (command_conversion_map_.count(command_string) == 0) {
return false;
}
*command = command_conversion_map_.find(command_string)->second;
return true;
}
void KeyMapManager::GetAvailableCommandNameDirect(
set<string> *command_names) const {
DCHECK(command_names);
for (map<string, DirectInputState::Commands>::const_iterator iter
= command_direct_map_.begin();
iter != command_direct_map_.end(); ++iter) {
command_names->insert(iter->first);
}
}
void KeyMapManager::GetAvailableCommandNamePrecomposition(
set<string> *command_names) const {
DCHECK(command_names);
for (map<string, PrecompositionState::Commands>::const_iterator iter
= command_precomposition_map_.begin();
iter != command_precomposition_map_.end(); ++iter) {
command_names->insert(iter->first);
}
}
void KeyMapManager::GetAvailableCommandNameComposition(
set<string> *command_names) const {
DCHECK(command_names);
for (map<string, CompositionState::Commands>::const_iterator iter
= command_composition_map_.begin();
iter != command_composition_map_.end(); ++iter) {
command_names->insert(iter->first);
}
}
void KeyMapManager::GetAvailableCommandNameConversion(
set<string> *command_names) const {
DCHECK(command_names);
for (map<string, ConversionState::Commands>::const_iterator iter
= command_conversion_map_.begin();
iter != command_conversion_map_.end(); ++iter) {
command_names->insert(iter->first);
}
}
void KeyMapManager::GetAvailableCommandNameZeroQuerySuggestion(
set<string> *command_names) const {
GetAvailableCommandNamePrecomposition(command_names);
}
void KeyMapManager::GetAvailableCommandNameSuggestion(
set<string> *command_names) const {
GetAvailableCommandNameComposition(command_names);
}
void KeyMapManager::GetAvailableCommandNamePrediction(
set<string> *command_names) const {
GetAvailableCommandNameConversion(command_names);
}
} // namespace keymap
} // namespace mozc
| 38.557276 | 80 | 0.703067 | [
"vector"
] |
c3be790675d79fa8739b5861a8c47e3dceb0bc0f | 1,596 | hh | C++ | packages/MC/mc/VR_Analog.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | 19 | 2015-06-04T09:02:41.000Z | 2021-04-27T19:32:55.000Z | packages/MC/mc/VR_Analog.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | null | null | null | packages/MC/mc/VR_Analog.hh | GCZhang/Profugus | d4d8fe295a92a257b26b6082224226ca1edbff5d | [
"BSD-2-Clause"
] | 5 | 2016-10-05T20:48:28.000Z | 2021-06-21T12:00:54.000Z | //----------------------------------*-C++-*----------------------------------//
/*!
* \file MC/mc/VR_Analog.hh
* \author Thomas M. Evans
* \date Fri May 09 13:09:17 2014
* \brief VR_Analog class definition.
* \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#ifndef MC_mc_VR_Analog_hh
#define MC_mc_VR_Analog_hh
#include "Variance_Reduction.hh"
namespace profugus
{
//===========================================================================//
/*!
* \class VR_Analog
* \brief Analog MC transport.
*/
//===========================================================================//
template <class Geometry>
class VR_Analog : public Variance_Reduction<Geometry>
{
typedef Variance_Reduction<Geometry> Base;
public:
//@{
//! Base-class typedefs.
typedef typename Base::Particle_t Particle_t;
typedef typename Base::Bank_t Bank_t;
//@}
public:
// Constructor.
explicit VR_Analog()
: Base()
{
Base::b_splitting = false;
}
//! Do nothing at surfaces
void post_surface(Particle_t& particle, Bank_t& bank) const { /* * */ }
//! Do nothing at collisions
void post_collision(Particle_t& particle, Bank_t& bank) const { /* * */ }
};
} // end namespace profugus
#endif // MC_mc_VR_Analog_hh
//---------------------------------------------------------------------------//
// end of VR_Analog.hh
//---------------------------------------------------------------------------//
| 26.6 | 79 | 0.45614 | [
"geometry"
] |
c3cb1b90876c1fdec62056ce8b35b647ba318bfa | 7,353 | hpp | C++ | include/subisosat.hpp | fcimeson/circuit_security | 9a0d179209ddc7e8fb9c33e42eaf56a4f76b88f3 | [
"Apache-2.0"
] | 1 | 2018-02-17T05:48:10.000Z | 2018-02-17T05:48:10.000Z | include/subisosat.hpp | fcimeson/circuit_security | 9a0d179209ddc7e8fb9c33e42eaf56a4f76b88f3 | [
"Apache-2.0"
] | null | null | null | include/subisosat.hpp | fcimeson/circuit_security | 9a0d179209ddc7e8fb9c33e42eaf56a4f76b88f3 | [
"Apache-2.0"
] | null | null | null | /********************************************************************************
Copyright 2017 Frank Imeson, Siddharth Garg, and Mahesh V. Tripunitara
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.
*********************************************************************************/
#ifndef SUBISO_H // guard
#define SUBISO_H
/********************************************************************************
* INCLUDE
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <igraph/igraph.h>
#include "formula.hpp"
/********************************************************************************
* Defs
********************************************************************************/
/********************************************************************************
* Prototypes
********************************************************************************/
int igraph_vertex_degree (const igraph_t *graph1, const igraph_integer_t vid);
igraph_bool_t igraph_compare_transitives (
const igraph_t *graph1,
const igraph_t *graph2,
const igraph_integer_t vid1,
const igraph_integer_t vid2,
void *arg);
//void igraph_vector_print (const igraph_vector_t *vector) {
// for (unsigned int i = 0; i < igraph_vector_size(vector); i++)
// std::cout << VECTOR(*vector)[i] << " ";
// std::cout << std::endl;
//};
// see cpp file for documentation
int igraph_test_isomorphic_map (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_bool_t *iso,
const igraph_vector_t *map12,
const igraph_vector_t *map21,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
// see cpp file for documentation
int igraph_subisomorphic_sat (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_bool_t *iso,
igraph_vector_t *map12,
igraph_vector_t *map21,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
// see cpp file for documentation
int igraph_get_subisomorphisms_sat (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_vector_ptr_t *maps,
igraph_vector_t *map12,
igraph_vector_t *map21,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
// see cpp file for documentation
int igraph_count_subisomorphisms_sat (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_integer_t *count,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
// see cpp file for documentation
int igraph_subisomorphic_function_sat (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_vector_t *map12,
igraph_vector_t *map21,
igraph_isohandler_t *isohandler_fn,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
/********************************************************************************
* isosat
********************************************************************************/
namespace isosat {
using namespace Minisat;
using namespace std;
struct M21;
class Isosat;
string str (const M21 &lit);
string str (const igraph_vector_t &vector);
struct M21 {
bool sign;
unsigned int vid2, vid1;
M21 () { vid1=0; vid2=0; sign=false;};
M21 (int _vid2, int _vid1, bool _sign=false) { vid1=_vid1; vid2=_vid2; sign=_sign; };
};
class Isosat {
private:
int error;
int v1_size, v2_size;
int conflict_budget, propagation_budget;
Solver solver;
void minisat_cb (
const VMap<lbool> &assigns,
const vec<Lit>& trail,
vec<Lit>& infer_list);
static void minisat_cb_wrapper (
void* object_pointer,
const VMap<lbool> &assigns,
const vec<Lit>& trail,
vec<Lit>& infer_list);
int set_size();
string str (const vec<Lit> &vector);
public:
Isosat (const igraph_t *graph1, const igraph_t *graph2,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
int add_edge (const igraph_t *graph1, const igraph_t *graph2,
const igraph_integer_t eid,
const igraph_vector_int_t *vertex_colour1,
const igraph_vector_int_t *vertex_colour2,
const igraph_vector_int_t *edge_colour1,
const igraph_vector_int_t *edge_colour2,
igraph_isocompat_t *node_compat_fn,
igraph_isocompat_t *edge_compat_fn,
void *arg);
int solve (
igraph_bool_t *iso,
igraph_vector_t *map12,
igraph_vector_t *map21,
const vec<Lit> *assumptions = NULL);
void setConfBudget(int budget) { conflict_budget = budget; };
void setPropBudget(int budget) { propagation_budget = budget; };
int negate (const igraph_vector_t *map12, igraph_vector_t *map21);
int negate (const M21 v21_map);
int get_error () {return error;}
Lit translate (const M21 &lit);
M21 translate (const Lit &lit);
};
} // end namespace
#endif
| 33.121622 | 89 | 0.584659 | [
"vector"
] |
c3d956e228021eae484a0940c24a11eef6ecf333 | 11,995 | cc | C++ | sfm.cc | pureexe/my-simple-sfm-ceres | 12eed6f2ef4be6d2304b4f8b3851c71e39b51cc1 | [
"MIT"
] | null | null | null | sfm.cc | pureexe/my-simple-sfm-ceres | 12eed6f2ef4be6d2304b4f8b3851c71e39b51cc1 | [
"MIT"
] | null | null | null | sfm.cc | pureexe/my-simple-sfm-ceres | 12eed6f2ef4be6d2304b4f8b3851c71e39b51cc1 | [
"MIT"
] | null | null | null | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// 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.
//
// Author: keir@google.com (Keir Mierle)
//
// A minimal, self-contained bundle adjuster using Ceres, that reads
// files from University of Washington' Bundle Adjustment in the Large dataset:
// http://grail.cs.washington.edu/projects/bal
//
// This does not use the best configuration for solving; see the more involved
// bundle_adjuster.cc file for details.
#include <cmath>
#include <cstdio>
#include <iostream>
#include <fstream>
#include "ceres/ceres.h"
#include "ceres/rotation.h"
typedef Eigen::Map<Eigen::VectorXd> VectorRef;
typedef Eigen::Map<const Eigen::VectorXd> ConstVectorRef;
// Read a Bundle Adjustment in the Large dataset.
class BALProblem {
public:
~BALProblem() {
delete[] point_index_;
delete[] camera_index_;
delete[] observations_;
delete[] parameters_;
}
int num_observations() const { return num_observations_; }
const double* observations() const { return observations_; }
double* mutable_cameras() { return parameters_; }
double* mutable_points() { return parameters_ + 9 * num_cameras_; }
double* mutable_camera_for_observation(int i) {
return mutable_cameras() + camera_index_[i] * 9;
}
double* mutable_point_for_observation(int i) {
return mutable_points() + point_index_[i] * 3;
}
bool LoadFile(const char* filename) {
FILE* fptr = fopen(filename, "r");
if (fptr == NULL) {
return false;
};
FscanfOrDie(fptr, "%d", &num_cameras_);
FscanfOrDie(fptr, "%d", &num_points_);
FscanfOrDie(fptr, "%d", &num_observations_);
point_index_ = new int[num_observations_];
camera_index_ = new int[num_observations_];
observations_ = new double[2 * num_observations_];
num_parameters_ = 9 * num_cameras_ + 3 * num_points_;
parameters_ = new double[num_parameters_];
for (int i = 0; i < num_observations_; ++i) {
FscanfOrDie(fptr, "%d", camera_index_ + i);
FscanfOrDie(fptr, "%d", point_index_ + i);
for (int j = 0; j < 2; ++j) {
FscanfOrDie(fptr, "%lf", observations_ + 2*i + j);
}
}
for (int i = 0; i < num_parameters_; ++i) {
FscanfOrDie(fptr, "%lf", parameters_ + i);
}
return true;
}
void WriteToFile(const std::string& filename) const {
FILE* fptr = fopen(filename.c_str(), "w");
if (fptr == NULL) {
LOG(FATAL) << "Error: unable to open file " << filename;
return;
};
fprintf(fptr, "%d %d %d\n", num_cameras_, num_points_, num_observations_);
for (int i = 0; i < num_observations_; ++i) {
fprintf(fptr, "%d %d", camera_index_[i], point_index_[i]);
for (int j = 0; j < 2; ++j) {
fprintf(fptr, " %g", observations_[2 * i + j]);
}
fprintf(fptr, "\n");
}
for (int i = 0; i < num_cameras_; ++i) {
double angleaxis[9];
memcpy(angleaxis, parameters_ + 9 * i, 9 * sizeof(double));
for (int j = 0; j < 9; ++j) {
fprintf(fptr, "%.16g\n", angleaxis[j]);
}
}
const double* points = parameters_ + 9 * num_cameras_;
for (int i = 0; i < num_points_; ++i) {
const double* point = points + i * 3;
for (int j = 0; j < 3; ++j) {
fprintf(fptr, "%.16g\n", point[j]);
}
}
fclose(fptr);
}
void WriteToPLYFile(const std::string& filename) const {
std::ofstream of(filename.c_str());
of << "ply"
<< '\n' << "format ascii 1.0"
<< '\n' << "element vertex " << num_cameras_ + num_points_
<< '\n' << "property float x"
<< '\n' << "property float y"
<< '\n' << "property float z"
<< '\n' << "property uchar red"
<< '\n' << "property uchar green"
<< '\n' << "property uchar blue"
<< '\n' << "end_header" << std::endl;
// Export extrinsic data (i.e. camera centers) as green points.
double angle_axis[3];
double center[3];
for (int i = 0; i < num_cameras_; ++i) {
const double* camera = parameters_ + 9 * i;
CameraToAngleAxisAndCenter(camera, angle_axis, center);
of << center[0] << ' ' << center[1] << ' ' << center[2]
<< " 0 255 0" << '\n';
}
// Export the structure (i.e. 3D Points) as white points.
const double* points = parameters_ + 9 * num_cameras_;
for (int i = 0; i < num_points_; ++i) {
const double* point = points + i * 3;
for (int j = 0; j < 3; ++j) {
of << point[j] << ' ';
}
of << "255 255 255\n";
}
of.close();
}
void CameraToAngleAxisAndCenter(const double* camera,
double* angle_axis,
double* center) const {
VectorRef angle_axis_ref(angle_axis, 3);
angle_axis_ref = ConstVectorRef(camera, 3);
// c = -R't
Eigen::VectorXd inverse_rotation = -angle_axis_ref;
ceres::AngleAxisRotatePoint(inverse_rotation.data(),
camera + 9 - 6,
center);
VectorRef(center, 3) *= -1.0;
}
private:
template<typename T>
void FscanfOrDie(FILE *fptr, const char *format, T *value) {
int num_scanned = fscanf(fptr, format, value);
if (num_scanned != 1) {
LOG(FATAL) << "Invalid UW data file.";
}
}
int num_cameras_;
int num_points_;
int num_observations_;
int num_parameters_;
int* point_index_;
int* camera_index_;
double* observations_;
double* parameters_;
};
// Templated pinhole camera model for used with Ceres. The camera is
// parameterized using 9 parameters: 3 for rotation, 3 for translation, 1 for
// focal length and 2 for radial distortion. The principal point is not modeled
// (i.e. it is assumed be located at the image center).
struct SnavelyReprojectionError {
SnavelyReprojectionError(double observed_x, double observed_y){
this->observed_x = observed_x;
this->observed_y = observed_y;
//this->camera_px = 0;
//this->camera_py = 0;
// temple
this->camera_px = 320;
this->camera_py = 240;
// penguin_one_angle
//this->camera_px = 920 / 2;
//this->camera_py = 1216 / 2;
}
template <typename T>
bool operator()(const T* const camera,
const T* const point,
T* residuals) const {
// camera[0,1,2] are the angle-axis rotation.
T p[3];
ceres::AngleAxisRotatePoint(camera, point, p);
// camera[3,4,5] are the translation.
p[0] += camera[3];
p[1] += camera[4];
p[2] += camera[5];
// Compute the center of distortion. The sign change comes from
// the camera model that Noah Snavely's Bundler assumes, whereby
// the camera coordinate system has a negative z axis.
T xp = p[0] / p[2];
T yp = p[1] / p[2];
// Apply second and fourth order radial distortion.
const T& l1 = camera[7];
const T& l2 = camera[8];
T r2 = xp*xp + yp*yp;
T distortion = 1.0 + r2 * (l1 + l2 * r2);
// Compute final projected point position.
const T& focal = camera[6];
T predicted_x = focal * distortion * xp + this->camera_px;
T predicted_y = focal * distortion * yp + this->camera_py;
// The error is the difference between the predicted and observed position.
residuals[0] = predicted_x - observed_x;
residuals[1] = predicted_y - observed_y;
return true;
}
// Factory to hide the construction of the CostFunction object from
// the client code.
static ceres::CostFunction* Create(const double observed_x,
const double observed_y) {
return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>(
new SnavelyReprojectionError(observed_x, observed_y)));
}
double observed_x;
double observed_y;
double camera_px;
double camera_py;
};
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
if (argc != 2) {
std::cerr << "usage: sfm <bal_problem>\n";
return 1;
}
BALProblem bal_problem;
if (!bal_problem.LoadFile(argv[1])) {
std::cerr << "ERROR: unable to open file " << argv[1] << "\n";
return 1;
}
std::string init_structure_filename = "";
init_structure_filename = init_structure_filename + argv[1] + "_init.ply";
bal_problem.WriteToPLYFile(init_structure_filename.c_str());
const double* observations = bal_problem.observations();
// Create residuals for each observation in the bundle adjustment problem. The
// parameters for cameras and points are added automatically.
ceres::Problem problem;
for (int i = 0; i < bal_problem.num_observations(); ++i) {
// Each Residual block takes a point and a camera as input and outputs a 2
// dimensional residual. Internally, the cost function stores the observed
// image location and compares the reprojection against the observation.
ceres::CostFunction* cost_function =
SnavelyReprojectionError::Create(observations[2 * i + 0],
observations[2 * i + 1]);
double* camera_ptr = bal_problem.mutable_camera_for_observation(i);
problem.AddResidualBlock(cost_function,
NULL /* squared loss */,
camera_ptr,
bal_problem.mutable_point_for_observation(i));
//problem.SetParameterBlockConstant(camera_ptr); //fix camera to not update
}
// Make Ceres automatically detect the bundle structure. Note that the
// standard solver, SPARSE_NORMAL_CHOLESKY, also works fine but it is slower
// for standard bundle adjustment problems.
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_SCHUR;
options.minimizer_progress_to_stdout = true;
options.max_num_iterations = 10000; // 1000 iteration
options.num_threads = 22; //use 20 thread
options.max_solver_time_in_seconds = 3600 * 3; // 1 hour
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
std::cout << summary.FullReport() << "\n";
std::string output_structure_filename = "";
output_structure_filename = output_structure_filename + argv[1] + "_final.ply";
bal_problem.WriteToPLYFile(output_structure_filename.c_str());
return 0;
} | 41.649306 | 81 | 0.631847 | [
"object",
"model",
"3d"
] |
c3d9dd2033906dc725c1931943cc6188a52d75f7 | 111,651 | cpp | C++ | IPlugExamples/IPlugGamma/gamma/src/fftpack++.cpp | iSynth/WDL-iSynth | 4099b154ca7f7acb979c84118f9418024c8eab62 | [
"Zlib"
] | 1 | 2017-05-07T13:28:30.000Z | 2017-05-07T13:28:30.000Z | IPlugExamples/IPlugGamma/gamma/src/fftpack++.cpp | iSynth/WDL-iSynth | 4099b154ca7f7acb979c84118f9418024c8eab62 | [
"Zlib"
] | null | null | null | IPlugExamples/IPlugGamma/gamma/src/fftpack++.cpp | iSynth/WDL-iSynth | 4099b154ca7f7acb979c84118f9418024c8eab62 | [
"Zlib"
] | null | null | null | /*
* This file is based largely on the following software distribution:
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* FFTPACK
*
* Reference
* P.N. Swarztrauber, Vectorizing the FFTs, in Parallel Computations
* (G. Rodrigue, ed.), Academic Press, 1982, pp. 51--83.
*
* http://www.netlib.org/fftpack/
*
* Updated to single, double, and extended precision,
* and translated to ISO-Standard C/C++ (without aliasing)
* on 10 October 2005 by Andrew Fernandes <andrew_AT_fernandes.org>
*
* Version 4 April 1985
*
* A Package of Fortran Subprograms for the Fast Fourier
* Transform of Periodic and other Symmetric Sequences
*
* by
*
* Paul N Swarztrauber
*
* National Center for Atmospheric Research, Boulder, Colorado 80307,
*
* which is sponsored by the National Science Foundation
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* There appears to be no explicit license for FFTPACK. However, the
* package has been incorporated verbatim into a large number of software
* systems over the years with numerous types of license without complaint
* from the original author; therefore it would appear
* that the code is effectively public domain. If you are in doubt,
* however, you will need to contact the author or the National Center
* for Atmospheric Research to be sure.
*
* All the changes from the original FFTPACK to the current file
* fall under the following BSD-style open-source license:
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright (c) 2005, Andrew Fernandes (andrew@fernandes.org);
* All rights reserved.
*
* 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.
*
* - Neither the name of the North Carolina State University nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* 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.
*
*/
static void s_cfftb1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac);
static void s_cfftf1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac);
static void s_cffti1(int *n, real_t *wa, int *ifac);
static void s_cosqb1(int *n, real_t *x, real_t *w, real_t *xh, int *ifac);
static void s_cosqf1(int *n, real_t *x, real_t *w, real_t *xh, int *ifac);
static void s_ezfft1(int *n, real_t *wa, int *ifac);
static void s_passb(int *nac, int *ido, int *ip, int *l1, int *idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch, real_t *ch2, real_t *wa);
static void s_passb2(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1);
static void s_passb3(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2);
static void s_passb4(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3);
static void s_passb5(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3, real_t *wa4);
static void s_passf(int *nac, int *ido, int *ip, int *l1, int *idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch, real_t *ch2, real_t *wa);
static void s_passf2(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1);
static void s_passf3(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2);
static void s_passf4(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3);
static void s_passf5(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3, real_t *wa4);
static void s_radb2(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1);
static void s_radb3(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2);
static void s_radb4(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3);
static void s_radb5(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3, real_t *wa4);
static void s_radbg(int *ido, int *ip, int *l1, int *idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch, real_t *ch2, real_t *wa);
static void s_radf2(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1);
static void s_radf3(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2);
static void s_radf4(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3);
static void s_radf5(int *ido, int *l1, real_t *cc, real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3, real_t *wa4);
static void s_radfg(int *ido, int *ip, int *l1, int *idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch, real_t *ch2, real_t *wa);
static void s_rfftb1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac);
static void s_rfftf1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac);
static void s_rffti1(int *n, real_t *wa, int *ifac);
static void s_sint1(int *n, real_t *war, real_t *was, real_t *xh, real_t *x, int *ifac);
/* Subroutine */ void FUNC(cfftb)(int *n, real_t *c__, real_t *wsave, int *ifac)
{
int iw1;
/* Parameter adjustments */
--ifac;
--wsave;
--c__;
/* Function Body */
if (*n == 1) {
return;
}
iw1 = *n + *n + 1;
s_cfftb1(n, &c__[1], &wsave[1], &wsave[iw1], &ifac[1]);
return;
} /* cfftb_ */
/* Subroutine */ static void s_cfftb1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k1, l1, l2, n2, na, nf, ip, iw, ix2, ix3, ix4, nac, ido, idl1, idot;
/* Parameter adjustments */
--ifac;
--wa;
--ch;
--c__;
/* Function Body */
nf = ifac[2];
na = 0;
l1 = 1;
iw = 1;
i__1 = nf;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
l2 = ip * l1;
ido = *n / l2;
idot = ido + ido;
idl1 = idot * l1;
if (ip != 4) {
goto L103;
}
ix2 = iw + idot;
ix3 = ix2 + idot;
if (na != 0) {
goto L101;
}
s_passb4(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3]);
goto L102;
L101:
s_passb4(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3]);
L102:
na = 1 - na;
goto L115;
L103:
if (ip != 2) {
goto L106;
}
if (na != 0) {
goto L104;
}
s_passb2(&idot, &l1, &c__[1], &ch[1], &wa[iw]);
goto L105;
L104:
s_passb2(&idot, &l1, &ch[1], &c__[1], &wa[iw]);
L105:
na = 1 - na;
goto L115;
L106:
if (ip != 3) {
goto L109;
}
ix2 = iw + idot;
if (na != 0) {
goto L107;
}
s_passb3(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2]);
goto L108;
L107:
s_passb3(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2]);
L108:
na = 1 - na;
goto L115;
L109:
if (ip != 5) {
goto L112;
}
ix2 = iw + idot;
ix3 = ix2 + idot;
ix4 = ix3 + idot;
if (na != 0) {
goto L110;
}
s_passb5(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
goto L111;
L110:
s_passb5(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
L111:
na = 1 - na;
goto L115;
L112:
if (na != 0) {
goto L113;
}
s_passb(&nac, &idot, &ip, &l1, &idl1, &c__[1], &c__[1], &c__[1], &ch[1], &ch[1], &wa[iw]);
goto L114;
L113:
s_passb(&nac, &idot, &ip, &l1, &idl1, &ch[1], &ch[1], &ch[1], &c__[1], &c__[1], &wa[iw]);
L114:
if (nac != 0) {
na = 1 - na;
}
L115:
l1 = l2;
iw += (ip - 1) * idot;
/* L116: */
}
if (na == 0) {
return;
}
n2 = *n + *n;
i__1 = n2;
for (i__ = 1; i__ <= i__1; ++i__) {
c__[i__] = ch[i__];
/* L117: */
}
return;
} /* s_cfftb1 */
/* Subroutine */ void FUNC(cfftf)(int *n, real_t *c__, real_t *wsave, int *ifac)
{
int iw1;
/* Parameter adjustments */
--ifac;
--wsave;
--c__;
/* Function Body */
if (*n == 1) {
return;
}
iw1 = *n + *n + 1;
s_cfftf1(n, &c__[1], &wsave[1], &wsave[iw1], &ifac[1]);
return;
} /* cfftf_ */
/* Subroutine */ static void s_cfftf1(int *n, real_t *c__, real_t *ch, real_t *wa, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k1, l1, l2, n2, na, nf, ip, iw, ix2, ix3, ix4, nac, ido, idl1, idot;
/* Parameter adjustments */
--ifac;
--wa;
--ch;
--c__;
/* Function Body */
nf = ifac[2];
na = 0;
l1 = 1;
iw = 1;
i__1 = nf;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
l2 = ip * l1;
ido = *n / l2;
idot = ido + ido;
idl1 = idot * l1;
if (ip != 4) {
goto L103;
}
ix2 = iw + idot;
ix3 = ix2 + idot;
if (na != 0) {
goto L101;
}
s_passf4(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3]);
goto L102;
L101:
s_passf4(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3]);
L102:
na = 1 - na;
goto L115;
L103:
if (ip != 2) {
goto L106;
}
if (na != 0) {
goto L104;
}
s_passf2(&idot, &l1, &c__[1], &ch[1], &wa[iw]);
goto L105;
L104:
s_passf2(&idot, &l1, &ch[1], &c__[1], &wa[iw]);
L105:
na = 1 - na;
goto L115;
L106:
if (ip != 3) {
goto L109;
}
ix2 = iw + idot;
if (na != 0) {
goto L107;
}
s_passf3(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2]);
goto L108;
L107:
s_passf3(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2]);
L108:
na = 1 - na;
goto L115;
L109:
if (ip != 5) {
goto L112;
}
ix2 = iw + idot;
ix3 = ix2 + idot;
ix4 = ix3 + idot;
if (na != 0) {
goto L110;
}
s_passf5(&idot, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
goto L111;
L110:
s_passf5(&idot, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
L111:
na = 1 - na;
goto L115;
L112:
if (na != 0) {
goto L113;
}
s_passf(&nac, &idot, &ip, &l1, &idl1, &c__[1], &c__[1], &c__[1], &ch[1], &ch[1], &wa[iw]);
goto L114;
L113:
s_passf(&nac, &idot, &ip, &l1, &idl1, &ch[1], &ch[1], &ch[1], &c__[1], &c__[1], &wa[iw]);
L114:
if (nac != 0) {
na = 1 - na;
}
L115:
l1 = l2;
iw += (ip - 1) * idot;
/* L116: */
}
if (na == 0) {
return;
}
n2 = *n + *n;
i__1 = n2;
for (i__ = 1; i__ <= i__1; ++i__) {
c__[i__] = ch[i__];
/* L117: */
}
return;
} /* cfftf1_ */
/* Subroutine */ void FUNC(cffti)(int *n, real_t *wsave, int *ifac)
{
int iw1;
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
if (*n == 1) {
return;
}
iw1 = *n + *n + 1;
s_cffti1(n, &wsave[iw1], &ifac[1]);
return;
} /* cffti_ */
/* Subroutine */ static void s_cffti1(int *n, real_t *wa, int *ifac)
{
/* Initialized data */
static int ntryh[4] = { 3,4,2,5 };
/* System generated locals */
int i__1, i__2, i__3;
/* Local variables */
int i__, j, i1, k1, l1, l2, ib;
real_t fi;
int ld, ii, nf, ip, nl, nq, nr;
real_t arg;
int ido, ipm;
real_t tpi, argh;
int idot, ntry=0;
real_t argld;
/* Parameter adjustments */
--ifac;
--wa;
/* Function Body */
nl = *n;
nf = 0;
j = 0;
L101:
++j;
if (j - 4 <= 0) {
goto L102;
} else {
goto L103;
}
L102:
ntry = ntryh[j - 1];
goto L104;
L103:
ntry += 2;
L104:
nq = nl / ntry;
nr = nl - ntry * nq;
if (nr != 0) {
goto L101;
} else {
goto L105;
}
L105:
++nf;
ifac[nf + 2] = ntry;
nl = nq;
if (ntry != 2) {
goto L107;
}
if (nf == 1) {
goto L107;
}
i__1 = nf;
for (i__ = 2; i__ <= i__1; ++i__) {
ib = nf - i__ + 2;
ifac[ib + 2] = ifac[ib + 1];
/* L106: */
}
ifac[3] = 2;
L107:
if (nl != 1) {
goto L104;
}
ifac[1] = *n;
ifac[2] = nf;
tpi = POST(6.283185307179586476925286766559005768394338798750211619498891846);
argh = tpi / (real_t) (*n);
i__ = 2;
l1 = 1;
i__1 = nf;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
ld = 0;
l2 = l1 * ip;
ido = *n / l2;
idot = ido + ido + 2;
ipm = ip - 1;
i__2 = ipm;
for (j = 1; j <= i__2; ++j) {
i1 = i__;
wa[i__ - 1] = POST(1.0);
wa[i__] = POST(0.0);
ld += l1;
fi = POST(0.0);
argld = (real_t) ld * argh;
i__3 = idot;
for (ii = 4; ii <= i__3; ii += 2) {
i__ += 2;
fi += POST(1.0);
arg = fi * argld;
wa[i__ - 1] = POST(cos)(arg);
wa[i__] = POST(sin)(arg);
/* L108: */
}
if (ip <= 5) {
goto L109;
}
wa[i1 - 1] = wa[i__ - 1];
wa[i1] = wa[i__];
L109:
;
}
l1 = l2;
/* L110: */
}
return;
} /* s_cffti1 */
/* Subroutine */ void FUNC(cosqb)(int *n, real_t *x, real_t *wsave, int *ifac)
{
/* Initialized data */
static real_t tsqrt2 = POST(2.82842712474619009760337744841939615713934375053896146353359476);
/* System generated locals */
int i__1;
/* Local variables */
real_t x1;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
if ((i__1 = *n - 2) < 0) {
goto L101;
} else if (i__1 == 0) {
goto L102;
} else {
goto L103;
}
L101:
x[1] *= POST(4.0);
return;
L102:
x1 = (x[1] + x[2]) * POST(4.0);
x[2] = tsqrt2 * (x[1] - x[2]);
x[1] = x1;
return;
L103:
s_cosqb1(n, &x[1], &wsave[1], &wsave[*n + 1], &ifac[1]);
return;
} /* cosqb_ */
/* Subroutine */ static void s_cosqb1(int *n, real_t *x, real_t *w, real_t *xh, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k, kc, np2, ns2;
real_t xim1;
int modn;
/* Parameter adjustments */
--ifac;
--xh;
--w;
--x;
/* Function Body */
ns2 = (*n + 1) / 2;
np2 = *n + 2;
i__1 = *n;
for (i__ = 3; i__ <= i__1; i__ += 2) {
xim1 = x[i__ - 1] + x[i__];
x[i__] -= x[i__ - 1];
x[i__ - 1] = xim1;
/* L101: */
}
x[1] += x[1];
modn = *n % 2;
if (modn == 0) {
x[*n] += x[*n];
}
FUNC(rfftb)(n, &x[1], &xh[1], &ifac[1]);
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np2 - k;
xh[k] = w[k - 1] * x[kc] + w[kc - 1] * x[k];
xh[kc] = w[k - 1] * x[k] - w[kc - 1] * x[kc];
/* L102: */
}
if (modn == 0) {
x[ns2 + 1] = w[ns2] * (x[ns2 + 1] + x[ns2 + 1]);
}
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np2 - k;
x[k] = xh[k] + xh[kc];
x[kc] = xh[k] - xh[kc];
/* L103: */
}
x[1] += x[1];
return;
} /* cosqb1_ */
/* Subroutine */ void FUNC(cosqf)(int *n, real_t *x, real_t *wsave, int *ifac)
{
/* Initialized data */
static real_t sqrt2 = POST(1.41421356237309504880168872420969807856967187536948073176679738);
/* System generated locals */
int i__1;
/* Local variables */
real_t tsqx;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
if ((i__1 = *n - 2) < 0) {
goto L102;
} else if (i__1 == 0) {
goto L101;
} else {
goto L103;
}
L101:
tsqx = sqrt2 * x[2];
x[2] = x[1] - tsqx;
x[1] += tsqx;
L102:
return;
L103:
s_cosqf1(n, &x[1], &wsave[1], &wsave[*n + 1], &ifac[1]);
return;
} /* cosqf_ */
/* Subroutine */ static void s_cosqf1(int *n, real_t *x, real_t *w,
real_t *xh, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k, kc, np2, ns2;
real_t xim1;
int modn;
/* Parameter adjustments */
--ifac;
--xh;
--w;
--x;
/* Function Body */
ns2 = (*n + 1) / 2;
np2 = *n + 2;
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np2 - k;
xh[k] = x[k] + x[kc];
xh[kc] = x[k] - x[kc];
/* L101: */
}
modn = *n % 2;
if (modn == 0) {
xh[ns2 + 1] = x[ns2 + 1] + x[ns2 + 1];
}
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np2 - k;
x[k] = w[k - 1] * xh[kc] + w[kc - 1] * xh[k];
x[kc] = w[k - 1] * xh[k] - w[kc - 1] * xh[kc];
/* L102: */
}
if (modn == 0) {
x[ns2 + 1] = w[ns2] * xh[ns2 + 1];
}
FUNC(rfftf)(n, &x[1], &xh[1], &ifac[1]);
i__1 = *n;
for (i__ = 3; i__ <= i__1; i__ += 2) {
xim1 = x[i__ - 1] - x[i__];
x[i__] = x[i__ - 1] + x[i__];
x[i__ - 1] = xim1;
/* L103: */
}
return;
} /* cosqf1_ */
/* Subroutine */ void FUNC(cosqi)(int *n, real_t *wsave, int *ifac)
{
/* Initialized data */
static real_t pih = POST(1.570796326794896619231321691639751442098584699687529104874722962);
/* System generated locals */
int i__1;
/* Local variables */
int k;
real_t fk, dt;
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
dt = pih / (real_t) (*n);
fk = POST(0.0);
i__1 = *n;
for (k = 1; k <= i__1; ++k) {
fk += POST(1.0);
wsave[k] = POST(cos)(fk * dt);
/* L101: */
}
FUNC(rffti)(n, &wsave[*n + 1], &ifac[1]);
return;
} /* cosqi_ */
/* Subroutine */ void FUNC(cost)(int *n, real_t *x, real_t *wsave, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k;
real_t c1, t1, t2;
int kc;
real_t xi;
int nm1, np1;
real_t x1h;
int ns2;
real_t tx2, x1p3, xim2;
int modn;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
nm1 = *n - 1;
np1 = *n + 1;
ns2 = *n / 2;
if ((i__1 = *n - 2) < 0) {
goto L106;
} else if (i__1 == 0) {
goto L101;
} else {
goto L102;
}
L101:
x1h = x[1] + x[2];
x[2] = x[1] - x[2];
x[1] = x1h;
return;
L102:
if (*n > 3) {
goto L103;
}
x1p3 = x[1] + x[3];
tx2 = x[2] + x[2];
x[2] = x[1] - x[3];
x[1] = x1p3 + tx2;
x[3] = x1p3 - tx2;
return;
L103:
c1 = x[1] - x[*n];
x[1] += x[*n];
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np1 - k;
t1 = x[k] + x[kc];
t2 = x[k] - x[kc];
c1 += wsave[kc] * t2;
t2 = wsave[k] * t2;
x[k] = t1 - t2;
x[kc] = t1 + t2;
/* L104: */
}
modn = *n % 2;
if (modn != 0) {
x[ns2 + 1] += x[ns2 + 1];
}
FUNC(rfftf)(&nm1, &x[1], &wsave[*n + 1], &ifac[1]);
xim2 = x[2];
x[2] = c1;
i__1 = *n;
for (i__ = 4; i__ <= i__1; i__ += 2) {
xi = x[i__];
x[i__] = x[i__ - 2] - x[i__ - 1];
x[i__ - 1] = xim2;
xim2 = xi;
/* L105: */
}
if (modn != 0) {
x[*n] = xim2;
}
L106:
return;
} /* cost_ */
/* Subroutine */ void FUNC(costi)(int *n, real_t *wsave, int *ifac)
{
/* Initialized data */
static real_t pi = POST(3.141592653589793238462643383279502884197169399375158209749445923);
/* System generated locals */
int i__1;
/* Local variables */
int k, kc;
real_t fk, dt;
int nm1, np1, ns2;
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
if (*n <= 3) {
return;
}
nm1 = *n - 1;
np1 = *n + 1;
ns2 = *n / 2;
dt = pi / (real_t) nm1;
fk = POST(0.0);
i__1 = ns2;
for (k = 2; k <= i__1; ++k) {
kc = np1 - k;
fk += POST(1.0);
wsave[k] = POST(sin)(fk * dt) * POST(2.0);
wsave[kc] = POST(cos)(fk * dt) * POST(2.0);
/* L101: */
}
FUNC(rffti)(&nm1, &wsave[*n + 1], &ifac[1]);
return;
} /* costi_ */
/* Subroutine */ static void s_ezfft1(int *n, real_t *wa, int *ifac)
{
/* Initialized data */
static int ntryh[4] = { 4,2,3,5 };
static real_t tpi = POST(6.283185307179586476925286766559005768394338798750211419498891846);
/* System generated locals */
int i__1, i__2, i__3;
/* Local variables */
int i__, j, k1, l1, l2, ib, ii, nf, ip, nl, is, nq, nr;
real_t ch1, sh1;
int ido, ipm;
real_t dch1, ch1h, arg1, dsh1;
int nfm1;
real_t argh;
int ntry=0;
/* Parameter adjustments */
--ifac;
--wa;
/* Function Body */
nl = *n;
nf = 0;
j = 0;
L101:
++j;
if (j - 4 <= 0) {
goto L102;
} else {
goto L103;
}
L102:
ntry = ntryh[j - 1];
goto L104;
L103:
ntry += 2;
L104:
nq = nl / ntry;
nr = nl - ntry * nq;
if (nr != 0) {
goto L101;
} else {
goto L105;
}
L105:
++nf;
ifac[nf + 2] = ntry;
nl = nq;
if (ntry != 2) {
goto L107;
}
if (nf == 1) {
goto L107;
}
i__1 = nf;
for (i__ = 2; i__ <= i__1; ++i__) {
ib = nf - i__ + 2;
ifac[ib + 2] = ifac[ib + 1];
/* L106: */
}
ifac[3] = 2;
L107:
if (nl != 1) {
goto L104;
}
ifac[1] = *n;
ifac[2] = nf;
argh = tpi / (real_t) (*n);
is = 0;
nfm1 = nf - 1;
l1 = 1;
if (nfm1 == 0) {
return;
}
i__1 = nfm1;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
l2 = l1 * ip;
ido = *n / l2;
ipm = ip - 1;
arg1 = (real_t) l1 * argh;
ch1 = POST(1.0);
sh1 = POST(0.0);
dch1 = POST(cos)(arg1);
dsh1 = POST(sin)(arg1);
i__2 = ipm;
for (j = 1; j <= i__2; ++j) {
ch1h = dch1 * ch1 - dsh1 * sh1;
sh1 = dch1 * sh1 + dsh1 * ch1;
ch1 = ch1h;
i__ = is + 2;
wa[i__ - 1] = ch1;
wa[i__] = sh1;
if (ido < 5) {
goto L109;
}
i__3 = ido;
for (ii = 5; ii <= i__3; ii += 2) {
i__ += 2;
wa[i__ - 1] = ch1 * wa[i__ - 3] - sh1 * wa[i__ - 2];
wa[i__] = ch1 * wa[i__ - 2] + sh1 * wa[i__ - 3];
/* L108: */
}
L109:
is += ido;
/* L110: */
}
l1 = l2;
/* L111: */
}
return;
} /* ezfft1_ */
/* Subroutine */ void FUNC(ezfftb)(int *n, real_t *r__, real_t *azero,
real_t *a, real_t *b, real_t *wsave, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, ns2;
/* Parameter adjustments */
--ifac;
--wsave;
--b;
--a;
--r__;
/* Function Body */
if ((i__1 = *n - 2) < 0) {
goto L101;
} else if (i__1 == 0) {
goto L102;
} else {
goto L103;
}
L101:
r__[1] = *azero;
return;
L102:
r__[1] = *azero + a[1];
r__[2] = *azero - a[1];
return;
L103:
ns2 = (*n - 1) / 2;
i__1 = ns2;
for (i__ = 1; i__ <= i__1; ++i__) {
r__[i__ * 2] = a[i__] * POST(0.5);
r__[(i__ << 1) + 1] = b[i__] * POST(-0.5);
/* L104: */
}
r__[1] = *azero;
if (*n % 2 == 0) {
r__[*n] = a[ns2 + 1];
}
FUNC(rfftb)(n, &r__[1], &wsave[*n + 1], &ifac[1]);
return;
} /* ezfftb_ */
/* Subroutine */ void FUNC(ezfftf)(int *n, real_t *r__, real_t *azero,
real_t *a, real_t *b, real_t *wsave, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__;
real_t cf;
int ns2;
real_t cfm;
int ns2m;
/* VERSION 3 JUNE 1979 */
/* Parameter adjustments */
--ifac;
--wsave;
--b;
--a;
--r__;
/* Function Body */
if ((i__1 = *n - 2) < 0) {
goto L101;
} else if (i__1 == 0) {
goto L102;
} else {
goto L103;
}
L101:
*azero = r__[1];
return;
L102:
*azero = (r__[1] + r__[2]) * POST(0.5);
a[1] = (r__[1] - r__[2]) * POST(0.5);
return;
L103:
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
wsave[i__] = r__[i__];
/* L104: */
}
FUNC(rfftf)(n, &wsave[1], &wsave[*n + 1], &ifac[1]);
cf = 2.0 / (real_t) (*n);
cfm = -cf;
*azero = cf * 0.5 * wsave[1];
ns2 = (*n + 1) / 2;
ns2m = ns2 - 1;
i__1 = ns2m;
for (i__ = 1; i__ <= i__1; ++i__) {
a[i__] = cf * wsave[i__ * 2];
b[i__] = cfm * wsave[(i__ << 1) + 1];
/* L105: */
}
if (*n % 2 == 1) {
return;
}
a[ns2] = cf * 0.5 * wsave[*n];
b[ns2] = POST(0.0);
return;
} /* ezfftf_ */
/* Subroutine */ void FUNC(ezffti)(int *n, real_t *wsave, int *ifac)
{
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
if (*n == 1) {
return;
}
s_ezfft1(n, &wsave[(*n << 1) + 1], &ifac[1]);
return;
} /* ezffti_ */
/* Subroutine */ static void s_passb(int *nac, int *ido, int *ip, int *
l1, int *idl1, real_t *cc, real_t *c1, real_t *c2,
real_t *ch, real_t *ch2, real_t *wa)
{
/* System generated locals */
int ch_dim1, ch_dim2, ch_offset, cc_dim1, cc_dim2, cc_offset, c1_dim1,
c1_dim2, c1_offset, c2_dim1, c2_offset, ch2_dim1, ch2_offset,
i__1, i__2, i__3;
/* Local variables */
int i__, j, k, l, jc, lc, ik, nt, idj, idl, inc, idp;
real_t wai, war;
int ipp2, idij, idlj, idot, ipph;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
c1_dim1 = *ido;
c1_dim2 = *l1;
c1_offset = 1 + c1_dim1 * (1 + c1_dim2);
c1 -= c1_offset;
cc_dim1 = *ido;
cc_dim2 = *ip;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
ch2_dim1 = *idl1;
ch2_offset = 1 + ch2_dim1;
ch2 -= ch2_offset;
c2_dim1 = *idl1;
c2_offset = 1 + c2_dim1;
c2 -= c2_offset;
--wa;
/* Function Body */
idot = *ido / 2;
nt = *ip * *idl1;
ipp2 = *ip + 2;
ipph = (*ip + 1) / 2;
idp = *ip * *ido;
if (*ido < *l1) {
goto L106;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 1; i__ <= i__3; ++i__) {
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + (j + k *
cc_dim2) * cc_dim1] + cc[i__ + (jc + k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + (j + k *
cc_dim2) * cc_dim1] - cc[i__ + (jc + k * cc_dim2) * cc_dim1];
/* L101: */
}
/* L102: */
}
/* L103: */
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) * cc_dim1];
/* L104: */
}
/* L105: */
}
goto L112;
L106:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + (j + k *
cc_dim2) * cc_dim1] + cc[i__ + (jc + k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + (j + k *
cc_dim2) * cc_dim1] - cc[i__ + (jc + k * cc_dim2) * cc_dim1];
/* L107: */
}
/* L108: */
}
/* L109: */
}
i__1 = *ido;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) * cc_dim1];
/* L110: */
}
/* L111: */
}
L112:
idl = 2 - *ido;
inc = 0;
i__1 = ipph;
for (l = 2; l <= i__1; ++l) {
lc = ipp2 - l;
idl += *ido;
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
c2[ik + l * c2_dim1] = ch2[ik + ch2_dim1] + wa[idl - 1] * ch2[ik + (ch2_dim1 << 1)];
c2[ik + lc * c2_dim1] = wa[idl] * ch2[ik + *ip * ch2_dim1];
/* L113: */
}
idlj = idl;
inc += *ido;
i__2 = ipph;
for (j = 3; j <= i__2; ++j) {
jc = ipp2 - j;
idlj += inc;
if (idlj > idp) {
idlj -= idp;
}
war = wa[idlj - 1];
wai = wa[idlj];
i__3 = *idl1;
for (ik = 1; ik <= i__3; ++ik) {
c2[ik + l * c2_dim1] += war * ch2[ik + j * ch2_dim1];
c2[ik + lc * c2_dim1] += wai * ch2[ik + jc * ch2_dim1];
/* L114: */
}
/* L115: */
}
/* L116: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
ch2[ik + ch2_dim1] += ch2[ik + j * ch2_dim1];
/* L117: */
}
/* L118: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *idl1;
for (ik = 2; ik <= i__2; ik += 2) {
ch2[ik - 1 + j * ch2_dim1] = c2[ik - 1 + j * c2_dim1] - c2[ik + jc * c2_dim1];
ch2[ik - 1 + jc * ch2_dim1] = c2[ik - 1 + j * c2_dim1] + c2[ik + jc * c2_dim1];
ch2[ik + j * ch2_dim1] = c2[ik + j * c2_dim1] + c2[ik - 1 + jc * c2_dim1];
ch2[ik + jc * ch2_dim1] = c2[ik + j * c2_dim1] - c2[ik - 1 + jc * c2_dim1];
/* L119: */
}
/* L120: */
}
*nac = 1;
if (*ido == 2) {
return;
}
*nac = 0;
i__1 = *idl1;
for (ik = 1; ik <= i__1; ++ik) {
c2[ik + c2_dim1] = ch2[ik + ch2_dim1];
/* L121: */
}
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
c1[(k + j * c1_dim2) * c1_dim1 + 1] = ch[(k + j * ch_dim2) * ch_dim1 + 1];
c1[(k + j * c1_dim2) * c1_dim1 + 2] = ch[(k + j * ch_dim2) * ch_dim1 + 2];
/* L122: */
}
/* L123: */
}
if (idot > *l1) {
goto L127;
}
idij = 0;
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
idij += 2;
i__2 = *ido;
for (i__ = 4; i__ <= i__2; i__ += 2) {
idij += 2;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] - wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] + wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L124: */
}
/* L125: */
}
/* L126: */
}
return;
L127:
idj = 2 - *ido;
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
idj += *ido;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
idij = idj;
i__3 = *ido;
for (i__ = 4; i__ <= i__3; i__ += 2) {
idij += 2;
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] - wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] + wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L128: */
}
/* L129: */
}
/* L130: */
}
return;
} /* passb_ */
/* Subroutine */ static void s_passb2(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1)
{
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ti2, tr2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 3;
cc -= cc_offset;
--wa1;
/* Function Body */
if (*ido > 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] + cc[((k << 1) + 2) * cc_dim1 + 1];
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] - cc[((k << 1) + 2) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[((k << 1) + 1) * cc_dim1 + 2] + cc[((k << 1) + 2) * cc_dim1 + 2];
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = cc[((k << 1) + 1) * cc_dim1 + 2] - cc[((k << 1) + 2) * cc_dim1 + 2];
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] + cc[i__ - 1 + ((k << 1) + 2) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] - cc[i__ - 1 + ((k <<1) + 2) * cc_dim1];
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + ((k << 1) + 1) * cc_dim1] + cc[i__ + ((k << 1) + 2) * cc_dim1];
ti2 = cc[i__ + ((k << 1) + 1) * cc_dim1] - cc[i__ + ((k << 1) + 2)* cc_dim1];
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * ti2 + wa1[i__] * tr2;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * tr2 - wa1[i__] * ti2;
/* L103: */
}
/* L104: */
}
return;
} /* passb2_ */
/* Subroutine */ static void s_passb3(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2)
{
/* Initialized data */
static real_t taur = POST(-0.5);
static real_t taui = POST(0.8660254037844386467637231707529361834710262690519031402790348975);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + (cc_dim1 << 2);
cc -= cc_offset;
--wa1;
--wa2;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
tr2 = cc[(k * 3 + 2) * cc_dim1 + 1] + cc[(k * 3 + 3) * cc_dim1 + 1];
cr2 = cc[(k * 3 + 1) * cc_dim1 + 1] + taur * tr2;
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 3 + 1) * cc_dim1 + 1] + tr2;
ti2 = cc[(k * 3 + 2) * cc_dim1 + 2] + cc[(k * 3 + 3) * cc_dim1 + 2];
ci2 = cc[(k * 3 + 1) * cc_dim1 + 2] + taur * ti2;
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[(k * 3 + 1) * cc_dim1 + 2] + ti2;
cr3 = taui * (cc[(k * 3 + 2) * cc_dim1 + 1] - cc[(k * 3 + 3) * cc_dim1 + 1]);
ci3 = taui * (cc[(k * 3 + 2) * cc_dim1 + 2] - cc[(k * 3 + 3) * cc_dim1 + 2]);
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr2 + ci3;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ci2 + cr3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ci2 - cr3;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
tr2 = cc[i__ - 1 + (k * 3 + 2) * cc_dim1] + cc[i__ - 1 + (k * 3 + 3) * cc_dim1];
cr2 = cc[i__ - 1 + (k * 3 + 1) * cc_dim1] + taur * tr2;
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 3 + 1) *cc_dim1] + tr2;
ti2 = cc[i__ + (k * 3 + 2) * cc_dim1] + cc[i__ + (k * 3 + 3) * cc_dim1];
ci2 = cc[i__ + (k * 3 + 1) * cc_dim1] + taur * ti2;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 3 + 1) * cc_dim1] + ti2;
cr3 = taui * (cc[i__ - 1 + (k * 3 + 2) * cc_dim1] - cc[i__ - 1 + (k * 3 + 3) * cc_dim1]);
ci3 = taui * (cc[i__ + (k * 3 + 2) * cc_dim1] - cc[i__ + (k * 3 + 3) * cc_dim1]);
dr2 = cr2 - ci3;
dr3 = cr2 + ci3;
di2 = ci2 + cr3;
di3 = ci2 - cr3;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * di2 + wa1[i__] * dr2;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * dr2 - wa1[i__] * di2;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * di3 + wa2[i__] * dr3;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * dr3 - wa2[i__] * di3;
/* L103: */
}
/* L104: */
}
return;
} /* passb3_ */
/* Subroutine */ static void s_passb4(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3)
{
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 5;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti1 = cc[((k << 2) + 1) * cc_dim1 + 2] - cc[((k << 2) + 3) * cc_dim1 + 2];
ti2 = cc[((k << 2) + 1) * cc_dim1 + 2] + cc[((k << 2) + 3) * cc_dim1 + 2];
tr4 = cc[((k << 2) + 4) * cc_dim1 + 2] - cc[((k << 2) + 2) * cc_dim1 + 2];
ti3 = cc[((k << 2) + 2) * cc_dim1 + 2] + cc[((k << 2) + 4) * cc_dim1 + 2];
tr1 = cc[((k << 2) + 1) * cc_dim1 + 1] - cc[((k << 2) + 3) * cc_dim1 + 1];
tr2 = cc[((k << 2) + 1) * cc_dim1 + 1] + cc[((k << 2) + 3) * cc_dim1 + 1];
ti4 = cc[((k << 2) + 2) * cc_dim1 + 1] - cc[((k << 2) + 4) * cc_dim1 + 1];
tr3 = cc[((k << 2) + 2) * cc_dim1 + 1] + cc[((k << 2) + 4) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 1] = tr2 + tr3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = tr2 - tr3;
ch[(k + ch_dim2) * ch_dim1 + 2] = ti2 + ti3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ti2 - ti3;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = tr1 + tr4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = tr1 - tr4;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ti1 + ti4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 2] = ti1 - ti4;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ti1 = cc[i__ + ((k << 2) + 1) * cc_dim1] - cc[i__ + ((k << 2) + 3)* cc_dim1];
ti2 = cc[i__ + ((k << 2) + 1) * cc_dim1] + cc[i__ + ((k << 2) + 3)* cc_dim1];
ti3 = cc[i__ + ((k << 2) + 2) * cc_dim1] + cc[i__ + ((k << 2) + 4)* cc_dim1];
tr4 = cc[i__ + ((k << 2) + 4) * cc_dim1] - cc[i__ + ((k << 2) + 2)* cc_dim1];
tr1 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] - cc[i__ - 1 + ((k <<2) + 3) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] + cc[i__ - 1 + ((k <<2) + 3) * cc_dim1];
ti4 = cc[i__ - 1 + ((k << 2) + 2) * cc_dim1] - cc[i__ - 1 + ((k <<2) + 4) * cc_dim1];
tr3 = cc[i__ - 1 + ((k << 2) + 2) * cc_dim1] + cc[i__ - 1 + ((k <<2) + 4) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = tr2 + tr3;
cr3 = tr2 - tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = ti2 + ti3;
ci3 = ti2 - ti3;
cr2 = tr1 + tr4;
cr4 = tr1 - tr4;
ci2 = ti1 + ti4;
ci4 = ti1 - ti4;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * cr2 - wa1[i__] * ci2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * ci2 + wa1[i__] * cr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * cr3 - wa2[i__] * ci3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * ci3 + wa2[i__] * cr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * cr4 - wa3[i__] * ci4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * ci4 + wa3[i__] * cr4;
/* L103: */
}
/* L104: */
}
return;
} /* passb4_ */
/* Subroutine */ static void s_passb5(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3,
real_t *wa4)
{
/* Initialized data */
static real_t tr11 = POST(0.3090169943749474241022934171828195886015458990288143106772431137);
static real_t ti11 = POST(0.9510565162951535721164393337938214340569863412575022244730564442);
static real_t tr12 = POST(-0.8090169943749474241022934171828190588601545899028814310677431135);
static real_t ti12 = POST(0.5877852522924731291687059546390727685976524376431459107227248076);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4,
ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 6;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
--wa4;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti5 = cc[(k * 5 + 2) * cc_dim1 + 2] - cc[(k * 5 + 5) * cc_dim1 + 2];
ti2 = cc[(k * 5 + 2) * cc_dim1 + 2] + cc[(k * 5 + 5) * cc_dim1 + 2];
ti4 = cc[(k * 5 + 3) * cc_dim1 + 2] - cc[(k * 5 + 4) * cc_dim1 + 2];
ti3 = cc[(k * 5 + 3) * cc_dim1 + 2] + cc[(k * 5 + 4) * cc_dim1 + 2];
tr5 = cc[(k * 5 + 2) * cc_dim1 + 1] - cc[(k * 5 + 5) * cc_dim1 + 1];
tr2 = cc[(k * 5 + 2) * cc_dim1 + 1] + cc[(k * 5 + 5) * cc_dim1 + 1];
tr4 = cc[(k * 5 + 3) * cc_dim1 + 1] - cc[(k * 5 + 4) * cc_dim1 + 1];
tr3 = cc[(k * 5 + 3) * cc_dim1 + 1] + cc[(k * 5 + 4) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 5 + 1) * cc_dim1 + 1] + tr2
+ tr3;
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[(k * 5 + 1) * cc_dim1 + 2] + ti2
+ ti3;
cr2 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr11 * tr2 + tr12 * tr3;
ci2 = cc[(k * 5 + 1) * cc_dim1 + 2] + tr11 * ti2 + tr12 * ti3;
cr3 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr12 * tr2 + tr11 * tr3;
ci3 = cc[(k * 5 + 1) * cc_dim1 + 2] + tr12 * ti2 + tr11 * ti3;
cr5 = ti11 * tr5 + ti12 * tr4;
ci5 = ti11 * ti5 + ti12 * ti4;
cr4 = ti12 * tr5 - ti11 * tr4;
ci4 = ti12 * ti5 - ti11 * ti4;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci5;
ch[(k + ch_dim2 * 5) * ch_dim1 + 1] = cr2 + ci5;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ci2 + cr5;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ci3 + cr4;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr3 - ci4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = cr3 + ci4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 2] = ci3 - cr4;
ch[(k + ch_dim2 * 5) * ch_dim1 + 2] = ci2 - cr5;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ti5 = cc[i__ + (k * 5 + 2) * cc_dim1] - cc[i__ + (k * 5 + 5) * cc_dim1];
ti2 = cc[i__ + (k * 5 + 2) * cc_dim1] + cc[i__ + (k * 5 + 5) * cc_dim1];
ti4 = cc[i__ + (k * 5 + 3) * cc_dim1] - cc[i__ + (k * 5 + 4) * cc_dim1];
ti3 = cc[i__ + (k * 5 + 3) * cc_dim1] + cc[i__ + (k * 5 + 4) * cc_dim1];
tr5 = cc[i__ - 1 + (k * 5 + 2) * cc_dim1] - cc[i__ - 1 + (k * 5 + 5) * cc_dim1];
tr2 = cc[i__ - 1 + (k * 5 + 2) * cc_dim1] + cc[i__ - 1 + (k * 5 + 5) * cc_dim1];
tr4 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] - cc[i__ - 1 + (k * 5 + 4) * cc_dim1];
tr3 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] + cc[i__ - 1 + (k * 5 + 4) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 5 + 1) *cc_dim1] + tr2 + tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 5 + 1) * cc_dim1] + ti2 + ti3;
cr2 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr11 * tr2 + tr12 * tr3;
ci2 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr11 * ti2 + tr12 * ti3;
cr3 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr12 * tr2 + tr11 * tr3;
ci3 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr12 * ti2 + tr11 * ti3;
cr5 = ti11 * tr5 + ti12 * tr4;
ci5 = ti11 * ti5 + ti12 * ti4;
cr4 = ti12 * tr5 - ti11 * tr4;
ci4 = ti12 * ti5 - ti11 * ti4;
dr3 = cr3 - ci4;
dr4 = cr3 + ci4;
di3 = ci3 + cr4;
di4 = ci3 - cr4;
dr5 = cr2 + ci5;
dr2 = cr2 - ci5;
di5 = ci2 - cr5;
di2 = ci2 + cr5;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * dr2 - wa1[i__] * di2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * di2 + wa1[i__] * dr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * dr3 - wa2[i__] * di3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * di3 + wa2[i__] * dr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * dr4 - wa3[i__] * di4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * di4 + wa3[i__] * dr4;
ch[i__ - 1 + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 1] * dr5 - wa4[i__] * di5;
ch[i__ + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 1] * di5 + wa4[i__] * dr5;
/* L103: */
}
/* L104: */
}
return;
} /* passb5_ */
/* Subroutine */ static void s_passf(int *nac, int *ido, int *ip, int *
l1, int *idl1, real_t *cc, real_t *c1, real_t *c2,
real_t *ch, real_t *ch2, real_t *wa)
{
/* System generated locals */
int ch_dim1, ch_dim2, ch_offset, cc_dim1, cc_dim2, cc_offset, c1_dim1,
c1_dim2, c1_offset, c2_dim1, c2_offset, ch2_dim1, ch2_offset,
i__1, i__2, i__3;
/* Local variables */
int i__, j, k, l, jc, lc, ik, nt, idj, idl, inc, idp;
real_t wai, war;
int ipp2, idij, idlj, idot, ipph;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
c1_dim1 = *ido;
c1_dim2 = *l1;
c1_offset = 1 + c1_dim1 * (1 + c1_dim2);
c1 -= c1_offset;
cc_dim1 = *ido;
cc_dim2 = *ip;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
ch2_dim1 = *idl1;
ch2_offset = 1 + ch2_dim1;
ch2 -= ch2_offset;
c2_dim1 = *idl1;
c2_offset = 1 + c2_dim1;
c2 -= c2_offset;
--wa;
/* Function Body */
idot = *ido / 2;
nt = *ip * *idl1;
ipp2 = *ip + 2;
ipph = (*ip + 1) / 2;
idp = *ip * *ido;
if (*ido < *l1) {
goto L106;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 1; i__ <= i__3; ++i__) {
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + (j + k * cc_dim2) * cc_dim1] + cc[i__ + (jc + k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + (j + k * cc_dim2) * cc_dim1] - cc[i__ + (jc + k * cc_dim2) * cc_dim1];
/* L101: */
}
/* L102: */
}
/* L103: */
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) * cc_dim1];
/* L104: */
}
/* L105: */
}
goto L112;
L106:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + (j + k * cc_dim2) * cc_dim1] + cc[i__ + (jc + k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + (j + k * cc_dim2) * cc_dim1] - cc[i__ + (jc + k * cc_dim2) * cc_dim1];
/* L107: */
}
/* L108: */
}
/* L109: */
}
i__1 = *ido;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) * cc_dim1];
/* L110: */
}
/* L111: */
}
L112:
idl = 2 - *ido;
inc = 0;
i__1 = ipph;
for (l = 2; l <= i__1; ++l) {
lc = ipp2 - l;
idl += *ido;
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
c2[ik + l * c2_dim1] = ch2[ik + ch2_dim1] + wa[idl - 1] * ch2[ik + (ch2_dim1 << 1)];
c2[ik + lc * c2_dim1] = -wa[idl] * ch2[ik + *ip * ch2_dim1];
/* L113: */
}
idlj = idl;
inc += *ido;
i__2 = ipph;
for (j = 3; j <= i__2; ++j) {
jc = ipp2 - j;
idlj += inc;
if (idlj > idp) {
idlj -= idp;
}
war = wa[idlj - 1];
wai = wa[idlj];
i__3 = *idl1;
for (ik = 1; ik <= i__3; ++ik) {
c2[ik + l * c2_dim1] += war * ch2[ik + j * ch2_dim1];
c2[ik + lc * c2_dim1] -= wai * ch2[ik + jc * ch2_dim1];
/* L114: */
}
/* L115: */
}
/* L116: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
ch2[ik + ch2_dim1] += ch2[ik + j * ch2_dim1];
/* L117: */
}
/* L118: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *idl1;
for (ik = 2; ik <= i__2; ik += 2) {
ch2[ik - 1 + j * ch2_dim1] = c2[ik - 1 + j * c2_dim1] - c2[ik + jc * c2_dim1];
ch2[ik - 1 + jc * ch2_dim1] = c2[ik - 1 + j * c2_dim1] + c2[ik + jc * c2_dim1];
ch2[ik + j * ch2_dim1] = c2[ik + j * c2_dim1] + c2[ik - 1 + jc * c2_dim1];
ch2[ik + jc * ch2_dim1] = c2[ik + j * c2_dim1] - c2[ik - 1 + jc * c2_dim1];
/* L119: */
}
/* L120: */
}
*nac = 1;
if (*ido == 2) {
return;
}
*nac = 0;
i__1 = *idl1;
for (ik = 1; ik <= i__1; ++ik) {
c2[ik + c2_dim1] = ch2[ik + ch2_dim1];
/* L121: */
}
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
c1[(k + j * c1_dim2) * c1_dim1 + 1] = ch[(k + j * ch_dim2) * ch_dim1 + 1];
c1[(k + j * c1_dim2) * c1_dim1 + 2] = ch[(k + j * ch_dim2) * ch_dim1 + 2];
/* L122: */
}
/* L123: */
}
if (idot > *l1) {
goto L127;
}
idij = 0;
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
idij += 2;
i__2 = *ido;
for (i__ = 4; i__ <= i__2; i__ += 2) {
idij += 2;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
c1[ i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] + wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[ i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] - wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L124: */
}
/* L125: */
}
/* L126: */
}
return;
L127:
idj = 2 - *ido;
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
idj += *ido;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
idij = idj;
i__3 = *ido;
for (i__ = 4; i__ <= i__3; i__ += 2) {
idij += 2;
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] + wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] - wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L128: */
}
/* L129: */
}
/* L130: */
}
return;
} /* passf_ */
/* Subroutine */ static void s_passf2(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1)
{
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ti2, tr2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 3;
cc -= cc_offset;
--wa1;
/* Function Body */
if (*ido > 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] + cc[((k << 1) + 2) * cc_dim1 + 1];
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] - cc[((k << 1) + 2) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[((k << 1) + 1) * cc_dim1 + 2] + cc[((k << 1) + 2) * cc_dim1 + 2];
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = cc[((k << 1) + 1) * cc_dim1 + 2] - cc[((k << 1) + 2) * cc_dim1 + 2];
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] + cc[i__ - 1 + ((k << 1) + 2) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] - cc[i__ - 1 + ((k <<1) + 2) * cc_dim1];
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + ((k << 1) + 1) * cc_dim1] + cc[i__ + ((k << 1) + 2) * cc_dim1];
ti2 = cc[i__ + ((k << 1) + 1) * cc_dim1] - cc[i__ + ((k << 1) + 2)* cc_dim1];
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * ti2 - wa1[i__] * tr2;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * tr2 + wa1[i__] * ti2;
/* L103: */
}
/* L104: */
}
return;
} /* passf2_ */
/* Subroutine */ static void s_passf3(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2)
{
/* Initialized data */
static real_t taur = POST(-0.5);
static real_t taui = POST(-0.8660254037844386467637231707529361834740262690519031402790348975);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + (cc_dim1 << 2);
cc -= cc_offset;
--wa1;
--wa2;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
tr2 = cc[(k * 3 + 2) * cc_dim1 + 1] + cc[(k * 3 + 3) * cc_dim1 + 1];
cr2 = cc[(k * 3 + 1) * cc_dim1 + 1] + taur * tr2;
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 3 + 1) * cc_dim1 + 1] + tr2;
ti2 = cc[(k * 3 + 2) * cc_dim1 + 2] + cc[(k * 3 + 3) * cc_dim1 + 2];
ci2 = cc[(k * 3 + 1) * cc_dim1 + 2] + taur * ti2;
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[(k * 3 + 1) * cc_dim1 + 2] + ti2;
cr3 = taui * (cc[(k * 3 + 2) * cc_dim1 + 1] - cc[(k * 3 + 3) * cc_dim1 + 1]);
ci3 = taui * (cc[(k * 3 + 2) * cc_dim1 + 2] - cc[(k * 3 + 3) * cc_dim1 + 2]);
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr2 + ci3;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ci2 + cr3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ci2 - cr3;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
tr2 = cc[i__ - 1 + (k * 3 + 2) * cc_dim1] + cc[i__ - 1 + (k * 3 + 3) * cc_dim1];
cr2 = cc[i__ - 1 + (k * 3 + 1) * cc_dim1] + taur * tr2;
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 3 + 1) *cc_dim1] + tr2;
ti2 = cc[i__ + (k * 3 + 2) * cc_dim1] + cc[i__ + (k * 3 + 3) * cc_dim1];
ci2 = cc[i__ + (k * 3 + 1) * cc_dim1] + taur * ti2;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 3 + 1) * cc_dim1] + ti2;
cr3 = taui * (cc[i__ - 1 + (k * 3 + 2) * cc_dim1] - cc[i__ - 1 + (k * 3 + 3) * cc_dim1]);
ci3 = taui * (cc[i__ + (k * 3 + 2) * cc_dim1] - cc[i__ + (k * 3 + 3) * cc_dim1]);
dr2 = cr2 - ci3;
dr3 = cr2 + ci3;
di2 = ci2 + cr3;
di3 = ci2 - cr3;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * di2 - wa1[i__] * dr2;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * dr2 + wa1[i__] * di2;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * di3 - wa2[i__] * dr3;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * dr3 + wa2[i__] * di3;
/* L103: */
}
/* L104: */
}
return;
} /* passf3_ */
/* Subroutine */ static void s_passf4(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3)
{
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2,
tr3, tr4;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 5;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti1 = cc[((k << 2) + 1) * cc_dim1 + 2] - cc[((k << 2) + 3) * cc_dim1 + 2];
ti2 = cc[((k << 2) + 1) * cc_dim1 + 2] + cc[((k << 2) + 3) * cc_dim1 + 2];
tr4 = cc[((k << 2) + 2) * cc_dim1 + 2] - cc[((k << 2) + 4) * cc_dim1 + 2];
ti3 = cc[((k << 2) + 2) * cc_dim1 + 2] + cc[((k << 2) + 4) * cc_dim1 + 2];
tr1 = cc[((k << 2) + 1) * cc_dim1 + 1] - cc[((k << 2) + 3) * cc_dim1 + 1];
tr2 = cc[((k << 2) + 1) * cc_dim1 + 1] + cc[((k << 2) + 3) * cc_dim1 + 1];
ti4 = cc[((k << 2) + 4) * cc_dim1 + 1] - cc[((k << 2) + 2) * cc_dim1 + 1];
tr3 = cc[((k << 2) + 2) * cc_dim1 + 1] + cc[((k << 2) + 4) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 1] = tr2 + tr3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = tr2 - tr3;
ch[(k + ch_dim2) * ch_dim1 + 2] = ti2 + ti3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ti2 - ti3;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = tr1 + tr4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = tr1 - tr4;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ti1 + ti4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 2] = ti1 - ti4;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ti1 = cc[i__ + ((k << 2) + 1) * cc_dim1] - cc[i__ + ((k << 2) + 3)* cc_dim1];
ti2 = cc[i__ + ((k << 2) + 1) * cc_dim1] + cc[i__ + ((k << 2) + 3)* cc_dim1];
ti3 = cc[i__ + ((k << 2) + 2) * cc_dim1] + cc[i__ + ((k << 2) + 4)* cc_dim1];
tr4 = cc[i__ + ((k << 2) + 2) * cc_dim1] - cc[i__ + ((k << 2) + 4)* cc_dim1];
tr1 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] - cc[i__ - 1 + ((k <<2) + 3) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] + cc[i__ - 1 + ((k <<2) + 3) * cc_dim1];
ti4 = cc[i__ - 1 + ((k << 2) + 4) * cc_dim1] - cc[i__ - 1 + ((k <<2) + 2) * cc_dim1];
tr3 = cc[i__ - 1 + ((k << 2) + 2) * cc_dim1] + cc[i__ - 1 + ((k <<2) + 4) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = tr2 + tr3;
cr3 = tr2 - tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = ti2 + ti3;
ci3 = ti2 - ti3;
cr2 = tr1 + tr4;
cr4 = tr1 - tr4;
ci2 = ti1 + ti4;
ci4 = ti1 - ti4;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * cr2 + wa1[i__] * ci2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * ci2 - wa1[i__] * cr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * cr3 + wa2[i__] * ci3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * ci3 - wa2[i__] * cr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * cr4 + wa3[i__] * ci4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * ci4 - wa3[i__] * cr4;
/* L103: */
}
/* L104: */
}
return;
} /* passf4_ */
/* Subroutine */ static void s_passf5(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3,
real_t *wa4)
{
/* Initialized data */
static real_t tr11 = POST(0.3090169943749474241022934171828195886015458990288143106772431137);
static real_t ti11 = POST(-0.9510565162951535721164393337938214340569863412575022244730564442);
static real_t tr12 = POST(-0.8090169943749474241022934171828190588601545899028814310677431135);
static real_t ti12 = POST(-0.5877852522924731291687059546390727685976524376431459107227248076);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k;
real_t ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4,
ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 6;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
--wa4;
/* Function Body */
if (*ido != 2) {
goto L102;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti5 = cc[(k * 5 + 2) * cc_dim1 + 2] - cc[(k * 5 + 5) * cc_dim1 + 2];
ti2 = cc[(k * 5 + 2) * cc_dim1 + 2] + cc[(k * 5 + 5) * cc_dim1 + 2];
ti4 = cc[(k * 5 + 3) * cc_dim1 + 2] - cc[(k * 5 + 4) * cc_dim1 + 2];
ti3 = cc[(k * 5 + 3) * cc_dim1 + 2] + cc[(k * 5 + 4) * cc_dim1 + 2];
tr5 = cc[(k * 5 + 2) * cc_dim1 + 1] - cc[(k * 5 + 5) * cc_dim1 + 1];
tr2 = cc[(k * 5 + 2) * cc_dim1 + 1] + cc[(k * 5 + 5) * cc_dim1 + 1];
tr4 = cc[(k * 5 + 3) * cc_dim1 + 1] - cc[(k * 5 + 4) * cc_dim1 + 1];
tr3 = cc[(k * 5 + 3) * cc_dim1 + 1] + cc[(k * 5 + 4) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 5 + 1) * cc_dim1 + 1] + tr2 + tr3;
ch[(k + ch_dim2) * ch_dim1 + 2] = cc[(k * 5 + 1) * cc_dim1 + 2] + ti2 + ti3;
cr2 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr11 * tr2 + tr12 * tr3;
ci2 = cc[(k * 5 + 1) * cc_dim1 + 2] + tr11 * ti2 + tr12 * ti3;
cr3 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr12 * tr2 + tr11 * tr3;
ci3 = cc[(k * 5 + 1) * cc_dim1 + 2] + tr12 * ti2 + tr11 * ti3;
cr5 = ti11 * tr5 + ti12 * tr4;
ci5 = ti11 * ti5 + ti12 * ti4;
cr4 = ti12 * tr5 - ti11 * tr4;
ci4 = ti12 * ti5 - ti11 * ti4;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci5;
ch[(k + ch_dim2 * 5) * ch_dim1 + 1] = cr2 + ci5;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 2] = ci2 + cr5;
ch[(k + ch_dim2 * 3) * ch_dim1 + 2] = ci3 + cr4;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr3 - ci4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = cr3 + ci4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 2] = ci3 - cr4;
ch[(k + ch_dim2 * 5) * ch_dim1 + 2] = ci2 - cr5;
/* L101: */
}
return;
L102:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 2; i__ <= i__2; i__ += 2) {
ti5 = cc[i__ + (k * 5 + 2) * cc_dim1] - cc[i__ + (k * 5 + 5) * cc_dim1];
ti2 = cc[i__ + (k * 5 + 2) * cc_dim1] + cc[i__ + (k * 5 + 5) * cc_dim1];
ti4 = cc[i__ + (k * 5 + 3) * cc_dim1] - cc[i__ + (k * 5 + 4) * cc_dim1];
ti3 = cc[i__ + (k * 5 + 3) * cc_dim1] + cc[i__ + (k * 5 + 4) * cc_dim1];
tr5 = cc[i__ - 1 + (k * 5 + 2) * cc_dim1] - cc[i__ - 1 + (k * 5 + 5) * cc_dim1];
tr2 = cc[i__ - 1 + (k * 5 + 2) * cc_dim1] + cc[i__ - 1 + (k * 5 + 5) * cc_dim1];
tr4 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] - cc[i__ - 1 + (k * 5 + 4) * cc_dim1];
tr3 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] + cc[i__ - 1 + (k * 5 + 4) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 5 + 1) *cc_dim1] + tr2 + tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 5 + 1) * cc_dim1] + ti2 + ti3;
cr2 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr11 * tr2 + tr12 * tr3;
ci2 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr11 * ti2 + tr12 * ti3;
cr3 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr12 * tr2 + tr11 * tr3;
ci3 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr12 * ti2 + tr11 * ti3;
cr5 = ti11 * tr5 + ti12 * tr4;
ci5 = ti11 * ti5 + ti12 * ti4;
cr4 = ti12 * tr5 - ti11 * tr4;
ci4 = ti12 * ti5 - ti11 * ti4;
dr3 = cr3 - ci4;
dr4 = cr3 + ci4;
di3 = ci3 + cr4;
di4 = ci3 - cr4;
dr5 = cr2 + ci5;
dr2 = cr2 - ci5;
di5 = ci2 - cr5;
di2 = ci2 + cr5;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * dr2 + wa1[i__] * di2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 1] * di2 - wa1[i__] * dr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * dr3 + wa2[i__] * di3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 1] * di3 - wa2[i__] * dr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * dr4 + wa3[i__] * di4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 1] * di4 - wa3[i__] * dr4;
ch[i__ - 1 + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 1] * dr5 + wa4[i__] * di5;
ch[i__ + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 1] * di5 - wa4[i__] * dr5;
/* L103: */
}
/* L104: */
}
return;
} /* passf5_ */
/* Subroutine */ static void s_radb2(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1)
{
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ti2, tr2;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 3;
cc -= cc_offset;
--wa1;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] + cc[*ido + ((k << 1) + 2) * cc_dim1];
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cc[((k << 1) + 1) * cc_dim1 + 1] - cc[*ido + ((k << 1) + 2) * cc_dim1];
/* L101: */
}
if ((i__1 = *ido - 2) < 0) {
goto L107;
} else if (i__1 == 0) {
goto L105;
} else {
goto L102;
}
L102:
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] + cc[ic - 1 + ((k << 1) + 2) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 1) + 1) * cc_dim1] - cc[ic - 1 + ((k << 1) + 2) * cc_dim1];
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + ((k << 1) + 1) * cc_dim1] - cc[ic + ((k << 1) + 2) * cc_dim1];
ti2 = cc[i__ + ((k << 1) + 1) * cc_dim1] + cc[ic + ((k << 1) + 2) * cc_dim1];
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * tr2 - wa1[i__ - 1] * ti2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * ti2 + wa1[i__ - 1] * tr2;
/* L103: */
}
/* L104: */
}
if (*ido % 2 == 1) {
return;
}
L105:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[*ido + (k + ch_dim2) * ch_dim1] = cc[*ido + ((k << 1) + 1) * cc_dim1] + cc[*ido + ((k << 1) + 1) * cc_dim1];
ch[*ido + (k + (ch_dim2 << 1)) * ch_dim1] = -(cc[((k << 1) + 2) * cc_dim1 + 1] + cc[((k << 1) + 2) * cc_dim1 + 1]);
/* L106: */
}
L107:
return;
} /* radb2_ */
/* Subroutine */ static void s_radb3(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2)
{
/* Initialized data */
static real_t taur = POST(-0.5);
static real_t taui = POST(0.8660254037844386467637231707529361834710262690519031402790348975);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + (cc_dim1 << 2);
cc -= cc_offset;
--wa1;
--wa2;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
tr2 = cc[*ido + (k * 3 + 2) * cc_dim1] + cc[*ido + (k * 3 + 2) * cc_dim1];
cr2 = cc[(k * 3 + 1) * cc_dim1 + 1] + taur * tr2;
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 3 + 1) * cc_dim1 + 1] + tr2;
ci3 = taui * (cc[(k * 3 + 3) * cc_dim1 + 1] + cc[(k * 3 + 3) * cc_dim1 + 1]);
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci3;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr2 + ci3;
/* L101: */
}
if (*ido == 1) {
return;
}
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
tr2 = cc[i__ - 1 + (k * 3 + 3) * cc_dim1] + cc[ic - 1 + (k * 3 + 2) * cc_dim1];
cr2 = cc[i__ - 1 + (k * 3 + 1) * cc_dim1] + taur * tr2;
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 3 + 1) *cc_dim1] + tr2;
ti2 = cc[i__ + (k * 3 + 3) * cc_dim1] - cc[ic + (k * 3 + 2) * cc_dim1];
ci2 = cc[i__ + (k * 3 + 1) * cc_dim1] + taur * ti2;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 3 + 1) * cc_dim1] + ti2;
cr3 = taui * (cc[i__ - 1 + (k * 3 + 3) * cc_dim1] - cc[ic - 1 + (k * 3 + 2) * cc_dim1]);
ci3 = taui * (cc[i__ + (k * 3 + 3) * cc_dim1] + cc[ic + (k * 3 + 2) * cc_dim1]);
dr2 = cr2 - ci3;
dr3 = cr2 + ci3;
di2 = ci2 + cr3;
di3 = ci2 - cr3;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * dr2 - wa1[i__ - 1] * di2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * di2 + wa1[i__ - 1] * dr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * dr3 - wa2[i__ - 1] * di3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * di3 + wa2[i__ - 1] * dr3;
/* L102: */
}
/* L103: */
}
return;
} /* radb3_ */
/* Subroutine */ static void s_radb4(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3)
{
/* Initialized data */
static real_t sqrt2 = POST(1.41421356237309504880168872420969807856967187536948073176679738);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2,
tr3, tr4;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 5;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
tr1 = cc[((k << 2) + 1) * cc_dim1 + 1] - cc[*ido + ((k << 2) + 4) * cc_dim1];
tr2 = cc[((k << 2) + 1) * cc_dim1 + 1] + cc[*ido + ((k << 2) + 4) * cc_dim1];
tr3 = cc[*ido + ((k << 2) + 2) * cc_dim1] + cc[*ido + ((k << 2) + 2) *cc_dim1];
tr4 = cc[((k << 2) + 3) * cc_dim1 + 1] + cc[((k << 2) + 3) * cc_dim1 + 1];
ch[(k + ch_dim2) * ch_dim1 + 1] = tr2 + tr3;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = tr1 - tr4;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = tr2 - tr3;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = tr1 + tr4;
/* L101: */
}
if ((i__1 = *ido - 2) < 0) {
goto L107;
} else if (i__1 == 0) {
goto L105;
} else {
goto L102;
}
L102:
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
ti1 = cc[i__ + ((k << 2) + 1) * cc_dim1] + cc[ic + ((k << 2) + 4) * cc_dim1];
ti2 = cc[i__ + ((k << 2) + 1) * cc_dim1] - cc[ic + ((k << 2) + 4) * cc_dim1];
ti3 = cc[i__ + ((k << 2) + 3) * cc_dim1] - cc[ic + ((k << 2) + 2) * cc_dim1];
tr4 = cc[i__ + ((k << 2) + 3) * cc_dim1] + cc[ic + ((k << 2) + 2) * cc_dim1];
tr1 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] - cc[ic - 1 + ((k << 2) + 4) * cc_dim1];
tr2 = cc[i__ - 1 + ((k << 2) + 1) * cc_dim1] + cc[ic - 1 + ((k << 2) + 4) * cc_dim1];
ti4 = cc[i__ - 1 + ((k << 2) + 3) * cc_dim1] - cc[ic - 1 + ((k << 2) + 2) * cc_dim1];
tr3 = cc[i__ - 1 + ((k << 2) + 3) * cc_dim1] + cc[ic - 1 + ((k << 2) + 2) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = tr2 + tr3;
cr3 = tr2 - tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = ti2 + ti3;
ci3 = ti2 - ti3;
cr2 = tr1 - tr4;
cr4 = tr1 + tr4;
ci2 = ti1 + ti4;
ci4 = ti1 - ti4;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * cr2 - wa1[i__ - 1] * ci2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * ci2 + wa1[i__ - 1] * cr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * cr3 - wa2[i__ - 1] * ci3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * ci3 + wa2[i__ - 1] * cr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 2] * cr4 - wa3[i__ - 1] * ci4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 2] * ci4 + wa3[i__ - 1] * cr4;
/* L103: */
}
/* L104: */
}
if (*ido % 2 == 1) {
return;
}
L105:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti1 = cc[((k << 2) + 2) * cc_dim1 + 1] + cc[((k << 2) + 4) * cc_dim1 + 1];
ti2 = cc[((k << 2) + 4) * cc_dim1 + 1] - cc[((k << 2) + 2) * cc_dim1 + 1];
tr1 = cc[*ido + ((k << 2) + 1) * cc_dim1] - cc[*ido + ((k << 2) + 3) *cc_dim1];
tr2 = cc[*ido + ((k << 2) + 1) * cc_dim1] + cc[*ido + ((k << 2) + 3) *cc_dim1];
ch[*ido + (k + ch_dim2) * ch_dim1] = tr2 + tr2;
ch[*ido + (k + (ch_dim2 << 1)) * ch_dim1] = sqrt2 * (tr1 - ti1);
ch[*ido + (k + ch_dim2 * 3) * ch_dim1] = ti2 + ti2;
ch[*ido + (k + (ch_dim2 << 2)) * ch_dim1] = -sqrt2 * (tr1 + ti1);
/* L106: */
}
L107:
return;
} /* radb4_ */
/* Subroutine */ static void s_radb5(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3,
real_t *wa4)
{
/* Initialized data */
static real_t tr11 = POST(0.3090169943749474241022934171828195886015458990288143106772431137);
static real_t ti11 = POST(0.9510565162951535721164393337938214340569863412575022244730564442);
static real_t tr12 = POST(-0.8090169943749474241022934171828190588601545899028814310677431135);
static real_t ti12 = POST(0.5877852522924731291687059546390727685976524376431459107227248076);
/* System generated locals */
int cc_dim1, cc_offset, ch_dim1, ch_dim2, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4,
ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_offset = 1 + cc_dim1 * 6;
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
--wa4;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti5 = cc[(k * 5 + 3) * cc_dim1 + 1] + cc[(k * 5 + 3) * cc_dim1 + 1];
ti4 = cc[(k * 5 + 5) * cc_dim1 + 1] + cc[(k * 5 + 5) * cc_dim1 + 1];
tr2 = cc[*ido + (k * 5 + 2) * cc_dim1] + cc[*ido + (k * 5 + 2) * cc_dim1];
tr3 = cc[*ido + (k * 5 + 4) * cc_dim1] + cc[*ido + (k * 5 + 4) * cc_dim1];
ch[(k + ch_dim2) * ch_dim1 + 1] = cc[(k * 5 + 1) * cc_dim1 + 1] + tr2 + tr3;
cr2 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr11 * tr2 + tr12 * tr3;
cr3 = cc[(k * 5 + 1) * cc_dim1 + 1] + tr12 * tr2 + tr11 * tr3;
ci5 = ti11 * ti5 + ti12 * ti4;
ci4 = ti12 * ti5 - ti11 * ti4;
ch[(k + (ch_dim2 << 1)) * ch_dim1 + 1] = cr2 - ci5;
ch[(k + ch_dim2 * 3) * ch_dim1 + 1] = cr3 - ci4;
ch[(k + (ch_dim2 << 2)) * ch_dim1 + 1] = cr3 + ci4;
ch[(k + ch_dim2 * 5) * ch_dim1 + 1] = cr2 + ci5;
/* L101: */
}
if (*ido == 1) {
return;
}
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
ti5 = cc[i__ + (k * 5 + 3) * cc_dim1] + cc[ic + (k * 5 + 2) * cc_dim1];
ti2 = cc[i__ + (k * 5 + 3) * cc_dim1] - cc[ic + (k * 5 + 2) * cc_dim1];
ti4 = cc[i__ + (k * 5 + 5) * cc_dim1] + cc[ic + (k * 5 + 4) * cc_dim1];
ti3 = cc[i__ + (k * 5 + 5) * cc_dim1] - cc[ic + (k * 5 + 4) * cc_dim1];
tr5 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] - cc[ic - 1 + (k * 5 + 2) * cc_dim1];
tr2 = cc[i__ - 1 + (k * 5 + 3) * cc_dim1] + cc[ic - 1 + (k * 5 + 2) * cc_dim1];
tr4 = cc[i__ - 1 + (k * 5 + 5) * cc_dim1] - cc[ic - 1 + (k * 5 + 4) * cc_dim1];
tr3 = cc[i__ - 1 + (k * 5 + 5) * cc_dim1] + cc[ic - 1 + (k * 5 + 4) * cc_dim1];
ch[i__ - 1 + (k + ch_dim2) * ch_dim1] = cc[i__ - 1 + (k * 5 + 1) *cc_dim1] + tr2 + tr3;
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * 5 + 1) * cc_dim1] + ti2 + ti3;
cr2 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr11 * tr2 + tr12 * tr3;
ci2 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr11 * ti2 + tr12 * ti3;
cr3 = cc[i__ - 1 + (k * 5 + 1) * cc_dim1] + tr12 * tr2 + tr11 * tr3;
ci3 = cc[i__ + (k * 5 + 1) * cc_dim1] + tr12 * ti2 + tr11 * ti3;
cr5 = ti11 * tr5 + ti12 * tr4;
ci5 = ti11 * ti5 + ti12 * ti4;
cr4 = ti12 * tr5 - ti11 * tr4;
ci4 = ti12 * ti5 - ti11 * ti4;
dr3 = cr3 - ci4;
dr4 = cr3 + ci4;
di3 = ci3 + cr4;
di4 = ci3 - cr4;
dr5 = cr2 + ci5;
dr2 = cr2 - ci5;
di5 = ci2 - cr5;
di2 = ci2 + cr5;
ch[i__ - 1 + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * dr2 - wa1[i__ - 1] * di2;
ch[i__ + (k + (ch_dim2 << 1)) * ch_dim1] = wa1[i__ - 2] * di2 + wa1[i__ - 1] * dr2;
ch[i__ - 1 + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * dr3 - wa2[i__ - 1] * di3;
ch[i__ + (k + ch_dim2 * 3) * ch_dim1] = wa2[i__ - 2] * di3 + wa2[i__ - 1] * dr3;
ch[i__ - 1 + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 2] * dr4 - wa3[i__ - 1] * di4;
ch[i__ + (k + (ch_dim2 << 2)) * ch_dim1] = wa3[i__ - 2] * di4 + wa3[i__ - 1] * dr4;
ch[i__ - 1 + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 2] * dr5 - wa4[i__ - 1] * di5;
ch[i__ + (k + ch_dim2 * 5) * ch_dim1] = wa4[i__ - 2] * di5 + wa4[i__ - 1] * dr5;
/* L102: */
}
/* L103: */
}
return;
} /* radb5_ */
/* Subroutine */ static void s_radbg(int *ido, int *ip, int *l1, int *
idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch,
real_t *ch2, real_t *wa)
{
/* Initialized data */
static real_t tpi = POST(6.283185307179586476925286766559005768394338798750116419498891846);
/* System generated locals */
int ch_dim1, ch_dim2, ch_offset, cc_dim1, cc_dim2, cc_offset, c1_dim1,
c1_dim2, c1_offset, c2_dim1, c2_offset, ch2_dim1, ch2_offset,
i__1, i__2, i__3;
/* Local variables */
int i__, j, k, l, j2, ic, jc, lc, ik, is;
real_t dc2, ai1, ai2, ar1, ar2, ds2;
int nbd;
real_t dcp, arg, dsp, ar1h, ar2h;
int idp2, ipp2, idij, ipph;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
c1_dim1 = *ido;
c1_dim2 = *l1;
c1_offset = 1 + c1_dim1 * (1 + c1_dim2);
c1 -= c1_offset;
cc_dim1 = *ido;
cc_dim2 = *ip;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
ch2_dim1 = *idl1;
ch2_offset = 1 + ch2_dim1;
ch2 -= ch2_offset;
c2_dim1 = *idl1;
c2_offset = 1 + c2_dim1;
c2 -= c2_offset;
--wa;
/* Function Body */
arg = tpi / (real_t) (*ip);
dcp = POST(cos)(arg);
dsp = POST(sin)(arg);
idp2 = *ido + 2;
nbd = (*ido - 1) / 2;
ipp2 = *ip + 2;
ipph = (*ip + 1) / 2;
if (*ido < *l1) {
goto L103;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) *
cc_dim1];
/* L101: */
}
/* L102: */
}
goto L106;
L103:
i__1 = *ido;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[i__ + (k + ch_dim2) * ch_dim1] = cc[i__ + (k * cc_dim2 + 1) *
cc_dim1];
/* L104: */
}
/* L105: */
}
L106:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
j2 = j + j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[(k + j * ch_dim2) * ch_dim1 + 1] = cc[*ido + (j2 - 2 + k *
cc_dim2) * cc_dim1] + cc[*ido + (j2 - 2 + k * cc_dim2) *
cc_dim1];
ch[(k + jc * ch_dim2) * ch_dim1 + 1] = cc[(j2 - 1 + k * cc_dim2) *
cc_dim1 + 1] + cc[(j2 - 1 + k * cc_dim2) * cc_dim1 + 1];
/* L107: */
}
/* L108: */
}
if (*ido == 1) {
goto L116;
}
if (nbd < *l1) {
goto L112;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
ic = idp2 - i__;
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = cc[i__ - 1 + ((j
<< 1) - 1 + k * cc_dim2) * cc_dim1] + cc[ic - 1 + ((j
<< 1) - 2 + k * cc_dim2) * cc_dim1];
ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] = cc[i__ - 1 + ((j
<< 1) - 1 + k * cc_dim2) * cc_dim1] - cc[ic - 1 + ((j
<< 1) - 2 + k * cc_dim2) * cc_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + ((j << 1) -
1 + k * cc_dim2) * cc_dim1] - cc[ic + ((j << 1) - 2 +
k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + ((j << 1) -
1 + k * cc_dim2) * cc_dim1] + cc[ic + ((j << 1) - 2 +
k * cc_dim2) * cc_dim1];
/* L109: */
}
/* L110: */
}
/* L111: */
}
goto L116;
L112:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = cc[i__ - 1 + ((j
<< 1) - 1 + k * cc_dim2) * cc_dim1] + cc[ic - 1 + ((j
<< 1) - 2 + k * cc_dim2) * cc_dim1];
ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] = cc[i__ - 1 + ((j
<< 1) - 1 + k * cc_dim2) * cc_dim1] - cc[ic - 1 + ((j
<< 1) - 2 + k * cc_dim2) * cc_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = cc[i__ + ((j << 1) -
1 + k * cc_dim2) * cc_dim1] - cc[ic + ((j << 1) - 2 +
k * cc_dim2) * cc_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = cc[i__ + ((j << 1) -
1 + k * cc_dim2) * cc_dim1] + cc[ic + ((j << 1) - 2 +
k * cc_dim2) * cc_dim1];
/* L113: */
}
/* L114: */
}
/* L115: */
}
L116:
ar1 = POST(1.0);
ai1 = POST(0.0);
i__1 = ipph;
for (l = 2; l <= i__1; ++l) {
lc = ipp2 - l;
ar1h = dcp * ar1 - dsp * ai1;
ai1 = dcp * ai1 + dsp * ar1;
ar1 = ar1h;
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
c2[ik + l * c2_dim1] = ch2[ik + ch2_dim1] + ar1 * ch2[ik + (ch2_dim1 << 1)];
c2[ik + lc * c2_dim1] = ai1 * ch2[ik + *ip * ch2_dim1];
/* L117: */
}
dc2 = ar1;
ds2 = ai1;
ar2 = ar1;
ai2 = ai1;
i__2 = ipph;
for (j = 3; j <= i__2; ++j) {
jc = ipp2 - j;
ar2h = dc2 * ar2 - ds2 * ai2;
ai2 = dc2 * ai2 + ds2 * ar2;
ar2 = ar2h;
i__3 = *idl1;
for (ik = 1; ik <= i__3; ++ik) {
c2[ik + l * c2_dim1] += ar2 * ch2[ik + j * ch2_dim1];
c2[ik + lc * c2_dim1] += ai2 * ch2[ik + jc * ch2_dim1];
/* L118: */
}
/* L119: */
}
/* L120: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
ch2[ik + ch2_dim1] += ch2[ik + j * ch2_dim1];
/* L121: */
}
/* L122: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[(k + j * ch_dim2) * ch_dim1 + 1] = c1[(k + j * c1_dim2) * c1_dim1 + 1] - c1[(k + jc * c1_dim2) * c1_dim1 + 1];
ch[(k + jc * ch_dim2) * ch_dim1 + 1] = c1[(k + j * c1_dim2) * c1_dim1 + 1] + c1[(k + jc * c1_dim2) * c1_dim1 + 1];
/* L123: */
}
/* L124: */
}
if (*ido == 1) {
goto L132;
}
if (nbd < *l1) {
goto L128;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = c1[i__ - 1 + (k +
j * c1_dim2) * c1_dim1] - c1[i__ + (k + jc * c1_dim2) * c1_dim1];
ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] = c1[i__ - 1 + (k
+ j * c1_dim2) * c1_dim1] + c1[i__ + (k + jc * c1_dim2) * c1_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = c1[i__ + (k + j *
c1_dim2) * c1_dim1] + c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = c1[i__ + (k + j *
c1_dim2) * c1_dim1] - c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1];
/* L125: */
}
/* L126: */
}
/* L127: */
}
goto L132;
L128:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = c1[i__ - 1 + (k +
j * c1_dim2) * c1_dim1] - c1[i__ + (k + jc * c1_dim2) * c1_dim1];
ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] = c1[i__ - 1 + (k
+ j * c1_dim2) * c1_dim1] + c1[i__ + (k + jc * c1_dim2) * c1_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = c1[i__ + (k + j *
c1_dim2) * c1_dim1] + c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1];
ch[i__ + (k + jc * ch_dim2) * ch_dim1] = c1[i__ + (k + j *
c1_dim2) * c1_dim1] - c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1];
/* L129: */
}
/* L130: */
}
/* L131: */
}
L132:
if (*ido == 1) {
return;
}
i__1 = *idl1;
for (ik = 1; ik <= i__1; ++ik) {
c2[ik + c2_dim1] = ch2[ik + ch2_dim1];
/* L133: */
}
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
c1[(k + j * c1_dim2) * c1_dim1 + 1] = ch[(k + j * ch_dim2) * ch_dim1 + 1];
/* L134: */
}
/* L135: */
}
if (nbd > *l1) {
goto L139;
}
is = -(*ido);
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
is += *ido;
idij = is;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
idij += 2;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] - wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] + wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L136: */
}
/* L137: */
}
/* L138: */
}
goto L143;
L139:
is = -(*ido);
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
is += *ido;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
idij = is;
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
idij += 2;
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[
i__ - 1 + (k + j * ch_dim2) * ch_dim1] - wa[idij] *
ch[i__ + (k + j * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = wa[idij - 1] * ch[i__
+ (k + j * ch_dim2) * ch_dim1] + wa[idij] * ch[i__ -
1 + (k + j * ch_dim2) * ch_dim1];
/* L140: */
}
/* L141: */
}
/* L142: */
}
L143:
return;
} /* radbg_ */
/* Subroutine */ static void s_radf2(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1)
{
/* System generated locals */
int ch_dim1, ch_offset, cc_dim1, cc_dim2, cc_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ti2, tr2;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_offset = 1 + ch_dim1 * 3;
ch -= ch_offset;
cc_dim1 = *ido;
cc_dim2 = *l1;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
--wa1;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[((k << 1) + 1) * ch_dim1 + 1] = cc[(k + cc_dim2) * cc_dim1 + 1] + cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1];
ch[*ido + ((k << 1) + 2) * ch_dim1] = cc[(k + cc_dim2) * cc_dim1 + 1] - cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1];
/* L101: */
}
if ((i__1 = *ido - 2) < 0) {
goto L107;
} else if (i__1 == 0) {
goto L105;
} else {
goto L102;
}
L102:
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
tr2 = wa1[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1]
+ wa1[i__ - 1] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1];
ti2 = wa1[i__ - 2] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1] -
wa1[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1];
ch[i__ + ((k << 1) + 1) * ch_dim1] = cc[i__ + (k + cc_dim2) * cc_dim1] + ti2;
ch[ic + ((k << 1) + 2) * ch_dim1] = ti2 - cc[i__ + (k + cc_dim2) *cc_dim1];
ch[i__ - 1 + ((k << 1) + 1) * ch_dim1] = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] + tr2;
ch[ic - 1 + ((k << 1) + 2) * ch_dim1] = cc[i__ - 1 + (k + cc_dim2)* cc_dim1] - tr2;
/* L103: */
}
/* L104: */
}
if (*ido % 2 == 1) {
return;
}
L105:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ch[((k << 1) + 2) * ch_dim1 + 1] = -cc[*ido + (k + (cc_dim2 << 1)) * cc_dim1];
ch[*ido + ((k << 1) + 1) * ch_dim1] = cc[*ido + (k + cc_dim2) * cc_dim1];
/* L106: */
}
L107:
return;
} /* radf2_ */
/* Subroutine */ static void s_radf3(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2)
{
/* Initialized data */
static real_t taur = POST(-0.5);
static real_t taui = POST(0.8660254037844386467637231707529361834710262690519031402790348975);
/* System generated locals */
int ch_dim1, ch_offset, cc_dim1, cc_dim2, cc_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, di2, di3, cr2, dr2, dr3, ti2, ti3, tr2, tr3;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_offset = 1 + (ch_dim1 << 2);
ch -= ch_offset;
cc_dim1 = *ido;
cc_dim2 = *l1;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
--wa1;
--wa2;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
cr2 = cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1] + cc[(k + cc_dim2 * 3) * cc_dim1 + 1];
ch[(k * 3 + 1) * ch_dim1 + 1] = cc[(k + cc_dim2) * cc_dim1 + 1] + cr2;
ch[(k * 3 + 3) * ch_dim1 + 1] = taui * (cc[(k + cc_dim2 * 3) * cc_dim1 + 1] - cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1]);
ch[*ido + (k * 3 + 2) * ch_dim1] = cc[(k + cc_dim2) * cc_dim1 + 1] + taur * cr2;
/* L101: */
}
if (*ido == 1) {
return;
}
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
dr2 = wa1[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1] + wa1[i__ - 1] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1];
di2 = wa1[i__ - 2] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1] - wa1[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1];
dr3 = wa2[i__ - 2] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1] + wa2[i__ - 1] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1];
di3 = wa2[i__ - 2] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1] - wa2[i__ - 1] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1];
cr2 = dr2 + dr3;
ci2 = di2 + di3;
ch[i__ - 1 + (k * 3 + 1) * ch_dim1] = cc[i__ - 1 + (k + cc_dim2) *cc_dim1] + cr2;
ch[i__ + (k * 3 + 1) * ch_dim1] = cc[i__ + (k + cc_dim2) * cc_dim1] + ci2;
tr2 = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] + taur * cr2;
ti2 = cc[i__ + (k + cc_dim2) * cc_dim1] + taur * ci2;
tr3 = taui * (di2 - di3);
ti3 = taui * (dr3 - dr2);
ch[i__ - 1 + (k * 3 + 3) * ch_dim1] = tr2 + tr3;
ch[ic - 1 + (k * 3 + 2) * ch_dim1] = tr2 - tr3;
ch[i__ + (k * 3 + 3) * ch_dim1] = ti2 + ti3;
ch[ic + (k * 3 + 2) * ch_dim1] = ti3 - ti2;
/* L102: */
}
/* L103: */
}
return;
} /* radf3_ */
/* Subroutine */ static void s_radf4(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3)
{
/* Initialized data */
static real_t hsqt2 = POST(0.70710678118654752440084436210484903928483593768474036588339869);
/* System generated locals */
int cc_dim1, cc_dim2, cc_offset, ch_dim1, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_offset = 1 + ch_dim1 * 5;
ch -= ch_offset;
cc_dim1 = *ido;
cc_dim2 = *l1;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
tr1 = cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1] + cc[(k + (cc_dim2 << 2))* cc_dim1 + 1];
tr2 = cc[(k + cc_dim2) * cc_dim1 + 1] + cc[(k + cc_dim2 * 3) * cc_dim1 + 1];
ch[((k << 2) + 1) * ch_dim1 + 1] = tr1 + tr2;
ch[*ido + ((k << 2) + 4) * ch_dim1] = tr2 - tr1;
ch[*ido + ((k << 2) + 2) * ch_dim1] = cc[(k + cc_dim2) * cc_dim1 + 1] - cc[(k + cc_dim2 * 3) * cc_dim1 + 1];
ch[((k << 2) + 3) * ch_dim1 + 1] = cc[(k + (cc_dim2 << 2)) * cc_dim1 + 1] - cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1];
/* L101: */
}
if ((i__1 = *ido - 2) < 0) {
goto L107;
} else if (i__1 == 0) {
goto L105;
} else {
goto L102;
}
L102:
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
cr2 = wa1[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1] + wa1[i__ - 1] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1];
ci2 = wa1[i__ - 2] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1] - wa1[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1];
cr3 = wa2[i__ - 2] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1] + wa2[i__ - 1] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1];
ci3 = wa2[i__ - 2] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1] - wa2[i__ - 1] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1];
cr4 = wa3[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 2)) * cc_dim1] + wa3[i__ - 1] * cc[i__ + (k + (cc_dim2 << 2)) * cc_dim1];
ci4 = wa3[i__ - 2] * cc[i__ + (k + (cc_dim2 << 2)) * cc_dim1] - wa3[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 2)) * cc_dim1];
tr1 = cr2 + cr4;
tr4 = cr4 - cr2;
ti1 = ci2 + ci4;
ti4 = ci2 - ci4;
ti2 = cc[i__ + (k + cc_dim2) * cc_dim1] + ci3;
ti3 = cc[i__ + (k + cc_dim2) * cc_dim1] - ci3;
tr2 = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] + cr3;
tr3 = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] - cr3;
ch[i__ - 1 + ((k << 2) + 1) * ch_dim1] = tr1 + tr2;
ch[ic - 1 + ((k << 2) + 4) * ch_dim1] = tr2 - tr1;
ch[i__ + ((k << 2) + 1) * ch_dim1] = ti1 + ti2;
ch[ic + ((k << 2) + 4) * ch_dim1] = ti1 - ti2;
ch[i__ - 1 + ((k << 2) + 3) * ch_dim1] = ti4 + tr3;
ch[ic - 1 + ((k << 2) + 2) * ch_dim1] = tr3 - ti4;
ch[i__ + ((k << 2) + 3) * ch_dim1] = tr4 + ti3;
ch[ic + ((k << 2) + 2) * ch_dim1] = tr4 - ti3;
/* L103: */
}
/* L104: */
}
if (*ido % 2 == 1) {
return;
}
L105:
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
ti1 = -hsqt2 * (cc[*ido + (k + (cc_dim2 << 1)) * cc_dim1] + cc[*ido + (k + (cc_dim2 << 2)) * cc_dim1]);
tr1 = hsqt2 * (cc[*ido + (k + (cc_dim2 << 1)) * cc_dim1] - cc[*ido + (k + (cc_dim2 << 2)) * cc_dim1]);
ch[*ido + ((k << 2) + 1) * ch_dim1] = tr1 + cc[*ido + (k + cc_dim2) * cc_dim1];
ch[*ido + ((k << 2) + 3) * ch_dim1] = cc[*ido + (k + cc_dim2) * cc_dim1] - tr1;
ch[((k << 2) + 2) * ch_dim1 + 1] = ti1 - cc[*ido + (k + cc_dim2 * 3) *cc_dim1];
ch[((k << 2) + 4) * ch_dim1 + 1] = ti1 + cc[*ido + (k + cc_dim2 * 3) *cc_dim1];
/* L106: */
}
L107:
return;
} /* radf4_ */
/* Subroutine */ static void s_radf5(int *ido, int *l1, real_t *cc,
real_t *ch, real_t *wa1, real_t *wa2, real_t *wa3,
real_t *wa4)
{
/* Initialized data */
static real_t tr11 = POST(0.3090169943749474241022934171828195886015458990288143106772431137);
static real_t ti11 = POST(0.9510565162951535721164393337938214340569863412575022244730564442);
static real_t tr12 = POST(-0.8090169943749474241022934171828190588601545899028814310677431135);
static real_t ti12 = POST(0.5877852522924731291687059546390727685976524376431459107227248076);
/* System generated locals */
int cc_dim1, cc_dim2, cc_offset, ch_dim1, ch_offset, i__1, i__2;
/* Local variables */
int i__, k, ic;
real_t ci2, di2, ci4, ci5, di3, di4, di5, ci3, cr2, cr3, dr2, dr3,
dr4, dr5, cr5, cr4, ti2, ti3, ti5, ti4, tr2, tr3, tr4, tr5;
int idp2;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_offset = 1 + ch_dim1 * 6;
ch -= ch_offset;
cc_dim1 = *ido;
cc_dim2 = *l1;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
--wa1;
--wa2;
--wa3;
--wa4;
/* Function Body */
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
cr2 = cc[(k + cc_dim2 * 5) * cc_dim1 + 1] + cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1];
ci5 = cc[(k + cc_dim2 * 5) * cc_dim1 + 1] - cc[(k + (cc_dim2 << 1)) * cc_dim1 + 1];
cr3 = cc[(k + (cc_dim2 << 2)) * cc_dim1 + 1] + cc[(k + cc_dim2 * 3) * cc_dim1 + 1];
ci4 = cc[(k + (cc_dim2 << 2)) * cc_dim1 + 1] - cc[(k + cc_dim2 * 3) * cc_dim1 + 1];
ch[(k * 5 + 1) * ch_dim1 + 1] = cc[(k + cc_dim2) * cc_dim1 + 1] + cr2 + cr3;
ch[*ido + (k * 5 + 2) * ch_dim1] = cc[(k + cc_dim2) * cc_dim1 + 1] + tr11 * cr2 + tr12 * cr3;
ch[(k * 5 + 3) * ch_dim1 + 1] = ti11 * ci5 + ti12 * ci4;
ch[*ido + (k * 5 + 4) * ch_dim1] = cc[(k + cc_dim2) * cc_dim1 + 1] + tr12 * cr2 + tr11 * cr3;
ch[(k * 5 + 5) * ch_dim1 + 1] = ti12 * ci5 - ti11 * ci4;
/* L101: */
}
if (*ido == 1) {
return;
}
idp2 = *ido + 2;
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
dr2 = wa1[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1] + wa1[i__ - 1] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1];
di2 = wa1[i__ - 2] * cc[i__ + (k + (cc_dim2 << 1)) * cc_dim1] - wa1[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 1)) * cc_dim1];
dr3 = wa2[i__ - 2] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1] + wa2[i__ - 1] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1];
di3 = wa2[i__ - 2] * cc[i__ + (k + cc_dim2 * 3) * cc_dim1] - wa2[i__ - 1] * cc[i__ - 1 + (k + cc_dim2 * 3) * cc_dim1];
dr4 = wa3[i__ - 2] * cc[i__ - 1 + (k + (cc_dim2 << 2)) * cc_dim1] + wa3[i__ - 1] * cc[i__ + (k + (cc_dim2 << 2)) * cc_dim1];
di4 = wa3[i__ - 2] * cc[i__ + (k + (cc_dim2 << 2)) * cc_dim1] - wa3[i__ - 1] * cc[i__ - 1 + (k + (cc_dim2 << 2)) * cc_dim1];
dr5 = wa4[i__ - 2] * cc[i__ - 1 + (k + cc_dim2 * 5) * cc_dim1] + wa4[i__ - 1] * cc[i__ + (k + cc_dim2 * 5) * cc_dim1];
di5 = wa4[i__ - 2] * cc[i__ + (k + cc_dim2 * 5) * cc_dim1] - wa4[i__ - 1] * cc[i__ - 1 + (k + cc_dim2 * 5) * cc_dim1];
cr2 = dr2 + dr5;
ci5 = dr5 - dr2;
cr5 = di2 - di5;
ci2 = di2 + di5;
cr3 = dr3 + dr4;
ci4 = dr4 - dr3;
cr4 = di3 - di4;
ci3 = di3 + di4;
ch[i__ - 1 + (k * 5 + 1) * ch_dim1] = cc[i__ - 1 + (k + cc_dim2) *cc_dim1] + cr2 + cr3;
ch[i__ + (k * 5 + 1) * ch_dim1] = cc[i__ + (k + cc_dim2) * cc_dim1] + ci2 + ci3;
tr2 = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] + tr11 * cr2 + tr12 * cr3;
ti2 = cc[i__ + (k + cc_dim2) * cc_dim1] + tr11 * ci2 + tr12 * ci3;
tr3 = cc[i__ - 1 + (k + cc_dim2) * cc_dim1] + tr12 * cr2 + tr11 * cr3;
ti3 = cc[i__ + (k + cc_dim2) * cc_dim1] + tr12 * ci2 + tr11 * ci3;
tr5 = ti11 * cr5 + ti12 * cr4;
ti5 = ti11 * ci5 + ti12 * ci4;
tr4 = ti12 * cr5 - ti11 * cr4;
ti4 = ti12 * ci5 - ti11 * ci4;
ch[i__ - 1 + (k * 5 + 3) * ch_dim1] = tr2 + tr5;
ch[ic - 1 + (k * 5 + 2) * ch_dim1] = tr2 - tr5;
ch[i__ + (k * 5 + 3) * ch_dim1] = ti2 + ti5;
ch[ic + (k * 5 + 2) * ch_dim1] = ti5 - ti2;
ch[i__ - 1 + (k * 5 + 5) * ch_dim1] = tr3 + tr4;
ch[ic - 1 + (k * 5 + 4) * ch_dim1] = tr3 - tr4;
ch[i__ + (k * 5 + 5) * ch_dim1] = ti3 + ti4;
ch[ic + (k * 5 + 4) * ch_dim1] = ti4 - ti3;
/* L102: */
}
/* L103: */
}
return;
} /* radf5_ */
/* Subroutine */ static void s_radfg(int *ido, int *ip, int *l1, int *
idl1, real_t *cc, real_t *c1, real_t *c2, real_t *ch,
real_t *ch2, real_t *wa)
{
/* Initialized data */
static real_t tpi = POST(6.283185307179586476925286766559005768394338798750116419498891846);
/* System generated locals */
int ch_dim1, ch_dim2, ch_offset, cc_dim1, cc_dim2, cc_offset, c1_dim1,
c1_dim2, c1_offset, c2_dim1, c2_offset, ch2_dim1, ch2_offset,
i__1, i__2, i__3;
/* Local variables */
int i__, j, k, l, j2, ic, jc, lc, ik, is;
real_t dc2, ai1, ai2, ar1, ar2, ds2;
int nbd;
real_t dcp, arg, dsp, ar1h, ar2h;
int idp2, ipp2, idij, ipph;
/* Parameter adjustments */
ch_dim1 = *ido;
ch_dim2 = *l1;
ch_offset = 1 + ch_dim1 * (1 + ch_dim2);
ch -= ch_offset;
c1_dim1 = *ido;
c1_dim2 = *l1;
c1_offset = 1 + c1_dim1 * (1 + c1_dim2);
c1 -= c1_offset;
cc_dim1 = *ido;
cc_dim2 = *ip;
cc_offset = 1 + cc_dim1 * (1 + cc_dim2);
cc -= cc_offset;
ch2_dim1 = *idl1;
ch2_offset = 1 + ch2_dim1;
ch2 -= ch2_offset;
c2_dim1 = *idl1;
c2_offset = 1 + c2_dim1;
c2 -= c2_offset;
--wa;
/* Function Body */
arg = tpi / (real_t) (*ip);
dcp = POST(cos)(arg);
dsp = POST(sin)(arg);
ipph = (*ip + 1) / 2;
ipp2 = *ip + 2;
idp2 = *ido + 2;
nbd = (*ido - 1) / 2;
if (*ido == 1) {
goto L119;
}
i__1 = *idl1;
for (ik = 1; ik <= i__1; ++ik) {
ch2[ik + ch2_dim1] = c2[ik + c2_dim1];
/* L101: */
}
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
ch[(k + j * ch_dim2) * ch_dim1 + 1] = c1[(k + j * c1_dim2) * c1_dim1 + 1];
/* L102: */
}
/* L103: */
}
if (nbd > *l1) {
goto L107;
}
is = -(*ido);
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
is += *ido;
idij = is;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
idij += 2;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = wa[idij - 1] * c1[
i__ - 1 + (k + j * c1_dim2) * c1_dim1] + wa[idij] *
c1[i__ + (k + j * c1_dim2) * c1_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = wa[idij - 1] * c1[i__
+ (k + j * c1_dim2) * c1_dim1] - wa[idij] * c1[i__ -
1 + (k + j * c1_dim2) * c1_dim1];
/* L104: */
}
/* L105: */
}
/* L106: */
}
goto L111;
L107:
is = -(*ido);
i__1 = *ip;
for (j = 2; j <= i__1; ++j) {
is += *ido;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
idij = is;
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
idij += 2;
ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] = wa[idij - 1] * c1[
i__ - 1 + (k + j * c1_dim2) * c1_dim1] + wa[idij] *
c1[i__ + (k + j * c1_dim2) * c1_dim1];
ch[i__ + (k + j * ch_dim2) * ch_dim1] = wa[idij - 1] * c1[i__
+ (k + j * c1_dim2) * c1_dim1] - wa[idij] * c1[i__ -
1 + (k + j * c1_dim2) * c1_dim1];
/* L108: */
}
/* L109: */
}
/* L110: */
}
L111:
if (nbd < *l1) {
goto L115;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] + ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1] = ch[i__ + (k + j *ch_dim2) * ch_dim1] - ch[i__ + (k + jc * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = ch[i__ + (k + j * ch_dim2) * ch_dim1] + ch[i__ + (k + jc * ch_dim2) * ch_dim1];
c1[i__ + (k + jc * c1_dim2) * c1_dim1] = ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] - ch[i__ - 1 + (k + j * ch_dim2)* ch_dim1];
/* L112: */
}
/* L113: */
}
/* L114: */
}
goto L121;
L115:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
c1[i__ - 1 + (k + j * c1_dim2) * c1_dim1] = ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] + ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
c1[i__ - 1 + (k + jc * c1_dim2) * c1_dim1] = ch[i__ + (k + j *ch_dim2) * ch_dim1] - ch[i__ + (k + jc * ch_dim2) * ch_dim1];
c1[i__ + (k + j * c1_dim2) * c1_dim1] = ch[i__ + (k + j * ch_dim2) * ch_dim1] + ch[i__ + (k + jc * ch_dim2) * ch_dim1];
c1[i__ + (k + jc * c1_dim2) * c1_dim1] = ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1] - ch[i__ - 1 + (k + j * ch_dim2)* ch_dim1];
/* L116: */
}
/* L117: */
}
/* L118: */
}
goto L121;
L119:
i__1 = *idl1;
for (ik = 1; ik <= i__1; ++ik) {
c2[ik + c2_dim1] = ch2[ik + ch2_dim1];
/* L120: */
}
L121:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
c1[(k + j * c1_dim2) * c1_dim1 + 1] = ch[(k + j * ch_dim2) * ch_dim1 + 1] + ch[(k + jc * ch_dim2) * ch_dim1 + 1];
c1[(k + jc * c1_dim2) * c1_dim1 + 1] = ch[(k + jc * ch_dim2) * ch_dim1 + 1] - ch[(k + j * ch_dim2) * ch_dim1 + 1];
/* L122: */
}
/* L123: */
}
ar1 = POST(1.0);
ai1 = POST(0.0);
i__1 = ipph;
for (l = 2; l <= i__1; ++l) {
lc = ipp2 - l;
ar1h = dcp * ar1 - dsp * ai1;
ai1 = dcp * ai1 + dsp * ar1;
ar1 = ar1h;
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
ch2[ik + l * ch2_dim1] = c2[ik + c2_dim1] + ar1 * c2[ik + (c2_dim1 << 1)];
ch2[ik + lc * ch2_dim1] = ai1 * c2[ik + *ip * c2_dim1];
/* L124: */
}
dc2 = ar1;
ds2 = ai1;
ar2 = ar1;
ai2 = ai1;
i__2 = ipph;
for (j = 3; j <= i__2; ++j) {
jc = ipp2 - j;
ar2h = dc2 * ar2 - ds2 * ai2;
ai2 = dc2 * ai2 + ds2 * ar2;
ar2 = ar2h;
i__3 = *idl1;
for (ik = 1; ik <= i__3; ++ik) {
ch2[ik + l * ch2_dim1] += ar2 * c2[ik + j * c2_dim1];
ch2[ik + lc * ch2_dim1] += ai2 * c2[ik + jc * c2_dim1];
/* L125: */
}
/* L126: */
}
/* L127: */
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
i__2 = *idl1;
for (ik = 1; ik <= i__2; ++ik) {
ch2[ik + ch2_dim1] += c2[ik + j * c2_dim1];
/* L128: */
}
/* L129: */
}
if (*ido < *l1) {
goto L132;
}
i__1 = *l1;
for (k = 1; k <= i__1; ++k) {
i__2 = *ido;
for (i__ = 1; i__ <= i__2; ++i__) {
cc[i__ + (k * cc_dim2 + 1) * cc_dim1] = ch[i__ + (k + ch_dim2) * ch_dim1];
/* L130: */
}
/* L131: */
}
goto L135;
L132:
i__1 = *ido;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
cc[i__ + (k * cc_dim2 + 1) * cc_dim1] = ch[i__ + (k + ch_dim2) * ch_dim1];
/* L133: */
}
/* L134: */
}
L135:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
j2 = j + j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
cc[*ido + (j2 - 2 + k * cc_dim2) * cc_dim1] = ch[(k + j * ch_dim2)* ch_dim1 + 1];
cc[(j2 - 1 + k * cc_dim2) * cc_dim1 + 1] = ch[(k + jc * ch_dim2) *ch_dim1 + 1];
/* L136: */
}
/* L137: */
}
if (*ido == 1) {
return;
}
if (nbd < *l1) {
goto L141;
}
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
j2 = j + j;
i__2 = *l1;
for (k = 1; k <= i__2; ++k) {
i__3 = *ido;
for (i__ = 3; i__ <= i__3; i__ += 2) {
ic = idp2 - i__;
cc[i__ - 1 + (j2 - 1 + k * cc_dim2) * cc_dim1]
= ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] + ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
cc[ic - 1 + (j2 - 2 + k * cc_dim2) * cc_dim1]
= ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] - ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
cc[i__ + (j2 - 1 + k * cc_dim2) * cc_dim1]
= ch[i__ + (k + j *ch_dim2) * ch_dim1] + ch[i__ + (k + jc * ch_dim2) * ch_dim1];
cc[ic + (j2 - 2 + k * cc_dim2) * cc_dim1]
= ch[i__ + (k + jc *ch_dim2) * ch_dim1] - ch[i__ + (k + j * ch_dim2) * ch_dim1];
/* L138: */
}
/* L139: */
}
/* L140: */
}
return;
L141:
i__1 = ipph;
for (j = 2; j <= i__1; ++j) {
jc = ipp2 - j;
j2 = j + j;
i__2 = *ido;
for (i__ = 3; i__ <= i__2; i__ += 2) {
ic = idp2 - i__;
i__3 = *l1;
for (k = 1; k <= i__3; ++k) {
cc[i__ - 1 + (j2 - 1 + k * cc_dim2) * cc_dim1]
= ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] + ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
cc[ic - 1 + (j2 - 2 + k * cc_dim2) * cc_dim1]
= ch[i__ - 1 + (k + j * ch_dim2) * ch_dim1] - ch[i__ - 1 + (k + jc * ch_dim2) * ch_dim1];
cc[i__ + (j2 - 1 + k * cc_dim2) * cc_dim1]
= ch[i__ + (k + j *ch_dim2) * ch_dim1] + ch[i__ + (k + jc * ch_dim2) * ch_dim1];
cc[ic + (j2 - 2 + k * cc_dim2) * cc_dim1]
= ch[i__ + (k + jc *ch_dim2) * ch_dim1] - ch[i__ + (k + j * ch_dim2) * ch_dim1];
/* L142: */
}
/* L143: */
}
/* L144: */
}
return;
} /* radfg_ */
/* Subroutine */ void FUNC(rfftb)(int *n, real_t *r__, real_t *wsave, int *ifac)
{
/* Parameter adjustments */
--ifac;
--wsave;
--r__;
/* Function Body */
if (*n == 1) {
return;
}
s_rfftb1(n, &r__[1], &wsave[1], &wsave[*n + 1], &ifac[1]);
return;
} /* rfftb_ */
/* Subroutine */ static void s_rfftb1(int *n, real_t *c__, real_t *ch,
real_t *wa, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k1, l1, l2, na, nf, ip, iw, ix2, ix3, ix4, ido, idl1;
/* Parameter adjustments */
--ifac;
--wa;
--ch;
--c__;
/* Function Body */
nf = ifac[2];
na = 0;
l1 = 1;
iw = 1;
i__1 = nf;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
l2 = ip * l1;
ido = *n / l2;
idl1 = ido * l1;
if (ip != 4) {
goto L103;
}
ix2 = iw + ido;
ix3 = ix2 + ido;
if (na != 0) {
goto L101;
}
s_radb4(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3]);
goto L102;
L101:
s_radb4(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3]);
L102:
na = 1 - na;
goto L115;
L103:
if (ip != 2) {
goto L106;
}
if (na != 0) {
goto L104;
}
s_radb2(&ido, &l1, &c__[1], &ch[1], &wa[iw]);
goto L105;
L104:
s_radb2(&ido, &l1, &ch[1], &c__[1], &wa[iw]);
L105:
na = 1 - na;
goto L115;
L106:
if (ip != 3) {
goto L109;
}
ix2 = iw + ido;
if (na != 0) {
goto L107;
}
s_radb3(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2]);
goto L108;
L107:
s_radb3(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2]);
L108:
na = 1 - na;
goto L115;
L109:
if (ip != 5) {
goto L112;
}
ix2 = iw + ido;
ix3 = ix2 + ido;
ix4 = ix3 + ido;
if (na != 0) {
goto L110;
}
s_radb5(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
goto L111;
L110:
s_radb5(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
L111:
na = 1 - na;
goto L115;
L112:
if (na != 0) {
goto L113;
}
s_radbg(&ido, &ip, &l1, &idl1, &c__[1], &c__[1], &c__[1], &ch[1], &ch[1], &wa[iw]);
goto L114;
L113:
s_radbg(&ido, &ip, &l1, &idl1, &ch[1], &ch[1], &ch[1], &c__[1], &c__[1], &wa[iw]);
L114:
if (ido == 1) {
na = 1 - na;
}
L115:
l1 = l2;
iw += (ip - 1) * ido;
/* L116: */
}
if (na == 0) {
return;
}
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
c__[i__] = ch[i__];
/* L117: */
}
return;
} /* rfftb1_ */
/* Subroutine */ void FUNC(rfftf)(int *n, real_t *r__, real_t *wsave,
int *ifac)
{
/* Parameter adjustments */
--ifac;
--wsave;
--r__;
/* Function Body */
if (*n == 1) {
return;
}
s_rfftf1(n, &r__[1], &wsave[1], &wsave[*n + 1], &ifac[1]);
return;
} /* rfftf_ */
/* Subroutine */ static void s_rfftf1(int *n, real_t *c__, real_t *ch,
real_t *wa, int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int i__, k1, l1, l2, na, kh, nf, ip, iw, ix2, ix3, ix4, ido, idl1;
/* Parameter adjustments */
--ifac;
--wa;
--ch;
--c__;
/* Function Body */
nf = ifac[2];
na = 1;
l2 = *n;
iw = *n;
i__1 = nf;
for (k1 = 1; k1 <= i__1; ++k1) {
kh = nf - k1;
ip = ifac[kh + 3];
l1 = l2 / ip;
ido = *n / l2;
idl1 = ido * l1;
iw -= (ip - 1) * ido;
na = 1 - na;
if (ip != 4) {
goto L102;
}
ix2 = iw + ido;
ix3 = ix2 + ido;
if (na != 0) {
goto L101;
}
s_radf4(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3]);
goto L110;
L101:
s_radf4(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3]);
goto L110;
L102:
if (ip != 2) {
goto L104;
}
if (na != 0) {
goto L103;
}
s_radf2(&ido, &l1, &c__[1], &ch[1], &wa[iw]);
goto L110;
L103:
s_radf2(&ido, &l1, &ch[1], &c__[1], &wa[iw]);
goto L110;
L104:
if (ip != 3) {
goto L106;
}
ix2 = iw + ido;
if (na != 0) {
goto L105;
}
s_radf3(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2]);
goto L110;
L105:
s_radf3(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2]);
goto L110;
L106:
if (ip != 5) {
goto L108;
}
ix2 = iw + ido;
ix3 = ix2 + ido;
ix4 = ix3 + ido;
if (na != 0) {
goto L107;
}
s_radf5(&ido, &l1, &c__[1], &ch[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
goto L110;
L107:
s_radf5(&ido, &l1, &ch[1], &c__[1], &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]);
goto L110;
L108:
if (ido == 1) {
na = 1 - na;
}
if (na != 0) {
goto L109;
}
s_radfg(&ido, &ip, &l1, &idl1, &c__[1], &c__[1], &c__[1], &ch[1], &ch[1], &wa[iw]);
na = 1;
goto L110;
L109:
s_radfg(&ido, &ip, &l1, &idl1, &ch[1], &ch[1], &ch[1], &c__[1], &c__[1], &wa[iw]);
na = 0;
L110:
l2 = l1;
/* L111: */
}
if (na == 1) {
return;
}
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
c__[i__] = ch[i__];
/* L112: */
}
return;
} /* rfftf1_ */
/* Subroutine */ void FUNC(rffti)(int *n, real_t *wsave, int *ifac)
{
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
if (*n == 1) {
return;
}
s_rffti1(n, &wsave[*n + 1], &ifac[1]);
return;
} /* rffti_ */
/* Subroutine */ static void s_rffti1(int *n, real_t *wa, int *ifac)
{
/* Initialized data */
static int ntryh[4] = { 4,2,3,5 };
/* System generated locals */
int i__1, i__2, i__3;
/* Local variables */
int i__, j, k1, l1, l2, ib;
real_t fi;
int ld, ii, nf, ip, nl, is, nq, nr;
real_t arg;
int ido, ipm;
real_t tpi;
int nfm1;
real_t argh;
int ntry=0;
real_t argld;
/* Parameter adjustments */
--ifac;
--wa;
/* Function Body */
nl = *n;
nf = 0;
j = 0;
L101:
++j;
if (j - 4 <= 0) {
goto L102;
} else {
goto L103;
}
L102:
ntry = ntryh[j - 1];
goto L104;
L103:
ntry += 2;
L104:
nq = nl / ntry;
nr = nl - ntry * nq;
if (nr != 0) {
goto L101;
} else {
goto L105;
}
L105:
++nf;
ifac[nf + 2] = ntry;
nl = nq;
if (ntry != 2) {
goto L107;
}
if (nf == 1) {
goto L107;
}
i__1 = nf;
for (i__ = 2; i__ <= i__1; ++i__) {
ib = nf - i__ + 2;
ifac[ib + 2] = ifac[ib + 1];
/* L106: */
}
ifac[3] = 2;
L107:
if (nl != 1) {
goto L104;
}
ifac[1] = *n;
ifac[2] = nf;
tpi = POST(6.283185307179586476925286766559005768394338798750211619498891846);
argh = tpi / (real_t) (*n);
is = 0;
nfm1 = nf - 1;
l1 = 1;
if (nfm1 == 0) {
return;
}
i__1 = nfm1;
for (k1 = 1; k1 <= i__1; ++k1) {
ip = ifac[k1 + 2];
ld = 0;
l2 = l1 * ip;
ido = *n / l2;
ipm = ip - 1;
i__2 = ipm;
for (j = 1; j <= i__2; ++j) {
ld += l1;
i__ = is;
argld = (real_t) ld * argh;
fi = POST(0.0);
i__3 = ido;
for (ii = 3; ii <= i__3; ii += 2) {
i__ += 2;
fi += POST(1.0);
arg = fi * argld;
wa[i__ - 1] = POST(cos)(arg);
wa[i__] = POST(sin)(arg);
/* L108: */
}
is += ido;
/* L109: */
}
l1 = l2;
/* L110: */
}
return;
} /* s_rffti1 */
/* Subroutine */ void FUNC(sinqb)(int *n, real_t *x, real_t *wsave,
int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int k, kc, ns2;
real_t xhold;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
if (*n > 1) {
goto L101;
}
x[1] *= POST(4.0);
return;
L101:
ns2 = *n / 2;
i__1 = *n;
for (k = 2; k <= i__1; k += 2) {
x[k] = -x[k];
/* L102: */
}
FUNC(cosqb)(n, &x[1], &wsave[1], &ifac[1]);
i__1 = ns2;
for (k = 1; k <= i__1; ++k) {
kc = *n - k;
xhold = x[k];
x[k] = x[kc + 1];
x[kc + 1] = xhold;
/* L103: */
}
return;
} /* sinqb_ */
/* Subroutine */ void FUNC(sinqf)(int *n, real_t *x, real_t *wsave,
int *ifac)
{
/* System generated locals */
int i__1;
/* Local variables */
int k, kc, ns2;
real_t xhold;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
if (*n == 1) {
return;
}
ns2 = *n / 2;
i__1 = ns2;
for (k = 1; k <= i__1; ++k) {
kc = *n - k;
xhold = x[k];
x[k] = x[kc + 1];
x[kc + 1] = xhold;
/* L101: */
}
FUNC(cosqf)(n, &x[1], &wsave[1], &ifac[1]);
i__1 = *n;
for (k = 2; k <= i__1; k += 2) {
x[k] = -x[k];
/* L102: */
}
return;
} /* sinqf_ */
/* Subroutine */ void FUNC(sinqi)(int *n, real_t *wsave, int *ifac)
{
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
FUNC(cosqi)(n, &wsave[1], &ifac[1]);
return;
} /* sinqi_ */
/* Subroutine */ void FUNC(sint)(int *n, real_t *x, real_t *wsave,
int *ifac)
{
int np1, iw1, iw2;
/* Parameter adjustments */
--ifac;
--wsave;
--x;
/* Function Body */
np1 = *n + 1;
iw1 = *n / 2 + 1;
iw2 = iw1 + np1;
s_sint1(n, &x[1], &wsave[1], &wsave[iw1], &wsave[iw2], &ifac[1]);
return;
} /* sint_ */
/* Subroutine */ static void s_sint1(int *n, real_t *war, real_t *was,
real_t *xh, real_t *x, int *ifac)
{
/* Initialized data */
static real_t sqrt3 = POST(1.732050807568877293527446341505872366942805253803806280558069795);
/* System generated locals */
int i__1;
/* Local variables */
int i__, k;
real_t t1, t2;
int kc, np1, ns2, modn;
real_t xhold;
/* Parameter adjustments */
--ifac;
--x;
--xh;
--was;
--war;
/* Function Body */
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
xh[i__] = war[i__];
war[i__] = x[i__];
/* L100: */
}
if ((i__1 = *n - 2) < 0) {
goto L101;
} else if (i__1 == 0) {
goto L102;
} else {
goto L103;
}
L101:
xh[1] += xh[1];
goto L106;
L102:
xhold = sqrt3 * (xh[1] + xh[2]);
xh[2] = sqrt3 * (xh[1] - xh[2]);
xh[1] = xhold;
goto L106;
L103:
np1 = *n + 1;
ns2 = *n / 2;
x[1] = POST(0.0);
i__1 = ns2;
for (k = 1; k <= i__1; ++k) {
kc = np1 - k;
t1 = xh[k] - xh[kc];
t2 = was[k] * (xh[k] + xh[kc]);
x[k + 1] = t1 + t2;
x[kc + 1] = t2 - t1;
/* L104: */
}
modn = *n % 2;
if (modn != 0) {
x[ns2 + 2] = xh[ns2 + 1] * POST(4.0);
}
s_rfftf1(&np1, &x[1], &xh[1], &war[1], &ifac[1]);
xh[1] = x[1] * POST(0.5);
i__1 = *n;
for (i__ = 3; i__ <= i__1; i__ += 2) {
xh[i__ - 1] = -x[i__];
xh[i__] = xh[i__ - 2] + x[i__ - 1];
/* L105: */
}
if (modn != 0) {
goto L106;
}
xh[*n] = -x[*n + 1];
L106:
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
x[i__] = war[i__];
war[i__] = xh[i__];
/* L107: */
}
return;
} /* sint1_ */
/* Subroutine */ void FUNC(sinti)(int *n, real_t *wsave, int *ifac)
{
/* Initialized data */
static real_t pi = POST(3.141592653589793238462643383279502884197169399375158209749445923);
/* System generated locals */
int i__1;
/* Local variables */
int k;
real_t dt;
int np1, ns2;
/* Parameter adjustments */
--ifac;
--wsave;
/* Function Body */
if (*n <= 1) {
return;
}
ns2 = *n / 2;
np1 = *n + 1;
dt = pi / (real_t) np1;
i__1 = ns2;
for (k = 1; k <= i__1; ++k) {
wsave[k] = POST(sin)(k * dt) * POST(2.0);
/* L101: */
}
FUNC(rffti)(&np1, &wsave[ns2 + 1], &ifac[1]);
return;
} /* sinti_ */
| 27.37215 | 174 | 0.500004 | [
"transform"
] |
c3fa00e09ab2af5bff147f6899eef5474d6cd652 | 3,135 | cpp | C++ | bench/bench-opc.cpp | oori/OrganizedPointFilters | 9030badec776e4bb4d98a397767630efb9dc078f | [
"MIT"
] | 2 | 2021-01-30T09:45:05.000Z | 2021-04-13T09:21:19.000Z | bench/bench-opc.cpp | oori/OrganizedPointFilters | 9030badec776e4bb4d98a397767630efb9dc078f | [
"MIT"
] | 3 | 2020-12-13T23:09:33.000Z | 2022-02-04T02:22:40.000Z | bench/bench-opc.cpp | oori/OrganizedPointFilters | 9030badec776e4bb4d98a397767630efb9dc078f | [
"MIT"
] | 3 | 2021-02-20T03:55:32.000Z | 2021-09-17T08:25:23.000Z | #include <iostream>
#include <sstream>
#include <vector>
#include <benchmark/benchmark.h>
#include "OrganizedPointFilters/Filter/Laplacian.hpp"
#include "OrganizedPointFilters/Filter/Normal.hpp"
#include "OrganizedPointFilters/Filter/Bilateral.hpp"
#include "OrganizedPointFilters/Types.hpp"
using namespace OrganizedPointFilters;
void InitRandom(Eigen::Ref<RowMatrixXVec3f> a)
{
for (auto i = 0; i < a.rows(); ++i)
{
for (auto j = 0; j < a.cols(); ++j)
{
a(i,j) = Eigen::Vector3f::Random();
}
}
}
static void BM_ComputeNormals(benchmark::State& st)
{
RowMatrixXVec3f a(st.range(0), st.range(0));
InitRandom(a);
// std::cout << a.rows() << std::endl;
for (auto _ : st)
{
auto result = Filter::ComputeNormals(a);
benchmark::DoNotOptimize(result.data());
}
}
static void BM_ComputeCentroid(benchmark::State& st)
{
RowMatrixXVec3f a(st.range(0), st.range(0));
InitRandom(a);
// std::cout << a.rows() << std::endl;
for (auto _ : st)
{
auto result = Filter::ComputeCentroids(a);
benchmark::DoNotOptimize(result.data());
}
}
static void BM_ComputeNormalsAndCentroids(benchmark::State& st)
{
RowMatrixXVec3f a(st.range(0), st.range(0));
InitRandom(a);
// std::cout << a.rows() << std::endl;
for (auto _ : st)
{
OrganizedTriangleMatrix normals;
OrganizedTriangleMatrix centroid;
std::tie(normals, centroid) = Filter::ComputeNormalsAndCentroids(a);
benchmark::DoNotOptimize(normals.data());
}
}
template<int kernel_size = 3>
static void BM_LaplacianT(benchmark::State& st)
{
RowMatrixXVec3f a(st.range(0), st.range(0));
InitRandom(a);
// std::cout << a.rows() << std::endl;
int iterations = 5;
float lambda = 1.0;
for (auto _ : st)
{
auto result = Filter::LaplacianT<kernel_size>(a, lambda, iterations, 0.25);
benchmark::DoNotOptimize(result.data());
}
}
// template<int kernel_size = 3>
static void BM_BilateralNormalFiltering(benchmark::State& st)
{
RowMatrixXVec3f a(st.range(0), st.range(0));
InitRandom(a);
// std::cout << a.rows() << std::endl;
int iterations = 5;
for (auto _ : st)
{
auto result = Filter::BilateralFilterNormals<3>(a, iterations);
benchmark::DoNotOptimize(result.data());
}
}
// BENCHMARK(BM_Laplacian)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_LaplacianT, 3)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_LaplacianT, 5)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_BilateralNormalFiltering)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_ComputeNormals)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_ComputeCentroid)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_ComputeNormalsAndCentroids)->UseRealTime()->DenseRange(250, 500, 250)->Unit(benchmark::kMillisecond);
| 31.666667 | 114 | 0.666986 | [
"vector"
] |
c3fe8a361cf5130b461272fa079bd41968b20180 | 3,505 | cpp | C++ | src/quantization.cpp | krishnateja95/AMDMIGraphX | dcbc9255328d9b1f4b303bb8299a0e24bf112206 | [
"MIT"
] | null | null | null | src/quantization.cpp | krishnateja95/AMDMIGraphX | dcbc9255328d9b1f4b303bb8299a0e24bf112206 | [
"MIT"
] | null | null | null | src/quantization.cpp | krishnateja95/AMDMIGraphX | dcbc9255328d9b1f4b303bb8299a0e24bf112206 | [
"MIT"
] | null | null | null | #include <migraphx/quantization.hpp>
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/iterator_for.hpp>
#include <migraphx/op/convert.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/ranges.hpp>
#include <utility>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
instruction_ref insert_fp16(program& prog,
instruction_ref& ins,
shape::type_t type,
std::unordered_map<instruction_ref, instruction_ref>& map_fp16)
{
if(map_fp16.count(ins) > 0)
{
return map_fp16[ins];
}
assert(ins->get_shape().type() == shape::float_type ||
ins->get_shape().type() == shape::double_type);
instruction_ref ins_fp16{};
ins_fp16 = prog.insert_instruction(std::next(ins), op::convert{type}, ins);
map_fp16[ins] = ins_fp16;
return ins_fp16;
}
void quantize(program& prog, const std::vector<std::string>& ins_names)
{
std::unordered_map<instruction_ref, instruction_ref> map_fp16;
for(auto ins : iterator_for(prog))
{
// all indicates every instruction is converted
if((not contains(ins_names, "all")) and (not contains(ins_names, ins->name())))
{
continue;
}
shape::type_t orig_type = ins->get_shape().type();
// process all inputs, if input is a fp32 or fp64, convert it
// to a fp16 by adding a convert operator.
auto inputs = ins->inputs();
std::vector<instruction_ref> converted_inputs;
for(auto input : inputs)
{
auto s = input->get_shape();
if(s.type() == shape::float_type || s.type() == shape::double_type)
{
// if the input is a convert operator, uses its input
// as its current input
instruction_ref input_fp16{};
if(input->name() == "convert")
{
input_fp16 = input->inputs().front();
}
else
{
input_fp16 = insert_fp16(prog, input, shape::half_type, map_fp16);
}
converted_inputs.push_back(input_fp16);
}
else
{
converted_inputs.push_back(input);
}
}
// no change for the input, go to the next instruction
if(inputs == converted_inputs)
{
continue;
}
auto op = ins->get_operator();
auto ins_shape = compute_shape(op, converted_inputs);
if(ins_shape.type() != orig_type)
{
// insert another convert instruction to convert it back
if(ins == std::prev(prog.end()))
{
prog.add_instruction(op::convert{orig_type}, ins);
}
else
{
// check the dead code case to avoid assert
bool output_empty = ins->outputs().empty();
auto ins_orig_type =
prog.insert_instruction(std::next(ins), op::convert{orig_type}, ins);
if(!output_empty)
{
prog.replace_instruction(ins, ins_orig_type);
}
}
}
prog.replace_instruction(ins, op, converted_inputs);
}
}
void quantize(program& prog) { quantize(prog, {"all"}); }
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
| 32.453704 | 91 | 0.548359 | [
"shape",
"vector"
] |
7f0dc07ccf5cacab2025c1ee2121826b83bed070 | 14,909 | cpp | C++ | ntt.cpp | itzmeanjan/ff-p256-gpu | acbedab1dd653f7270ac917755286c565d2a8927 | [
"CC0-1.0"
] | 1 | 2022-03-03T08:47:36.000Z | 2022-03-03T08:47:36.000Z | ntt.cpp | itzmeanjan/ff-p256-gpu | acbedab1dd653f7270ac917755286c565d2a8927 | [
"CC0-1.0"
] | null | null | null | ntt.cpp | itzmeanjan/ff-p256-gpu | acbedab1dd653f7270ac917755286c565d2a8927 | [
"CC0-1.0"
] | null | null | null | #include <ntt.hpp>
ff_p254_t get_root_of_unity(uint64_t n) {
uint64_t pow_ = 1ul << (28 - n);
ff_p254_t pow(pow_);
return static_cast<ff_p254_t>(
cbn::mod_exp(TWO_ADIC_ROOT_OF_UNITY.data, pow.data, mod_p254_bn));
}
sycl::event matrix_transposed_initialise(
sycl::queue &q, ff_p254_t *vec_src, ff_p254_t *vec_dst, const uint64_t rows,
const uint64_t cols, const uint64_t width, const uint64_t wg_size,
std::vector<sycl::event> evts) {
return q.submit([&](sycl::handler &h) {
h.depends_on(evts);
h.parallel_for<class kernelMatrixTransposedInitialise>(
sycl::nd_range<2>{sycl::range<2>{rows, cols},
sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(32)]] {
sycl::sub_group sg = it.get_sub_group();
const size_t r = it.get_global_id(0);
const size_t c = it.get_global_id(1);
const uint64_t width_ = sycl::group_broadcast(sg, width);
*(vec_dst + r * width_ + c) = *(vec_src + c * width_ + r);
});
});
}
sycl::event matrix_transpose(sycl::queue &q, ff_p254_t *data,
const uint64_t dim,
std::vector<sycl::event> evts) {
constexpr size_t TILE_DIM = 1 << 4;
constexpr size_t BLOCK_ROWS = 1 << 3;
assert(TILE_DIM >= BLOCK_ROWS);
return q.submit([&](sycl::handler &h) {
sycl::accessor<ff_p254_t, 2, sycl::access_mode::read_write,
sycl::target::local>
tile_s{sycl::range<2>{TILE_DIM, TILE_DIM + 1}, h};
sycl::accessor<ff_p254_t, 2, sycl::access_mode::read_write,
sycl::target::local>
tile_d{sycl::range<2>{TILE_DIM, TILE_DIM + 1}, h};
h.depends_on(evts);
h.parallel_for<class kernelMatrixTransposition>(
sycl::nd_range<2>{sycl::range<2>{dim / (TILE_DIM / BLOCK_ROWS), dim},
sycl::range<2>{BLOCK_ROWS, TILE_DIM}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
sycl::group<2> grp = it.get_group();
const size_t grp_id_x = it.get_group().get_id(1);
const size_t grp_id_y = it.get_group().get_id(0);
const size_t loc_id_x = it.get_local_id(1);
const size_t loc_id_y = it.get_local_id(0);
const size_t grp_width_x = it.get_group().get_group_range(1);
// @note x denotes index along x-axis
// while y denotes index along y-axis
//
// so in usual (row, col) indexing of 2D array
// row = y, col = x
const size_t x = grp_id_x * TILE_DIM + loc_id_x;
const size_t y = grp_id_y * TILE_DIM + loc_id_y;
const size_t width = grp_width_x * TILE_DIM;
// non-diagonal cell blocks
if (grp_id_y > grp_id_x) {
size_t dx = grp_id_y * TILE_DIM + loc_id_x;
size_t dy = grp_id_x * TILE_DIM + loc_id_y;
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
tile_s[loc_id_y + j][loc_id_x] = *(data + (y + j) * width + x);
}
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
tile_d[loc_id_y + j][loc_id_x] = *(data + (dy + j) * width + dx);
}
sycl::group_barrier(grp, sycl::memory_scope::work_group);
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
*(data + (dy + j) * width + dx) = tile_s[loc_id_x][loc_id_y + j];
}
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
*(data + (y + j) * width + x) = tile_d[loc_id_x][loc_id_y + j];
}
return;
}
// diagonal cell blocks
if (grp_id_y == grp_id_x) {
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
tile_s[loc_id_y + j][loc_id_x] = *(data + (y + j) * width + x);
}
sycl::group_barrier(grp, sycl::memory_scope::work_group);
for (size_t j = 0; j < TILE_DIM; j += BLOCK_ROWS) {
*(data + (y + j) * width + x) = tile_s[loc_id_x][loc_id_y + j];
}
}
});
});
}
sycl::event twiddle_multiplication(sycl::queue &q, ff_p254_t *vec,
ff_p254_t *omega, const uint64_t rows,
const uint64_t cols, const uint64_t width,
const uint64_t wg_size,
std::vector<sycl::event> evts) {
assert(cols == width || 2 * cols == width);
return q.submit([&](sycl::handler &h) {
sycl::accessor<ff_p254_t, 1, sycl::access_mode::read_write,
sycl::target::local>
lds{sycl::range<1>{1}, h};
h.depends_on(evts);
h.parallel_for<class kernelTwiddleMultiplication>(
sycl::nd_range<2>{sycl::range<2>{rows, cols},
sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
const uint64_t r = it.get_global_id(0);
const uint64_t c = it.get_global_id(1);
sycl::group<2> grp = it.get_group();
// only work-group leader helps in caching
// twiddle in local memory
if (it.get_local_linear_id() == 0) {
lds[0] = *omega;
}
// until all work-items of this work-group
// arrives here, wait !
sycl::group_barrier(grp);
// after that all work-items of work-group reads from cached twiddle
// from local memory
*(vec + r * width + c) *= static_cast<ff_p254_t>(
cbn::mod_exp(lds[0].data, ff_p254_t(r * c).data, mod_p254_bn));
});
});
}
sycl::event row_wise_transform(sycl::queue &q, ff_p254_t *vec, ff_p254_t *omega,
const uint64_t rows, const uint64_t cols,
const uint64_t width, const uint64_t wg_size,
std::vector<sycl::event> evts) {
uint64_t log_2_dim = (uint64_t)sycl::log2((float)cols);
std::vector<sycl::event> _evts;
_evts.reserve(log_2_dim);
// if you change this number, make sure
// you also change `[[intel::reqd_sub_group_size(Z)]]`
// below, such that SUBGROUP_SIZE == Z
constexpr uint64_t SUBGROUP_SIZE = 1ul << 5;
assert((SUBGROUP_SIZE & (SUBGROUP_SIZE - 1ul)) == 0ul &&
(SUBGROUP_SIZE <= (1ul << 6)));
assert((wg_size % SUBGROUP_SIZE) == 0);
for (int64_t i = log_2_dim - 1ul; i >= 0; i--) {
sycl::event evt = q.submit([&](sycl::handler &h) {
if (i == log_2_dim - 1ul) {
// only first submission depends on
// previous kernel executions, whose events
// are passed as argument to this function
h.depends_on(evts);
} else {
// all next kernel submissions
// depend on just previous kernel submission
// from body of this loop
h.depends_on(_evts.at(log_2_dim - (i + 2)));
}
h.parallel_for<class kernelCooleyTukeyRowWiseFFT>(
sycl::nd_range<2>{sycl::range<2>{rows, cols},
sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
const uint64_t r = it.get_global_id(0);
const uint64_t k = it.get_global_id(1);
const uint64_t p = 1ul << i;
const uint64_t q = cols / p;
uint64_t k_rev = bit_rev(k, log_2_dim) % q;
ff_p254_t ω = static_cast<ff_p254_t>(cbn::mod_exp(
(*omega).data, ff_p254_t(p * k_rev).data, mod_p254_bn));
if (k < (k ^ p)) {
ff_p254_t tmp_k = *(vec + r * width + k);
ff_p254_t tmp_k_p = *(vec + r * width + (k ^ p));
ff_p254_t tmp_k_p_ω = tmp_k_p * ω;
*(vec + r * width + k) = tmp_k + tmp_k_p_ω;
*(vec + r * width + (k ^ p)) = tmp_k - tmp_k_p_ω;
}
});
});
_evts.push_back(evt);
}
return q.submit([&](sycl::handler &h) {
// final reordering kernel depends on very
// last kernel submission performed in above loop
h.depends_on(_evts.at(log_2_dim - 1));
h.parallel_for<class kernelCooleyTukeyRowWiseFFTFinalReorder>(
sycl::nd_range<2>{sycl::range<2>{rows, cols},
sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
const uint64_t r = it.get_global_id(0);
const uint64_t k = it.get_global_id(1);
const uint64_t k_perm = permute_index(k, cols);
if (k_perm > k) {
ff_p254_t a = *(vec + r * width + k);
ff_p254_t b = *(vec + r * width + k_perm);
*(vec + r * width + k) = b;
*(vec + r * width + k_perm) = a;
}
});
});
}
uint64_t bit_rev(uint64_t v, uint64_t max_bit_width) {
uint64_t v_rev = 0ul;
for (uint64_t i = 0; i < max_bit_width; i++) {
v_rev += ((v >> i) & 0b1) * (1ul << (max_bit_width - 1ul - i));
}
return v_rev;
}
uint64_t rev_all_bits(uint64_t n) {
uint64_t rev = 0;
for (uint8_t i = 0; i < 64; i++) {
if ((1ul << i) & n) {
rev |= (1ul << (63 - i));
}
}
return rev;
}
uint64_t permute_index(uint64_t idx, uint64_t size) {
if (size == 1ul) {
return 0ul;
}
uint64_t bits = sycl::ext::intel::ctz(size);
return rev_all_bits(idx) >> (64ul - bits);
}
sycl::event six_step_fft(sycl::queue &q, ff_p254_t *vec, ff_p254_t *vec_scratch,
ff_p254_t *omega_dim, ff_p254_t *omega_n1,
ff_p254_t *omega_n2, const uint64_t dim,
const uint64_t wg_size,
std::vector<sycl::event> evts) {
assert((dim & (dim - 1ul)) == 0);
uint64_t log_2_dim = (uint64_t)sycl::log2((float)dim);
uint64_t n1 = 1 << (log_2_dim / 2);
uint64_t n2 = dim / n1;
uint64_t n = sycl::max(n1, n2);
uint64_t log_2_n1 = (uint64_t)sycl::log2((float)n1);
uint64_t log_2_n2 = (uint64_t)sycl::log2((float)n2);
assert(n1 == n2 || n2 == 2 * n1);
assert(log_2_dim > 0 && log_2_dim <= TWO_ADICITY_);
// compute i-th root of unity, where i = {dim, n1, n2}
sycl::event evt_0 = q.submit([&](sycl::handler &h) {
h.depends_on(evts);
h.single_task([=]() {
*omega_dim = get_root_of_unity(log_2_dim);
*omega_n1 = get_root_of_unity(log_2_n1);
*omega_n2 = get_root_of_unity(log_2_n2);
});
});
// Step 1: Transpose Matrix
sycl::event evt_1 = matrix_transposed_initialise(q, vec, vec_scratch, n2, n1,
n, wg_size, evts);
// Step 2: n2-many parallel n1-point Cooley-Tukey style NTT
sycl::event evt_2 = row_wise_transform(q, vec_scratch, omega_n1, n2, n1, n,
wg_size, {evt_0, evt_1});
// Step 3: Multiply by twiddle factors
sycl::event evt_3 = twiddle_multiplication(q, vec_scratch, omega_dim, n2, n1,
n, wg_size, {evt_2});
// Step 4: Transpose Matrix
sycl::event evt_4 = matrix_transpose(q, vec_scratch, n, {evt_3});
// Step 5: n1-many parallel n2-point Cooley-Tukey NTT
sycl::event evt_5 =
row_wise_transform(q, vec_scratch, omega_n2, n1, n2, n, wg_size, {evt_4});
// Step 6: Transpose Matrix
sycl::event evt_6 = matrix_transpose(q, vec_scratch, n, {evt_5});
// copy result back to source vector
return q.submit([&](sycl::handler &h) {
h.depends_on(evt_6);
h.parallel_for<class kernelFFTCopyBack>(
sycl::nd_range<2>{sycl::range<2>{n2, n1}, sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
const size_t r = it.get_global_id(0);
const size_t c = it.get_global_id(1);
*(vec + it.get_global_linear_id()) = *(vec_scratch + r * n + c);
});
});
}
sycl::event six_step_ifft(sycl::queue &q, ff_p254_t *vec,
ff_p254_t *vec_scratch, ff_p254_t *omega_dim_inv,
ff_p254_t *omega_n1_inv, ff_p254_t *omega_n2_inv,
ff_p254_t *omega_domain_size_inv, const uint64_t dim,
const uint64_t wg_size,
std::vector<sycl::event> evts) {
assert((dim & (dim - 1ul)) == 0);
uint64_t log_2_dim = (uint64_t)sycl::log2((float)dim);
uint64_t n1 = 1 << (log_2_dim / 2);
uint64_t n2 = dim / n1;
uint64_t n = sycl::max(n1, n2);
uint64_t log_2_n1 = (uint64_t)sycl::log2((float)n1);
uint64_t log_2_n2 = (uint64_t)sycl::log2((float)n2);
assert(n1 == n2 || n2 == 2 * n1);
assert(log_2_dim > 0 && log_2_dim <= TWO_ADICITY_);
// compute inverse of i-th root of unity, where i = {dim, n1, n2}
sycl::event evt_0 = q.submit([&](sycl::handler &h) {
h.depends_on(evts);
h.single_task([=]() {
*omega_dim_inv = static_cast<ff_p254_t>(
cbn::mod_inv(get_root_of_unity(log_2_dim).data, mod_p254_bn));
*omega_n1_inv = static_cast<ff_p254_t>(
cbn::mod_inv(get_root_of_unity(log_2_n1).data, mod_p254_bn));
*omega_n2_inv = static_cast<ff_p254_t>(
cbn::mod_inv(get_root_of_unity(log_2_n2).data, mod_p254_bn));
*omega_domain_size_inv = static_cast<ff_p254_t>(
cbn::mod_inv(ff_p254_t(dim).data, mod_p254_bn));
});
});
// Step 1: Transpose Matrix
sycl::event evt_1 = matrix_transposed_initialise(q, vec, vec_scratch, n2, n1,
n, wg_size, evts);
// Step 2: n2-many parallel n1-point Cooley-Tukey style IFFT
sycl::event evt_2 = row_wise_transform(q, vec_scratch, omega_n1_inv, n2, n1,
n, wg_size, {evt_0, evt_1});
// Step 3: Multiply by twiddle factors
sycl::event evt_3 = twiddle_multiplication(q, vec_scratch, omega_dim_inv, n2,
n1, n, wg_size, {evt_2});
// Step 4: Transpose Matrix
sycl::event evt_4 = matrix_transpose(q, vec_scratch, n, {evt_3});
// Step 5: n1-many parallel n2-point Cooley-Tukey IFFT
sycl::event evt_5 = row_wise_transform(q, vec_scratch, omega_n2_inv, n1, n2,
n, wg_size, {evt_4});
// Step 6: Transpose Matrix
sycl::event evt_6 = matrix_transpose(q, vec_scratch, n, {evt_5});
// copy result back to source vector, while
// also multiplying by inverse of domain size
return q.submit([&](sycl::handler &h) {
h.depends_on({evt_6});
h.parallel_for<class kernelIFFTCopyBack>(
sycl::nd_range<2>{sycl::range<2>{n2, n1}, sycl::range<2>{1, wg_size}},
[=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(16)]] {
const size_t r = it.get_global_id(0);
const size_t c = it.get_global_id(1);
*(vec + it.get_global_linear_id()) =
*omega_domain_size_inv * *(vec_scratch + r * n + c);
});
});
}
| 37.459799 | 80 | 0.562278 | [
"vector"
] |
7f0f8a5219783affdec95adae44ebe60837c7dc2 | 6,731 | cc | C++ | camera/features/auto_framing/face_tracker.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/features/auto_framing/face_tracker.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/features/auto_framing/face_tracker.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2021 The Chromium OS 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 "features/auto_framing/face_tracker.h"
#include <algorithm>
#include "common/reloadable_config_file.h"
#include "cros-camera/common.h"
namespace cros {
namespace {
constexpr char kFacePhaseInThresholdMs[] = "face_phase_in_threshold_ms";
constexpr char kFacePhaseOutThresholdMs[] = "face_phase_out_threshold_ms";
constexpr char kPanAngleRange[] = "pan_angle_range";
int ElapsedTimeMs(base::TimeTicks ticks) {
return (base::TimeTicks::Now() - ticks).InMilliseconds();
}
} // namespace
FaceTracker::FaceTracker(const Options& options) : options_(options) {}
void FaceTracker::OnNewFaceData(
const std::vector<human_sensing::CrosFace>& faces) {
// Given |f1| and |f2| from two different (usually consecutive) frames, treat
// the two rectangles as the same face if their position delta is less than
// kFaceDistanceThresholdSquare.
//
// This is just a heuristic and is not accurate in some corner cases, but we
// don't have face tracking.
auto is_same_face = [&](const Rect<float>& f1,
const Rect<float>& f2) -> bool {
const float center_f1_x = f1.left + f1.width / 2;
const float center_f1_y = f1.top + f1.height / 2;
const float center_f2_x = f2.left + f2.width / 2;
const float center_f2_y = f2.top + f2.height / 2;
constexpr float kFaceDistanceThresholdSquare = 0.1 * 0.1;
const float dist_square = std::pow(center_f1_x - center_f2_x, 2.0f) +
std::pow(center_f1_y - center_f2_y, 2.0f);
return dist_square < kFaceDistanceThresholdSquare;
};
for (const auto& f : faces) {
FaceState s = {
.normalized_bounding_box = Rect<float>(
f.bounding_box.x1 / options_.active_array_dimension.width,
f.bounding_box.y1 / options_.active_array_dimension.height,
(f.bounding_box.x2 - f.bounding_box.x1) /
options_.active_array_dimension.width,
(f.bounding_box.y2 - f.bounding_box.y1) /
options_.active_array_dimension.height),
.last_detected_ticks = base::TimeTicks::Now(),
.has_attention = std::fabs(f.pan_angle) < options_.pan_angle_range};
bool found_matching_face = false;
for (auto& known_face : faces_) {
if (is_same_face(s.normalized_bounding_box,
known_face.normalized_bounding_box)) {
found_matching_face = true;
if (!s.has_attention) {
// If the face isn't looking at the camera, reset the timer.
s.first_detected_ticks = base::TimeTicks::Max();
} else if (!known_face.has_attention && s.has_attention) {
// If the face starts looking at the camera, start the timer.
s.first_detected_ticks = base::TimeTicks::Now();
} else {
s.first_detected_ticks = known_face.first_detected_ticks;
}
known_face = s;
break;
}
}
if (!found_matching_face) {
s.first_detected_ticks = base::TimeTicks::Now();
faces_.push_back(s);
}
}
// Flush expired face states.
for (auto it = faces_.begin(); it != faces_.end();) {
if (ElapsedTimeMs(it->last_detected_ticks) >
options_.face_phase_out_threshold_ms) {
it = faces_.erase(it);
} else {
++it;
}
}
}
std::vector<Rect<float>> FaceTracker::GetActiveFaceRectangles() const {
std::vector<Rect<float>> face_rectangles;
face_rectangles.reserve(faces_.size());
for (const auto& f : faces_) {
if (f.has_attention && ElapsedTimeMs(f.first_detected_ticks) >
options_.face_phase_in_threshold_ms) {
face_rectangles.emplace_back(f.normalized_bounding_box);
}
}
return face_rectangles;
}
Rect<float> FaceTracker::GetActiveBoundingRectangleOnActiveStream() const {
std::vector<Rect<float>> faces = GetActiveFaceRectangles();
if (faces.empty()) {
return Rect<float>();
}
float min_x0 = 1.0f, min_y0 = 1.0f, max_x1 = 0.0f, max_y1 = 0.0f;
for (const auto& f : faces) {
min_x0 = std::min(f.left, min_x0);
min_y0 = std::min(f.top, min_y0);
max_x1 = std::max(f.right(), max_x1);
max_y1 = std::max(f.bottom(), max_y1);
}
Rect<float> bounding_rect(min_x0, min_y0, max_x1 - min_x0, max_y1 - min_y0);
VLOGF(2) << "Active bounding rect w.r.t active array: " << bounding_rect;
// Transform the normalized rectangle in the active sensor array space to the
// active stream space.
const float active_array_aspect_ratio =
static_cast<float>(options_.active_array_dimension.width) /
static_cast<float>(options_.active_array_dimension.height);
const float active_stream_aspect_ratio =
static_cast<float>(options_.active_stream_dimension.width) /
static_cast<float>(options_.active_stream_dimension.height);
if (active_array_aspect_ratio < active_stream_aspect_ratio) {
// The active stream is cropped into letterbox with smaller height than the
// active sensor array. Adjust the y coordinates accordingly.
const float height_ratio =
active_array_aspect_ratio / active_stream_aspect_ratio;
bounding_rect.height = std::min(bounding_rect.height / height_ratio, 1.0f);
const float y_offset = (1.0f - height_ratio) / 2;
bounding_rect.top =
std::max(bounding_rect.top - y_offset, 0.0f) / height_ratio;
} else {
// The active stream is cropped into pillarbox with smaller width than the
// active sensor array. Adjust the x coordinates accordingly.
const float width_ratio =
active_stream_aspect_ratio / active_array_aspect_ratio;
bounding_rect.width = std::min(bounding_rect.width / width_ratio, 1.0f);
const float x_offset = (1.0f - width_ratio) / 2;
bounding_rect.left =
std::max(bounding_rect.left - x_offset, 0.0f) / width_ratio;
}
VLOGF(2) << "Active bounding rect w.r.t active stream: " << bounding_rect;
return bounding_rect;
}
void FaceTracker::OnOptionsUpdated(const base::Value& json_values) {
LoadIfExist(json_values, kFacePhaseInThresholdMs,
&options_.face_phase_in_threshold_ms);
LoadIfExist(json_values, kFacePhaseOutThresholdMs,
&options_.face_phase_out_threshold_ms);
LoadIfExist(json_values, kPanAngleRange, &options_.pan_angle_range);
VLOGF(1) << "FaceTracker options:"
<< " face_phase_in_threshold_ms"
<< options_.face_phase_in_threshold_ms
<< " face_phase_out_threshold_ms="
<< options_.face_phase_out_threshold_ms
<< " pan_angle_range=" << options_.pan_angle_range;
}
} // namespace cros
| 39.362573 | 79 | 0.682217 | [
"vector",
"transform"
] |
7f1673747f2b7821cf127fd645769b42fa33f6af | 14,935 | hpp | C++ | sample/common/common.hpp | tonghudan/camport3 | a334d06cddd75ea3d7942bb480a6fd00d52eccf1 | [
"MIT-0"
] | null | null | null | sample/common/common.hpp | tonghudan/camport3 | a334d06cddd75ea3d7942bb480a6fd00d52eccf1 | [
"MIT-0"
] | null | null | null | sample/common/common.hpp | tonghudan/camport3 | a334d06cddd75ea3d7942bb480a6fd00d52eccf1 | [
"MIT-0"
] | null | null | null | #ifndef SAMPLE_COMMON_COMMON_HPP_
#define SAMPLE_COMMON_COMMON_HPP_
#include "Utils.hpp"
#include <fstream>
#include <iterator>
#include <opencv2/opencv.hpp>
#include "DepthRender.hpp"
#include "MatViewer.hpp"
#include "TYThread.hpp"
#include "TyIsp.h"
static inline int parseFrame(const TY_FRAME_DATA& frame, cv::Mat* pDepth
, cv::Mat* pLeftIR, cv::Mat* pRightIR
, cv::Mat* pColor, TY_ISP_HANDLE color_isp_handle = NULL)
{
for (int i = 0; i < frame.validCount; i++){
// get depth image
if (pDepth && frame.image[i].componentID == TY_COMPONENT_DEPTH_CAM){
*pDepth = cv::Mat(frame.image[i].height, frame.image[i].width
, CV_16U, frame.image[i].buffer).clone();
}
// get left ir image
if (pLeftIR && frame.image[i].componentID == TY_COMPONENT_IR_CAM_LEFT){
*pLeftIR = cv::Mat(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer).clone();
}
// get right ir image
if (pRightIR && frame.image[i].componentID == TY_COMPONENT_IR_CAM_RIGHT){
*pRightIR = cv::Mat(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer).clone();
}
// get BGR
if (pColor && frame.image[i].componentID == TY_COMPONENT_RGB_CAM){
if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_JPEG){
cv::Mat jpeg(frame.image[i].height, frame.image[i].width
, CV_8UC1, frame.image[i].buffer);
*pColor = cv::imdecode(jpeg, CV_LOAD_IMAGE_COLOR);
}
if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_YVYU){
cv::Mat yuv(frame.image[i].height, frame.image[i].width
, CV_8UC2, frame.image[i].buffer);
cv::cvtColor(yuv, *pColor, cv::COLOR_YUV2BGR_YVYU);
}
else if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_YUYV){
cv::Mat yuv(frame.image[i].height, frame.image[i].width
, CV_8UC2, frame.image[i].buffer);
cv::cvtColor(yuv, *pColor, cv::COLOR_YUV2BGR_YUYV);
}
else if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_RGB){
cv::Mat rgb(frame.image[i].height, frame.image[i].width
, CV_8UC3, frame.image[i].buffer);
cv::cvtColor(rgb, *pColor, cv::COLOR_RGB2BGR);
}
else if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_BGR){
*pColor = cv::Mat(frame.image[i].height, frame.image[i].width
, CV_8UC3, frame.image[i].buffer);
}
else if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_BAYER8GB){
if (!color_isp_handle){
cv::Mat raw(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer);
cv::cvtColor(raw, *pColor, cv::COLOR_BayerGB2BGR);
}
else{
cv::Mat raw(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer);
TY_IMAGE_DATA _img = frame.image[i];
pColor->create(_img.height, _img.width, CV_8UC3);
int sz = _img.height* _img.width * 3;
TY_IMAGE_DATA out_buff = TYInitImageData(sz, pColor->data, _img.width, _img.height);
out_buff.pixelFormat = TY_PIXEL_FORMAT_BGR;
int res = TYISPProcessImage(color_isp_handle, &_img, &out_buff);
if (res != TY_STATUS_OK){
//fall back to using opencv api
cv::Mat raw(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer);
cv::cvtColor(raw, *pColor, cv::COLOR_BayerGB2BGR);
}
}
}
else if (frame.image[i].pixelFormat == TY_PIXEL_FORMAT_MONO){
cv::Mat gray(frame.image[i].height, frame.image[i].width
, CV_8U, frame.image[i].buffer);
cv::cvtColor(gray, *pColor, cv::COLOR_GRAY2BGR);
}
}
}
return 0;
}
enum{
PC_FILE_FORMAT_XYZ = 0,
};
static void writePC_XYZ(const cv::Point3f* pnts, const cv::Vec3b *color, size_t n, FILE* fp)
{
if (color){
for (size_t i = 0; i < n; i++){
if (!std::isnan(pnts[i].x)){
fprintf(fp, "%f %f %f %d %d %d\n", pnts[i].x, pnts[i].y, pnts[i].z, color[i][0], color[i][1], color[i][2]);
}
}
}
else{
for (size_t i = 0; i < n; i++){
if (!std::isnan(pnts[i].x)){
fprintf(fp, "%f %f %f 0 0 0\n", pnts[i].x, pnts[i].y, pnts[i].z);
}
}
}
}
static void writePointCloud(const cv::Point3f* pnts, const cv::Vec3b *color, size_t n, const char* file, int format)
{
FILE* fp = fopen(file, "w");
if (!fp){
return;
}
switch (format){
case PC_FILE_FORMAT_XYZ:
writePC_XYZ(pnts, color, n, fp);
break;
default:
break;
}
fclose(fp);
}
class CallbackWrapper
{
public:
typedef void(*TY_FRAME_CALLBACK) (TY_FRAME_DATA*, void* userdata);
CallbackWrapper(){
_hDevice = NULL;
_cb = NULL;
_userdata = NULL;
}
TY_STATUS TYRegisterCallback(TY_DEV_HANDLE hDevice, TY_FRAME_CALLBACK v, void* userdata)
{
_hDevice = hDevice;
_cb = v;
_userdata = userdata;
_exit = false;
_cbThread.create(&workerThread, this);
return TY_STATUS_OK;
}
void TYUnregisterCallback()
{
_exit = true;
_cbThread.destroy();
}
private:
static void* workerThread(void* userdata)
{
CallbackWrapper* pWrapper = (CallbackWrapper*)userdata;
TY_FRAME_DATA frame;
while (!pWrapper->_exit)
{
int err = TYFetchFrame(pWrapper->_hDevice, &frame, 100);
if (!err) {
pWrapper->_cb(&frame, pWrapper->_userdata);
}
}
LOGI("frameCallback exit!");
return NULL;
}
TY_DEV_HANDLE _hDevice;
TY_FRAME_CALLBACK _cb;
void* _userdata;
bool _exit;
TYThread _cbThread;
};
#ifdef _WIN32
static int get_fps() {
static int fps_counter = 0;
static clock_t fps_tm = 0;
const int kMaxCounter = 250;
fps_counter++;
if (fps_counter < kMaxCounter) {
return -1;
}
int elapse = (clock() - fps_tm);
int v = (int)(((float)fps_counter) / elapse * CLOCKS_PER_SEC);
fps_tm = clock();
fps_counter = 0;
return v;
}
#else
static int get_fps() {
static int fps_counter = 0;
static clock_t fps_tm = 0;
const int kMaxCounter = 200;
struct timeval start;
fps_counter++;
if (fps_counter < kMaxCounter) {
return -1;
}
gettimeofday(&start, NULL);
int elapse = start.tv_sec * 1000 + start.tv_usec / 1000 - fps_tm;
int v = (int)(((float)fps_counter) / elapse * 1000);
gettimeofday(&start, NULL);
fps_tm = start.tv_sec * 1000 + start.tv_usec / 1000;
fps_counter = 0;
return v;
}
#endif
static int __TYCompareFirmwareVersion(const TY_DEVICE_BASE_INFO &info, int major, int minor){
const TY_VERSION_INFO &v = info.firmwareVersion;
if (v.major < major){
return -1;
}
if (v.major == major && v.minor < minor){
return -1;
}
if (v.major == major && v.minor == minor){
return 0;
}
return 1;
}
static TY_STATUS __TYDetectOldVer21ColorCam(TY_DEV_HANDLE dev_handle,bool *is_v21_color_device){
TY_DEVICE_BASE_INFO info;
TY_STATUS res = TYGetDeviceInfo(dev_handle, &info);
if (res != TY_STATUS_OK){
LOGI("get device info failed");
return res;
}
*is_v21_color_device = false;
if (info.iface.type == TY_INTERFACE_USB){
*is_v21_color_device = true;
}
if ((info.iface.type == TY_INTERFACE_ETHERNET || info.iface.type == TY_INTERFACE_RAW) &&
__TYCompareFirmwareVersion(info, 2, 2) < 0){
*is_v21_color_device = true;
}
return TY_STATUS_OK;
}
///init color isp setting
///for bayer raw image process
static TY_STATUS ColorIspInitSetting(TY_ISP_HANDLE isp_handle, TY_DEV_HANDLE dev_handle){
bool is_v21_color_device ;
TY_STATUS res = __TYDetectOldVer21ColorCam(dev_handle, &is_v21_color_device);//old version device has different config
if (res != TY_STATUS_OK){
return res;
}
if (is_v21_color_device){
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_BLACK_LEVEL, 11));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_BLACK_LEVEL_GAIN, 256.f / (256 - 11)));
}
else{
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_BLACK_LEVEL, 0));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_BLACK_LEVEL_GAIN, 1.f));
bool b;
ASSERT_OK(TYHasFeature(dev_handle, TY_COMPONENT_RGB_CAM, TY_INT_ANALOG_GAIN, &b));
if (b){
TYSetInt(dev_handle, TY_COMPONENT_RGB_CAM, TY_INT_ANALOG_GAIN, 1);
}
}
float shading[9] = { 0.30890417098999026, 10.63355541229248, -6.433426856994629,
0.24413758516311646, 11.739893913269043, -8.148622512817383,
0.1255662441253662, 11.88359546661377, -7.865192413330078 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_SHADING, (uint8_t*)shading, sizeof(shading)));
int shading_center[2] = { 640, 480 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_SHADING_CENTER, (uint8_t*)shading_center, sizeof(shading_center)));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_CCM_ENABLE, 0));//we are not using ccm by default
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_CAM_DEV_HANDLE, (uint8_t*)&dev_handle, sizeof(dev_handle)));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_CAM_DEV_COMPONENT, int32_t(TY_COMPONENT_RGB_CAM)));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_GAMMA, 1.f));
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_AUTOBRIGHT, 1));//enable auto bright control
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_ENABLE_AUTO_EXPOSURE_GAIN, 0));//disable ae by default
int image_size[2] = { 1280, 960 };// image size for current parameters
int current_image_width = 1280;
TYGetInt(dev_handle, TY_COMPONENT_RGB_CAM, TY_INT_WIDTH, ¤t_image_width);
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_IMAGE_SIZE, (uint8_t*)&image_size, sizeof(image_size)));//input raw image size
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_INPUT_RESAMPLE_SCALE, image_size[0] / current_image_width));
#if 1
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_ENABLE_AUTO_WHITEBALANCE, 1)); //eanble auto white balance
#else
//manual wb gain control
const float wb_rgb_gain[3] = { 2.0123140811920168, 1, 1.481866478919983 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_WHITEBALANCE_GAIN, (uint8_t*)wb_rgb_gain, sizeof(wb_rgb_gain)));
#endif
//try to load specifical device config from device storage
int32_t comp_all;
ASSERT_OK(TYGetComponentIDs(dev_handle, &comp_all));
if (!(comp_all & TY_COMPONENT_STORAGE)){
return TY_STATUS_OK;
}
bool has_isp_block = false;
ASSERT_OK(TYHasFeature(dev_handle, TY_COMPONENT_STORAGE, TY_BYTEARRAY_ISP_BLOCK, &has_isp_block));
if (!has_isp_block){
return TY_STATUS_OK;
}
uint32_t sz = 0;
ASSERT_OK(TYGetByteArraySize(dev_handle, TY_COMPONENT_STORAGE, TY_BYTEARRAY_ISP_BLOCK, &sz));
if (sz <= 0){
return TY_STATUS_OK;
}
std::vector<uint8_t> buff(sz);
ASSERT_OK(TYGetByteArray(dev_handle, TY_COMPONENT_STORAGE, TY_BYTEARRAY_ISP_BLOCK, &buff[0], buff.size()));
res = TYISPLoadConfig(isp_handle, &buff[0], buff.size());
if (res == TY_STATUS_OK){
LOGD("Load RGB ISP Config From Device");
}
return TY_STATUS_OK;
}
static TY_STATUS ColorIspInitAutoExposure(TY_ISP_HANDLE isp_handle, TY_DEV_HANDLE dev_handle){
bool is_v21_color_device;
TY_STATUS res = __TYDetectOldVer21ColorCam(dev_handle, &is_v21_color_device);//old version device has different config
if (res != TY_STATUS_OK){
return res;
}
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_ENABLE_AUTO_EXPOSURE_GAIN, 1));
if(is_v21_color_device){
const int old_auto_gain_range[2] = { 33, 255 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_AUTO_GAIN_RANGE, (uint8_t*)&old_auto_gain_range, sizeof(old_auto_gain_range)));
}
else{
const int auto_gain_range[2] = { 15, 255 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_AUTO_GAIN_RANGE, (uint8_t*)&auto_gain_range, sizeof(auto_gain_range)));
}
#if 1
//constraint exposure time
const int auto_expo_range[2] = { 10, 100 };
ASSERT_OK(TYISPSetFeature(isp_handle, TY_ISP_FEATURE_AUTO_EXPOSURE_RANGE, (uint8_t*)&auto_expo_range, sizeof(auto_expo_range)));
#endif
return TY_STATUS_OK;
}
static TY_STATUS ColorIspShowSupportedFeatures(TY_ISP_HANDLE handle){
int sz;
TY_STATUS res = TYISPGetFeatureInfoListSize(handle,&sz);
if (res != TY_STATUS_OK){
return res;
}
std::vector<TY_ISP_FEATURE_INFO> info;
info.resize(sz);
TYISPGetFeatureInfoList(handle, &info[0], info.size());
for (int idx = 0; idx < sz; idx++){
printf("feature name : %-50s type : %s \n", info[idx].name, info[idx].value_type);
}
return TY_STATUS_OK;
}
static std::vector<uint8_t> TYReadBinaryFile(const char* filename)
{
// open the file:
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()){
return std::vector<uint8_t>();
}
// Stop eating new lines in binary mode!!!
file.unsetf(std::ios::skipws);
// get its size:
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// reserve capacity
std::vector<uint8_t> vec;
vec.reserve(fileSize);
// read the data:
vec.insert(vec.begin(),
std::istream_iterator<uint8_t>(file),
std::istream_iterator<uint8_t>());
return vec;
}
#endif
| 37.244389 | 141 | 0.602343 | [
"vector"
] |
7f2148da9b31721970a69c5409d39c08bc0df10a | 745 | hpp | C++ | src/engine/console.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/console.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/console.hpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | #pragma once
#include <core/coredef.hpp>
#include <core/lua/luamanager.hpp>
#include <imgui.h>
namespace eXl
{
struct LuaConsole
{
char InputBuf[256];
Vector<AString> Items;
bool ScrollToBottom;
Vector<AString> History;
int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
LuaWorld LuaCtx;
LuaConsole();
~LuaConsole();
void ClearLog();
void AddLog(const char* fmt, ...) IM_FMTARGS(2);
void Draw(/*const char* title, bool* p_open*/);
void ExecCommand(const char* command_line);
static int TextEditCallbackStub(ImGuiInputTextCallbackData* data);
int TextEditCallback(ImGuiInputTextCallbackData* data);
};
} | 21.285714 | 88 | 0.636242 | [
"vector"
] |
7f2b15e2a9d07472dc3c2ebc1c68a4e46dbe5edb | 2,410 | hpp | C++ | server/drivers/eeprom.hpp | Koheron/koheron-sdk | 82b732635f1adf5dd0b04b9290b589c1fc091f29 | [
"MIT"
] | 77 | 2016-09-20T18:44:14.000Z | 2022-03-30T16:04:09.000Z | server/drivers/eeprom.hpp | rsarwar87/koheron-sdk | 02c35bf3c1c29f1029fad18b881dbd193efac5a7 | [
"MIT"
] | 101 | 2016-09-05T15:44:25.000Z | 2022-03-29T09:22:09.000Z | server/drivers/eeprom.hpp | rsarwar87/koheron-sdk | 02c35bf3c1c29f1029fad18b881dbd193efac5a7 | [
"MIT"
] | 34 | 2016-12-12T07:21:57.000Z | 2022-01-12T21:00:52.000Z | #ifndef __DRIVERS_EEPROM_HPP__
#define __DRIVERS_EEPROM_HPP__
#include <vector>
#include <thread>
#include <chrono>
#include <context.hpp>
// EEPROM instructions
// http://www.atmel.com/images/Atmel-5193-SEEPROM-AT93C46D-Datasheet.pdf
namespace Eeprom_instr {
constexpr uint32_t write = 1 << 2; // Write memory location
constexpr uint32_t read = 2 << 2; // Reads data stored in memory at specified address
constexpr uint32_t erase = 3 << 2; // Erases memory location
constexpr uint32_t ewds = 0; // Disable all programming instructions
constexpr uint32_t wral = 1; // Disable all programming instructions
constexpr uint32_t eral = 2; // Erase all memory locations
constexpr uint32_t ewen = 3; // Write Enable, must precede all programming modes
}
class Eeprom
{
public:
Eeprom(Context& ctx_)
: ctx(ctx_)
, ctl(ctx.mm.get<mem::control>())
, sts(ctx.mm.get<mem::status>())
{
using namespace std::chrono_literals;
write_enable();
std::this_thread::sleep_for(10ms);
}
uint32_t read(uint32_t addr) {
using namespace std::chrono_literals;
ctl.write<reg::eeprom_ctl>((Eeprom_instr::read << 5) + (addr << 1));
ctl.set_bit<reg::eeprom_ctl, 0>();
std::this_thread::sleep_for(100us);
return sts.read<reg::eeprom_sts>();
}
void write_enable() {
ctl.write<reg::eeprom_ctl>(Eeprom_instr::ewen << 5);
ctl.set_bit<reg::eeprom_ctl, 0>();
}
void erase(uint32_t addr) {
ctl.write<reg::eeprom_ctl>((Eeprom_instr::erase << 5) + (addr << 1));
ctl.set_bit<reg::eeprom_ctl, 0>();
}
void write(uint32_t addr, uint32_t data_in) {
ctl.write<reg::eeprom_ctl>((data_in << 16) + (Eeprom_instr::write << 5) + (addr << 1));
ctl.set_bit<reg::eeprom_ctl, 0>();
}
void erase_all() {
ctl.write<reg::eeprom_ctl>(Eeprom_instr::eral << 5);
ctl.set_bit<reg::eeprom_ctl, 0>();
}
void write_all(uint32_t data_in) {
ctl.write<reg::eeprom_ctl>((data_in << 16) + (Eeprom_instr::wral << 5));
ctl.set_bit<reg::eeprom_ctl, 0>();
}
void erase_write_disable() {
ctl.write<reg::eeprom_ctl>(Eeprom_instr::ewds << 5);
ctl.set_bit<reg::eeprom_ctl, 0>();
}
private:
Context& ctx;
Memory<mem::control>& ctl;
Memory<mem::status>& sts;
};
#endif // __DRIVERS_EEPROM_HPP__ | 30.506329 | 95 | 0.63361 | [
"vector"
] |
b54fab872eca4f6d5d7f9fa7217dbb6c3b489fc9 | 4,587 | cc | C++ | meituan/TOVGD1.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | meituan/TOVGD1.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | meituan/TOVGD1.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <map>
#include <list>
#include <algorithm>
struct Paste
{
Paste(int l, int r, int x) : l(l), r(r), x(x) {}
int l;
int r;
int x;
};
int main()
{
#ifndef DEBUG
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
#endif
int n;
std::cin >> n;
// std::string input;
// while (std::cin >> input)
// std::cerr << input << std::endl;
// std::cerr << "NNNNNNN; " << n << std::endl;
std::vector<int> buffer(n + 1);
for (int i = 1; i <= n; i++)
std::cin >> buffer[i];
#ifdef DEBUG
std::cout << "buffer=[";
for (int i = 1; i <= n; i++)
std::cout << buffer[i] << ", ";
std::cout << "]" << std::endl;
#endif
int m;
std::cin >> m;
std::list<Paste> paste;
std::vector<int> res;
paste.emplace_back(1, n, -1);
while (m--)
{
#ifdef DEBUG
std::for_each(paste.begin(), paste.end(), [&](Paste i)
{ std::cout << "[" << i.l << ", " << i.r << ", " << i.x << "]->"; });
std::cout << std::endl;
#endif
int op;
std::cin >> op;
if (op == 1)
{
int k, x, y;
std::cin >> k >> x >> y;
int new_r = std::min(y + k - 1, n);
#ifdef DEBUG
std::cout << "op=" << op << ", k=" << k << ", x=" << x << ", y=" << y << ", new_r=" << new_r << std::endl;
#endif
for (auto iter = paste.begin(); iter != paste.end(); iter++)
{
#ifdef DEBUG
std::cout << "[" << iter->l << ", " << iter->r << ", " << iter->x << "]" << std::endl;
#endif
if (y > iter->r)
continue;
bool is_break = y >= iter->l;
if (y == iter->l && new_r == iter->r)
iter->x = x;
else if (y == iter->l && new_r < iter->r)
{
paste.emplace(iter, y, new_r, x);
if (iter->x != -1)
iter->x += new_r + 1 - iter->l;
iter->l = new_r + 1;
}
else if (y > iter->l && new_r == iter->r)
{
paste.emplace(iter, iter->l, y - 1, iter->x);
iter->l = y;
iter->x = x;
}
else if (y > iter->l && new_r < iter->r)
{
paste.emplace(iter, iter->l, y - 1, iter->x);
paste.emplace(iter, y, new_r, x);
if (iter->x != -1)
iter->x += new_r + 1 - iter->l;
iter->l = new_r + 1;
}
else if (y >= iter->l && new_r > iter->r)
{
auto cur = iter;
cur++;
while (cur != paste.end() && new_r >= cur->r)
{
auto now = cur++;
paste.erase(now);
}
if (cur != paste.end())
{
if (cur->x != -1)
cur->x += new_r + 1 - cur->l;
cur->l = new_r + 1;
}
if (y == iter->l)
{
iter->r = new_r;
iter->x = x;
}
else
{
paste.emplace(iter, iter->l, y - 1, iter->x);
iter->l = y;
iter->r = new_r;
iter->x = x;
}
}
if (is_break)
break;
}
}
else
{
int query_pos;
std::cin >> query_pos;
#ifdef DEBUG
std::cout << "op=" << op << ", query_pos=" << query_pos << std::endl;
#endif
for (auto iter = paste.cbegin(); iter != paste.cend(); iter++)
{
if (query_pos >= iter->l && query_pos <= iter->r)
{
if (iter->x != -1)
res.push_back(buffer[iter->x + query_pos - iter->l]);
else
res.push_back(-1);
break;
}
}
#ifdef DEBUG
std::cout << "res=" << res.back() << std::endl;
#endif
}
}
for (int i = 0; i < res.size(); i++)
std::cout << res[i] << std::endl;
return 0;
}
| 27.142012 | 118 | 0.334859 | [
"vector"
] |
b55fec59b97d3f98e65a42e9da8a686a32b8503d | 801 | cpp | C++ | general/reverse.cpp | amazingpython/cppinterview | 1a475a7e9fde3cb2c23a329c962f98c8ced3c1c7 | [
"Apache-2.0"
] | 1 | 2019-02-26T17:05:12.000Z | 2019-02-26T17:05:12.000Z | general/reverse.cpp | amazingpython/cppinterview | 1a475a7e9fde3cb2c23a329c962f98c8ced3c1c7 | [
"Apache-2.0"
] | null | null | null | general/reverse.cpp | amazingpython/cppinterview | 1a475a7e9fde3cb2c23a329c962f98c8ced3c1c7 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <math.h>
#include <climits>
/**
* This reverse an integer, with 32 bit limits
*/
using namespace std;
int reverse(int x) {
int newX = 0, tempX = x, min_limit = INT_MIN/10, max_limit = INT_MAX/10, min_r = INT_MIN%10, max_r = INT_MAX%10;
while (tempX != 0) {
newX = newX * 10 + (tempX%10);
tempX = tempX/10;
if (x > 0 && newX > max_limit && tempX != 0) return 0;
if (x < 0 && newX < min_limit && tempX != 0) return 0;
if (x > 0 && newX == max_limit && tempX > max_r) return 0;
if (x < 0 && newX == min_limit && tempX < min_r) return 0;
}
//cout << newX << " " << INT_MAX << " " << INT_MIN << endl;
return newX;
}
int main()
{
cout << reverse(-123) << endl;
return 0;
}
| 22.25 | 116 | 0.541823 | [
"vector"
] |
b5630f63cdc56164ac2eefea1be603066557210d | 1,074 | cpp | C++ | Codeforces/Round-708-Div2/B.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | Codeforces/Round-708-Div2/B.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | Codeforces/Round-708-Div2/B.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | // Tags: Math
// Difficulty: 2.0
// Priority: 3
// Date: 17-03-2021
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n, m;
cin >> n >> m;
vi frec(m, 0);
for (int i = 0; i < n; i++) {
int ai;
cin >> ai;
frec[ai % m] += 1;
}
int need = 0;
if (frec[0]) need += 1;
for (int i = 1; i + i < m; i++) {
int x = frec[i];
int y = frec[m - i];
if (x == 0 and y == 0) continue;
need += 1;
int z = min(x, y) + 1;
x -= z;
y -= z;
need += max({0, x, y});
}
if (m % 2 == 0 and frec[m / 2]) need += 1;
cout << need << '\n';
}
return (0);
}
| 19.888889 | 46 | 0.495345 | [
"vector"
] |
b564d1349ad464f51e15ea7f6525467d6f448fe4 | 13,251 | cpp | C++ | src/vkfw_core/gfx/vk/Framebuffer.cpp | dasmysh/VulkanFramework_Lib | baeaeb3158d23187f2ffa5044e32d8a5145284aa | [
"MIT"
] | null | null | null | src/vkfw_core/gfx/vk/Framebuffer.cpp | dasmysh/VulkanFramework_Lib | baeaeb3158d23187f2ffa5044e32d8a5145284aa | [
"MIT"
] | null | null | null | src/vkfw_core/gfx/vk/Framebuffer.cpp | dasmysh/VulkanFramework_Lib | baeaeb3158d23187f2ffa5044e32d8a5145284aa | [
"MIT"
] | null | null | null | /**
* @file Framebuffer.cpp
* @author Sebastian Maisch <sebastian.maisch@googlemail.com>
* @date 2016.10.26
*
* @brief Implementation of a framebuffer object for Vulkan.
*/
#include "gfx/vk/Framebuffer.h"
#include "gfx/vk/LogicalDevice.h"
#include "gfx/vk/wrappers/CommandBuffer.h"
#include "gfx/vk/wrappers/PipelineBarriers.h"
#include "gfx/vk/wrappers/DescriptorSet.h"
#include "gfx/vk/wrappers/VertexInputResources.h"
namespace vkfw_core::gfx {
Framebuffer::Framebuffer(const LogicalDevice* logicalDevice, std::string_view name, const glm::uvec2& size,
const std::vector<vk::Image>& images, const RenderPass& renderPass,
const FramebufferDescriptor& desc, const std::vector<std::uint32_t>& queueFamilyIndices,
std::optional<std::reference_wrapper<CommandBuffer>> cmdBuffer)
: VulkanObjectPrivateWrapper{logicalDevice->GetHandle(), name, vk::UniqueFramebuffer{}}
, m_device{logicalDevice}
, m_size{size}
, m_renderPass{&renderPass}
, m_desc(desc)
, m_memoryGroup{logicalDevice, fmt::format("Mem:{}", name), vk::MemoryPropertyFlags()}
, m_extImages{images}
, m_queueFamilyIndices{queueFamilyIndices}
, m_barrier{m_device}
{
for (std::size_t i = 0; i < m_extImages.size(); ++i) {
m_extTextures.emplace_back(m_device, fmt::format("FBO:{}-ExtTex:{}", name, i), desc.m_attachments[i].m_tex,
vk::ImageLayout::eUndefined, m_queueFamilyIndices);
m_extTextures.back().InitializeExternalImage(m_extImages[i], glm::u32vec4(m_size, 1, 1), 1, false);
}
CreateImages(cmdBuffer);
CreateFB();
}
Framebuffer::Framebuffer(const LogicalDevice* logicalDevice, std::string_view name, const glm::uvec2& size,
const RenderPass& renderPass, const FramebufferDescriptor& desc,
const std::vector<std::uint32_t>& queueFamilyIndices,
std::optional<std::reference_wrapper<CommandBuffer>> cmdBuffer)
: Framebuffer(logicalDevice, name, size, std::vector<vk::Image>(), renderPass, desc, queueFamilyIndices,
cmdBuffer)
{
}
Framebuffer::Framebuffer(const Framebuffer& rhs)
: Framebuffer(rhs.m_device, fmt::format("{}-Copy", GetName()), rhs.m_size, rhs.m_extImages, *rhs.m_renderPass,
rhs.m_desc, rhs.m_queueFamilyIndices)
{
}
Framebuffer& Framebuffer::operator=(const Framebuffer& rhs)
{
if (this != &rhs) {
auto tmp{rhs};
std::swap(*this, tmp);
}
return *this;
}
Framebuffer::Framebuffer(Framebuffer&& rhs) noexcept
: VulkanObjectPrivateWrapper{std::move(rhs)}
, m_device{rhs.m_device}
, m_size{rhs.m_size}
, m_renderPass{rhs.m_renderPass}
, m_desc(std::move(rhs.m_desc))
, m_memoryGroup{std::move(rhs.m_memoryGroup)}
, m_extTextures{std::move(rhs.m_extTextures)}
, m_extImages{std::move(rhs.m_extImages)}
, m_queueFamilyIndices{std::move(rhs.m_queueFamilyIndices)}
, m_barrier{std::move(rhs.m_barrier)}
{
}
Framebuffer& Framebuffer::operator=(Framebuffer&& rhs) noexcept
{
this->~Framebuffer();
VulkanObjectPrivateWrapper::operator=(std::move(rhs));
m_device = rhs.m_device;
m_size = rhs.m_size;
m_renderPass = rhs.m_renderPass;
m_desc = std::move(rhs.m_desc);
m_memoryGroup = std::move(rhs.m_memoryGroup);
m_extTextures = std::move(rhs.m_extTextures);
m_extImages = std::move(rhs.m_extImages);
m_queueFamilyIndices = std::move(rhs.m_queueFamilyIndices);
m_barrier = std::move(rhs.m_barrier);
return *this;
}
Framebuffer::~Framebuffer() = default;
Texture& Framebuffer::GetTexture(std::size_t index)
{
assert(index < m_desc.m_attachments.size());
if (index < m_extTextures.size()) {
return m_extTextures[index];
} else {
return *m_memoryGroup.GetTexture(static_cast<unsigned int>(index - m_extTextures.size()));
}
}
void Framebuffer::CreateImages(std::optional<std::reference_wrapper<CommandBuffer>> cmdBuffer)
{
std::vector<vk::ImageLayout> imageLayouts;
imageLayouts.resize(m_desc.m_attachments.size() - m_extTextures.size());
for (auto i = m_extTextures.size(); i < m_desc.m_attachments.size(); ++i) {
imageLayouts[i - m_extTextures.size()] = GetFittingAttachmentLayout(m_desc.m_attachments[i].m_tex.m_format);
m_memoryGroup.AddTextureToGroup(fmt::format("FBO:{}-Tex{}", GetName(), i), m_desc.m_attachments[i].m_tex,
vk::ImageLayout::eUndefined, glm::u32vec4(m_size, 1, 1), 1,
m_queueFamilyIndices);
}
m_memoryGroup.FinalizeDeviceGroup();
CommandBuffer ucmdBuffer{m_device};
if (!cmdBuffer.has_value()) {
ucmdBuffer = CommandBuffer::beginSingleTimeSubmit(
m_device, fmt::format("FBO:{} CreateImagesCmdBuffer", GetName()),
fmt::format("FBO:{} CreateImages", GetName()), m_device->GetCommandPool(0));
}
PipelineBarrier barrier{m_device};
for (auto i = 0U; i < m_memoryGroup.GetImagesInGroup(); ++i) {
vk::AccessFlags2KHR access = GetFittingAttachmentAccessFlags(m_desc.m_attachments[i].m_tex.m_format);
vk::PipelineStageFlags2KHR pipelineStage =
GetFittingAttachmentPipelineStage(m_desc.m_attachments[i].m_tex.m_format);
m_memoryGroup.GetTexture(i)->AccessBarrier(access, pipelineStage, imageLayouts[i], barrier);
}
barrier.Record(cmdBuffer.has_value() ? cmdBuffer.value().get() : ucmdBuffer);
if (!cmdBuffer.has_value()) {
auto& queue = m_device->GetQueue(0, 0);
auto fence = CommandBuffer::endSingleTimeSubmit(queue, ucmdBuffer);
fence->Wait(m_device, defaultFenceTimeout);
// queue.WaitIdle();
}
}
void Framebuffer::CreateFB()
{
assert(m_desc.m_type == vk::ImageViewType::e2D || m_desc.m_type == vk::ImageViewType::eCube);
assert(m_extTextures.size() + m_memoryGroup.GetImagesInGroup() == m_desc.m_attachments.size());
constexpr std::uint32_t CUBE_MAP_LAYERS = 6;
std::uint32_t layerCount = 1;
if (m_desc.m_type == vk::ImageViewType::eCube) { layerCount = CUBE_MAP_LAYERS; }
// TODO: handle cube textures. [3/20/2017 Sebastian Maisch]
std::vector<vk::ImageView> attachments;
for (auto& tex : m_extTextures) {
tex.InitializeImageView();
auto descriptorIndex = attachments.size();
vk::AccessFlags2KHR access =
GetFittingAttachmentAccessFlags(m_desc.m_attachments[descriptorIndex].m_tex.m_format);
vk::PipelineStageFlags2KHR pipelineStage =
GetFittingAttachmentPipelineStage(m_desc.m_attachments[descriptorIndex].m_tex.m_format);
vk::ImageLayout layout =
m_desc.m_attachments[descriptorIndex].m_initialLayout == vk::ImageLayout::eUndefined
? tex.GetImageLayout()
: m_desc.m_attachments[descriptorIndex].m_initialLayout;
attachments.push_back(tex.GetImageView(access, pipelineStage, layout, m_barrier).GetHandle());
}
attachments.reserve(m_desc.m_attachments.size());
for (auto i = 0U; i < m_memoryGroup.GetImagesInGroup(); ++i) {
auto descriptorIndex = attachments.size();
vk::AccessFlags2KHR access =
GetFittingAttachmentAccessFlags(m_desc.m_attachments[descriptorIndex].m_tex.m_format);
vk::PipelineStageFlags2KHR pipelineStage =
GetFittingAttachmentPipelineStage(m_desc.m_attachments[descriptorIndex].m_tex.m_format);
vk::ImageLayout layout =
m_desc.m_attachments[descriptorIndex].m_initialLayout == vk::ImageLayout::eUndefined
? m_memoryGroup.GetTexture(i)->GetImageLayout()
: m_desc.m_attachments[descriptorIndex].m_initialLayout;
attachments.push_back(
m_memoryGroup.GetTexture(i)->GetImageView(access, pipelineStage, layout, m_barrier).GetHandle());
}
vk::FramebufferCreateInfo fbCreateInfo{vk::FramebufferCreateFlags(),
m_renderPass->GetHandle(),
static_cast<std::uint32_t>(m_desc.m_attachments.size()),
attachments.data(),
m_size.x,
m_size.y,
layerCount};
SetHandle(m_device->GetHandle(), m_device->GetHandle().createFramebufferUnique(fbCreateInfo));
}
Framebuffer Framebuffer::CreateWithSameImages(std::string_view name, const FramebufferDescriptor& desc,
const std::vector<std::uint32_t>& queueFamilyIndices,
std::optional<std::reference_wrapper<CommandBuffer>> cmdBuffer) const
{
std::vector<vk::Image> images;
for (const auto& tex : m_extTextures) { images.push_back(tex.GetAccessNoBarrier()); }
for (auto i = 0U; i < m_memoryGroup.GetImagesInGroup(); ++i) {
images.push_back(m_memoryGroup.GetTexture(i)->GetAccessNoBarrier());
}
return Framebuffer(m_device, name, m_size, images, *m_renderPass, desc, queueFamilyIndices, cmdBuffer);
}
void Framebuffer::BeginRenderPass(CommandBuffer& cmdBuffer, const RenderPass& renderPass,
std::span<DescriptorSet*> descriptorSets,
std::span<VertexInputResources*> vertexInputs, const vk::Rect2D& renderArea,
std::span<vk::ClearValue> clearColor, vk::SubpassContents subpassContents)
{
m_barrier.Record(cmdBuffer);
for (auto descriptorSet : descriptorSets) { descriptorSet->BindBarrier(cmdBuffer); }
for (auto vertexInput : vertexInputs) { vertexInput->BindBarrier(cmdBuffer); }
vk::RenderPassBeginInfo renderPassBeginInfo{renderPass.GetHandle(), GetHandle(), renderArea,
static_cast<std::uint32_t>(clearColor.size()), clearColor.data()};
cmdBuffer.GetHandle().beginRenderPass(renderPassBeginInfo, subpassContents);
}
bool Framebuffer::IsAnyDepthOrStencilFormat(vk::Format format)
{
return IsDepthFormat(format) || IsStencilFormat(format) || IsDepthStencilFormat(format);
}
bool Framebuffer::IsDepthStencilFormat(vk::Format format)
{
if (format == vk::Format::eD16UnormS8Uint) {
return true;
} else if (format == vk::Format::eD24UnormS8Uint) {
return true;
} else if (format == vk::Format::eD32SfloatS8Uint) {
return true;
}
return false;
}
bool Framebuffer::IsStencilFormat(vk::Format format)
{
if (format == vk::Format::eS8Uint) {
return true;
}
return false;
}
bool Framebuffer::IsDepthFormat(vk::Format format)
{
if (format == vk::Format::eD16Unorm) {
return true;
} else if (format == vk::Format::eX8D24UnormPack32) {
return true;
} else if (format == vk::Format::eD32Sfloat) {
return true;
}
return false;
}
vk::ImageLayout Framebuffer::GetFittingAttachmentLayout(vk::Format format)
{
// at this point feature separateDepthStencilLayouts is not enabled -> all layouts that fit depth or stencil are d/s layouts.
// if (IsDepthFormat(format)) {
// return vk::ImageLayout::eDepthAttachmentOptimal;
// } else if (IsStencilFormat(format)) {
// return vk::ImageLayout::eStencilAttachmentOptimal;
// } else if (IsDepthStencilFormat(format)) {
// return vk::ImageLayout::eDepthStencilAttachmentOptimal;
// }
if (IsAnyDepthOrStencilFormat(format)) {
return vk::ImageLayout::eDepthStencilAttachmentOptimal;
}
return vk::ImageLayout::eColorAttachmentOptimal;
}
vk::AccessFlags2KHR Framebuffer::GetFittingAttachmentAccessFlags(vk::Format format)
{
if (IsAnyDepthOrStencilFormat(format)) {
return vk::AccessFlagBits2KHR::eDepthStencilAttachmentWrite;
}
return vk::AccessFlagBits2KHR::eColorAttachmentWrite;
}
vk::PipelineStageFlags2KHR Framebuffer::GetFittingAttachmentPipelineStage(vk::Format format)
{
if (IsAnyDepthOrStencilFormat(format)) {
return vk::PipelineStageFlagBits2KHR::eEarlyFragmentTests;
}
return vk::PipelineStageFlagBits2KHR::eColorAttachmentOutput;
}
}
| 45.851211 | 133 | 0.618368 | [
"object",
"vector"
] |
b565e2f4e8f12bc708cf2bf4f9d82baca771fe1b | 3,154 | hpp | C++ | numerical/fem/FEProblem.hpp | frRoy/Numerical | 97e2167cf794eceaeba395bb1958fee72d8cbecf | [
"MIT"
] | null | null | null | numerical/fem/FEProblem.hpp | frRoy/Numerical | 97e2167cf794eceaeba395bb1958fee72d8cbecf | [
"MIT"
] | null | null | null | numerical/fem/FEProblem.hpp | frRoy/Numerical | 97e2167cf794eceaeba395bb1958fee72d8cbecf | [
"MIT"
] | null | null | null | /**
* @file FEProblem.hpp
* @brief Defines basis functions.
* @author Francois Roy
* @date 01/06/2020
*/
#ifndef FEPROBLEM_H
#define FEPROBLEM_H
#include <vector>
#include <cmath>
#include <math.h>
#include <Eigen/Core>
#include "spdlog/spdlog.h"
#include "FEMesh.hpp"
namespace numerical {
namespace fem {
/**
* Defines the finite element problem over a line.
*
* This class only define the 1D diffusion problem with Dirichlet/Neumann
* boundary conditions and heterogenous diffusion coefficient (for now).
*
* Support for hyperbolic equations (wave and convection diffusion) will be
* added later.
*/
template <typename T>
class FEProblem { // TODO inherit from common/Problem
typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;
typedef std::vector<Eigen::Matrix<T, 3, 1>> Coord;
// function pointer to member functions
typedef T (FEProblem<T>::*fctptr)(T x1, T x2, T time);
private:
Vec m_t;
std::vector<T> m_dx;
T m_dt;
protected:
FEMesh<T>* m_mesh; // mesh
// boundary types (0=Dirichlet, 1=Neumann) for left and right boundaries.
int m_bc_types[2];
public:
FEProblem():
m_bc_types{0, 0} {
// define mesh
// m_mesh = new Mesh<T>();
}
virtual ~FEProblem(){
// delete m_mesh;
}
/**
* Domain LHS (bilinear form)
*/
virtual void dlhs(T e, T phi, T r, T s, T X, T x, T h){
}
/**
* Domain RHS (linear form)
*/
virtual void drhs(T e, T phi, T r, T X, T x, T h){
}
/**
* Boundary RHS (bilinear form)
*/
virtual void blhs(T e, T phi, T r, T s, T X, T x, T h){
}
/**
* Boundary LHS (linear form)
*/
virtual void brhs(T e, T phi, T r, T X, T x, T h){
}
/**
* Get the reference solution at a specified mesh location.
*
* @param x The \f$x\f$-, \f$y\f$-, and \f$z\f$-coordinates of the mesh
* node.
* @param t The discrete time.
* @return The reference solution at a specified mesh location.
*/
virtual T reference(const Eigen::Matrix<T, 3, 1>& x, T t){
return 0.0;
}
/**
* User defined function: right boundary.
*
* Right boundary value, i.e. for x = lengths[0][1].
*
* @param u The state variable.
* @param t The discrete time.
* @return The boundary value at a specified mesh location.
*/
virtual T right(T u, T t){
return 0.0;
}
/**
* User defined function: left boundary.
*
* Left boundary value, i.e. for x = lengths[0][1].
*
* @param u The state variable.
* @param t The discrete time.
* @return The boundary value at a specified mesh location.
*/
virtual T left(T u, T t){
return 0.0;
}
/**
* User defined function: source term.
*
* @param x The \f$x\f$-, \f$y\f$-, and \f$z\f$-coordinates of the mesh
* node.
* @param t The discrete time.
* @param u The state variable for nonlinear problems.
* @return The source term at a specified mesh location.
*/
virtual T source(const Eigen::Matrix<T, 3, 1>& x, T t, T u=0){
return 0.0;
}
};
} // namespace fem
} // namespace numerical
#endif // FEMPROBLEM_H | 24.640625 | 76 | 0.602093 | [
"mesh",
"vector"
] |
b56d6c7c7b4168221773328286ad6dc7cfae26bd | 8,874 | cc | C++ | test_tools/example_gen/example_gen.cc | jakub-szymanski/reinforcement_learning | 529f9bf70881a868fae4edccb626b4989c37b2c4 | [
"MIT"
] | null | null | null | test_tools/example_gen/example_gen.cc | jakub-szymanski/reinforcement_learning | 529f9bf70881a868fae4edccb626b4989c37b2c4 | [
"MIT"
] | null | null | null | test_tools/example_gen/example_gen.cc | jakub-szymanski/reinforcement_learning | 529f9bf70881a868fae4edccb626b4989c37b2c4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <cstring>
#include <boost/program_options.hpp>
#include "config_utility.h"
#include "live_model.h"
#include "constants.h"
namespace r = reinforcement_learning;
namespace u = reinforcement_learning::utility;
namespace m = reinforcement_learning::model_management;
namespace nm = reinforcement_learning::name;
namespace val = reinforcement_learning::value;
namespace err = reinforcement_learning::error_code;
namespace cfg = reinforcement_learning::utility::config;
namespace po = boost::program_options;
//global var, yeah ugg
bool enable_dedup = false;
static const char *options[] = {
"cb",
"ccb",
"ccb-baseline",
"slates",
"ca",
"f-reward",
"fi-reward",
"fs-reward",
"s-reward",
"si-reward",
"ss-reward",
"action-taken",
nullptr
};
enum options{
CB_ACTION,
CCB_ACTION,
CCB_BASELINE_ACTION,
SLATES_ACTION,
CA_ACTION,
// Put interaction actions before F_REWARD
F_REWARD,
F_I_REWARD,
F_S_REWARD,
S_REWARD,
S_I_REWARD,
S_S_REWARD,
ACTION_TAKEN,
};
void load_config_from_json(int action, u::configuration& config)
{
std::string file_name(options[action]);
file_name += "_v2.fb";
config.set("ApplicationID", "<appid>");
config.set("interaction.sender.implementation", "INTERACTION_FILE_SENDER");
config.set("observation.sender.implementation", "OBSERVATION_FILE_SENDER");
config.set("decisions.sender.implementation", "INTERACTION_FILE_SENDER");
config.set("model.source", "NO_MODEL_DATA");
bool is_observation = action >= F_REWARD;
if(is_observation) {
config.set("observation.file.name", file_name.c_str());
config.set("interaction.file.name", "/dev/null");
} else {
config.set("observation.file.name", "/dev/null");
config.set("interaction.file.name", file_name.c_str());
}
config.set("protocol.version", "2");
config.set("InitialExplorationEpsilon", "1.0");
if(enable_dedup) {
config.set(nm::INTERACTION_USE_DEDUP, "true");
config.set(nm::INTERACTION_USE_COMPRESSION, "true");
}
if(action == CCB_ACTION || action == CCB_BASELINE_ACTION) {
config.set(r::name::MODEL_VW_INITIAL_COMMAND_LINE, "--ccb_explore_adf --json --quiet --epsilon 0.0 --first_only --id N/A");
} else if (action == SLATES_ACTION) {
config.set(r::name::MODEL_VW_INITIAL_COMMAND_LINE, "--slates --ccb_explore_adf --json --quiet --epsilon 0.0 --first_only --id N/A");
}
else if (action == CA_ACTION)
{
config.set(r::name::MODEL_VW_INITIAL_COMMAND_LINE, "--cats 4 --min_value 1 --max_value 100 --bandwidth 1 --json --quiet --id N/A");
}
}
const auto JSON_CB_CONTEXT = R"({"GUser":{"id":"a","major":"eng","hobby":"hiking"},"_multi":[{"TAction":{"a1":"f1"}},{"TAction":{"a2":"f2"}}]})";
const auto JSON_CCB_CONTEXT = R"({"GUser":{"id":"a","major":"eng","hobby":"hiking"},"_multi":[{"TAction":{"a1":"f1"}},{"TAction":{"a2":"f2"}}],"_slots":[{"Slot":{"a1":"f1"}},{"Slot":{"a1":"f1"}}]})";
const auto JSON_SLATES_CONTEXT = R"({"GUser":{"id":"a","major":"eng","hobby":"hiking"},"_multi":[{"TAction":{"a1":"f1"},"_slot_id":0},{"TAction":{"a2":"f2"},"_slot_id":0},{"TAction":{"a3":"f3"},"_slot_id":1},{"TAction":{"a4":"f4"},"_slot_id":1},{"TAction":{"a5":"f5"},"_slot_id":1}],"_slots":[{"Slot":{"a1":"f1"}},{"Slot":{"a2":"f2"}}]})";
const auto JSON_CA_CONTEXT = R"({"RobotJoint1":{"friction":78}})";
int take_action(r::live_model& rl, const char *event_id, int action) {
r::api_status status;
switch(action) {
case CB_ACTION: {// "cb",
r::ranking_response response;
if(rl.choose_rank(event_id, JSON_CB_CONTEXT, response, &status))
std::cout << status.get_error_msg() << std::endl;
break;
}
case CCB_ACTION: {// "ccb",
r::multi_slot_response response;
if(rl.request_multi_slot_decision(event_id, JSON_CCB_CONTEXT, 0, response, &status) != err::success)
std::cout << status.get_error_msg() << std::endl;
break;
};
case SLATES_ACTION: {// "slates",
r::multi_slot_response response;
if(rl.request_multi_slot_decision(event_id, JSON_SLATES_CONTEXT, response, &status) != err::success)
std::cout << status.get_error_msg() << std::endl;
break;
};
case CA_ACTION: {// "ca",
r::continuous_action_response response;
if(rl.request_continuous_action(event_id, JSON_CA_CONTEXT, 0, response, &status) != err::success)
std::cout << status.get_error_msg() << std::endl;
break;
};
case F_REWARD: // "float"
if( rl.report_outcome(event_id, 1.5, &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case F_I_REWARD: // "float-int",
if( rl.report_outcome(event_id, 1, 1.5, &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case F_S_REWARD: // "float-string"
if( rl.report_outcome(event_id, "index_id", 1.5, &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case S_REWARD: // "string-reward",
if( rl.report_outcome(event_id, "reward-str", &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case S_I_REWARD: // "string-int-reward",
if( rl.report_outcome(event_id, 1, "reward-str", &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case S_S_REWARD: // "string-string-reward",
if( rl.report_outcome(event_id, "index_id", "reward-str", &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case ACTION_TAKEN:
if( rl.report_action_taken(event_id, &status) != err::success )
std::cout << status.get_error_msg() << std::endl;
break;
case CCB_BASELINE_ACTION: {// "ccb",
r::multi_slot_response response;
std::vector<int> baselines { 1, 0 };
if(rl.request_multi_slot_decision(event_id, JSON_CCB_CONTEXT, 0, response, &baselines[0], 2, &status) != err::success)
std::cout << status.get_error_msg() << std::endl;
break;
};
default:
std::cout << "Invalid action " << action << std::endl;
return -1;
}
return 0;
}
// We use this instead of rand to ensure it's xplat
int pseudo_random(int seed) {
constexpr uint64_t CONSTANT_A = 0xeece66d5deece66dULL;
constexpr uint64_t CONSTANT_C = 2147483647;
uint64_t val = CONSTANT_A * seed + CONSTANT_C;
return (int)(val & 0xFFFFFFFF);
}
int run_config(int action, int count, int initial_seed) {
u::configuration config;
load_config_from_json(action, config);
r::api_status status;
r::live_model rl(config);
if( rl.init(&status) != err::success ) {
std::cout << status.get_error_msg() << std::endl;
return -1;
}
for(int i = 0; i < count; ++i) {
char event_id[128];
if(initial_seed == -1)
strcpy(event_id, "abcdefghijklm");
else
sprintf(event_id, "%x", pseudo_random(initial_seed + i * 997739));
int r = take_action(rl, event_id, action);
if(r)
return r;
}
return 0;
}
int main(int argc, char *argv[]) {
po::options_description desc("example-gen");
std::string action_name;
bool gen_all = false;
int count = 1;
int seed = 473747277; //much random
desc.add_options()
("help", "Produce help message")
("all", "use all args")
("dedup", "Enable dedup/zstd")
("count", po::value<int>(), "Number of events to produce")
("seed", po::value<int>(), "Initial seed used to produce event ids")
("kind", po::value<std::string>(), "which kind of example to generate (cb,ccb,ccb-baseline,slates,ca,(f|s)(s|i)?-reward,action-taken)");
po::positional_options_description pd;
pd.add("kind", 1);
po::variables_map vm;
try {
store(po::command_line_parser(argc, argv).options(desc).positional(pd).run(), vm);
po::notify(vm);
gen_all = vm.count("all");
enable_dedup = vm.count("dedup");
if(vm.count("kind") > 0)
action_name = vm["kind"].as<std::string>();
if(vm.count("count") > 0)
count = vm["count"].as<int>();
if(vm.count("seed") > 0)
seed = vm["seed"].as<int>();
} catch(std::exception& e) {
std::cout << e.what() << std::endl;
std::cout << desc << std::endl;
return 0;
}
if(vm.count("help") > 0 || (action_name.empty() && !gen_all)) {
std::cout << desc << std::endl;
return 0;
}
if(gen_all) {
for(int i = 0; options[i]; ++i) {
if(run_config(i, count, seed))
return -1;
}
return 0;
}
int action = -1;
for (int i = 0; options[i]; ++i) {
if(action_name == options[i]) {
action = i;
break;
}
}
if(action == -1) {
std::cout << "Invalid action: " << action_name << std::endl;
std::cout << desc << std::endl;
return -1;
}
return run_config(action, count, seed);
} | 32.505495 | 339 | 0.629141 | [
"vector",
"model"
] |
b5857c3468df8f97f40d6085d23f965d82c03f1b | 9,671 | cpp | C++ | pepnovo/src/MSBSequence.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/MSBSequence.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/MSBSequence.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | #include "MSBlast.h"
bool MSBSequence::operator== (const MSBSequence& rhs) const
{
if (seq.size() != rhs.seq.size())
return false;
for (size_t i=0; i<seq.size(); i++)
if (seq[i] != rhs.seq[i])
return false;
return true;
}
/**********************************************************
Calcs the expected score for an MSB seq. Bases calculation
on the probabilities of the predicted amino acids, the
presence of marked aa's and the presense of problematic
combinations of amino acids. Uses lots of empirically
derived thresholds.
***********************************************************/
float MSBSequence::calcExpectedMSBScore(const Config *config)
{
// Emprical probabilities
static const float prob_R = 0.80;
static const float prob_W = 0.70;
static const float prob_N = 0.96;
static const float prob_Q = 0.96;
static const float prob_GV = 0.85;
static const float prob_VS = 0.95;
static const float prob_SV = 0.95;
static const float prob_DA = 0.90;
static const float prob_AD = 0.95;
static const float prob_AG = 0.96;
static const float prob_F_vs_Met_ox = 0.9; // probs for single aa mixup
static const float prob_K_first = 0.45;
static const float prob_K_mid = 0.25;
static const float prob_K_last = 1.0;
static const float minProbForAa = 0.275; // if the probability of the amino acid is below this, it will get
// a negative score
static const float multProbForAa = 1.0/(1.0-minProbForAa);
const int oxidizedMetAA = config->get_aa_from_label("M+16");
const size_t seqLength = seq.size();
if (seqLength<MIN_MSB_DENOVO_SEQ_LENGTH)
return NEG_INF;
vector<float> prefixScores(seqLength+1, 0.0);
vector<float> suffixScores(seqLength+1, 0.0);
if (seq[0] == X_SYM)
{
prefixScores[0]=0.0;
}
else if (seq[0] == Z_SYM)
{
prefixScores[0] = aaProbs[0]*0.5;
}
else
prefixScores[0] = aaProbs[0];
for (size_t i=1; i<seqLength; i++)
{
prefixScores[i] = prefixScores[i-1];
if (seq[i] == X_SYM)
continue;
float modProb = (aaProbs[i]- minProbForAa)*multProbForAa;
if (seq[i]==Z_SYM)
{
prefixScores[i]+= modProb*0.5;
}
else
prefixScores[i] += modProb;
}
suffixScores[seqLength]=0.0;
for (int i=seqLength-1; i>=0; i--)
{
suffixScores[i] = suffixScores[i+1];
if (seq[i]==X_SYM)
continue;
float modProb = (aaProbs[i]- minProbForAa)*multProbForAa;
if (seq[i]==Z_SYM)
{
suffixScores[i] += modProb * 0.5;
}
else
suffixScores[i] += modProb;
}
float simpleMatchScore = prefixScores[seqLength-1];
// discount occurences of substituteable single amino acids
// F <=> M* , K <=>Q
// the score adjustment works as follows:
// with prob 1-k we have the wrong amino acid, we first need to substract
// the positive score given (aaProbs[i]), and then add the mismatch
// penalty (+1).
if (seq[0] == B_SYM && seq[1] ==Lys)
{
simpleMatchScore -= ((1-prob_K_first)*(aaProbs[1]+1));
}
else if (seq[0] == B_SYM && seq[1] ==Gln)
{
simpleMatchScore -= (prob_K_first*(aaProbs[1]+1));
}
size_t start = (seq[0] == B_SYM) ? 2 : 0;
for (size_t i=start; i<seqLength-1; i++)
{
if (seq[i] == Lys)
{
simpleMatchScore -= ((1-prob_K_mid)*(aaProbs[i]+1));
}
else if (seq[i] == Gln)
{
simpleMatchScore -= (prob_K_mid*(aaProbs[i]+1));
}
}
if (seq[seqLength-1] == Lys)
{
simpleMatchScore -= ((1-prob_K_last)*(aaProbs[seqLength-1]+1));
}
else if (seq[seqLength-1] == Gln)
{
simpleMatchScore -= (prob_K_last*(aaProbs[seqLength-1]+1));
}
if (oxidizedMetAA >0)
{
for (size_t i=0; i<seqLength; i++)
{
if (seq[i] == oxidizedMetAA)
{
simpleMatchScore -= ((prob_F_vs_Met_ox)*(aaProbs[i]+1));
}
else if (seq[i] == Phe )
{
simpleMatchScore -= ((1-prob_F_vs_Met_ox)*(aaProbs[i]+1));
}
}
}
float min_score = simpleMatchScore;
// first consider single amino acids that could be replaced by doubles
// look only in the center, because if it appears on the edge, it can do
// much damage.
for (size_t i=1; i< seqLength-1; i++)
{
if (seq[i] == X_SYM)
continue;
float prob = -1.0;
switch (seq[i])
{
case Arg : prob = prob_R; break;
case Asn : prob = prob_N; break;
case Gln : prob = prob_Q; break;
case Trp : prob = prob_W; break;
}
if (prob <0)
continue;
float pre_match = prefixScores[i-1] - seqLength+ i;
float suf_match = suffixScores[i+1] - i - 1;
float mismatch_score = (pre_match>suf_match ) ? pre_match : suf_match;
float exp_score = prob * simpleMatchScore + (1-prob)*mismatch_score;
if (exp_score<min_score)
min_score=exp_score;
}
// look for double combos that appear within the peptide
for (size_t i=1; i<seqLength-2; i++)
{
if (seq[i]== X_SYM)
continue;
float prob=-1.0;
if (seq[i]==Gly && seq[i+1] == Val)
{
prob = prob_GV;
}
else if (seq[i]==Val && seq[i+1]==Ser)
{
prob = prob_VS;
}
else if (seq[i]==Ser && seq[i+1]==Val)
{
prob = prob_SV;
}
else if (seq[i]==Asp && seq[i+1]==Ala)
{
prob = prob_DA;
}
else if (seq[i]==Ala && seq[i+1]==Asp)
{
prob = prob_AD;
}
else if (seq[i]==Ala && seq[i+1]==Gly)
{
prob = prob_AG;
}
else
continue;
const float pre_match = prefixScores[i-1] - seqLength+ i;
const float suf_match = suffixScores[i+1] - i - 1;
float mismatch_score = (pre_match>suf_match ) ? pre_match : suf_match;
float exp_score = prob * simpleMatchScore + (1-prob)*mismatch_score;
if (exp_score<min_score)
min_score=exp_score;
// printf("%d : pre score %.2f suf_score: %.2f\n",i,pre_match,suf_match);
// printf("mismatach score: %.2f prob: %.2f exp_score %.2f\n",
// mismatch_score,prob,exp_score);
}
msbScore = min_score;
return min_score;
}
void MSBSequence::cloneAndReplace(const MSBSequence& org,
size_t orgPos,
size_t orgSegmentLength,
int *new_aas,
size_t newSegmentLength)
{
assert(orgSegmentLength>0 && newSegmentLength>0);
int deltaLength = newSegmentLength - orgSegmentLength;
const int newSize = org.seq.size() + deltaLength;
const int orgSize = org.seq.size();
float orgProb = 1.0;
for (size_t i=0; i<orgSegmentLength; i++)
if (org.aaProbs[orgPos+i]>0.0)
orgProb *= org.aaProbs[orgPos+i];
float newProb=pow(static_cast<float>(1.0-orgProb),static_cast<float>(1.0/newSegmentLength));
if (newProb<0.03)
newProb = 0.03;
*this=org;
seq.resize(newSize);
aaProbs.resize(newSize);
markedAas.resize(newSize);
// update swap area
for (size_t i=0; i<newSegmentLength; i++)
{
const size_t pos = i+orgPos;
seq[pos]=new_aas[i];
aaProbs[pos]=newProb;
markedAas[pos]=true; // don't mess with these aas any more
if (new_aas[i] == X_SYM) // give fixed low prob for X
aaProbs[i+orgPos] = 0.05;
}
// add right portion
for (size_t i=orgPos+orgSegmentLength; i<orgSize; i++)
{
const size_t pos = i+deltaLength;
seq[pos] = org.seq[i];
aaProbs[pos]=org.aaProbs[i];
markedAas[pos] = org.markedAas[i];
}
assert(seq.size()>0);
assert(aaProbs.size() == seq.size());
assert(markedAas.size() == seq.size());
}
float MSBSequence::calcMatchScore(const Config* config, const string& pep) const
{
const string msb = makeSeqString(config);
float maxScore = -999.0;
for (size_t i=0; i<msb.length(); i++)
{
float score = 0.0;
for (size_t j=0; j<pep.length(); j++)
{
if (i+j>=msb.length())
break;
char m=msb[i+j];
char p=pep[j];
if (m==p)
{
score+=1.0;
continue;
}
if (m=='X')
continue;
if ((m=='I' || m=='L') && (p=='I' || p=='L'))
{
score+=1.0;
continue;
}
if (m == 'Z' && (p=='Q' || p=='K'))
{
score+=0.5;
continue;
}
score -= 0.5;
}
if (score > maxScore)
maxScore=score;
}
for (size_t i=0; i<pep.length(); i++)
{
float score = 0.0;
for (size_t j=0; j<msb.length(); j++)
{
if (i+j>=pep.length())
break;
char p=pep[i+j];
char m=msb[j];
if (m==p)
{
score+=1.0;
continue;
}
if ((m=='I' || m=='L') && (p=='I' || p=='L'))
{
score+=1.0;
continue;
}
if (m == 'Z' && (p=='Q' || p=='K'))
{
score+=0.5;
continue;
}
score -= 0.5;
}
if (score > maxScore)
maxScore=score;
}
return maxScore;
}
string MSBSequence::makeSeqString(const Config* config) const
{
ostringstream oss;
if (seq.size()<=0)
return (std::string());
const vector<char>& aa2Char = config->get_aa2char();
const vector<int>& orgAAs = config->get_org_aa();
for (size_t i=0; i<seq.size(); i++)
{
if (seq[i] == B_SYM)
{
oss << "B";
continue;
}
if (seq[i] == X_SYM)
{
oss << "X";
continue;
}
if (seq[i] == Z_SYM)
{
oss << "Z";
continue;
}
if (seq[i]>Val)
{
oss << aa2Char[orgAAs[seq[i]]];
oss << ".";
continue;
}
assert(seq[i]>=Ala && seq[i]<=Val);
oss << aa2Char[seq[i]];
}
return oss.str();
}
void MSBSequence::print(const Config* config) const
{
cout << setprecision(3) << fixed;
cout << msbScore << "\t" << makeSeqString(config);
for (size_t j=0; j<aaProbs.size(); j++)
cout << " " << aaProbs[j];
cout << "\t";
for (size_t k=0; k<markedAas.size(); k++)
if (markedAas[k])
{
cout << "1";
}
else
cout << "0";
}
| 22.130435 | 109 | 0.574604 | [
"vector"
] |
b585fc28a3da588db302d0baf0aabd592199eb52 | 4,123 | hpp | C++ | include/oglplus/error/object.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | include/oglplus/error/object.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | include/oglplus/error/object.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /**
* @file oglplus/error/object.hpp
* @brief Declaration of OGLplus object-related error
*
* @author Matus Chochlik
*
* Copyright 2010-2019 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_ERROR_OBJECT_1107121317_HPP
#define OGLPLUS_ERROR_OBJECT_1107121317_HPP
#include <oglplus/error/basic.hpp>
#include <oglplus/object/name.hpp>
#include <oglplus/object/tags.hpp>
#include <oglplus/object/type.hpp>
namespace oglplus {
/// Exception class for GL object-related errors
class ObjectError : public Error {
private:
#if !OGLPLUS_ERROR_NO_OBJECT_TYPE
GLenum _obj_type;
#endif
#if !OGLPLUS_ERROR_NO_BIND_TARGET
GLenum _bind_tgt;
#endif
#if !OGLPLUS_ERROR_NO_TARGET_NAME
const char* _tgt_name;
#endif
int _obj_typeid;
GLuint _obj_name;
public:
ObjectError(const char* message);
ObjectError& ObjectType(oglplus::ObjectType obj_type) {
#if !OGLPLUS_ERROR_NO_OBJECT_TYPE
_obj_type = GLenum(obj_type);
#endif
OGLPLUS_FAKE_USE(obj_type);
return *this;
}
/// Returns the object type
GLenum ObjectType() const override;
/// Returns the class name
const char* ObjectTypeName() const override;
template <typename BindTarget_>
ObjectError& BindTarget(BindTarget_ bind_tgt) {
#if !OGLPLUS_ERROR_NO_BIND_TARGET
_bind_tgt = GLenum(bind_tgt);
#endif
#if !OGLPLUS_ERROR_NO_TARGET_NAME
_tgt_name = EnumValueName(bind_tgt).c_str();
#endif
OGLPLUS_FAKE_USE(bind_tgt);
return *this;
}
/// Returns the bind target
GLenum BindTarget() const override;
/// Returns the bind target name
const char* TargetName() const override;
template <typename ObjTag>
ObjectError& Object(oglplus::ObjectName<ObjTag> object) {
#if !OGLPLUS_ERROR_NO_OBJECT_TYPE
_obj_type = GLenum(ObjTypeOps<ObjTag>::ObjectType());
#endif
_obj_typeid = ObjTag::value;
_obj_name = GetGLName(object);
return *this;
}
/// Object GL name
GLint ObjectName() const override;
/// Object textual description
const String& ObjectDesc() const override;
template <typename BindTarget_>
ObjectError& ObjectBinding(BindTarget_ bind_tgt) {
using Tag = typename ObjectTargetTag<BindTarget_>::Type;
Object(ObjBindingOps<Tag>::Binding(bind_tgt));
return BindTarget(bind_tgt);
}
template <typename BindTarget_>
ObjectError& ObjectBinding(BindTarget_ bind_tgt, GLuint index) {
using Tag = typename ObjectTargetTag<BindTarget_>::Type;
Object(ObjBindingOps<Tag>::Binding(bind_tgt, index));
return BindTarget(bind_tgt);
}
};
class ObjectPairError : public ObjectError {
private:
#if !OGLPLUS_ERROR_NO_OBJECT_TYPE
GLenum _sub_type;
#endif
int _sub_typeid;
GLuint _sub_name;
public:
ObjectPairError(const char* message);
ObjectPairError& SubjectType(oglplus::ObjectType sub_type) {
#if !OGLPLUS_ERROR_NO_OBJECT_TYPE
_sub_type = GLenum(sub_type);
#endif
OGLPLUS_FAKE_USE(sub_type);
return *this;
}
/// Returns the subject type
GLenum SubjectType() const override;
/// Returns the subject class name
const char* SubjectTypeName() const override;
template <typename ObjTag>
ObjectPairError& Subject(oglplus::ObjectName<ObjTag> subject) {
_sub_typeid = ObjTag::value;
_sub_name = GetGLName(subject);
return *this;
}
/// Subject GL name
GLint SubjectName() const override;
/// Object textual description
const String& SubjectDesc() const override;
template <typename BindTarget_>
ObjectPairError& SubjectBinding(BindTarget_ bind_tgt) {
using Tag = typename ObjectTargetTag<BindTarget_>::Type;
return Subject(ObjBindingOps<Tag>::Binding(bind_tgt));
}
};
} // namespace oglplus
#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/error/object.ipp>
#endif
#endif // include guard
| 26.429487 | 68 | 0.70798 | [
"object"
] |
b59ab2fbf51f301d0ac18ea59e24f197ccc41767 | 3,417 | cpp | C++ | src/DiMP/Graph/Tree.cpp | ytazz/DiMP | 71e680a18ed82a3a3cdacd7fcc5c165bd21f167d | [
"MIT"
] | null | null | null | src/DiMP/Graph/Tree.cpp | ytazz/DiMP | 71e680a18ed82a3a3cdacd7fcc5c165bd21f167d | [
"MIT"
] | null | null | null | src/DiMP/Graph/Tree.cpp | ytazz/DiMP | 71e680a18ed82a3a3cdacd7fcc5c165bd21f167d | [
"MIT"
] | null | null | null | #include <DiMP/Graph/Tree.h>
#include <DiMP/Graph/Object.h>
#include <DiMP/Graph/Joint.h>
#include <DiMP/Graph/Graph.h>
#include <DiMP/Render/Config.h>
namespace DiMP{;
//-------------------------------------------------------------------------------------------------
// TreeKey
void TreeKey::AddVar(Solver* solver){
Tree* tree = (Tree*)node;
int nobj = 0;
int njnt = 0;
int ndof = 0;
objects.clear();
joints .clear();
for(Object* obj : tree->objects){
objects.push_back( (ObjectKey*)obj->traj.GetKeypoint(tick) );
nobj++;
}
for(Joint* jnt : tree->joints){
joints.push_back( (JointKey*)jnt->traj.GetKeypoint(tick) );
njnt++;
ndof += jnt->dof;
}
Jv.resize(nobj);
Jw.resize(nobj);
for(int i = 0; i < nobj; i++){
Jv[i].resize(ndof);
Jw[i].resize(ndof);
}
}
void TreeKey::AddCon(Solver* solver){
}
void TreeKey::Prepare(){
Tree* tree = (Tree*)node;
// ヤコビアン
int i = 0, j, j2;
for(ObjectKey* obj : objects){
j = 0;
j2 = 0;
for(JointKey* jnt : joints){
int ndof = ((Joint*)jnt->node)->dof;
for(int n = 0; n < ndof; n++){
if(tree->dependent[i][j]){
Jv[i][j2] = jnt->Jv[n] + jnt->Jw[n] % (obj->pos_t->val - (jnt->sockObj->pos_t->val + jnt->r[n]));
Jw[i][j2] = jnt->Jw[n];
}
else{
Jv[i][j2].clear();
Jw[i][j2].clear();
}
j2++;
}
j++;
}
i++;
}
}
//-------------------------------------------------------------------------------------------------
// Tree
Tree::Tree(Graph* g, string n):TrajectoryNode(g, n){
root = 0;
type = Type::Tree;
graph->trees.Add(this);
}
Tree::~Tree(){
graph->trees.Remove(this);
}
bool Tree::IsDependent(int i, int j){
if(parObject[i] == -1)
return false;
if(parJoint[i] == j)
return true;
return IsDependent(parObject[i], j);
}
void Tree::Extract(){
objects .clear();
joints .clear();
parObject.clear();
parJoint .clear();
dependent.clear();
int dofTotal = 0;
root->tree = this;
root->treeIndex = 0;
objects .push_back(root);
parObject.push_back(-1);
parJoint .push_back(-1);
bool updated;
do{
updated = false;
for(Joint* jnt : graph->joints){
if(jnt->tree)
continue;
Object* sockObj = jnt->sock->obj;
Object* plugObj = jnt->plug->obj;
if(sockObj->tree == this && !plugObj->tree){
plugObj->tree = this;
plugObj->treeIndex = (int)objects.size();
jnt ->tree = this;
jnt ->treeIndex = (int)joints.size();
jnt ->treeDofIndex = dofTotal;
objects.push_back(plugObj);
joints .push_back(jnt );
dofTotal += jnt->dof;
uint isock;
for(isock = 0; isock < objects.size(); isock++){
if(objects[isock] == sockObj)
break;
}
parObject.push_back(isock);
parJoint .push_back((int)joints.size() - 1);
updated = true;
}
}
}
while(updated);
// 依存関係
uint nobj = (uint)objects.size();
uint njnt = (uint)joints .size();
dependent.resize(nobj);
for(uint i = 0; i < nobj; i++){
dependent[i].resize(njnt);
for(uint j = 0; j < njnt; j++)
dependent[i][j] = IsDependent(i, j);
}
}
void Tree::Prepare(){
TrajectoryNode::Prepare();
}
//-------------------------------------------------------------------------------------------------
void Trees::Extract(){
for(int i = 0; i < (int)size(); i++)
at(i)->Extract();
}
void Trees::ForwardKinematics(){
for(int i = 0; i < (int)size(); i++)
at(i)->root->ForwardKinematics();
}
}
| 19.982456 | 102 | 0.530582 | [
"render",
"object"
] |
b59f2626f5d029bc2d3094d3c0cf7cfea0752854 | 81,784 | cpp | C++ | guilib/src/DatabaseViewer.cpp | izikhuang/rtabmap | 2cc34cbe7e52d2165dc821b439ff175558d4374c | [
"BSD-3-Clause"
] | 1 | 2016-02-20T01:40:14.000Z | 2016-02-20T01:40:14.000Z | guilib/src/DatabaseViewer.cpp | izikhuang/rtabmap | 2cc34cbe7e52d2165dc821b439ff175558d4374c | [
"BSD-3-Clause"
] | null | null | null | guilib/src/DatabaseViewer.cpp | izikhuang/rtabmap | 2cc34cbe7e52d2165dc821b439ff175558d4374c | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
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.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
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.
*/
#include "rtabmap/gui/DatabaseViewer.h"
#include "rtabmap/gui/CloudViewer.h"
#include "ui_DatabaseViewer.h"
#include <QtGui/QMessageBox>
#include <QtGui/QFileDialog>
#include <QtGui/QInputDialog>
#include <QtGui/QGraphicsLineItem>
#include <QtGui/QCloseEvent>
#include <QtGui/QGraphicsOpacityEffect>
#include <QtCore/QBuffer>
#include <QtCore/QTextStream>
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UConversion.h>
#include <opencv2/core/core_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <rtabmap/utilite/UTimer.h>
#include "rtabmap/core/Memory.h"
#include "rtabmap/core/DBDriver.h"
#include "rtabmap/gui/KeypointItem.h"
#include "rtabmap/gui/UCv2Qt.h"
#include "rtabmap/core/util3d.h"
#include "rtabmap/core/Signature.h"
#include "rtabmap/core/Features2d.h"
#include "rtabmap/core/Compression.h"
#include "rtabmap/core/Graph.h"
#include "rtabmap/gui/DataRecorder.h"
#include "rtabmap/core/SensorData.h"
#include "ExportDialog.h"
#include "DetailedProgressDialog.h"
#include <pcl/io/pcd_io.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/common/transforms.h>
namespace rtabmap {
DatabaseViewer::DatabaseViewer(QWidget * parent) :
QMainWindow(parent),
memory_(0)
{
pathDatabase_ = QDir::homePath()+"/Documents/RTAB-Map"; //use home directory by default
if(!UDirectory::exists(pathDatabase_.toStdString()))
{
pathDatabase_ = QDir::homePath();
}
ui_ = new Ui_DatabaseViewer();
ui_->setupUi(this);
ui_->dockWidget_constraints->setVisible(false);
ui_->dockWidget_graphView->setVisible(false);
ui_->dockWidget_icp->setVisible(false);
ui_->dockWidget_visual->setVisible(false);
ui_->dockWidget_stereoView->setVisible(false);
ui_->dockWidget_icp->setFloating(true);
ui_->dockWidget_visual->setFloating(true);
ui_->menuView->addAction(ui_->dockWidget_constraints->toggleViewAction());
ui_->menuView->addAction(ui_->dockWidget_graphView->toggleViewAction());
ui_->menuView->addAction(ui_->dockWidget_icp->toggleViewAction());
ui_->menuView->addAction(ui_->dockWidget_visual->toggleViewAction());
ui_->menuView->addAction(ui_->dockWidget_stereoView->toggleViewAction());
connect(ui_->dockWidget_graphView->toggleViewAction(), SIGNAL(triggered()), this, SLOT(updateGraphView()));
connect(ui_->actionQuit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui_->buttonBox, SIGNAL(rejected()), this, SLOT(close()));
// connect actions with custom slots
connect(ui_->actionOpen_database, SIGNAL(triggered()), this, SLOT(openDatabase()));
connect(ui_->actionExport, SIGNAL(triggered()), this, SLOT(exportDatabase()));
connect(ui_->actionExtract_images, SIGNAL(triggered()), this, SLOT(extractImages()));
connect(ui_->actionGenerate_graph_dot, SIGNAL(triggered()), this, SLOT(generateGraph()));
connect(ui_->actionGenerate_local_graph_dot, SIGNAL(triggered()), this, SLOT(generateLocalGraph()));
connect(ui_->actionGenerate_TORO_graph_graph, SIGNAL(triggered()), this, SLOT(generateTOROGraph()));
connect(ui_->actionView_3D_map, SIGNAL(triggered()), this, SLOT(view3DMap()));
connect(ui_->actionGenerate_3D_map_pcd, SIGNAL(triggered()), this, SLOT(generate3DMap()));
connect(ui_->actionDetect_more_loop_closures, SIGNAL(triggered()), this, SLOT(detectMoreLoopClosures()));
connect(ui_->actionRefine_all_neighbor_links, SIGNAL(triggered()), this, SLOT(refineAllNeighborLinks()));
connect(ui_->actionRefine_all_loop_closure_links, SIGNAL(triggered()), this, SLOT(refineAllLoopClosureLinks()));
connect(ui_->actionVisual_Refine_all_neighbor_links, SIGNAL(triggered()), this, SLOT(refineVisuallyAllNeighborLinks()));
connect(ui_->actionVisual_Refine_all_loop_closure_links, SIGNAL(triggered()), this, SLOT(refineVisuallyAllLoopClosureLinks()));
//ICP buttons
connect(ui_->pushButton_refine, SIGNAL(clicked()), this, SLOT(refineConstraint()));
connect(ui_->pushButton_refineVisually, SIGNAL(clicked()), this, SLOT(refineConstraintVisually()));
connect(ui_->pushButton_add, SIGNAL(clicked()), this, SLOT(addConstraint()));
connect(ui_->pushButton_reset, SIGNAL(clicked()), this, SLOT(resetConstraint()));
connect(ui_->pushButton_reject, SIGNAL(clicked()), this, SLOT(rejectConstraint()));
ui_->pushButton_refine->setEnabled(false);
ui_->pushButton_refineVisually->setEnabled(false);
ui_->pushButton_add->setEnabled(false);
ui_->pushButton_reset->setEnabled(false);
ui_->pushButton_reject->setEnabled(false);
ui_->actionGenerate_TORO_graph_graph->setEnabled(false);
ui_->horizontalSlider_A->setTracking(false);
ui_->horizontalSlider_B->setTracking(false);
ui_->horizontalSlider_A->setEnabled(false);
ui_->horizontalSlider_B->setEnabled(false);
connect(ui_->horizontalSlider_A, SIGNAL(valueChanged(int)), this, SLOT(sliderAValueChanged(int)));
connect(ui_->horizontalSlider_B, SIGNAL(valueChanged(int)), this, SLOT(sliderBValueChanged(int)));
connect(ui_->horizontalSlider_A, SIGNAL(sliderMoved(int)), this, SLOT(sliderAMoved(int)));
connect(ui_->horizontalSlider_B, SIGNAL(sliderMoved(int)), this, SLOT(sliderBMoved(int)));
ui_->horizontalSlider_neighbors->setTracking(false);
ui_->horizontalSlider_loops->setTracking(false);
ui_->horizontalSlider_neighbors->setEnabled(false);
ui_->horizontalSlider_loops->setEnabled(false);
connect(ui_->horizontalSlider_neighbors, SIGNAL(valueChanged(int)), this, SLOT(sliderNeighborValueChanged(int)));
connect(ui_->horizontalSlider_loops, SIGNAL(valueChanged(int)), this, SLOT(sliderLoopValueChanged(int)));
connect(ui_->horizontalSlider_neighbors, SIGNAL(sliderMoved(int)), this, SLOT(sliderNeighborValueChanged(int)));
connect(ui_->horizontalSlider_loops, SIGNAL(sliderMoved(int)), this, SLOT(sliderLoopValueChanged(int)));
connect(ui_->checkBox_showOptimized, SIGNAL(stateChanged(int)), this, SLOT(updateConstraintView()));
ui_->checkBox_showOptimized->setEnabled(false);
ui_->horizontalSlider_iterations->setTracking(false);
ui_->dockWidget_graphView->setEnabled(false);
connect(ui_->horizontalSlider_iterations, SIGNAL(valueChanged(int)), this, SLOT(sliderIterationsValueChanged(int)));
connect(ui_->horizontalSlider_iterations, SIGNAL(sliderMoved(int)), this, SLOT(sliderIterationsValueChanged(int)));
connect(ui_->spinBox_iterations, SIGNAL(editingFinished()), this, SLOT(updateGraphView()));
connect(ui_->spinBox_optimizationsFrom, SIGNAL(editingFinished()), this, SLOT(updateGraphView()));
connect(ui_->checkBox_initGuess, SIGNAL(stateChanged(int)), this, SLOT(updateGraphView()));
connect(ui_->checkBox_ignoreCovariance, SIGNAL(stateChanged(int)), this, SLOT(updateGraphView()));
ui_->constraintsViewer->setCameraLockZ(false);
ui_->constraintsViewer->setCameraFree();
}
DatabaseViewer::~DatabaseViewer()
{
delete ui_;
if(memory_)
{
delete memory_;
}
}
void DatabaseViewer::openDatabase()
{
QString path = QFileDialog::getOpenFileName(this, tr("Select file"), pathDatabase_, tr("Databases (*.db)"));
if(!path.isEmpty())
{
openDatabase(path);
}
}
bool DatabaseViewer::openDatabase(const QString & path)
{
UDEBUG("Open database \"%s\"", path.toStdString().c_str());
if(QFile::exists(path))
{
if(memory_)
{
delete memory_;
memory_ = 0;
ids_.clear();
idToIndex_.clear();
neighborLinks_.clear();
loopLinks_.clear();
graphes_.clear();
poses_.clear();
links_.clear();
linksAdded_.clear();
linksRefined_.clear();
linksRemoved_.clear();
scans_.clear();
ui_->actionGenerate_TORO_graph_graph->setEnabled(false);
ui_->checkBox_showOptimized->setEnabled(false);
}
std::string driverType = "sqlite3";
rtabmap::ParametersMap parameters;
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kDbSqlite3InMemory(), "false"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemIncrementalMemory(), "false"));
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kMemInitWMWithAllNodes(), "true"));
// use BruteForce dictionary because we don't know which type of descriptors are saved in database
parameters.insert(rtabmap::ParametersPair(rtabmap::Parameters::kKpNNStrategy(), "3"));
memory_ = new rtabmap::Memory();
if(!memory_->init(path.toStdString(), false, parameters))
{
QMessageBox::warning(this, "Database error", tr("Can't open database \"%1\"").arg(path));
}
else
{
pathDatabase_ = UDirectory::getDir(path.toStdString()).c_str();
updateIds();
return true;
}
}
else
{
QMessageBox::warning(this, "Database error", tr("Database \"%1\" does not exist.").arg(path));
}
return false;
}
void DatabaseViewer::closeEvent(QCloseEvent* event)
{
if(linksAdded_.size() || linksRefined_.size() || linksRemoved_.size())
{
QMessageBox::StandardButton button = QMessageBox::question(this,
tr("Links modified"),
tr("Some links are modified (%1 added, %2 refined, %3 removed), do you want to save them?")
.arg(linksAdded_.size()).arg(linksRefined_.size()).arg(linksRemoved_.size()),
QMessageBox::Cancel | QMessageBox::Yes | QMessageBox::No,
QMessageBox::Cancel);
if(button == QMessageBox::Yes)
{
// Added links
for(std::multimap<int, rtabmap::Link>::iterator iter=linksAdded_.begin(); iter!=linksAdded_.end(); ++iter)
{
std::multimap<int, rtabmap::Link>::iterator refinedIter = rtabmap::findLink(linksRefined_, iter->second.from(), iter->second.to());
if(refinedIter != linksRefined_.end())
{
memory_->addLoopClosureLink(refinedIter->second.to(), refinedIter->second.from(), refinedIter->second.transform(), refinedIter->second.type(), refinedIter->second.variance());
}
else
{
memory_->addLoopClosureLink(iter->second.to(), iter->second.from(), iter->second.transform(), iter->second.type(), iter->second.variance());
}
}
//Refined links
for(std::multimap<int, rtabmap::Link>::iterator iter=linksRefined_.begin(); iter!=linksRefined_.end(); ++iter)
{
if(!containsLink(linksAdded_, iter->second.from(), iter->second.to()))
{
memory_->rejectLoopClosure(iter->second.to(), iter->second.from());
memory_->addLoopClosureLink(iter->second.to(), iter->second.from(), iter->second.transform(), iter->second.type(), iter->second.variance());
}
}
// Rejected links
for(std::multimap<int, rtabmap::Link>::iterator iter=linksRemoved_.begin(); iter!=linksRemoved_.end(); ++iter)
{
memory_->rejectLoopClosure(iter->second.to(), iter->second.from());
}
}
if(button == QMessageBox::Yes || button == QMessageBox::No)
{
event->accept();
}
else
{
event->ignore();
}
}
else
{
event->accept();
}
if(event->isAccepted())
{
if(memory_)
{
delete memory_;
memory_ = 0;
}
}
}
void DatabaseViewer::showEvent(QShowEvent* anEvent)
{
ui_->graphicsView_A->fitInView(ui_->graphicsView_A->sceneRect(), Qt::KeepAspectRatio);
ui_->graphicsView_B->fitInView(ui_->graphicsView_B->sceneRect(), Qt::KeepAspectRatio);
ui_->graphicsView_A->resetZoom();
ui_->graphicsView_B->resetZoom();
}
void DatabaseViewer::resizeEvent(QResizeEvent* anEvent)
{
ui_->graphicsView_A->fitInView(ui_->graphicsView_A->sceneRect(), Qt::KeepAspectRatio);
ui_->graphicsView_B->fitInView(ui_->graphicsView_B->sceneRect(), Qt::KeepAspectRatio);
ui_->graphicsView_A->resetZoom();
ui_->graphicsView_B->resetZoom();
}
void DatabaseViewer::exportDatabase()
{
if(!memory_ || ids_.size() == 0)
{
return;
}
rtabmap::ExportDialog dialog;
if(dialog.exec())
{
if(!dialog.outputPath().isEmpty())
{
int framesIgnored = dialog.framesIgnored();
QString path = dialog.outputPath();
rtabmap::DataRecorder recorder;
if(recorder.init(path, false))
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(ids_.size() / (1+framesIgnored) + 1);
progressDialog.show();
for(int i=0; i<ids_.size(); i+=1+framesIgnored)
{
int id = ids_.at(i);
Signature data = memory_->getSignatureData(id, true);
rtabmap::SensorData sensorData = data.toSensorData();
recorder.addData(sensorData);
progressDialog.appendText(tr("Exported node %1").arg(id));
progressDialog.incrementStep();
QApplication::processEvents();
}
progressDialog.setValue(progressDialog.maximumSteps());
progressDialog.appendText("Export finished!");
}
else
{
UERROR("DataRecorder init failed?!");
}
}
else
{
QMessageBox::warning(this, tr("Cannot export database"), tr("An output path must be set!"));
}
}
}
void DatabaseViewer::extractImages()
{
if(!memory_ || ids_.size() == 0)
{
return;
}
QString path = QFileDialog::getExistingDirectory(this, tr("Select directory where to save images..."), QDir::homePath());
if(!path.isNull())
{
for(int i=0; i<ids_.size(); i+=1)
{
int id = ids_.at(i);
cv::Mat compressedRgb = memory_->getImageCompressed(id);
if(!compressedRgb.empty())
{
cv::Mat imageMat = rtabmap::uncompressImage(compressedRgb);
cv::imwrite(QString("%1/%2.png").arg(path).arg(id).toStdString(), imageMat);
UINFO(QString("Saved %1/%2.png").arg(path).arg(id).toStdString().c_str());
}
}
}
}
void DatabaseViewer::updateIds()
{
if(!memory_)
{
return;
}
std::set<int> ids = memory_->getAllSignatureIds();
ids_ = QList<int>::fromStdList(std::list<int>(ids.begin(), ids.end()));
idToIndex_.clear();
for(int i=0; i<ids_.size(); ++i)
{
idToIndex_.insert(ids_[i], i);
}
poses_.clear();
links_.clear();
linksAdded_.clear();
linksRefined_.clear();
linksRemoved_.clear();
if(memory_->getLastWorkingSignature())
{
std::map<int, int> nids = memory_->getNeighborsId(memory_->getLastWorkingSignature()->id(), 0, -1, true);
memory_->getMetricConstraints(uKeys(nids), poses_, links_, true);
if(poses_.size())
{
bool nullPoses = poses_.begin()->second.isNull();
for(std::map<int,Transform>::iterator iter=poses_.begin(); iter!=poses_.end(); ++iter)
{
if((!iter->second.isNull() && nullPoses) ||
(iter->second.isNull() && !nullPoses))
{
UWARN("Mixed valid and null poses! Ignoring graph...");
poses_.clear();
links_.clear();
break;
}
}
if(nullPoses)
{
poses_.clear();
links_.clear();
}
int first = nids.begin()->first;
ui_->spinBox_optimizationsFrom->setRange(first, memory_->getLastWorkingSignature()->id());
ui_->spinBox_optimizationsFrom->setValue(first);
}
}
ui_->actionGenerate_TORO_graph_graph->setEnabled(false);
graphes_.clear();
neighborLinks_.clear();
loopLinks_.clear();
for(std::multimap<int, rtabmap::Link>::iterator iter = links_.begin(); iter!=links_.end(); ++iter)
{
if(!iter->second.transform().isNull())
{
if(iter->second.type() == rtabmap::Link::kNeighbor)
{
neighborLinks_.append(iter->second);
}
else
{
loopLinks_.append(iter->second);
}
}
else
{
UERROR("Transform null for link from %d to %d", iter->first, iter->second.to());
}
}
UINFO("Loaded %d ids", ids_.size());
if(ids_.size())
{
ui_->horizontalSlider_A->setMinimum(0);
ui_->horizontalSlider_B->setMinimum(0);
ui_->horizontalSlider_A->setMaximum(ids_.size()-1);
ui_->horizontalSlider_B->setMaximum(ids_.size()-1);
ui_->horizontalSlider_A->setEnabled(true);
ui_->horizontalSlider_B->setEnabled(true);
ui_->horizontalSlider_A->setSliderPosition(0);
ui_->horizontalSlider_B->setSliderPosition(0);
sliderAValueChanged(0);
sliderBValueChanged(0);
}
else
{
ui_->horizontalSlider_A->setEnabled(false);
ui_->horizontalSlider_B->setEnabled(false);
ui_->label_idA->setText("NaN");
ui_->label_idB->setText("NaN");
}
if(neighborLinks_.size())
{
ui_->horizontalSlider_neighbors->setMinimum(0);
ui_->horizontalSlider_neighbors->setMaximum(neighborLinks_.size()-1);
ui_->horizontalSlider_neighbors->setEnabled(true);
ui_->horizontalSlider_neighbors->setSliderPosition(0);
}
else
{
ui_->horizontalSlider_neighbors->setEnabled(false);
}
if(ids_.size())
{
updateLoopClosuresSlider();
updateGraphView();
}
}
void DatabaseViewer::generateGraph()
{
if(!memory_)
{
QMessageBox::warning(this, tr("Cannot generate a graph"), tr("A database must must loaded first...\nUse File->Open database."));
return;
}
QString path = QFileDialog::getSaveFileName(this, tr("Save File"), pathDatabase_+"/Graph.dot", tr("Graphiz file (*.dot)"));
if(!path.isEmpty())
{
memory_->generateGraph(path.toStdString());
}
}
void DatabaseViewer::generateLocalGraph()
{
if(!ids_.size() || !memory_)
{
QMessageBox::warning(this, tr("Cannot generate a graph"), tr("The database is empty..."));
return;
}
bool ok = false;
int id = QInputDialog::getInt(this, tr("Around which location?"), tr("Location ID"), ids_.first(), ids_.first(), ids_.last(), 1, &ok);
if(ok)
{
int margin = QInputDialog::getInt(this, tr("Depth around the location?"), tr("Margin"), 4, 1, 100, 1, &ok);
if(ok)
{
QString path = QFileDialog::getSaveFileName(this, tr("Save File"), pathDatabase_+"/Graph" + QString::number(id) + ".dot", tr("Graphiz file (*.dot)"));
if(!path.isEmpty())
{
std::map<int, int> ids = memory_->getNeighborsId(id, margin, -1, false);
if(ids.size() > 0)
{
ids.insert(std::pair<int,int>(id, 0));
std::set<int> idsSet;
for(std::map<int, int>::iterator iter = ids.begin(); iter!=ids.end(); ++iter)
{
idsSet.insert(idsSet.end(), iter->first);
UINFO("Node %d", iter->first);
}
UINFO("idsSet=%d", idsSet.size());
memory_->generateGraph(path.toStdString(), idsSet);
}
else
{
QMessageBox::critical(this, tr("Error"), tr("No neighbors found for signature %1.").arg(id));
}
}
}
}
}
void DatabaseViewer::generateTOROGraph()
{
std::multimap<int, Link> links = updateLinksWithModifications(links_);
if(!graphes_.size() || !links.size())
{
QMessageBox::warning(this, tr("Cannot generate a TORO graph"), tr("No poses or no links..."));
return;
}
bool ok = false;
int id = QInputDialog::getInt(this, tr("Which iteration?"), tr("Iteration (0 -> %1)").arg((int)graphes_.size()-1), (int)graphes_.size()-1, 0, graphes_.size()-1, 1, &ok);
if(ok)
{
QString path = QFileDialog::getSaveFileName(this, tr("Save File"), pathDatabase_+"/constraints" + QString::number(id) + ".graph", tr("TORO file (*.graph)"));
if(!path.isEmpty())
{
rtabmap::saveTOROGraph(path.toStdString(), uValueAt(graphes_, id), links);
}
}
}
void DatabaseViewer::view3DMap()
{
if(!ids_.size() || !memory_)
{
QMessageBox::warning(this, tr("Cannot view 3D map"), tr("The database is empty..."));
return;
}
if(graphes_.empty())
{
this->updateGraphView();
if(graphes_.empty() || ui_->horizontalSlider_iterations->maximum() != (int)graphes_.size()-1)
{
QMessageBox::warning(this, tr("Cannot generate a graph"), tr("No graph in database?!"));
return;
}
}
bool ok = false;
QStringList items;
items.append("1");
items.append("2");
items.append("4");
items.append("8");
items.append("16");
QString item = QInputDialog::getItem(this, tr("Decimation?"), tr("Image decimation"), items, 2, false, &ok);
if(ok)
{
int decimation = item.toInt();
double maxDepth = QInputDialog::getDouble(this, tr("Camera depth?"), tr("Maximum depth (m, 0=no max):"), 4.0, 0, 10, 2, &ok);
if(ok)
{
const std::map<int, Transform> & optimizedPoses = uValueAt(graphes_, ui_->horizontalSlider_iterations->value());
if(optimizedPoses.size() > 0)
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(optimizedPoses.size());
progressDialog.show();
// create a window
QDialog * window = new QDialog(this, Qt::Window);
window->setModal(this->isModal());
window->setWindowTitle(tr("3D Map"));
window->setMinimumWidth(800);
window->setMinimumHeight(600);
rtabmap::CloudViewer * viewer = new rtabmap::CloudViewer(window);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(viewer);
viewer->setCameraLockZ(false);
window->setLayout(layout);
connect(window, SIGNAL(finished(int)), viewer, SLOT(clear()));
window->show();
for(std::map<int, Transform>::const_iterator iter = optimizedPoses.begin(); iter!=optimizedPoses.end(); ++iter)
{
rtabmap::Transform pose = iter->second;
if(!pose.isNull())
{
Signature data = memory_->getSignatureData(iter->first, true);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
UASSERT(data.getImageRaw().empty() || data.getImageRaw().type()==CV_8UC3 || data.getImageRaw().type() == CV_8UC1);
UASSERT(data.getDepthRaw().empty() || data.getDepthRaw().type()==CV_8UC1 || data.getDepthRaw().type() == CV_16UC1 || data.getDepthRaw().type() == CV_32FC1);
if(data.getDepthRaw().type() == CV_8UC1)
{
cv::Mat leftImg;
if(data.getImageRaw().channels() == 3)
{
cv::cvtColor(data.getImageRaw(), leftImg, CV_BGR2GRAY);
}
else
{
leftImg = data.getImageRaw();
}
cloud = rtabmap::util3d::cloudFromDisparityRGB(
data.getImageRaw(),
util3d::disparityFromStereoImages(leftImg, data.getDepthRaw()),
data.getDepthCx(), data.getDepthCy(),
data.getDepthFx(), data.getDepthFy(),
decimation);
}
else
{
cloud = rtabmap::util3d::cloudFromDepthRGB(
data.getImageRaw(),
data.getDepthRaw(),
data.getDepthCx(), data.getDepthCy(),
data.getDepthFx(), data.getDepthFy(),
decimation);
}
if(maxDepth)
{
cloud = rtabmap::util3d::passThrough<pcl::PointXYZRGB>(cloud, "z", 0, maxDepth);
}
cloud = rtabmap::util3d::transformPointCloud<pcl::PointXYZRGB>(cloud, data.getLocalTransform());
QColor color = Qt::red;
int mapId = memory_->getMapId(iter->first);
if(mapId >= 0)
{
color = (Qt::GlobalColor)(mapId % 12 + 7 );
}
viewer->addCloud(uFormat("cloud%d", iter->first), cloud, pose, color);
UINFO("Generated %d (%d points)", iter->first, cloud->size());
progressDialog.appendText(QString("Generated %1 (%2 points)").arg(iter->first).arg(cloud->size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
}
progressDialog.setValue(progressDialog.maximumSteps());
}
else
{
QMessageBox::critical(this, tr("Error"), tr("No neighbors found for node %1.").arg(ui_->spinBox_optimizationsFrom->value()));
}
}
}
}
void DatabaseViewer::generate3DMap()
{
if(!ids_.size() || !memory_)
{
QMessageBox::warning(this, tr("Cannot generate a graph"), tr("The database is empty..."));
return;
}
bool ok = false;
QStringList items;
items.append("1");
items.append("2");
items.append("4");
items.append("8");
items.append("16");
QString item = QInputDialog::getItem(this, tr("Decimation?"), tr("Image decimation"), items, 2, false, &ok);
if(ok)
{
int decimation = item.toInt();
double maxDepth = QInputDialog::getDouble(this, tr("Camera depth?"), tr("Maximum depth (m, 0=no max):"), 4.0, 0, 10, 2, &ok);
if(ok)
{
QString path = QFileDialog::getExistingDirectory(this, tr("Save directory"), pathDatabase_);
if(!path.isEmpty())
{
const std::map<int, Transform> & optimizedPoses = uValueAt(graphes_, ui_->horizontalSlider_iterations->value());
if(optimizedPoses.size() > 0)
{
rtabmap::DetailedProgressDialog progressDialog;
progressDialog.setMaximumSteps((int)optimizedPoses.size());
progressDialog.show();
for(std::map<int, Transform>::const_iterator iter = optimizedPoses.begin(); iter!=optimizedPoses.end(); ++iter)
{
const rtabmap::Transform & pose = iter->second;
if(!pose.isNull())
{
Signature data = memory_->getSignatureData(iter->first, true);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud;
UASSERT(data.getImageRaw().empty() || data.getImageRaw().type()==CV_8UC3 || data.getImageRaw().type() == CV_8UC1);
UASSERT(data.getDepthRaw().empty() || data.getDepthRaw().type()==CV_8UC1 || data.getDepthRaw().type() == CV_16UC1 || data.getDepthRaw().type() == CV_32FC1);
if(data.getDepthRaw().type() == CV_8UC1)
{
cv::Mat leftImg;
if(data.getImageRaw().channels() == 3)
{
cv::cvtColor(data.getImageRaw(), leftImg, CV_BGR2GRAY);
}
else
{
leftImg = data.getImageRaw();
}
cloud = rtabmap::util3d::cloudFromDisparityRGB(
data.getImageRaw(),
util3d::disparityFromStereoImages(leftImg, data.getDepthRaw()),
data.getDepthCx(), data.getDepthCy(),
data.getDepthFx(), data.getDepthFy(),
decimation);
}
else
{
cloud = rtabmap::util3d::cloudFromDepthRGB(
data.getImageRaw(),
data.getDepthRaw(),
data.getDepthCx(), data.getDepthCy(),
data.getDepthFx(), data.getDepthFy(),
decimation);
}
if(maxDepth)
{
cloud = rtabmap::util3d::passThrough<pcl::PointXYZRGB>(cloud, "z", 0, maxDepth);
}
cloud = rtabmap::util3d::transformPointCloud<pcl::PointXYZRGB>(cloud, pose*data.getLocalTransform());
std::string name = uFormat("%s/node%d.pcd", path.toStdString().c_str(), iter->first);
pcl::io::savePCDFile(name, *cloud);
UINFO("Saved %s (%d points)", name.c_str(), cloud->size());
progressDialog.appendText(QString("Saved %1 (%2 points)").arg(name.c_str()).arg(cloud->size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
}
progressDialog.setValue(progressDialog.maximumSteps());
QMessageBox::information(this, tr("Finished"), tr("%1 clouds generated to %2.").arg(optimizedPoses.size()).arg(path));
}
else
{
QMessageBox::critical(this, tr("Error"), tr("No neighbors found for node %1.").arg(ui_->spinBox_optimizationsFrom->value()));
}
}
}
}
}
void DatabaseViewer::detectMoreLoopClosures()
{
const std::map<int, Transform> & optimizedPoses = graphes_.back();
int iterations = ui_->doubleSpinBox_detectMore_iterations->value();
UASSERT(iterations > 0);
int added = 0;
for(int n=0; n<iterations; ++n)
{
UINFO("iteration %d/%d", n+1, iterations);
std::multimap<int, int> clusters = rtabmap::radiusPosesClustering(
optimizedPoses,
ui_->doubleSpinBox_detectMore_radius->value(),
ui_->doubleSpinBox_detectMore_angle->value()*CV_PI/180.0);
std::set<int> addedLinks;
for(std::multimap<int, int>::iterator iter=clusters.begin(); iter!= clusters.end(); ++iter)
{
int from = iter->first;
int to = iter->second;
if(from < to)
{
from = iter->second;
to = iter->first;
}
if(!findActiveLink(from, to).isValid() && !containsLink(linksRemoved_, from, to) &&
addedLinks.find(from) == addedLinks.end() && addedLinks.find(to) == addedLinks.end())
{
if(addConstraint(from, to, true, false))
{
UINFO("Added new loop closure between %d and %d.", from, to);
++added;
addedLinks.insert(from);
addedLinks.insert(to);
}
}
}
UINFO("Iteration %d/%d: added %d loop closures.", n+1, iterations, (int)addedLinks.size()/2);
if(addedLinks.size() == 0)
{
break;
}
}
if(added)
{
this->updateGraphView();
}
UINFO("Total added %d loop closures.", added);
}
void DatabaseViewer::refineAllNeighborLinks()
{
if(neighborLinks_.size())
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(neighborLinks_.size());
progressDialog.show();
for(int i=0; i<neighborLinks_.size(); ++i)
{
int from = neighborLinks_[i].from();
int to = neighborLinks_[i].to();
this->refineConstraint(neighborLinks_[i].from(), neighborLinks_[i].to(), false);
progressDialog.appendText(tr("Refined link %1->%2 (%3/%4)").arg(from).arg(to).arg(i+1).arg(neighborLinks_.size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
this->updateGraphView();
progressDialog.setValue(progressDialog.maximumSteps());
progressDialog.appendText("Refining links finished!");
}
}
void DatabaseViewer::refineAllLoopClosureLinks()
{
if(loopLinks_.size())
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(loopLinks_.size());
progressDialog.show();
for(int i=0; i<loopLinks_.size(); ++i)
{
int from = loopLinks_[i].from();
int to = loopLinks_[i].to();
this->refineConstraint(loopLinks_[i].from(), loopLinks_[i].to(), false);
progressDialog.appendText(tr("Refined link %1->%2 (%3/%4)").arg(from).arg(to).arg(i+1).arg(loopLinks_.size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
this->updateGraphView();
progressDialog.setValue(progressDialog.maximumSteps());
progressDialog.appendText("Refining links finished!");
}
}
void DatabaseViewer::refineVisuallyAllNeighborLinks()
{
if(neighborLinks_.size())
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(neighborLinks_.size());
progressDialog.show();
for(int i=0; i<neighborLinks_.size(); ++i)
{
int from = neighborLinks_[i].from();
int to = neighborLinks_[i].to();
this->refineConstraintVisually(neighborLinks_[i].from(), neighborLinks_[i].to(), false);
progressDialog.appendText(tr("Refined link %1->%2 (%3/%4)").arg(from).arg(to).arg(i+1).arg(neighborLinks_.size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
this->updateGraphView();
progressDialog.setValue(progressDialog.maximumSteps());
progressDialog.appendText("Refining links finished!");
}
}
void DatabaseViewer::refineVisuallyAllLoopClosureLinks()
{
if(loopLinks_.size())
{
rtabmap::DetailedProgressDialog progressDialog(this);
progressDialog.setMaximumSteps(loopLinks_.size());
progressDialog.show();
for(int i=0; i<loopLinks_.size(); ++i)
{
int from = loopLinks_[i].from();
int to = loopLinks_[i].to();
this->refineConstraintVisually(loopLinks_[i].from(), loopLinks_[i].to(), false);
progressDialog.appendText(tr("Refined link %1->%2 (%3/%4)").arg(from).arg(to).arg(i+1).arg(loopLinks_.size()));
progressDialog.incrementStep();
QApplication::processEvents();
}
this->updateGraphView();
progressDialog.setValue(progressDialog.maximumSteps());
progressDialog.appendText("Refining links finished!");
}
}
void DatabaseViewer::sliderAValueChanged(int value)
{
this->update(value,
ui_->label_indexA,
ui_->label_parentsA,
ui_->label_childrenA,
ui_->graphicsView_A,
ui_->label_idA);
}
void DatabaseViewer::sliderBValueChanged(int value)
{
this->update(value,
ui_->label_indexB,
ui_->label_parentsB,
ui_->label_childrenB,
ui_->graphicsView_B,
ui_->label_idB);
}
void DatabaseViewer::update(int value,
QLabel * labelIndex,
QLabel * labelParents,
QLabel * labelChildren,
rtabmap::ImageView * view,
QLabel * labelId,
bool updateConstraintView)
{
UTimer timer;
labelIndex->setText(QString::number(value));
labelParents->clear();
labelChildren->clear();
QRectF rect;
if(value >= 0 && value < ids_.size())
{
view->clear();
view->resetTransform();
int id = ids_.at(value);
int mapId = -1;
labelId->setText(QString::number(id));
if(id>0)
{
//image
QImage img;
QImage imgDepth;
if(memory_)
{
Signature data = memory_->getSignatureData(id, true);
if(!data.getImageRaw().empty())
{
img = uCvMat2QImage(data.getImageRaw());
}
if(!data.getDepthRaw().empty())
{
imgDepth = uCvMat2QImage(data.getDepthRaw());
}
if(data.getWords().size())
{
view->setFeatures(data.getWords());
}
mapId = memory_->getMapId(id);
//stereo
if(!data.getDepthRaw().empty() && data.getDepthRaw().type() == CV_8UC1)
{
this->updateStereo(&data);
}
}
if(!imgDepth.isNull())
{
view->setImageDepth(imgDepth);
rect = imgDepth.rect();
}
else
{
ULOGGER_DEBUG("Image depth is empty");
}
if(!img.isNull())
{
view->setImage(img);
rect = img.rect();
}
else
{
ULOGGER_DEBUG("Image is empty");
}
// loops
std::map<int, rtabmap::Link> loopClosures;
loopClosures = memory_->getLoopClosureLinks(id, true);
if(loopClosures.size())
{
QString strParents, strChildren;
for(std::map<int, rtabmap::Link>::iterator iter=loopClosures.begin(); iter!=loopClosures.end(); ++iter)
{
if(iter->first < id)
{
strChildren.append(QString("%1 ").arg(iter->first));
}
else
{
strParents.append(QString("%1 ").arg(iter->first));
}
}
labelParents->setText(strParents);
labelChildren->setText(strChildren);
}
}
if(mapId>=0)
{
labelId->setText(QString("%1 [%2]").arg(id).arg(mapId));
}
else
{
labelId->setText(QString::number(id));
}
}
else
{
ULOGGER_ERROR("Slider index out of range ?");
}
updateConstraintButtons();
updateWordsMatching();
if(updateConstraintView)
{
// update constraint view
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
bool set = false;
for(int i=0; i<loopLinks_.size() || i<neighborLinks_.size(); ++i)
{
if(i < loopLinks_.size())
{
if((loopLinks_[i].from() == from && loopLinks_[i].to() == to) ||
(loopLinks_[i].from() == to && loopLinks_[i].to() == from))
{
if(i != ui_->horizontalSlider_loops->value())
{
ui_->horizontalSlider_loops->blockSignals(true);
ui_->horizontalSlider_loops->setValue(i);
ui_->horizontalSlider_loops->blockSignals(false);
this->updateConstraintView(loopLinks_.at(i),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
false);
}
ui_->horizontalSlider_neighbors->blockSignals(true);
ui_->horizontalSlider_neighbors->setValue(0);
ui_->horizontalSlider_neighbors->blockSignals(false);
set = true;
break;
}
}
if(i < neighborLinks_.size())
{
if((neighborLinks_[i].from() == from && neighborLinks_[i].to() == to) ||
(neighborLinks_[i].from() == to && neighborLinks_[i].to() == from))
{
if(i != ui_->horizontalSlider_neighbors->value())
{
ui_->horizontalSlider_neighbors->blockSignals(true);
ui_->horizontalSlider_neighbors->setValue(i);
ui_->horizontalSlider_neighbors->blockSignals(false);
this->updateConstraintView(neighborLinks_.at(i),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
false);
}
ui_->horizontalSlider_loops->blockSignals(true);
ui_->horizontalSlider_loops->setValue(0);
ui_->horizontalSlider_loops->blockSignals(false);
set = true;
break;
}
}
}
if(!set)
{
ui_->horizontalSlider_loops->blockSignals(true);
ui_->horizontalSlider_neighbors->blockSignals(true);
ui_->horizontalSlider_loops->setValue(0);
ui_->horizontalSlider_neighbors->setValue(0);
ui_->constraintsViewer->removeAllClouds();
ui_->constraintsViewer->render();
ui_->horizontalSlider_loops->blockSignals(false);
ui_->horizontalSlider_neighbors->blockSignals(false);
}
}
if(rect.isValid())
{
view->setSceneRect(rect);
}
else
{
view->setSceneRect(view->scene()->itemsBoundingRect());
}
view->fitInView(view->sceneRect(), Qt::KeepAspectRatio);
}
void DatabaseViewer::updateStereo(const Signature * data)
{
if(data && ui_->dockWidget_stereoView->isVisible() && !data->getImageRaw().empty() && !data->getDepthRaw().empty() && data->getDepthRaw().type() == CV_8UC1)
{
cv::Mat leftMono;
if(data->getImageRaw().channels() == 3)
{
cv::cvtColor(data->getImageRaw(), leftMono, CV_BGR2GRAY);
}
else
{
leftMono = data->getImageRaw();
}
UTimer timer;
// generate kpts
std::vector<cv::KeyPoint> kpts;
cv::Rect roi = Feature2D::computeRoi(leftMono, "0.03 0.03 0.04 0.04");
ParametersMap parameters;
parameters.insert(ParametersPair(Parameters::kGFTTMaxCorners(), "1000"));
parameters.insert(ParametersPair(Parameters::kGFTTMinDistance(), "5"));
Feature2D::Type type = Feature2D::kFeatureGfttBrief;
Feature2D * kptDetector = Feature2D::create(type, parameters);
kpts = kptDetector->generateKeypoints(leftMono, 0, roi);
delete kptDetector;
float timeKpt = timer.ticks();
std::vector<cv::Point2f> leftCorners;
cv::KeyPoint::convert(kpts, leftCorners);
// Find features in the new left image
std::vector<unsigned char> status;
std::vector<float> err;
std::vector<cv::Point2f> rightCorners;
cv::calcOpticalFlowPyrLK(
leftMono,
data->getDepthRaw(),
leftCorners,
rightCorners,
status,
err,
cv::Size(Parameters::defaultStereoWinSize(), Parameters::defaultStereoWinSize()), Parameters::defaultStereoMaxLevel(),
cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, Parameters::defaultStereoIterations(), Parameters::defaultStereoEps()));
float timeFlow = timer.ticks();
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
cloud->resize(kpts.size());
float bad_point = std::numeric_limits<float>::quiet_NaN ();
UASSERT(status.size() == kpts.size());
int oi = 0;
for(unsigned int i=0; i<status.size(); ++i)
{
pcl::PointXYZ pt(bad_point, bad_point, bad_point);
if(status[i])
{
float disparity = leftCorners[i].x - rightCorners[i].x;
if(disparity > 0.0f)
{
if(fabs((leftCorners[i].y-rightCorners[i].y) / (leftCorners[i].x-rightCorners[i].x)) < Parameters::defaultStereoMaxSlope())
{
pcl::PointXYZ tmpPt = util3d::projectDisparityTo3D(
leftCorners[i],
disparity,
data->getDepthCx(), data->getDepthCy(), data->getDepthFx(), data->getDepthFy());
if(pcl::isFinite(tmpPt))
{
pt = pcl::transformPoint(tmpPt, data->getLocalTransform().toEigen3f());
if(fabs(pt.x) > 2 || fabs(pt.y) > 2 || fabs(pt.z) > 2)
{
status[i] = 100; //blue
}
cloud->at(oi++) = pt;
}
}
else
{
status[i] = 101; //yellow
}
}
else
{
status[i] = 102; //magenta
}
}
}
cloud->resize(oi);
UINFO("correspondences = %d/%d (%f) (time kpt=%fs flow=%fs)",
(int)cloud->size(), (int)leftCorners.size(), float(cloud->size())/float(leftCorners.size()), timeKpt, timeFlow);
ui_->stereoViewer->updateCameraTargetPosition(Transform::getIdentity());
ui_->stereoViewer->addOrUpdateCloud("stereo", cloud);
ui_->stereoViewer->render();
std::vector<cv::KeyPoint> rightKpts;
cv::KeyPoint::convert(rightCorners, rightKpts);
std::vector<cv::DMatch> good_matches(kpts.size());
for(unsigned int i=0; i<good_matches.size(); ++i)
{
good_matches[i].trainIdx = i;
good_matches[i].queryIdx = i;
}
//
//cv::Mat imageMatches;
//cv::drawMatches( leftMono, kpts, data->getDepthRaw(), rightKpts,
// good_matches, imageMatches, cv::Scalar::all(-1), cv::Scalar::all(-1),
// std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//ui_->graphicsView_stereo->setImage(uCvMat2QImage(imageMatches));
ui_->graphicsView_stereo->scene()->clear();
ui_->graphicsView_stereo->setSceneRect(0,0,(float)leftMono.cols, (float)leftMono.rows);
ui_->graphicsView_stereo->setLinesShown(true);
ui_->graphicsView_stereo->setFeaturesShown(false);
QGraphicsPixmapItem * item1 = ui_->graphicsView_stereo->scene()->addPixmap(QPixmap::fromImage(uCvMat2QImage(data->getImageRaw())));
QGraphicsPixmapItem * item2 = ui_->graphicsView_stereo->scene()->addPixmap(QPixmap::fromImage(uCvMat2QImage(data->getDepthRaw())));
QGraphicsOpacityEffect * effect1 = new QGraphicsOpacityEffect();
QGraphicsOpacityEffect * effect2 = new QGraphicsOpacityEffect();
effect1->setOpacity(0.5);
effect2->setOpacity(0.5);
item1->setGraphicsEffect(effect1);
item2->setGraphicsEffect(effect2);
// Draw lines between corresponding features...
for(unsigned int i=0; i<kpts.size(); ++i)
{
QColor c = Qt::green;
if(status[i] == 0)
{
c = Qt::red;
}
else if(status[i] == 100)
{
c = Qt::blue;
}
else if(status[i] == 101)
{
c = Qt::yellow;
}
else if(status[i] == 102)
{
c = Qt::magenta;
}
QGraphicsLineItem * item = ui_->graphicsView_stereo->scene()->addLine(
kpts[i].pt.x,
kpts[i].pt.y,
rightKpts[i].pt.x,
rightKpts[i].pt.y,
QPen(c));
item->setZValue(1);
}
}
}
void DatabaseViewer::updateWordsMatching()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
if(from && to)
{
int alpha = 70;
ui_->graphicsView_A->clearLines();
ui_->graphicsView_A->setFeaturesColor(QColor(255, 255, 0, alpha)); // yellow
ui_->graphicsView_B->clearLines();
ui_->graphicsView_B->setFeaturesColor(QColor(255, 255, 0, alpha)); // yellow
const QMultiMap<int, KeypointItem*> & wordsA = ui_->graphicsView_A->getFeatures();
const QMultiMap<int, KeypointItem*> & wordsB = ui_->graphicsView_B->getFeatures();
if(wordsA.size() && wordsB.size())
{
QList<int> ids = wordsA.uniqueKeys();
for(int i=0; i<ids.size(); ++i)
{
if(wordsA.count(ids[i]) == 1 && wordsB.count(ids[i]) == 1)
{
// PINK features
ui_->graphicsView_A->setFeatureColor(ids[i], QColor(255, 0, 255, alpha));
ui_->graphicsView_B->setFeatureColor(ids[i], QColor(255, 0, 255, alpha));
// Add lines
// Draw lines between corresponding features...
float deltaX = ui_->graphicsView_A->sceneRect().width();
float deltaY = 0;
const KeypointItem * kptA = wordsA.value(ids[i]);
const KeypointItem * kptB = wordsB.value(ids[i]);
QGraphicsLineItem * item = ui_->graphicsView_A->scene()->addLine(
kptA->rect().x()+kptA->rect().width()/2,
kptA->rect().y()+kptA->rect().height()/2,
kptB->rect().x()+kptB->rect().width()/2+deltaX,
kptB->rect().y()+kptB->rect().height()/2+deltaY,
QPen(QColor(0, 255, 255, alpha)));
item->setVisible(ui_->graphicsView_A->isLinesShown());
item->setZValue(1);
item = ui_->graphicsView_B->scene()->addLine(
kptA->rect().x()+kptA->rect().width()/2-deltaX,
kptA->rect().y()+kptA->rect().height()/2-deltaY,
kptB->rect().x()+kptB->rect().width()/2,
kptB->rect().y()+kptB->rect().height()/2,
QPen(QColor(0, 255, 255, alpha)));
item->setVisible(ui_->graphicsView_B->isLinesShown());
item->setZValue(1);
}
}
}
}
}
void DatabaseViewer::sliderAMoved(int value)
{
ui_->label_indexA->setText(QString::number(value));
if(value>=0 && value < ids_.size())
{
ui_->label_idA->setText(QString::number(ids_.at(value)));
}
else
{
ULOGGER_ERROR("Slider index out of range ?");
}
}
void DatabaseViewer::sliderBMoved(int value)
{
ui_->label_indexB->setText(QString::number(value));
if(value>=0 && value < ids_.size())
{
ui_->label_idB->setText(QString::number(ids_.at(value)));
}
else
{
ULOGGER_ERROR("Slider index out of range ?");
}
}
void DatabaseViewer::sliderNeighborValueChanged(int value)
{
this->updateConstraintView(neighborLinks_.at(value));
}
void DatabaseViewer::sliderLoopValueChanged(int value)
{
this->updateConstraintView(loopLinks_.at(value));
}
// only called when ui_->checkBox_showOptimized state changed
void DatabaseViewer::updateConstraintView()
{
this->updateConstraintView(neighborLinks_.at(ui_->horizontalSlider_neighbors->value()),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>),
false);
}
void DatabaseViewer::updateConstraintView(const rtabmap::Link & linkIn,
const pcl::PointCloud<pcl::PointXYZ>::Ptr & cloudFrom,
const pcl::PointCloud<pcl::PointXYZ>::Ptr & cloudTo,
bool updateImageSliders)
{
std::multimap<int, Link>::iterator iter = rtabmap::findLink(linksRefined_, linkIn.from(), linkIn.to());
rtabmap::Link link = linkIn;
if(iter != linksRefined_.end())
{
link = iter->second;
}
rtabmap::Transform t = link.transform();
ui_->label_constraint->clear();
ui_->label_constraint_opt->clear();
ui_->checkBox_showOptimized->setEnabled(false);
UASSERT(!t.isNull() && memory_);
ui_->label_constraint->setText(QString("%1 (%2=%3)").arg(t.prettyPrint().c_str()).arg(QChar(0xc3, 0x03)).arg(sqrt(link.variance())));
if(link.type() == Link::kNeighbor &&
graphes_.size() &&
(int)graphes_.size()-1 == ui_->horizontalSlider_iterations->maximum())
{
std::map<int, rtabmap::Transform> & graph = uValueAt(graphes_, ui_->horizontalSlider_iterations->value());
if(link.type() == Link::kNeighbor)
{
std::map<int, rtabmap::Transform>::iterator iterFrom = graph.find(link.from());
std::map<int, rtabmap::Transform>::iterator iterTo = graph.find(link.to());
if(iterFrom != graph.end() && iterTo != graph.end())
{
ui_->checkBox_showOptimized->setEnabled(true);
Transform topt = iterFrom->second.inverse()*iterTo->second;
Transform delta = t.inverse()*topt;
Transform v1 = t.rotation()*Transform(1,0,0,0,0,0);
Transform v2 = topt.rotation()*Transform(1,0,0,0,0,0);
float a = pcl::getAngle3D(Eigen::Vector4f(v1.x(), v1.y(), v1.z(), 0), Eigen::Vector4f(v2.x(), v2.y(), v2.z(), 0));
a = (a *180.0f) / CV_PI;
ui_->label_constraint_opt->setText(QString("%1 (error=%2% a=%3)").arg(topt.prettyPrint().c_str()).arg((delta.getNorm()/t.getNorm())*100.0f).arg(a));
if(ui_->checkBox_showOptimized->isChecked())
{
t = topt;
}
}
}
}
if(updateImageSliders)
{
bool updateA = false;
bool updateB = false;
ui_->horizontalSlider_A->blockSignals(true);
ui_->horizontalSlider_B->blockSignals(true);
// set from on left and to on right
if(ui_->horizontalSlider_A->value() != idToIndex_.value(link.from()))
{
ui_->horizontalSlider_A->setValue(idToIndex_.value(link.from()));
updateA=true;
}
if(ui_->horizontalSlider_B->value() != idToIndex_.value(link.to()))
{
ui_->horizontalSlider_B->setValue(idToIndex_.value(link.to()));
updateB=true;
}
ui_->horizontalSlider_A->blockSignals(false);
ui_->horizontalSlider_B->blockSignals(false);
if(updateA)
{
this->update(idToIndex_.value(link.from()),
ui_->label_indexA,
ui_->label_parentsA,
ui_->label_childrenA,
ui_->graphicsView_A,
ui_->label_idA,
false); // don't update constraints view!
}
if(updateB)
{
this->update(idToIndex_.value(link.to()),
ui_->label_indexB,
ui_->label_parentsB,
ui_->label_childrenB,
ui_->graphicsView_B,
ui_->label_idB,
false); // don't update constraints view!
}
}
if(ui_->constraintsViewer->isVisible())
{
if(cloudFrom->size() == 0 && cloudTo->size() == 0)
{
Signature dataFrom, dataTo;
dataFrom = memory_->getSignatureData(link.from(), true);
UASSERT(dataFrom.getImageRaw().empty() || dataFrom.getImageRaw().type()==CV_8UC3 || dataFrom.getImageRaw().type() == CV_8UC1);
UASSERT(dataFrom.getDepthRaw().empty() || dataFrom.getDepthRaw().type()==CV_8UC1 || dataFrom.getDepthRaw().type() == CV_16UC1 || dataFrom.getDepthRaw().type() == CV_32FC1);
dataTo = memory_->getSignatureData(link.to(), true);
UASSERT(dataTo.getImageRaw().empty() || dataTo.getImageRaw().type()==CV_8UC3 || dataTo.getImageRaw().type() == CV_8UC1);
UASSERT(dataTo.getDepthRaw().empty() || dataTo.getDepthRaw().type()==CV_8UC1 || dataTo.getDepthRaw().type() == CV_16UC1 || dataTo.getDepthRaw().type() == CV_32FC1);
//cloud 3d
if(!ui_->checkBox_show3DWords->isChecked())
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudFrom;
if(dataFrom.getDepthRaw().type() == CV_8UC1)
{
cloudFrom = rtabmap::util3d::cloudFromStereoImages(
dataFrom.getImageRaw(),
dataFrom.getDepthRaw(),
dataFrom.getDepthCx(), dataFrom.getDepthCy(),
dataFrom.getDepthFx(), dataFrom.getDepthFy(),
1);
}
else
{
cloudFrom = rtabmap::util3d::cloudFromDepthRGB(
dataFrom.getImageRaw(),
dataFrom.getDepthRaw(),
dataFrom.getDepthCx(), dataFrom.getDepthCy(),
dataFrom.getDepthFx(), dataFrom.getDepthFy(),
1);
}
cloudFrom = rtabmap::util3d::removeNaNFromPointCloud<pcl::PointXYZRGB>(cloudFrom);
cloudFrom = rtabmap::util3d::transformPointCloud<pcl::PointXYZRGB>(cloudFrom, dataFrom.getLocalTransform());
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudTo;
if(dataTo.getDepthRaw().type() == CV_8UC1)
{
cloudTo = rtabmap::util3d::cloudFromStereoImages(
dataTo.getImageRaw(),
dataTo.getDepthRaw(),
dataTo.getDepthCx(), dataTo.getDepthCy(),
dataTo.getDepthFx(), dataTo.getDepthFy(),
1);
}
else
{
cloudTo = rtabmap::util3d::cloudFromDepthRGB(
dataTo.getImageRaw(),
dataTo.getDepthRaw(),
dataTo.getDepthCx(), dataTo.getDepthCy(),
dataTo.getDepthFx(), dataTo.getDepthFy(),
1);
}
cloudTo = rtabmap::util3d::removeNaNFromPointCloud<pcl::PointXYZRGB>(cloudTo);
cloudTo = rtabmap::util3d::transformPointCloud<pcl::PointXYZRGB>(cloudTo, t*dataTo.getLocalTransform());
if(cloudFrom->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud0", cloudFrom);
}
if(cloudTo->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud1", cloudTo);
}
}
else
{
const Signature * sFrom = memory_->getSignature(link.from());
const Signature * sTo = memory_->getSignature(link.to());
if(sFrom && sTo)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudFrom(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudTo(new pcl::PointCloud<pcl::PointXYZ>);
cloudFrom->resize(sFrom->getWords3().size());
cloudTo->resize(sTo->getWords3().size());
int i=0;
for(std::multimap<int, pcl::PointXYZ>::const_iterator iter=sFrom->getWords3().begin();
iter!=sFrom->getWords3().end();
++iter)
{
cloudFrom->at(i++) = iter->second;
}
i=0;
for(std::multimap<int, pcl::PointXYZ>::const_iterator iter=sTo->getWords3().begin();
iter!=sTo->getWords3().end();
++iter)
{
cloudTo->at(i++) = iter->second;
}
if(cloudFrom->size())
{
cloudFrom = rtabmap::util3d::removeNaNFromPointCloud<pcl::PointXYZ>(cloudFrom);
}
if(cloudTo->size())
{
cloudTo = rtabmap::util3d::removeNaNFromPointCloud<pcl::PointXYZ>(cloudTo);
cloudTo = rtabmap::util3d::transformPointCloud<pcl::PointXYZ>(cloudTo, t);
}
if(cloudFrom->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud0", cloudFrom);
}
else
{
UWARN("Empty 3D words for node %d", link.from());
}
if(cloudTo->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud1", cloudTo);
}
else
{
UWARN("Empty 3D words for node %d", link.to());
}
}
else
{
UERROR("Not found signature %d or %d in RAM", link.from(), link.to());
}
}
//cloud 2d
pcl::PointCloud<pcl::PointXYZ>::Ptr scanA, scanB;
scanA = rtabmap::util3d::laserScanToPointCloud(dataFrom.getLaserScanRaw());
scanB = rtabmap::util3d::laserScanToPointCloud(dataTo.getLaserScanRaw());
scanB = rtabmap::util3d::transformPointCloud<pcl::PointXYZ>(scanB, t);
if(scanA->size())
{
ui_->constraintsViewer->addOrUpdateCloud("scan0", scanA);
}
if(scanB->size())
{
ui_->constraintsViewer->addOrUpdateCloud("scan1", scanB);
}
}
else
{
if(cloudFrom->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud0", cloudFrom);
}
if(cloudTo->size())
{
ui_->constraintsViewer->addOrUpdateCloud("cloud1", cloudTo);
}
}
//update cordinate
ui_->constraintsViewer->updateCameraTargetPosition(t);
ui_->constraintsViewer->clearTrajectory();
ui_->constraintsViewer->render();
}
// update buttons
updateConstraintButtons();
}
void DatabaseViewer::updateConstraintButtons()
{
ui_->pushButton_refine->setEnabled(false);
ui_->pushButton_refineVisually->setEnabled(false);
ui_->pushButton_reset->setEnabled(false);
ui_->pushButton_add->setEnabled(false);
ui_->pushButton_reject->setEnabled(false);
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
if(from!=to && from && to)
{
if((!containsLink(links_, from ,to) && !containsLink(linksAdded_, from ,to)) ||
containsLink(linksRemoved_, from ,to))
{
ui_->pushButton_add->setEnabled(true);
}
}
Link currentLink = findActiveLink(from ,to);
if(currentLink.isValid() &&
((currentLink.from() == from && currentLink.to() == to) || (currentLink.from() == to && currentLink.to() == from)))
{
if(!containsLink(linksRemoved_, from ,to))
{
ui_->pushButton_reject->setEnabled(currentLink.type() != Link::kNeighbor);
}
//check for modified link
bool modified = false;
std::multimap<int, Link>::iterator iter = rtabmap::findLink(linksRefined_, currentLink.from(), currentLink.to());
if(iter != linksRefined_.end())
{
currentLink = iter->second;
ui_->pushButton_reset->setEnabled(true);
modified = true;
}
if(!modified)
{
ui_->pushButton_reset->setEnabled(false);
}
ui_->pushButton_refine->setEnabled(true);
ui_->pushButton_refineVisually->setEnabled(true);
}
}
void DatabaseViewer::sliderIterationsValueChanged(int value)
{
if(memory_ && value >=0 && value < (int)graphes_.size())
{
if(ui_->dockWidget_graphView->isVisible() && scans_.size() == 0)
{
//update scans
UINFO("Update scans list...");
for(int i=0; i<ids_.size(); ++i)
{
Signature data = memory_->getSignatureData(ids_.at(i), false);
if(!data.getLaserScanCompressed().empty())
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
cv::Mat laserScan = rtabmap::uncompressData(data.getLaserScanCompressed());
cloud = rtabmap::util3d::laserScanToPointCloud(laserScan);
scans_.insert(std::make_pair(ids_.at(i), cloud));
}
}
UINFO("Update scans list... done");
}
std::map<int, rtabmap::Transform> & graph = uValueAt(graphes_, value);
std::multimap<int, Link> links = updateLinksWithModifications(links_);
ui_->graphViewer->updateGraph(graph, links);
if(graph.size() && scans_.size())
{
float xMin, yMin;
float cell = 0.05;
cv::Mat map = rtabmap::util3d::convertMap2Image8U(rtabmap::util3d::create2DMap(graph, scans_, cell, true, xMin, yMin));
ui_->graphViewer->updateMap(map, cell, xMin, yMin);
}
ui_->label_iterations->setNum(value);
//compute total length (neighbor links)
float length = 0.0f;
for(std::multimap<int, rtabmap::Link>::const_iterator iter=links.begin(); iter!=links.end(); ++iter)
{
std::map<int, rtabmap::Transform>::const_iterator jterA = graph.find(iter->first);
std::map<int, rtabmap::Transform>::const_iterator jterB = graph.find(iter->second.to());
if(jterA != graph.end() && jterB != graph.end())
{
const rtabmap::Transform & poseA = jterA->second;
const rtabmap::Transform & poseB = jterB->second;
if(iter->second.type() == rtabmap::Link::kNeighbor)
{
Eigen::Vector3f vA, vB;
poseA.getTranslation(vA[0], vA[1], vA[2]);
poseB.getTranslation(vB[0], vB[1], vB[2]);
length += (vB - vA).norm();
}
}
}
ui_->label_pathLength->setNum(length);
}
}
void DatabaseViewer::updateGraphView()
{
if(poses_.size())
{
if(!uContains(poses_, ui_->spinBox_optimizationsFrom->value()))
{
QMessageBox::warning(this, tr(""), tr("Graph optimization from id (%1) for which node is not linked to graph.\n Minimum=%2, Maximum=%3")
.arg(ui_->spinBox_optimizationsFrom->value())
.arg(poses_.begin()->first)
.arg(poses_.rbegin()->first));
return;
}
graphes_.clear();
std::map<int, rtabmap::Transform> finalPoses;
graphes_.push_back(poses_);
ui_->actionGenerate_TORO_graph_graph->setEnabled(true);
std::multimap<int, rtabmap::Link> links = updateLinksWithModifications(links_);
std::map<int, int> depthGraph = rtabmap::generateDepthGraph(links, ui_->spinBox_optimizationsFrom->value(), 0);
rtabmap::optimizeTOROGraph(
depthGraph,
poses_,
links, finalPoses,
ui_->spinBox_iterations->value(),
ui_->checkBox_initGuess->isChecked(),
ui_->checkBox_ignoreCovariance->isChecked(),
&graphes_);
graphes_.push_back(finalPoses);
}
if(graphes_.size())
{
ui_->horizontalSlider_iterations->setMaximum(graphes_.size()-1);
ui_->horizontalSlider_iterations->setValue(graphes_.size()-1);
ui_->dockWidget_graphView->setEnabled(true);
sliderIterationsValueChanged(graphes_.size()-1);
}
else
{
ui_->dockWidget_graphView->setEnabled(false);
}
}
Link DatabaseViewer::findActiveLink(int from, int to)
{
Link link;
std::multimap<int, Link>::iterator findIter = rtabmap::findLink(linksRefined_, from ,to);
if(findIter != linksRefined_.end())
{
link = findIter->second;
}
else
{
findIter = rtabmap::findLink(linksAdded_, from ,to);
if(findIter != linksAdded_.end())
{
link = findIter->second;
}
else if(!containsLink(linksRemoved_, from ,to))
{
findIter = rtabmap::findLink(links_, from ,to);
if(findIter != links_.end())
{
link = findIter->second;
}
}
}
return link;
}
bool DatabaseViewer::containsLink(std::multimap<int, Link> & links, int from, int to)
{
return rtabmap::findLink(links, from, to) != links.end();
}
void DatabaseViewer::refineConstraint()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
refineConstraint(from, to, true);
}
void DatabaseViewer::refineConstraint(int from, int to, bool updateGraph)
{
if(from == to)
{
UWARN("Cannot refine link to same node");
return;
}
Link currentLink = findActiveLink(from, to);
if(!currentLink.isValid())
{
UERROR("Not found link! (%d->%d)", from, to);
return;
}
Transform t = currentLink.transform();
if(ui_->checkBox_showOptimized->isChecked() &&
currentLink.type() == Link::kNeighbor &&
graphes_.size() &&
(int)graphes_.size()-1 == ui_->horizontalSlider_iterations->maximum())
{
std::map<int, rtabmap::Transform> & graph = uValueAt(graphes_, ui_->horizontalSlider_iterations->value());
if(currentLink.type() == Link::kNeighbor)
{
std::map<int, rtabmap::Transform>::iterator iterFrom = graph.find(currentLink.from());
std::map<int, rtabmap::Transform>::iterator iterTo = graph.find(currentLink.to());
if(iterFrom != graph.end() && iterTo != graph.end())
{
Transform topt = iterFrom->second.inverse()*iterTo->second;
t = topt;
}
}
}
bool hasConverged = false;
double variance = -1.0;
int correspondences = 0;
Transform transform;
Signature dataFrom, dataTo;
dataFrom = memory_->getSignatureData(currentLink.from(), false);
dataTo = memory_->getSignatureData(currentLink.to(), false);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudA(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloudB(new pcl::PointCloud<pcl::PointXYZ>);
if(ui_->checkBox_icp_2d->isChecked())
{
//2D
cv::Mat oldLaserScan = rtabmap::uncompressData(dataFrom.getLaserScanCompressed());
cv::Mat newLaserScan = rtabmap::uncompressData(dataTo.getLaserScanCompressed());
if(!oldLaserScan.empty() && !newLaserScan.empty())
{
// 2D
pcl::PointCloud<pcl::PointXYZ>::Ptr oldCloud = util3d::cvMat2Cloud(oldLaserScan);
pcl::PointCloud<pcl::PointXYZ>::Ptr newCloud = util3d::cvMat2Cloud(newLaserScan, t);
//voxelize
if(ui_->doubleSpinBox_icp_voxel->value() > 0.0f)
{
oldCloud = util3d::voxelize<pcl::PointXYZ>(oldCloud, ui_->doubleSpinBox_icp_voxel->value());
newCloud = util3d::voxelize<pcl::PointXYZ>(newCloud, ui_->doubleSpinBox_icp_voxel->value());
}
if(newCloud->size() && oldCloud->size())
{
transform = util3d::icp2D(newCloud,
oldCloud,
ui_->doubleSpinBox_icp_maxCorrespDistance->value(),
ui_->spinBox_icp_iteration->value(),
&hasConverged,
&variance,
&correspondences);
}
}
}
else
{
//3D
cv::Mat depthA = rtabmap::uncompressImage(dataFrom.getDepthCompressed());
cv::Mat depthB = rtabmap::uncompressImage(dataTo.getDepthCompressed());
if(depthA.type() == CV_8UC1)
{
cv::Mat leftMono;
cv::Mat left = rtabmap::uncompressImage(dataFrom.getImageCompressed());
if(left.channels() > 1)
{
cv::cvtColor(left, leftMono, CV_BGR2GRAY);
}
else
{
leftMono = left;
}
cloudA = util3d::cloudFromDisparity(util3d::disparityFromStereoImages(leftMono, depthA), dataFrom.getDepthCx(), dataFrom.getDepthCy(), dataFrom.getDepthFx(), dataFrom.getDepthFy(), ui_->spinBox_icp_decimation->value());
if(ui_->doubleSpinBox_icp_maxDepth->value() > 0)
{
cloudA = util3d::passThrough<pcl::PointXYZ>(cloudA, "z", 0, ui_->doubleSpinBox_icp_maxDepth->value());
}
if(ui_->doubleSpinBox_icp_voxel->value() > 0)
{
cloudA = util3d::voxelize<pcl::PointXYZ>(cloudA, ui_->doubleSpinBox_icp_voxel->value());
}
cloudA = util3d::transformPointCloud<pcl::PointXYZ>(cloudA, dataFrom.getLocalTransform());
}
else
{
cloudA = util3d::getICPReadyCloud(depthA,
dataFrom.getDepthFx(), dataFrom.getDepthFy(), dataFrom.getDepthCx(), dataFrom.getDepthCy(),
ui_->spinBox_icp_decimation->value(),
ui_->doubleSpinBox_icp_maxDepth->value(),
ui_->doubleSpinBox_icp_voxel->value(),
0, // no sampling
dataFrom.getLocalTransform());
}
if(depthB.type() == CV_8UC1)
{
cv::Mat leftMono;
cv::Mat left = rtabmap::uncompressImage(dataTo.getImageCompressed());
if(left.channels() > 1)
{
cv::cvtColor(left, leftMono, CV_BGR2GRAY);
}
else
{
leftMono = left;
}
cloudB = util3d::cloudFromDisparity(util3d::disparityFromStereoImages(leftMono, depthB), dataTo.getDepthCx(), dataTo.getDepthCy(), dataTo.getDepthFx(), dataTo.getDepthFy(), ui_->spinBox_icp_decimation->value());
if(ui_->doubleSpinBox_icp_maxDepth->value() > 0)
{
cloudB = util3d::passThrough<pcl::PointXYZ>(cloudB, "z", 0, ui_->doubleSpinBox_icp_maxDepth->value());
}
if(ui_->doubleSpinBox_icp_voxel->value() > 0)
{
cloudB = util3d::voxelize<pcl::PointXYZ>(cloudB, ui_->doubleSpinBox_icp_voxel->value());
}
cloudB = util3d::transformPointCloud<pcl::PointXYZ>(cloudB, t * dataTo.getLocalTransform());
}
else
{
cloudB = util3d::getICPReadyCloud(depthB,
dataTo.getDepthFx(), dataTo.getDepthFy(), dataTo.getDepthCx(), dataTo.getDepthCy(),
ui_->spinBox_icp_decimation->value(),
ui_->doubleSpinBox_icp_maxDepth->value(),
ui_->doubleSpinBox_icp_voxel->value(),
0, // no sampling
t * dataTo.getLocalTransform());
}
if(ui_->checkBox_icp_p2plane->isChecked())
{
pcl::PointCloud<pcl::PointNormal>::Ptr cloudANormals = util3d::computeNormals(cloudA, ui_->spinBox_icp_normalKSearch->value());
pcl::PointCloud<pcl::PointNormal>::Ptr cloudBNormals = util3d::computeNormals(cloudB, ui_->spinBox_icp_normalKSearch->value());
cloudANormals = util3d::removeNaNNormalsFromPointCloud<pcl::PointNormal>(cloudANormals);
if(cloudA->size() != cloudANormals->size())
{
UWARN("removed nan normals...");
}
cloudBNormals = util3d::removeNaNNormalsFromPointCloud<pcl::PointNormal>(cloudBNormals);
if(cloudB->size() != cloudBNormals->size())
{
UWARN("removed nan normals...");
}
transform = util3d::icpPointToPlane(cloudBNormals,
cloudANormals,
ui_->doubleSpinBox_icp_maxCorrespDistance->value(),
ui_->spinBox_icp_iteration->value(),
&hasConverged,
&variance,
&correspondences);
}
else
{
transform = util3d::icp(cloudB,
cloudA,
ui_->doubleSpinBox_icp_maxCorrespDistance->value(),
ui_->spinBox_icp_iteration->value(),
&hasConverged,
&variance,
&correspondences);
}
}
if(hasConverged && !transform.isNull())
{
Link newLink(currentLink.from(), currentLink.to(), currentLink.type(), transform*t, variance);
bool updated = false;
std::multimap<int, Link>::iterator iter = linksRefined_.find(currentLink.from());
while(iter != linksRefined_.end() && iter->first == currentLink.from())
{
if(iter->second.to() == currentLink.to() &&
iter->second.type() == currentLink.type())
{
iter->second = newLink;
updated = true;
break;
}
++iter;
}
if(!updated)
{
linksRefined_.insert(std::make_pair<int, Link>(newLink.from(), newLink));
if(updateGraph)
{
this->updateGraphView();
}
}
if(ui_->dockWidget_constraints->isVisible())
{
cloudB = util3d::transformPointCloud<pcl::PointXYZ>(cloudB, transform);
this->updateConstraintView(newLink, cloudA, cloudB);
}
}
}
void DatabaseViewer::refineConstraintVisually()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
refineConstraintVisually(from, to, true);
}
void DatabaseViewer::refineConstraintVisually(int from, int to, bool updateGraph)
{
if(from == to)
{
UWARN("Cannot refine link to same node");
return;
}
Link currentLink = findActiveLink(from, to);
if(!currentLink.isValid())
{
UERROR("Not found link! (%d->%d)", from, to);
return;
}
Transform t;
std::string rejectedMsg;
double variance = -1.0;
int inliers = -1;
if(ui_->checkBox_visual_recomputeFeatures->isChecked())
{
// create a fake memory to regenerate features
ParametersMap parameters;
parameters.insert(ParametersPair(Parameters::kSURFHessianThreshold(), uNumber2Str(ui_->doubleSpinBox_visual_hessian->value())));
parameters.insert(ParametersPair(Parameters::kLccBowInlierDistance(), uNumber2Str(ui_->doubleSpinBox_visual_maxCorrespDistance->value())));
parameters.insert(ParametersPair(Parameters::kKpMaxDepth(), uNumber2Str(ui_->doubleSpinBox_visual_maxDepth->value())));
parameters.insert(ParametersPair(Parameters::kKpNndrRatio(), uNumber2Str(ui_->doubleSpinBox_visual_nndr->value())));
parameters.insert(ParametersPair(Parameters::kLccBowIterations(), uNumber2Str(ui_->spinBox_visual_iteration->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMinInliers(), uNumber2Str(ui_->spinBox_visual_minCorrespondences->value())));
parameters.insert(ParametersPair(Parameters::kMemGenerateIds(), "false"));
parameters.insert(ParametersPair(Parameters::kMemRehearsalSimilarity(), "1.0"));
parameters.insert(ParametersPair(Parameters::kKpWordsPerImage(), "0"));
Memory tmpMemory(parameters);
// Add signatures
SensorData dataFrom = memory_->getSignatureData(from, true).toSensorData();
SensorData dataTo = memory_->getSignatureData(to, true).toSensorData();
if(from > to)
{
tmpMemory.update(dataTo);
tmpMemory.update(dataFrom);
}
else
{
tmpMemory.update(dataFrom);
tmpMemory.update(dataTo);
}
t = tmpMemory.computeVisualTransform(to, from, &rejectedMsg, &inliers, &variance);
}
else
{
ParametersMap parameters;
parameters.insert(ParametersPair(Parameters::kLccBowInlierDistance(), uNumber2Str(ui_->doubleSpinBox_visual_maxCorrespDistance->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMaxDepth(), uNumber2Str(ui_->doubleSpinBox_visual_maxDepth->value())));
parameters.insert(ParametersPair(Parameters::kLccBowIterations(), uNumber2Str(ui_->spinBox_visual_iteration->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMinInliers(), uNumber2Str(ui_->spinBox_visual_minCorrespondences->value())));
memory_->parseParameters(parameters);
t = memory_->computeVisualTransform(to, from, &rejectedMsg, &inliers, &variance);
}
if(!t.isNull())
{
Link newLink(currentLink.from(), currentLink.to(), currentLink.type(), t, variance);
bool updated = false;
std::multimap<int, Link>::iterator iter = linksRefined_.find(currentLink.from());
while(iter != linksRefined_.end() && iter->first == currentLink.from())
{
if(iter->second.to() == currentLink.to() &&
iter->second.type() == currentLink.type())
{
iter->second = newLink;
updated = true;
break;
}
++iter;
}
if(!updated)
{
linksRefined_.insert(std::make_pair<int, Link>(newLink.from(), newLink));
if(updateGraph)
{
this->updateGraphView();
}
}
if(ui_->dockWidget_constraints->isVisible())
{
this->updateConstraintView(newLink);
}
}
}
void DatabaseViewer::addConstraint()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
addConstraint(from, to, false, true);
}
bool DatabaseViewer::addConstraint(int from, int to, bool silent, bool updateGraph)
{
if(from < to)
{
int tmp = to;
to = from;
from = tmp;
}
if(from == to)
{
UWARN("Cannot add link to same node");
return false;
}
bool updateSlider = false;
if(!containsLink(linksAdded_, from, to) &&
!containsLink(links_, from, to))
{
UASSERT(!containsLink(linksRemoved_, from, to));
UASSERT(!containsLink(linksRefined_, from, to));
Transform t;
std::string rejectedMsg;
double variance = -1.0;
int inliers = -1;
if(ui_->checkBox_visual_recomputeFeatures->isChecked())
{
// create a fake memory to regenerate features
ParametersMap parameters;
parameters.insert(ParametersPair(Parameters::kSURFHessianThreshold(), uNumber2Str(ui_->doubleSpinBox_visual_hessian->value())));
parameters.insert(ParametersPair(Parameters::kLccBowInlierDistance(), uNumber2Str(ui_->doubleSpinBox_visual_maxCorrespDistance->value())));
parameters.insert(ParametersPair(Parameters::kKpMaxDepth(), uNumber2Str(ui_->doubleSpinBox_visual_maxDepth->value())));
parameters.insert(ParametersPair(Parameters::kKpNndrRatio(), uNumber2Str(ui_->doubleSpinBox_visual_nndr->value())));
parameters.insert(ParametersPair(Parameters::kLccBowIterations(), uNumber2Str(ui_->spinBox_visual_iteration->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMinInliers(), uNumber2Str(ui_->spinBox_visual_minCorrespondences->value())));
parameters.insert(ParametersPair(Parameters::kMemGenerateIds(), "false"));
parameters.insert(ParametersPair(Parameters::kMemRehearsalSimilarity(), "1.0"));
parameters.insert(ParametersPair(Parameters::kKpWordsPerImage(), "0"));
Memory tmpMemory(parameters);
// Add signatures
SensorData dataFrom = memory_->getSignatureData(from, true).toSensorData();
SensorData dataTo = memory_->getSignatureData(to, true).toSensorData();
if(from > to)
{
tmpMemory.update(dataTo);
tmpMemory.update(dataFrom);
}
else
{
tmpMemory.update(dataFrom);
tmpMemory.update(dataTo);
}
t = tmpMemory.computeVisualTransform(to, from, &rejectedMsg, &inliers, &variance);
}
else
{
ParametersMap parameters;
parameters.insert(ParametersPair(Parameters::kLccBowInlierDistance(), uNumber2Str(ui_->doubleSpinBox_visual_maxCorrespDistance->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMaxDepth(), uNumber2Str(ui_->doubleSpinBox_visual_maxDepth->value())));
parameters.insert(ParametersPair(Parameters::kLccBowIterations(), uNumber2Str(ui_->spinBox_visual_iteration->value())));
parameters.insert(ParametersPair(Parameters::kLccBowMinInliers(), uNumber2Str(ui_->spinBox_visual_minCorrespondences->value())));
memory_->parseParameters(parameters);
t = memory_->computeVisualTransform(to, from, &rejectedMsg, &inliers, &variance);
}
if(t.isNull())
{
if(!silent)
{
QMessageBox::warning(this,
tr("Add link"),
tr("Cannot find a transformation between nodes %1 and %2: %3").arg(from).arg(to).arg(rejectedMsg.c_str()));
}
}
else
{
if(ui_->checkBox_visual_2d->isChecked())
{
// We are 2D here, make sure the guess has only YAW rotation
float x,y,z,r,p,yaw;
t.getTranslationAndEulerAngles(x,y,z, r,p,yaw);
t = Transform::fromEigen3f(pcl::getTransformation(x,y,0, 0, 0, yaw));
}
// transform is valid, make a link
linksAdded_.insert(std::make_pair(from, Link(from, to, Link::kUserClosure, t, variance)));
updateSlider = true;
}
}
else if(containsLink(linksRemoved_, from, to))
{
//simply remove from linksRemoved
linksRemoved_.erase(rtabmap::findLink(linksRemoved_, from, to));
updateSlider = true;
}
if(updateSlider)
{
updateLoopClosuresSlider(from, to);
if(updateGraph)
{
this->updateGraphView();
}
}
return updateSlider;
}
void DatabaseViewer::resetConstraint()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
if(from < to)
{
int tmp = to;
to = from;
from = tmp;
}
if(from == to)
{
UWARN("Cannot reset link to same node");
return;
}
std::multimap<int, Link>::iterator iter = rtabmap::findLink(linksRefined_, from, to);
if(iter != linksRefined_.end())
{
linksRefined_.erase(iter);
this->updateGraphView();
}
iter = rtabmap::findLink(links_, from, to);
if(iter != links_.end())
{
this->updateConstraintView(iter->second);
}
iter = rtabmap::findLink(linksAdded_, from, to);
if(iter != linksAdded_.end())
{
this->updateConstraintView(iter->second);
}
}
void DatabaseViewer::rejectConstraint()
{
int from = ids_.at(ui_->horizontalSlider_A->value());
int to = ids_.at(ui_->horizontalSlider_B->value());
if(from < to)
{
int tmp = to;
to = from;
from = tmp;
}
if(from == to)
{
UWARN("Cannot reject link to same node");
return;
}
bool removed = false;
// find the original one
std::multimap<int, Link>::iterator iter;
iter = rtabmap::findLink(links_, from, to);
if(iter != links_.end())
{
if(iter->second.type() == Link::kNeighbor)
{
UWARN("Cannot reject neighbor links (%d->%d)", from, to);
return;
}
linksRemoved_.insert(*iter);
removed = true;
}
// remove from refined and added
iter = rtabmap::findLink(linksRefined_, from, to);
if(iter != linksRefined_.end())
{
linksRefined_.erase(iter);
removed = true;
}
iter = rtabmap::findLink(linksAdded_, from, to);
if(iter != linksAdded_.end())
{
linksAdded_.erase(iter);
removed = true;
}
if(removed)
{
this->updateGraphView();
}
updateLoopClosuresSlider();
}
std::multimap<int, rtabmap::Link> DatabaseViewer::updateLinksWithModifications(
const std::multimap<int, rtabmap::Link> & edgeConstraints)
{
std::multimap<int, rtabmap::Link> links;
for(std::multimap<int, rtabmap::Link>::const_iterator iter=edgeConstraints.begin();
iter!=edgeConstraints.end();
++iter)
{
std::multimap<int, rtabmap::Link>::iterator findIter;
findIter = rtabmap::findLink(linksRemoved_, iter->second.from(), iter->second.to());
if(findIter != linksRemoved_.end())
{
if(!(iter->second.from() == findIter->second.from() &&
iter->second.to() == findIter->second.to() &&
iter->second.type() == findIter->second.type()))
{
UWARN("Links (%d->%d,%d) and (%d->%d,%d) are not equal!?",
iter->second.from(), iter->second.to(), iter->second.type(),
findIter->second.from(), findIter->second.to(), findIter->second.type());
}
else
{
//UINFO("Removed link (%d->%d, %d)", iter->second.from(), iter->second.to(), iter->second.type());
continue; // don't add this link
}
}
findIter = rtabmap::findLink(linksRefined_, iter->second.from(), iter->second.to());
if(findIter!=linksRefined_.end())
{
if(iter->second.from() == findIter->second.from() &&
iter->second.to() == findIter->second.to() &&
iter->second.type() == findIter->second.type())
{
links.insert(*findIter); // add the refined link
//UINFO("Updated link (%d->%d, %d)", iter->second.from(), iter->second.to(), iter->second.type());
continue;
}
else
{
UWARN("Links (%d->%d,%d) and (%d->%d,%d) are not equal!?",
iter->second.from(), iter->second.to(), iter->second.type(),
findIter->second.from(), findIter->second.to(), findIter->second.type());
}
}
links.insert(*iter); // add original link
}
//look for added links
for(std::multimap<int, rtabmap::Link>::const_iterator iter=linksAdded_.begin();
iter!=linksAdded_.end();
++iter)
{
//UINFO("Added link (%d->%d, %d)", iter->second.from(), iter->second.to(), iter->second.type());
links.insert(*iter);
}
return links;
}
void DatabaseViewer::updateLoopClosuresSlider(int from, int to)
{
int size = loopLinks_.size();
loopLinks_.clear();
std::multimap<int, Link> links = updateLinksWithModifications(links_);
int position = ui_->horizontalSlider_loops->value();
for(std::multimap<int, rtabmap::Link>::iterator iter = links.begin(); iter!=links.end(); ++iter)
{
if(!iter->second.transform().isNull())
{
if(iter->second.type() != rtabmap::Link::kNeighbor)
{
if((iter->second.from() == from && iter->second.to() == to) ||
(iter->second.to() == from && iter->second.from() == to))
{
position = loopLinks_.size();
}
loopLinks_.append(iter->second);
}
}
else
{
UERROR("Transform null for link from %d to %d", iter->first, iter->second.to());
}
}
if(loopLinks_.size())
{
ui_->horizontalSlider_loops->setMinimum(0);
ui_->horizontalSlider_loops->setMaximum(loopLinks_.size()-1);
ui_->horizontalSlider_loops->setEnabled(true);
if(position != ui_->horizontalSlider_loops->value())
{
ui_->horizontalSlider_loops->setValue(position);
}
else if(size != loopLinks_.size())
{
this->updateConstraintView(loopLinks_.at(position));
}
}
else
{
ui_->horizontalSlider_loops->setEnabled(false);
ui_->constraintsViewer->removeAllClouds();
ui_->constraintsViewer->render();
updateConstraintButtons();
}
}
} // namespace rtabmap
| 32.726691 | 223 | 0.658478 | [
"render",
"vector",
"transform",
"3d"
] |
b5a431ff0a2befca4fc09b65e2579165ceff683e | 1,565 | hpp | C++ | include/dotto/audio.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | 4 | 2018-03-05T22:51:40.000Z | 2018-03-11T00:54:38.000Z | include/dotto/audio.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | null | null | null | include/dotto/audio.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | 1 | 2019-09-14T19:44:14.000Z | 2019-09-14T19:44:14.000Z | #pragma once
#include <unordered_map>
#include <vector>
#include <string>
#include "mackron/miniaudio.h"
namespace audio
{
struct source
{
public:
source();
ma_decoder decoder;
// a volume level betewen 0 and 1
float volume;
long elapsed_time;
void close();
};
class player
{
private:
// the MAL audio player
ma_device device;
// list of active sources
std::unordered_map<int, source*> sources;
// callback for the audio playing subsystem
static void on_send_frames_to_device(
ma_device* device,
void* out,
const void* input,
ma_uint32 frame_count
);
public:
/**
* @brief loads an audio file
*
* @param path the ABSOLUTE path to the audio file
* @return source* a pointer to the audio source
*/
source* load_audio(std::string path);
/**
* @brief plays an audio source
*
* @param source the source to play
* @return int the playback ID of the source (to pause or stop it)
*/
int play(source* source, int ID);
/**
* @brief Init the audio system. Cleans up on failure.
*
* @return true
* @return false
*/
bool init();
/**
* @brief Clean up the audio system, freeing memory and such.
*
*/
void close();
};
} // namespace audio
| 20.866667 | 74 | 0.517572 | [
"vector"
] |
b283f34493aabd789ff5341f8c95e6e5f53dffd2 | 76,758 | cpp | C++ | unittest/source/ut_xmlparserwriter.cpp | onbings/bofstd | 366ff7f7d8871d5fa5785d5690d90506a7714ecc | [
"MIT"
] | null | null | null | unittest/source/ut_xmlparserwriter.cpp | onbings/bofstd | 366ff7f7d8871d5fa5785d5690d90506a7714ecc | [
"MIT"
] | 1 | 2021-03-20T14:46:54.000Z | 2021-03-20T14:47:10.000Z | unittest/source/ut_xmlparserwriter.cpp | onbings/bofstd | 366ff7f7d8871d5fa5785d5690d90506a7714ecc | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015-2025, OnBings All rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* This module implements the unit tests of the xmlparser library
*
* Name: ut_xmlparser.cpp
* Author: b.harmel@gmail.com
* Revision: 1.0
*
* Rem: Based on google test
*
* History:
*
* V 1.00 vendredi 30 mai 2014 16:51:15 b.harmel : Initial release
*/
/*** Include files ***********************************************************/
#include <gtest/gtest.h>
#include <bofstd/bofxmlwriter.h>
#include <bofstd/bofxmlparser.h>
#include <bofstd/bofsocket.h>
#include <bofstd/boffs.h>
USE_BOF_NAMESPACE()
/*** Global variables ********************************************************/
/*** Factory functions called at the beginning/end of each test case **********/
/*** Test case ******************************************************************/
#include "ut_parser.h"
BOFERR XmlParseResultUltimateCheck(uint32_t /*_Index_U32*/, const BOFPARAMETER & /*_rBofCommandlineOption_X*/, const bool _CheckOk_B, const char * /*_pOptNewVal_c*/)
{
BOFERR Rts_E = _CheckOk_B ? BOF_ERR_NO_ERROR:BOF_ERR_NO;
// printf("Check is '%s'\r\n", _CheckOk_B ? "TRUE" : "FALSE");
// printf("Op pUser %p Name %s Tp %d OldVal %p NewVal %s\r\n", _rBofCommandlineOption_X.pUser, _rBofCommandlineOption_X.Name_S.c_str(), _rBofCommandlineOption_X.ArgType_E, _rBofCommandlineOption_X.pValue, _pOptNewVal_c ? _pOptNewVal_c : "nullptr");
return Rts_E;
}
bool XmlParseError(int /*_Sts_i*/, const BOFPARAMETER & /*_rXmlEntry_X*/, const char * /*_pValue*/)
{
bool Rts_B = true;
// printf("XML error %d on entry pUser %p value %s\r\n", _Sts_i, _rXmlEntry_X.pUser, _pValue ? _pValue : "nullptr");
return Rts_B;
}
BOFERR XmlWriteResultUltimateCheck(uint32_t /*_Index_U32*/, const BOFPARAMETER & /*_rBofCommandlineOption_X*/, const bool _CheckOk_B, const char * /*_pOptNewVal_c*/)
{
BOFERR Rts_E = _CheckOk_B ? BOF_ERR_NO_ERROR:BOF_ERR_NO;
// printf("Check is '%s'\r\n", _CheckOk_B ? "TRUE" : "FALSE");
// printf("Op pUser %p Name %s Tp %d OldVal %p NewVal %s\r\n", _rBofCommandlineOption_X.pUser, _rBofCommandlineOption_X.Name_S.c_str(), _rBofCommandlineOption_X.ArgType_E, _rBofCommandlineOption_X.pValue, _pOptNewVal_c ? _pOptNewVal_c : "nullptr");
return Rts_E;
}
bool XmlWriteError(int /*_Sts_i*/, const BOFPARAMETER & /*_rXmlEntry_X*/, const char * /*_pValue*/)
{
bool Rts_B = true;
// printf("XML error %d on entry pUser %p value %s\r\n", _Sts_i, _rXmlEntry_X.pUser, _pValue ? _pValue : "nullptr");
return Rts_B;
}
static APPPARAM S_AppParamXml_X;
static std::vector< BOFPARAMETER > S_pOptionXml_X =
{
{ nullptr, "DeployIpAddress", "DeployIpAddress", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.DeployIpAddress_X, IPV4, 0, 0) },
{ nullptr, "DeployIpPort", "DeployIpPort", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.DeployIpPort_U16, UINT16, 0, 0) },
{ nullptr, "DeployProtocol", "DeployProtocol", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pDeployProtocol_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pDeployProtocol_c) - 1) },
{ nullptr, "DeployDirectory", "DeployDirectory", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pDeployDirectory_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pDeployDirectory_c) - 1) },
{ nullptr, "LoginUser", "LoginUser", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pLoginUser_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pLoginUser_c) - 1) },
{ nullptr, "LoginPassword", "LoginPassword", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pLoginPassword_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pLoginPassword_c) - 1) },
{ nullptr, "Email", "Email", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pEmail_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pEmail_c) - 1) },
{ nullptr, "UserName", "UserName", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pUserName_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pUserName_c) - 1) },
{ nullptr, "UserCompany", "UserCompany", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pUserCompany_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pUserCompany_c) - 1) },
{ nullptr, "ToolChainBaseDirectory", "ToolChainBaseDirectory", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pToolChainBaseDirectory_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pToolChainBaseDirectory_c) - 1) },
{ nullptr, "TemplateProjectBaseDirectory", "TemplateProjectBaseDirectory", "", "MulFtpUserSetting", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VARIABLE(S_AppParamXml_X.pTemplateProjectBaseDirectory_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pTemplateProjectBaseDirectory_c) - 1) },
// For xml serialize xml array entry must be contiguous MulFtpUserSetting.catalog.book
{ nullptr, "id", "id", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::XML_ATTRIBUTE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pId_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pBook_X[0].pId_c) - 1) },
{ nullptr, "author", "author", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pAuthor_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pBook_X[0].pAuthor_c) - 1) },
{ nullptr, "title", "title", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pTitle_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pBook_X[0].pTitle_c) - 1) },
{ nullptr, "genre", "genre", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pGenre_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pBook_X[0].pGenre_c) - 1) },
{ nullptr, "price", "price", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, Price_f, FLOAT, 0, 0) },
// BAD for json { nullptr, "tag", "dbg1", "", "MulFtpUserSetting.catalog.book.bhaattr", BOFPARAMETER_ARG_FLAG::XML_ATTRIBUTE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pBha1_c, CHARSTRING, 0, 0) },
{ nullptr, "bha", "dbg2", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pBha2_c, CHARSTRING, 0, 0) },
{ nullptr, "publish_date", "publish_date", "%Y-%m-%d", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, PublishDate_X, DATE, 0, 0) },
{ nullptr, "description", "description", "", "MulFtpUserSetting.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(BOOKPARAM, S_AppParamXml_X.pBook_X, pDescription_c, CHARSTRING, 1, sizeof(S_AppParamXml_X.pBook_X[0].pDescription_c) - 1) },
{ nullptr, "a", "other a", "", "MulFtpUserSetting.arrayofother.other", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(OTHER, S_AppParamXml_X.pOther_X, a_U32, UINT32, 0, 0) },
{ nullptr, "b", "other b", "", "MulFtpUserSetting.arrayofother.other", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(OTHER, S_AppParamXml_X.pOther_X, b_U32, UINT32, 0, 0) },
{ nullptr, "c", "other c", "", "MulFtpUserSetting.arrayofother.other", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_ARRAY_OF_STRUCT(OTHER, S_AppParamXml_X.pOther_X, c_U32, UINT32, 0, 0) },
};
TEST(XmlParser_Test, Xml)
{
int Sts_i;
BofXmlParser *pBofXmlParser_O;
const char *pValue_c;
BofPath CrtDir, Path;
std::string XmlData_S;
S_AppParamXml_X.Reset();
Bof_GetCurrentDirectory(CrtDir);
Path = CrtDir + "xmlparser.xml";
EXPECT_EQ(Bof_ReadFile(Path, XmlData_S), BOF_ERR_NO_ERROR);
pBofXmlParser_O = new BofXmlParser(XmlData_S);
EXPECT_TRUE(pBofXmlParser_O != nullptr);
Sts_i = pBofXmlParser_O->ToByte(S_pOptionXml_X, XmlParseResultUltimateCheck, XmlParseError);
EXPECT_EQ(Sts_i, 0);
// Check S_AppParam_X content
pValue_c = pBofXmlParser_O->GetFirstElementFromOid(false, "MulFtpUserSetting.DeployIpAddress");
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetNextElementFromOid();
EXPECT_TRUE(pValue_c == nullptr);
pValue_c = pBofXmlParser_O->GetFirstElementFromOid(true, "MulFtpUserSetting.catalog.book.id");
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetNextElementFromOid();
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetFirstElementFromOid(true, "MulFtpUserSetting.catalog.book.bhaattr.tag");
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetNextElementFromOid();
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetNextElementFromOid();
EXPECT_TRUE(pValue_c != nullptr);
pValue_c = pBofXmlParser_O->GetNextElementFromOid();
EXPECT_TRUE(pValue_c == nullptr);
BOF_SAFE_DELETE(pBofXmlParser_O);
}
static APPPARAMVECTOR S_AppParamVector_X;
static std::vector< BOFPARAMETER > S_pOptionVector_X =
{
{ nullptr, "id", "id", "", "XmlVector.catalog.book", BOFPARAMETER_ARG_FLAG::XML_ATTRIBUTE, BOF_PARAM_DEF_VECTOR(S_AppParamVector_X.IdCollection, STDSTRING, 1, 0x1000) },
{ nullptr, "author", "Pure vector of std::string.", "", "XmlVector.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VECTOR(S_AppParamVector_X.StringCollection, STDSTRING, 1, 0x1000) },
{ nullptr, "price", "Pure vector of float.", "", "XmlVector.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VECTOR(S_AppParamVector_X.FloatCollection, FLOAT, 0, 0) },
{ nullptr, "publish_date", "Pure vector of struct tm.", "%Y-%m-%d", "XmlVector.catalog.book", BOFPARAMETER_ARG_FLAG::NONE, BOF_PARAM_DEF_VECTOR(S_AppParamVector_X.DateTimeCollection, DATE, 0,0) },
};
TEST(XmlParser_Test, XmlVector)
{
int Sts_i;
BofXmlParser *pBofXmlParser_O;
BofPath CrtDir, Path;
std::string XmlData_S;
S_AppParamVector_X.Reset();
Bof_GetCurrentDirectory(CrtDir);
Path = CrtDir + "xmlvectorparser.xml";
EXPECT_EQ(Bof_ReadFile(Path, XmlData_S), BOF_ERR_NO_ERROR);
pBofXmlParser_O = new BofXmlParser(XmlData_S);
EXPECT_TRUE(pBofXmlParser_O != nullptr);
std::string XmlIn_S = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<--Comment-->\n\r<MulFtpUserSetting\r\n\t xmlns : xsi = \"http://www.w3.org/2001/XMLSchema-instance\" xmlns : xsd = \"http://www.w3.org/2001/XMLSchema\">";
EXPECT_STREQ("MulFtpUserSetting", BofXmlParser::S_RootName(XmlIn_S).c_str());
EXPECT_TRUE(pBofXmlParser_O->IsValid());
EXPECT_STREQ(pBofXmlParser_O->RootName().c_str(), "XmlVector");
EXPECT_STREQ(pBofXmlParser_O->RootName().c_str(), BofXmlParser::S_RootName(XmlData_S).c_str());
Sts_i = pBofXmlParser_O->ToByte(S_pOptionVector_X, XmlParseResultUltimateCheck, XmlParseError);
EXPECT_EQ(Sts_i, 0);
BOF_SAFE_DELETE(pBofXmlParser_O);
}
TEST(XmlWriter_Test, XmlVector)
{
int Sts_i;
BofXmlParser *pBofXmlParser_O;
BofPath CrtDir, Path;
std::string XmlData_S, XmlOut_S;
BofXmlWriter BofXmlWriter_O;
S_AppParamVector_X.Reset();
Bof_GetCurrentDirectory(CrtDir);
Path = CrtDir + "xmlvectorparser.xml";
EXPECT_EQ(Bof_ReadFile(Path, XmlData_S), BOF_ERR_NO_ERROR);
pBofXmlParser_O = new BofXmlParser(XmlData_S);
EXPECT_TRUE(pBofXmlParser_O != nullptr);
XmlOut_S = "";
// Sts_i = BofXmlWriter_O.FromByte("<?xml version='1.0' encoding=\"utf-8\"?>\r\n<!--This is a comment-->\r\n", S_pOptionVector_X, XmlOut_S);
//EXPECT_EQ(Sts_i, 0);
Sts_i = pBofXmlParser_O->ToByte(S_pOptionVector_X, XmlWriteResultUltimateCheck, XmlWriteError);
EXPECT_EQ(Sts_i, 0);
XmlOut_S = "";
Sts_i = BofXmlWriter_O.FromByte("<?xml version='1.0' encoding=\"utf-8\"?>\r\n<!--This is a comment-->\r\n", S_pOptionVector_X, XmlOut_S);
EXPECT_EQ(Sts_i, 0);
std::string Res_S =
"<?xml version='1.0' encoding=\"utf-8\"?>\r\n"\
"<!--This is a comment-->\r\n"\
"<XmlVector xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n"\
"<catalog>\r\n"\
"<book id=\"bk101\">\r\n"\
"<author>Gambardella, Matthew</author>\r\n"\
"<price>44.950001</price>\r\n"\
"<publish_date>2016-05-26</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk102\">\r\n"\
"<author>Ralls, Kim</author>\r\n"\
"<price>5.950000</price>\r\n"\
"<publish_date>2000-12-16</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk103\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<price>5.950000</price>\r\n"\
"<publish_date>2000-11-17</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk104\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<price>5.950000</price>\r\n"\
"<publish_date>2001-03-10</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk105\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<price>5.950000</price>\r\n"\
"<publish_date>2001-09-10</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk106\">\r\n"\
"<author>Randall, Cynthia</author>\r\n"\
"<price>4.950000</price>\r\n"\
"<publish_date>2000-09-02</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk107\">\r\n"\
"<author>Thurman, Paula</author>\r\n"\
"<price>4.950000</price>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk108\">\r\n"\
"<author>Knorr, Stefan</author>\r\n"\
"<price>4.950000</price>\r\n"\
"<publish_date>2000-12-06</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk109\">\r\n"\
"<author>Kress, Peter</author>\r\n"\
"<price>6.950000</price>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk110\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<price>36.950001</price>\r\n"\
"<publish_date>2000-12-09</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk111\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<price>36.950001</price>\r\n"\
"<publish_date>2000-12-01</publish_date>\r\n"\
"</book>\r\n"\
"<book id=\"bk112\">\r\n"\
"<author>Galos, Mike</author>\r\n"\
"<price>49.950001</price>\r\n"\
"<publish_date>2001-04-16</publish_date>\r\n"\
"</book>\r\n"\
"<book></book>\r\n"\
"</catalog>\r\n"\
"</XmlVector>\r\n";
/*
const char *p = XmlOut_S.c_str();
const char *q = Res_S.c_str();
while (*p == *q) { printf("%c", *p); p++; q++; }
while (*p == *q) { p++; q++; }
*/
EXPECT_STREQ(XmlOut_S.c_str(), Res_S.c_str());
BOF_SAFE_DELETE(pBofXmlParser_O);
}
TEST(XmlWriter_Test, Xml)
{
int Sts_i;
BofXmlWriter BofXmlWriter_O;
BofXmlParser *pBofXmlParser_O;
BofPath CrtDir, Path;
std::string XmlData_S, XmlOut_S;
S_AppParamXml_X.Reset();
Bof_GetCurrentDirectory(CrtDir);
Path = CrtDir + "xmlparser.xml";
EXPECT_EQ(Bof_ReadFile(Path, XmlData_S), BOF_ERR_NO_ERROR);
pBofXmlParser_O = new BofXmlParser(XmlData_S);
EXPECT_TRUE(pBofXmlParser_O != nullptr);
Sts_i = pBofXmlParser_O->ToByte(S_pOptionXml_X, XmlWriteResultUltimateCheck, XmlWriteError);
EXPECT_EQ(Sts_i, 0);
Sts_i = BofXmlWriter_O.FromByte("<?xml version='1.0' encoding=\"utf-8\"?>\r\n<!--This is a comment-->\r\n", S_pOptionXml_X, XmlOut_S);
EXPECT_EQ(Sts_i, 0);
#if defined(_WIN32) //TODO comprendre: en linux toutes les fin de ligne sont \r\n, en win 32 on a un m�lange de \n et de \r\n
std::string Res_S =
"<?xml version='1.0' encoding=\"utf-8\"?>\r\n"\
"<!--This is a comment-->\r\n"\
"<MulFtpUserSetting xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n"\
"<DeployIpAddress>192.168.1.21</DeployIpAddress>\r\n"\
"<DeployIpPort>2000</DeployIpPort>\r\n"\
"<DeployProtocol>ssh</DeployProtocol>\r\n"\
"<DeployDirectory>/tmp/</DeployDirectory>\r\n"\
"<LoginUser>root</LoginUser>\r\n"\
"<LoginPassword>a</LoginPassword>\r\n"\
"<Email>b.harmel@gmail.com</Email>\r\n"\
"<UserName>b.harmel</UserName>\r\n"\
"<UserCompany>OnBings</UserCompany>\r\n"\
"<ToolChainBaseDirectory>D:\\SysGCC\\</ToolChainBaseDirectory>\r\n"\
"<TemplateProjectBaseDirectory>D:\\cloudstation\\pro\\vsmake-project-template\\</TemplateProjectBaseDirectory>\r\n"\
"<catalog>\r\n"\
"<book id=\"bk101\">\r\n"\
"<author>Gambardella, Matthew</author>\r\n"\
"<title>XML Developer's Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>44.950001</price>\r\n"\
"<bha>AZ</bha>\r\n"\
"<publish_date>2016-05-26</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tAn in-depth look at creating applications\n"\
"\t\t\t\twith XML.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk102\">\r\n"\
"<author>Ralls, Kim</author>\r\n"\
"<title>Midnight Rain</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha>QS</bha>\r\n"\
"<publish_date>2000-12-16</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tA former architect battles corporate zombies,\n"\
"\t\t\t\tan evil sorceress, and her own childhood to become queen\n"\
"\t\t\t\tof the world.\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk103\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>Maeve Ascendant</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha>WX</bha>\r\n"\
"<publish_date>2000-11-17</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tAfter the collapse of a nanotechnology\n"\
"\t\t\t\tsociety in England, the young survivors lay the\n"\
"\t\t\t\tfoundation for a new society.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk104\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>Oberon's Legacy</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-03-10</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tIn post-apocalypse England, the mysterious\n"\
"\t\t\t\tagent known only as Oberon helps to create a new life\n"\
"\t\t\t\tfor the inhabitants of London. Sequel to Maeve\n"\
"\t\t\t\tAscendant.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk105\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>The Sundered Grail</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-09-10</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tThe two daughters of Maeve, half-sisters,\n"\
"\t\t\t\tbattle one another for control of England. Sequel to\n"\
"\t\t\t\tOberon's Legacy.\n\t\t"\
"\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk106\">\r\n"\
"<author>Randall, Cynthia</author>\r\n"\
"<title>Lover Birds</title>\r\n"\
"<genre>Romance</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-09-02</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tWhen Carla meets Paul at an ornithology\n"\
"\t\t\t\tconference, tempers fly as feathers get ruffled.\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk107\">\r\n"\
"<author>Thurman, Paula</author>\r\n"\
"<title>Splish Splash</title>\r\n"\
"<genre>Romance</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tA deep sea diver finds true love twenty\n"\
"\t\t\t\tthousand leagues beneath the sea.\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk108\">\r\n"\
"<author>Knorr, Stefan</author>\r\n"\
"<title>Creepy Crawlies</title>\r\n"\
"<genre>Horror</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-06</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tAn anthology of horror stories about roaches,\n"\
"\t\t\t\tcentipedes, scorpions and other insects.\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk109\">\r\n"\
"<author>Kress, Peter</author>\r\n"\
"<title>Paradox Lost</title>\r\n"\
"<genre>Science Fiction</genre>\r\n"\
"<price>6.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tAfter an inadvertant trip through a Heisenberg\n"\
"\t\t\t\tUncertainty Device, James Salway discovers the problems\n"\
"\t\t\t\tof being quantum.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk110\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<title>Microsoft .NET: The Programming Bible</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>36.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-09</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tMicrosoft's .NET initiative is explored in\n"\
"\t\t\t\tdetail in this deep programmer's reference.\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk111\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<title>MSXML3: A Comprehensive Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>36.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-01</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tThe Microsoft MSXML3 parser is covered in\n"\
"\t\t\t\tdetail, with attention to XML DOM interfaces, XSLT processing,\n"\
"\t\t\t\tSAX and more.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk112\">\r\n"\
"<author>Galos, Mike</author>\r\n"\
"<title>Visual Studio 7: A Comprehensive Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>49.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-04-16</publish_date>\r\n"\
"<description>\n"\
"\t\t\t\tMicrosoft Visual Studio 7 is explored in depth,\n"\
"\t\t\t\tlooking at how Visual Basic, Visual C++, C#, and ASP+ are\n"\
"\t\t\t\tintegrated into a comprehensive development\n"\
"\t\t\t\tenvironment.\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book></book>\r\n"\
"</catalog>\r\n"\
"<arrayofother>\r\n"\
"<other>\r\n"\
"<a>1</a>\r\n"\
"<b>2</b>\r\n"\
"<c>3</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>4</a>\r\n"\
"<b>5</b>\r\n"\
"<c>6</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>7</a>\r\n"\
"<b>8</b>\r\n"\
"<c>9</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>10</a>\r\n"\
"<b>11</b>\r\n"\
"<c>12</c>\r\n"\
"</other>\r\n"\
"<other></other>\r\n"\
"</arrayofother>\r\n"\
"</MulFtpUserSetting>\r\n";
#else
std::string Res_S =
"<?xml version='1.0' encoding=\"utf-8\"?>\r\n"\
"<!--This is a comment-->\r\n"\
"<MulFtpUserSetting xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n"\
"<DeployIpAddress>192.168.1.21</DeployIpAddress>\r\n"\
"<DeployIpPort>2000</DeployIpPort>\r\n"\
"<DeployProtocol>ssh</DeployProtocol>\r\n"\
"<DeployDirectory>/tmp/</DeployDirectory>\r\n"\
"<LoginUser>root</LoginUser>\r\n"\
"<LoginPassword>a</LoginPassword>\r\n"\
"<Email>b.harmel@gmail.com</Email>\r\n"\
"<UserName>b.harmel</UserName>\r\n"\
"<UserCompany>OnBings</UserCompany>\r\n"\
"<ToolChainBaseDirectory>D:\\SysGCC\\</ToolChainBaseDirectory>\r\n"\
"<TemplateProjectBaseDirectory>D:\\cloudstation\\pro\\vsmake-project-template\\</TemplateProjectBaseDirectory>\r\n"\
"<catalog>\r\n"\
"<book id=\"bk101\">\r\n"\
"<author>Gambardella, Matthew</author>\r\n"\
"<title>XML Developer's Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>44.950001</price>\r\n"\
"<bha>AZ</bha>\r\n"\
"<publish_date>2016-05-26</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tAn in-depth look at creating applications\r\n"\
"\t\t\t\twith XML.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk102\">\r\n"\
"<author>Ralls, Kim</author>\r\n"\
"<title>Midnight Rain</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha>QS</bha>\r\n"\
"<publish_date>2000-12-16</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tA former architect battles corporate zombies,\r\n"\
"\t\t\t\tan evil sorceress, and her own childhood to become queen\r\n"\
"\t\t\t\tof the world.\r\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk103\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>Maeve Ascendant</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha>WX</bha>\r\n"\
"<publish_date>2000-11-17</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tAfter the collapse of a nanotechnology\r\n"\
"\t\t\t\tsociety in England, the young survivors lay the\r\n"\
"\t\t\t\tfoundation for a new society.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk104\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>Oberon's Legacy</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-03-10</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tIn post-apocalypse England, the mysterious\r\n"\
"\t\t\t\tagent known only as Oberon helps to create a new life\r\n"\
"\t\t\t\tfor the inhabitants of London. Sequel to Maeve\r\n"\
"\t\t\t\tAscendant.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk105\">\r\n"\
"<author>Corets, Eva</author>\r\n"\
"<title>The Sundered Grail</title>\r\n"\
"<genre>Fantasy</genre>\r\n"\
"<price>5.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-09-10</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tThe two daughters of Maeve, half-sisters,\r\n"\
"\t\t\t\tbattle one another for control of England. Sequel to\r\n"\
"\t\t\t\tOberon's Legacy.\r\n\t\t"\
"\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk106\">\r\n"\
"<author>Randall, Cynthia</author>\r\n"\
"<title>Lover Birds</title>\r\n"\
"<genre>Romance</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-09-02</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tWhen Carla meets Paul at an ornithology\r\n"\
"\t\t\t\tconference, tempers fly as feathers get ruffled.\r\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk107\">\r\n"\
"<author>Thurman, Paula</author>\r\n"\
"<title>Splish Splash</title>\r\n"\
"<genre>Romance</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tA deep sea diver finds true love twenty\r\n"\
"\t\t\t\tthousand leagues beneath the sea.\r\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk108\">\r\n"\
"<author>Knorr, Stefan</author>\r\n"\
"<title>Creepy Crawlies</title>\r\n"\
"<genre>Horror</genre>\r\n"\
"<price>4.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-06</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tAn anthology of horror stories about roaches,\r\n"\
"\t\t\t\tcentipedes, scorpions and other insects.\r\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk109\">\r\n"\
"<author>Kress, Peter</author>\r\n"\
"<title>Paradox Lost</title>\r\n"\
"<genre>Science Fiction</genre>\r\n"\
"<price>6.950000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-11-02</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tAfter an inadvertant trip through a Heisenberg\r\n"\
"\t\t\t\tUncertainty Device, James Salway discovers the problems\r\n"\
"\t\t\t\tof being quantum.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk110\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<title>Microsoft .NET: The Programming Bible</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>36.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-09</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tMicrosoft's .NET initiative is explored in\r\n"\
"\t\t\t\tdetail in this deep programmer's reference.\r\n\t\t\t"\
"</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk111\">\r\n"\
"<author>O'Brien, Tim</author>\r\n"\
"<title>MSXML3: A Comprehensive Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>36.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2000-12-01</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tThe Microsoft MSXML3 parser is covered in\r\n"\
"\t\t\t\tdetail, with attention to XML DOM interfaces, XSLT processing,\r\n"\
"\t\t\t\tSAX and more.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"bk112\">\r\n"\
"<author>Galos, Mike</author>\r\n"\
"<title>Visual Studio 7: A Comprehensive Guide</title>\r\n"\
"<genre>Computer</genre>\r\n"\
"<price>49.950001</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date>2001-04-16</publish_date>\r\n"\
"<description>\r\n"\
"\t\t\t\tMicrosoft Visual Studio 7 is explored in depth,\r\n"\
"\t\t\t\tlooking at how Visual Basic, Visual C++, C#, and ASP+ are\r\n"\
"\t\t\t\tintegrated into a comprehensive development\r\n"\
"\t\t\t\tenvironment.\r\n"\
"\t\t\t</description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book id=\"\">\r\n"\
"<author></author>\r\n"\
"<title></title>\r\n"\
"<genre></genre>\r\n"\
"<price>0.000000</price>\r\n"\
"<bha></bha>\r\n"\
"<publish_date></publish_date>\r\n"\
"<description></description>\r\n"\
"</book>\r\n"\
"<book></book>\r\n"\
"</catalog>\r\n"\
"<arrayofother>\r\n"\
"<other>\r\n"\
"<a>1</a>\r\n"\
"<b>2</b>\r\n"\
"<c>3</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>4</a>\r\n"\
"<b>5</b>\r\n"\
"<c>6</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>7</a>\r\n"\
"<b>8</b>\r\n"\
"<c>9</c>\r\n"\
"</other>\r\n"\
"<other>\r\n"\
"<a>10</a>\r\n"\
"<b>11</b>\r\n"\
"<c>12</c>\r\n"\
"</other>\r\n"\
"<other></other>\r\n"\
"</arrayofother>\r\n"\
"</MulFtpUserSetting>\r\n";
#endif
const char *p = XmlOut_S.c_str();
const char *q = Res_S.c_str();
while (*p == *q) { p++; q++; }
printf("%d ok on %d\r\n", static_cast<uint32_t>(p - XmlOut_S.c_str()), static_cast<uint32_t>(XmlOut_S.size()));
EXPECT_STREQ(XmlOut_S.c_str(), Res_S.c_str());
Sts_i = BofXmlWriter_O.FromByte("", S_pOptionXml_X, XmlOut_S);
EXPECT_EQ(Sts_i, 0);
BOF_SAFE_DELETE(pBofXmlParser_O);
} | 33.315104 | 350 | 0.555642 | [
"vector"
] |
b284dc91269ccc434cd4c980a6020f2fe5c78484 | 3,304 | cpp | C++ | src/apps/tests/tests/Interpolation_tests.cpp | Adnn/Math | 017e7c42bfdd665c78557109b0b379567bfe8e7c | [
"MIT"
] | null | null | null | src/apps/tests/tests/Interpolation_tests.cpp | Adnn/Math | 017e7c42bfdd665c78557109b0b379567bfe8e7c | [
"MIT"
] | 11 | 2021-08-02T18:59:37.000Z | 2021-08-12T16:18:07.000Z | src/apps/tests/tests/Interpolation_tests.cpp | Adnn/math | 017e7c42bfdd665c78557109b0b379567bfe8e7c | [
"MIT"
] | 1 | 2021-03-18T10:56:44.000Z | 2021-03-18T10:56:44.000Z | #include "catch.hpp"
#include <math/Interpolation/Interpolation.h>
#include <math/Vector.h>
using namespace ad::math;
SCENARIO("Clamped type")
{
GIVEN("A few Clamped doubles.")
{
Clamped<> a{-5};
Clamped<> b{0.5};
Clamped<> c{1.5};
THEN("They are clamped as expected")
{
REQUIRE(a == 0.);
REQUIRE(b == 0.5);
REQUIRE(c == 1.);
}
}
GIVEN("A few Clamped integers")
{
using Clamp_t = Clamped<int, 3, 10>;
Clamp_t a{-5};
Clamp_t b{4};
Clamp_t c{11};
THEN("They are clamped as expected")
{
REQUIRE(a == 3);
REQUIRE(b == 4);
REQUIRE(c == 10);
}
}
}
SCENARIO("Linear interpolation")
{
GIVEN("Two vectors")
{
Vec<2> a{10., 10.};
Vec<2> b{20., 40.};
THEN("They can lerp")
{
REQUIRE(lerp(a, b, 0.) == a);
REQUIRE(lerp(a, b, 1.) == b);
REQUIRE(lerp(a, b, 3.) == b);
REQUIRE(lerp(a, b, -1.) == a);
REQUIRE(lerp(a, b, 0.5) == Vec<2>{15., 25.});
}
THEN("They can unbound (extrapolations")
{
REQUIRE(lerpUnbound(a, b, 0.) == a);
REQUIRE(lerpUnbound(a, b, 1.) == b);
REQUIRE(lerpUnbound(a, b, 3.) == Vec<2>{40., 100.});
REQUIRE(lerpUnbound(a, b, -1.) == Vec<2>{ 0., -20.});
REQUIRE(lerpUnbound(a, b, 0.5) == Vec<2>{15., 25.});
}
}
}
SCENARIO("Interpolation class")
{
GIVEN("A linear and a smoothstep Interpolations betwen two vectors")
{
Vec<2> a{10., 10.};
Vec<2> b{20., 40.};
double duration = 10;
auto linear = makeInterpolation(a, b, duration);
auto smoothstep = makeInterpolation<None ,ease::SmoothStep>(a, b, duration);
WHEN("The interpolations advances")
{
Vec<2> interpolatedHalf = linear.advance(duration/2.);
// Note that this advance will be on top of previous advance
Vec<2> interpolatedThreeQuarter = linear.advance(duration/4.);
Vec<2> smoothHalf = smoothstep.advance(duration/2.);
// Note that this advance will be on top of previous advance
Vec<2> smoothThreeQuarter = smoothstep.advance(duration/4.);
REQUIRE_FALSE(linear.isCompleted());
REQUIRE_FALSE(smoothstep.isCompleted());
THEN("The result is interpolated")
{
REQUIRE(interpolatedHalf == a + 1./2. * (b - a));
REQUIRE(interpolatedThreeQuarter == a + 3./4. * (b - a));
REQUIRE(interpolatedHalf == smoothHalf);
REQUIRE(interpolatedThreeQuarter.x() < smoothThreeQuarter.x());
REQUIRE(interpolatedThreeQuarter.y() < smoothThreeQuarter.y());
}
WHEN("They are advanced to or past the end.")
{
linear.advance(duration/4.);
smoothstep.advance(duration);
THEN("They indicate completion")
{
REQUIRE(linear.isCompleted());
REQUIRE(smoothstep.isCompleted());
}
}
}
}
}
| 27.081967 | 84 | 0.495157 | [
"vector"
] |
b287e7138ab8cbbd02a8c8622b91c7ea2623bdec | 432 | hpp | C++ | library/number_theory/prime_factor.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | library/number_theory/prime_factor.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | library/number_theory/prime_factor.hpp | fura2/competitive-programming-library | fc101651640ac5418155efce74f5ec103443bc8c | [
"MIT"
] | null | null | null | /* 素因数列挙 */
/*
説明
a の素因数をすべて求める
引数
a : 整数
戻り値
a の素因数のリスト
制約
a > 0
計算量
O(sqrt(a))
備考
a = 1 のときは空のリストが返る
*/
vector<long long> prime_factors(long long a){
vector<long long> res;
if(a%2==0){
do a/=2; while(a%2==0);
res.emplace_back(2);
}
for(long long p=3;p*p<=a;p+=2) if(a%p==0) {
do a/=p; while(a%p==0);
res.emplace_back(p);
}
if(a>1) res.emplace_back(a);
sort(res.begin(),res.end());
return res;
}
| 13.935484 | 45 | 0.576389 | [
"vector"
] |
b294264b1f67d28a38bab0158ab9ce481ecee33e | 5,657 | cpp | C++ | cpp/portalPython.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 134 | 2015-01-06T14:24:18.000Z | 2022-03-13T22:38:56.000Z | cpp/portalPython.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 103 | 2015-01-02T14:01:29.000Z | 2021-11-12T18:45:54.000Z | cpp/portalPython.cpp | jrrk2/connectal | 6c05f083e227423c1b2d8ae5a2364db180a82f4a | [
"MIT"
] | 39 | 2015-07-14T20:20:13.000Z | 2021-12-01T00:49:23.000Z | /* Copyright (c) 2014 Quanta Research Cambridge, Inc
* Copyright (c) 2016 ConnectalProject
*
* 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 <stdio.h>
#include "GeneratedTypes.h"
#include <python2.7/Python.h>
static int tracePython;// = 1;
static PortalInternal pythonTransport;
#define STUB \
{ \
fprintf(stderr, "[%s:%d]\n", __FUNCTION__, __LINE__); \
exit(-1); \
}
static volatile unsigned int *pythonTransportMAPCHANNELIND(struct PortalInternal *pint, unsigned int v)
{
return &pythonTransport.map_base[0];
}
static volatile unsigned int *pythonTransportMAPCHANNELREQ(struct PortalInternal *pint, unsigned int v, unsigned int size)
{
return &pythonTransport.map_base[0];
}
static void pythonTransportSENDMSG(struct PortalInternal *pint, volatile unsigned int *buffer, unsigned int hdr, int sendFd)
{
if (tracePython)
fprintf(stderr, "%s:%d %s\n", __FUNCTION__, __LINE__, (const char *)buffer);
}
static int pythonTransportTRANSPORTINIT(struct PortalInternal *pint, void *param) STUB
static unsigned int pythonTransportREADWORD(struct PortalInternal *pint, volatile unsigned int **addr) STUB
static void pythonTransportWRITEWORD(struct PortalInternal *pint, volatile unsigned int **addr, unsigned int v) STUB
static void pythonTransportWRITEFDWORD(struct PortalInternal *pint, volatile unsigned int **addr, unsigned int v) STUB
static int pythonTransportRECVMSG(struct PortalInternal *pint, volatile unsigned int *buffer, int len, int *recvfd) STUB
static int pythonTransportBUSYWAIT(struct PortalInternal *pint, unsigned int v, const char *str) STUB
static void pythonTransportENABLEINT(struct PortalInternal *pint, int val) STUB
static int pythonTransportEVENT(struct PortalInternal *pint) STUB
static int pythonTransportNOTFULL(struct PortalInternal *pint, unsigned int v) STUB
PortalTransportFunctions callbackTransport = {
pythonTransportTRANSPORTINIT, pythonTransportREADWORD, pythonTransportWRITEWORD, pythonTransportWRITEFDWORD,
pythonTransportMAPCHANNELIND, pythonTransportMAPCHANNELREQ, pythonTransportSENDMSG, pythonTransportRECVMSG,
pythonTransportBUSYWAIT, pythonTransportENABLEINT, pythonTransportEVENT, pythonTransportNOTFULL};
extern "C" {
typedef int (*HandleMessage)(struct PortalInternal *pint, unsigned int channel, int messageFd);
struct PortalPython {
struct PortalInternal pint;
HandleMessage handleMessage;
PyObject *callbackFunction;
};
static int handleIndicationMessage(struct PortalInternal *pint, unsigned int channel, int messageFd)
{
struct PortalPython *ppython = (struct PortalPython *)pint;
HandleMessage handleMessage = ppython->handleMessage;
pint->json_arg_vector = 1;
int value = handleMessage(pint, channel, messageFd);
PyGILState_STATE gstate = PyGILState_Ensure();
const char *jsonp = (const char *)pint->parent;
if (tracePython) fprintf(stderr, "handleIndicationMessage: json=%s\n", jsonp);
if (ppython->callbackFunction) {
PyEval_CallMethod(ppython->callbackFunction, "callback", "(s)", jsonp, NULL);
} else {
fprintf(stderr, "%s:%d no callback for portal\n", __FUNCTION__, __LINE__);
}
PyGILState_Release(gstate);
return value;
}
void set_callback(struct PortalPython *ppython, PyObject *param)
{
Py_INCREF(param);
ppython->callbackFunction = param;
pythonTransport.transport = &callbackTransport;
pythonTransport.map_base = (volatile unsigned int *)malloc(1000);
}
void *newRequestPortal(int ifcname, int reqinfo)
{
struct PortalInternal *pint = (struct PortalInternal *)calloc(1, sizeof(struct PortalInternal));
void *parent = NULL;;
if (tracePython) fprintf(stderr, "%s:%d ifcname=%x reqinfo=%08x pint=%p\n", __FUNCTION__, __LINE__, ifcname, reqinfo, pint);
init_portal_internal(pint, ifcname, DEFAULT_TILE, NULL, NULL, NULL, NULL, parent, reqinfo);
return pint;
}
void *newIndicationPortal(int ifcname, int reqinfo, HandleMessage handleMessage, void *proxyreq)
{
void *parent = malloc(4096);
struct PortalPython *ppython = (struct PortalPython *)calloc(1, sizeof(struct PortalPython));
ppython->handleMessage = handleMessage;
if (tracePython)
fprintf(stderr, "%s:%d ifcname=%x reqinfo=%08x handleMessage=%p proxyreq=%p pint=%p\n",
__FUNCTION__, __LINE__, ifcname, reqinfo, handleMessage, proxyreq, ppython);
init_portal_internal(&ppython->pint, ifcname, DEFAULT_TILE,
(PORTAL_INDFUNC) handleIndicationMessage, proxyreq, NULL, NULL, parent, reqinfo);
// encode message as vector ["methodname", arg0, arg1, ...]
pythonTransport.json_arg_vector = 1;
return ppython;
}
} // extern "C"
| 46.368852 | 128 | 0.763832 | [
"vector"
] |
b2a3af9da320966af91432931afad1264a8395da | 1,012 | cc | C++ | stapl_release/tools/mtl-2.0/contrib/examples/tri_pack_sol.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/tools/mtl-2.0/contrib/examples/tri_pack_sol.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/tools/mtl-2.0/contrib/examples/tri_pack_sol.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | #include "mtl/matrix.h"
#include "mtl/mtl.h"
#include "mtl/utils.h"
#include "mtl/linalg_vec.h"
/*
Sample Output
A in packed form
[
[1,],
[2,1,],
[3,5,1,],
[4,6,7,1,],
]
b:
[8,25,79,167,]
A^-1 * b:
[8,9,10,11,]
*/
using namespace mtl;
typedef matrix< double, triangle<lower>, packed<>, row_major>::type Matrix;
typedef external_vec<double> Vector;
int
main()
{
//begin
const int N = 4;
Matrix A(N, N);
set_diagonal(A, 1);
//C 1.0 8.0
//C A = 2.0 1.0 b = 25.0
//C 3.0 5.0 1.0 79.0
//C 4.0 6.0 7.0 1.0 167.0
A(1,0) = 2; A(2,1) = 5; A(3,2) = 7;
A(2,0) = 3; A(3,1) = 6;
A(3,0) = 4;
//end
double db[] = { 8, 25, 79, 167 };
Vector b(db, N);
std::cout << "A in packed form" << std::endl;
print_row(A);
std::cout << "b:" << std::endl;
print_vector(b);
tri_solve(A, b);
std::cout << "A^-1 * b:" << std::endl;
print_vector(b);
return 0;
}
| 15.8125 | 75 | 0.469368 | [
"vector"
] |
b2a87802a010eed7418001bd513c68c9bfd9e6a3 | 6,082 | hpp | C++ | src/Buckle/Bronze/include/compiler.hpp | flamechain/BELTE | a53ba207ff8b524d75d1b2561022992436550bf3 | [
"MIT"
] | 3 | 2022-03-11T15:31:49.000Z | 2022-03-11T22:53:55.000Z | src/Buckle/Bronze/include/compiler.hpp | flamechain/belte | c09175c4fb034703290f51a1d63b0ae0cb421665 | [
"MIT"
] | null | null | null | src/Buckle/Bronze/include/compiler.hpp | flamechain/belte | c09175c4fb034703290f51a1d63b0ae0cb421665 | [
"MIT"
] | null | null | null | /* Compiler entry point */
#pragma once
#ifndef COMPILER_HPP
#define COMPILER_HPP
#include "utils.hpp"
namespace compiler {
enum TokenType {
EOFToken,
BadToken,
NUMBER,
PLUS,
MINUS,
ASTERISK,
SLASH,
LPAREN,
RPAREN,
WHITESPACE,
};
enum NodeType {
BadNode,
TokenNode,
NUMBER_EXPR,
BINARY_EXPR,
UNARY_EXPR,
PAREN_EXPR,
};
class Node {
public:
const NodeType type;
virtual vector<shared_ptr<Node>> GetChildren() const { return { }; }
Node() : type(NodeType::BadNode) { }
Node(NodeType _type) : type(_type) { }
string Type() const {
switch (type) {
case NodeType::BadNode: return "InvalidNode";
case NodeType::TokenNode: return "TokenNode";
case NodeType::NUMBER_EXPR: return "NumberNode";
case NodeType::BINARY_EXPR: return "BinaryExpression";
case NodeType::UNARY_EXPR: return "UnaryExpression";
default: return "UnknownNode";
}
}
};
class Token : public Node {
public:
string text;
TokenType type;
size_t pos;
int val_int;
bool is_null = true;
Token() : Node(NodeType::TokenNode), type(TokenType::BadToken) { }
Token(TokenType _type) : Node(NodeType::TokenNode), type(_type) { }
static string Type(TokenType _type) {
switch (_type) {
case TokenType::EOFToken: return "EOFToken";
case TokenType::BadToken: return "InvalidToken";
case TokenType::NUMBER: return "NumberToken";
case TokenType::PLUS: return "PLUS";
case TokenType::MINUS: return "MINUS";
case TokenType::ASTERISK: return "ASTERISK";
case TokenType::SLASH: return "SLASH";
case TokenType::LPAREN: return "LPAREN";
case TokenType::RPAREN: return "RPAREN";
case TokenType::WHITESPACE: return "WHITESPACE";
default: return "UnknownToken";
}
}
string Type() const { return Token::Type(type); }
void operator=(const Token& token) {
text = token.text;
type = token.type;
pos = token.pos;
val_int = token.val_int;
is_null = token.is_null;
}
};
class EndOfFileToken : public Token {
public:
EndOfFileToken(string _text, size_t _pos) : Token(TokenType::EOFToken) {
text = _text;
pos = _pos;
}
};
class NumberToken : public Token {
public:
NumberToken(string _text, size_t _pos, int _value) : Token(TokenType::NUMBER) {
text = _text;
pos = _pos;
val_int = _value;
is_null = false;
}
NumberToken(string _text, size_t _pos, bool _value): Token(TokenType::NUMBER) {
text = _text;
pos = _pos;
is_null = _value;
}
};
class WhitespaceToken : public Token {
public:
WhitespaceToken(string _text, size_t _pos) : Token(TokenType::WHITESPACE) {
text = _text;
pos = _pos;
}
};
class PlusToken : public Token {
public:
PlusToken(string _text, size_t _pos) : Token(TokenType::PLUS) {
text = _text;
pos = _pos;
}
};
class MinusToken : public Token {
public:
MinusToken(string _text, size_t _pos) : Token(TokenType::MINUS) {
text = _text;
pos = _pos;
}
};
class AsteriskToken : public Token {
public:
AsteriskToken(string _text, size_t _pos) : Token(TokenType::ASTERISK) {
text = _text;
pos = _pos;
}
};
class SolidusToken : public Token {
public:
SolidusToken(string _text, size_t _pos) : Token(TokenType::SLASH) {
text = _text;
pos = _pos;
}
};
class LParenToken : public Token {
public:
LParenToken(string _text, size_t _pos) : Token(TokenType::LPAREN) {
text = _text;
pos = _pos;
}
};
class RParenToken : public Token {
public:
RParenToken(string _text, size_t _pos) : Token(TokenType::RPAREN) {
text = _text;
pos = _pos;
}
};
class InvalidToken : public Token {
public:
InvalidToken(string _text, size_t _pos) : Token(TokenType::BadToken) {
text = _text;
pos = _pos;
}
};
class Expression : public Node {
public:
Expression(NodeType _type) : Node(_type) { }
};
class InvalidNode : public Node {
public:
InvalidNode() : Node(NodeType::BadNode) { }
};
class NumberNode : public Expression {
public:
Token token;
NumberNode(Token _token) : Expression(NodeType::NUMBER_EXPR), token(_token) { }
vector<shared_ptr<Node>> GetChildren() const { return { make_shared<Token>(token) }; }
};
class BinaryExpression : public Expression {
public:
shared_ptr<Expression> left;
shared_ptr<Token> op;
shared_ptr<Expression> right;
BinaryExpression(shared_ptr<Expression> _left, shared_ptr<Token> _op, shared_ptr<Expression> _right) : Expression(NodeType::BINARY_EXPR) {
left = _left;
op = _op;
right = _right;
}
vector<shared_ptr<Node>> GetChildren() const { return { left, op, right }; }
};
class UnaryExpression : public Expression {
};
class ParenExpression : public Expression {
public:
shared_ptr<Token> OpenParen;
shared_ptr<Expression> Expr;
shared_ptr<Token> CloseParen;
ParenExpression(shared_ptr<Token> openParen, shared_ptr<Expression> expr, shared_ptr<Token> closeParen) : Expression(NodeType::PAREN_EXPR) {
OpenParen = openParen;
Expr = expr;
CloseParen = closeParen;
}
vector<shared_ptr<Node>> GetChildren() const { return { OpenParen, Expr, CloseParen }; }
};
class SyntaxTree {
public:
vector<string> Diagnostics;
shared_ptr<Expression> Root;
Token EOFToken;
SyntaxTree(vector<string> diagnostics, shared_ptr<Expression> root, Token EOFtoken) {
Root = root;
EOFToken = EOFtoken;
Diagnostics = diagnostics;
}
};
void PrettyPrint(shared_ptr<Node> node, wstring index=L"", bool last=true);
Token CreateToken(TokenType type, size_t pos);
}
class Compiler {
private:
Compiler() {}
public:
static void compile() noexcept;
};
#endif
| 22.950943 | 144 | 0.628741 | [
"vector"
] |
b2ab773e848b1d1dbf9f7dc313caa993186aadda | 1,439 | cpp | C++ | src/Wall.cpp | rabowling/senior-project | 07d7a1fba73376bc197f2ff045c057f0808d7612 | [
"MIT"
] | 1 | 2021-06-15T01:44:41.000Z | 2021-06-15T01:44:41.000Z | src/Wall.cpp | rabowling/senior-project | 07d7a1fba73376bc197f2ff045c057f0808d7612 | [
"MIT"
] | null | null | null | src/Wall.cpp | rabowling/senior-project | 07d7a1fba73376bc197f2ff045c057f0808d7612 | [
"MIT"
] | null | null | null | #include "Wall.h"
#include "Application.h"
#include "Utils.h"
#include <glm/gtc/matrix_transform.hpp>
using namespace physx;
using namespace glm;
void Wall::init(PxVec3 position, PxVec3 size, PxQuat orientation) {
this->size = size;
pShape = app.physics.getPhysics()->createShape(PxBoxGeometry(size), *app.physics.defaultMaterial);
gWall = app.physics.getPhysics()->createRigidStatic(PxTransform(position, orientation));
gWall->attachShape(*pShape);
app.physics.getScene()->addActor(*gWall);
pShape->release();
}
void Wall::draw(MatrixStack &M) {
M.pushMatrix();
PxTransform t = gWall->getGlobalPose();
M.translate(vec3(t.p.x, t.p.y, t.p.z));
M.rotate(quat(t.q.w, t.q.x, t.q.y, t.q.z));
M.scale(vec3(size.x, size.y, size.z));
glUniformMatrix4fv(app.shaderManager.getUniform("M"), 1, GL_FALSE, value_ptr(getTransform()));
if (!app.renderingCubemap) {
glUniform3f(app.shaderManager.getUniform("scale"), size.x, size.y, size.z);
app.materialManager.bind("concrete");
}
app.modelManager.draw("cube");
M.popMatrix();
}
Shape *Wall::getModel() const {
return app.modelManager.get("cube");
}
glm::mat4 Wall::getTransform() const {
PxTransform t = gWall->getGlobalPose();
return scale(translate(mat4(1), px2glm(t.p)) * mat4_cast(px2glm(t.q)), px2glm(size));
}
Material *Wall::getMaterial() const {
return app.materialManager.get("concrete");
}
| 31.282609 | 102 | 0.678944 | [
"shape"
] |
b2ad857a5059babfd28a40f9f74bfbf489a312ba | 10,943 | hpp | C++ | include/mtao/geometry/kdtree.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | include/mtao/geometry/kdtree.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | 4 | 2020-04-18T16:16:05.000Z | 2020-04-18T16:17:36.000Z | include/mtao/geometry/kdtree.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | #pragma once
#include <Eigen/Core>
#include <vector>
#include <memory>
#include <array>
#include "mtao/types.h"
#include <sstream>
#include <numeric>
namespace mtao { namespace geometry {
template <typename T, int D>
class KDTree;
template <typename T, int D, int Axis>
//class KDNode: public KDNodeBase<KDNode<T,D,Axis>> {
class KDNode {
public:
using Vec = mtao::Vector<T,D>;
using NodeType = KDNode<T,D,Axis>;
constexpr static int ChildAxis = (Axis+1)%D;
constexpr static int ParentAxis = (Axis-1+D)%D;
using ChildNodeType = KDNode<T,D,ChildAxis>;
using ParentNodeType = KDNode<T,D,ParentAxis>;
//balanced construciton iterator, used for one constructor
using BCIt = mtao::vector<size_t>::iterator;
~KDNode() = default;
KDNode() = delete;
KDNode(const KDNode&) = delete;
KDNode(KDNode&&) = delete;
KDNode& operator=(const KDNode&) = delete;
KDNode& operator=(KDNode&&) = delete;
KDNode(const KDTree<T,D>& tree, KDNode&& o): m_tree(tree), m_index(o.m_index) {
if(o.left()) {
left() = std::make_unique<ChildNodeType>(tree,std::move(*o.left()));
}
if(o.right()) {
right() = std::make_unique<ChildNodeType>(tree,std::move(*o.right()));
}
}
KDNode(const KDTree<T,D>& tree, int index): m_tree(tree), m_index(index) {}
KDNode(const KDTree<T,D>& tree, const BCIt& begin, const BCIt& end): m_tree(tree) {
assert(std::distance(begin,end) > 0);
std::sort(begin,end,[&](size_t a, size_t b) {
return point(a)(Axis) < point(b)(Axis);
});
BCIt mid = begin + std::distance(begin,end)/2;
BCIt right_start = mid+1;
m_index = *mid;
if(std::distance(begin,mid) > 0) {
left() = std::make_unique<ChildNodeType>(m_tree,begin,mid);
}
if(std::distance(right_start,end) > 0) {
right() = std::make_unique<ChildNodeType>(m_tree,right_start,end);
}
}
auto&& point() const {
return point(m_index);
}
auto&& point(size_t idx) const {return m_tree.point(idx);}
size_t index()const {return m_index;}
template <typename Derived>
bool operator<(const Eigen::MatrixBase<Derived>& p) const {
//positive -> right
//negative -> left
return axis_dist(p) < 0;
}
template <typename Derived>
T axis_dist(const Eigen::MatrixBase<Derived>& p) const {
return p(Axis) - point()(Axis);
}
template <typename Derived>
size_t axis_choice(const Eigen::MatrixBase<Derived>& p) const {
return (*this < p)?0:1;
}
template <typename Derived>
auto&& pick_child(const Eigen::MatrixBase<Derived>& p) {
return m_children[axis_choice(p)];
}
template <typename Derived>
auto&& pick_child(const Eigen::MatrixBase<Derived>& p) const {
return m_children[axis_choice(p)];
}
void insert(size_t idx) {
auto&& c = pick_child(point(idx));
if(c) {
c->insert(idx);
} else {
c = std::make_unique<ChildNodeType>(m_tree,idx);
}
}
template <typename Derived>
void nearest(const Eigen::MatrixBase<Derived>& p, size_t& nearest_index, T& nearest_dist) const {
T dist = (point() - p).norm();
if(dist < nearest_dist) {
nearest_index = index();
nearest_dist = dist;
}
auto comp_child = [&](const std::unique_ptr<ChildNodeType>& c) {
if(c) {
c->nearest(p,nearest_index,nearest_dist);
}
};
T ad = axis_dist(p);
bool in_nearband = nearest_dist >= std::abs(ad);
//[ node point child]
//[ node child point]
//[ point node child]
//axis nearest_dist is negative and considering going down right child
if(ad >= 0 || in_nearband) {
comp_child(right());
}
//[ point child node]
//[ child point node]
//[ child node point]
//axis nearest_dist is positive and considering going down left child
if(ad < 0 || in_nearband) {
comp_child(left());
}
}
std::unique_ptr<ChildNodeType>& left() { return m_children[0]; }
const std::unique_ptr<ChildNodeType>& left() const { return m_children[0]; }
std::unique_ptr<ChildNodeType>& right() { return m_children[1]; }
const std::unique_ptr<ChildNodeType>& right() const { return m_children[1]; }
int max_depth() const {
int depth = 0;
if(left()) {
depth = std::max(left()->max_depth()+1,depth);
}
if(right()) {
depth = std::max(right()->max_depth()+1,depth);
}
return depth;
}
operator std::string() const {
std::stringstream ss;
ss << m_index << "[";
if(left()) {
ss << std::string(*left());
} else {
ss << ".";
}
ss << " | ";
if(right()) {
ss << std::string(*right());
} else {
ss << ".";
}
ss << "]";
return ss.str();
}
private:
const KDTree<T,D>& m_tree;
size_t m_index;
std::array<std::unique_ptr<ChildNodeType>,2> m_children;
};
template <typename T, int D>
class KDTree {
public:
using Vec = mtao::Vector<T,D>;
constexpr static int Axis = 0;
using NodeType = KDNode<T,D,0>;
const mtao::vector<Vec>& points()const {return m_points;}
auto&& point(size_t idx) const {return m_points[idx];}
size_t size() const { return points().size(); }
void rebalance() {
std::vector<size_t> P(m_points.size());
std::iota(P.begin(),P.end(),0);
m_node = std::make_unique<NodeType>(*this,P.begin(),P.end());
}
KDTree() = default;
KDTree(const KDTree&) = delete;
KDTree(KDTree&&) = delete;
~KDTree() = default;
KDTree& operator=(const KDTree&) = delete;
KDTree& operator=(KDTree&& o) {
m_points = std::move(o.m_points);
if(o.m_node) {
m_node = std::make_unique<NodeType>(*this,std::move(*o.m_node));
}
return *this;
}
void reserve(size_t size) { m_points.reserve(size); }
KDTree(const mtao::vector<Vec>& points): m_points(points) {
rebalance();
}
size_t insert(const Vec& p) {
size_t newidx = m_points.size();
m_points.push_back(p);
if(!m_node) {
m_node = std::make_unique<NodeType>(*this, newidx);
} else {
m_node->insert(newidx);
}
return newidx;
}
size_t pruning_insertion(const Vec& p, T eps = T(1e-5)) {
if(m_node) {
auto [ni,d] = nearest(p);
if(eps == 0) {
if(point(ni) == p) {
return ni;
}
}
else if(d < eps) {
return ni;
}
}
return insert(p);
}
template <typename Derived>
std::tuple<size_t,T> nearest(const typename Eigen::MatrixBase<Derived>& p) const {
size_t idx = 0;
T d = std::numeric_limits<T>::max();
assert(m_node);
m_node->nearest(p,idx,d);
return {idx,d};
}
template <typename Derived>
size_t nearest_index(const typename Eigen::MatrixBase<Derived>& p) const {
return std::get<0>(nearest(p));
}
template <typename Derived>
size_t nearest_distance(const typename Eigen::MatrixBase<Derived>& p) const {
return std::get<1>(nearest(p));
}
template <typename Derived>
const Vec& nearest_point(const typename Eigen::MatrixBase<Derived>& p) const { return point(nearest_index(p)); }
operator std::string() const { return *m_node; }
int max_depth() const {
if(m_node) {
return m_node->max_depth() + 1;
}
return 0;
}
private:
std::unique_ptr<NodeType> m_node;
mtao::vector<Vec> m_points;
};
}}
| 39.937956 | 132 | 0.408572 | [
"geometry",
"vector"
] |
b2b06f2ad7243bad0751b1ea02b3573ef85b74db | 3,109 | cpp | C++ | src/gen_tileset_main.cpp | kant2002/scm2txt | f69904a9f838ef572be0332b467f4a68dbf24ad4 | [
"MIT"
] | 3 | 2018-04-09T18:12:55.000Z | 2020-03-05T15:37:13.000Z | src/gen_tileset_main.cpp | kant2002/scm2txt | f69904a9f838ef572be0332b467f4a68dbf24ad4 | [
"MIT"
] | null | null | null | src/gen_tileset_main.cpp | kant2002/scm2txt | f69904a9f838ef572be0332b467f4a68dbf24ad4 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <fstream>
#include "mapreader.h"
#include "tilesetreader.h"
using namespace std;
namespace {
std::array<const char*, 8> tileset_names = {
"badlands",
"platform",
"install",
"ashworld",
"jungle",
"desert",
"ice",
"twilight"
};
}
void printUsage()
{
cout << "gen_tileset <sc_dir>" << endl;
}
void print_vf4_code(ostream& cout, string expression, std::vector<vf4_entry> vf4)
{
cout << expression << " = {" << endl;
for (auto entry : vf4)
{
cout << "{"
<< entry.flags[0] << "," << entry.flags[1] << "," << entry.flags[2] << "," << entry.flags[3] << ","
<< entry.flags[4] << "," << entry.flags[5] << "," << entry.flags[6] << "," << entry.flags[7] << ","
<< entry.flags[8] << "," << entry.flags[9] << "," << entry.flags[10] << "," << entry.flags[11] << ","
<< entry.flags[12] << "," << entry.flags[13] << "," << entry.flags[14] << "," << entry.flags[15] << ","
<< "}," << endl;
}
cout << "};" << endl;
}
void print_cv5_code(ostream& cout, string expression, std::vector<cv5_entry> cv5)
{
cout << expression << " = {" << endl;
for (auto entry : cv5)
{
cout << "{" << entry.flags << ",{"
<< entry.mega_tile_index[0] << "," << entry.mega_tile_index[1] << "," << entry.mega_tile_index[2] << "," << entry.mega_tile_index[3] << ","
<< entry.mega_tile_index[4] << "," << entry.mega_tile_index[5] << "," << entry.mega_tile_index[6] << "," << entry.mega_tile_index[7] << ","
<< entry.mega_tile_index[8] << "," << entry.mega_tile_index[9] << "," << entry.mega_tile_index[10] << "," << entry.mega_tile_index[11] << ","
<< entry.mega_tile_index[12] << "," << entry.mega_tile_index[13] << "," << entry.mega_tile_index[14] << "," << entry.mega_tile_index[15] << ","
<< "}}," << endl;
}
cout << "};" << endl;
}
void print_tileset_code_header(ostream& cout)
{
cout << "#include <vector>" << endl;
cout << "#include <array>" << endl;
cout << "#include \"mapreader.h\"" << endl;
cout << endl;
}
void print_tileset_code(ostream& cout, string prefix, tileset_data& tileset)
{
print_vf4_code(cout, string("std::vector<vf4_entry> ") + prefix + "_vf4", tileset.vf4);
print_cv5_code(cout, string("std::vector<cv5_entry> ") + prefix + "_cv5", tileset.cv5);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
printUsage();
return -1;
}
string starcraftDir(argv[1]);
tileset_data tileset;
starcraft_tileset_parse_status tileset_status;
ofstream generated_data("tileset.cpp");
print_tileset_code_header(generated_data);
for (auto i = 0; i < 8; i++)
{
parse_starcraft_tileset(argv[1], i, tileset, tileset_status);
switch (tileset_status.error_code)
{
case StarcraftTilesetParse_FileOpenError:
cerr << "Failed to open the tileset file" << endl;
break;
case StarcraftTilesetParse_CV5Missing:
cerr << "CV5 file for specified tileset is missing" << endl;
break;
case StarcraftTilesetParse_VF4Missing:
cerr << "VF4 file for specified tileset is missing" << endl;
break;
default:
print_tileset_code(generated_data, tileset_names[i], tileset);
break;
}
}
return 0;
} | 29.056075 | 146 | 0.614024 | [
"vector"
] |
b2b3e0fdd6ac095d8ddcb95425919dcd550e180f | 19,504 | cpp | C++ | include/delfem2/lsmats.cpp | nobuyuki83/delfem2 | 118768431ccc5b77ed10b8f76f625d38e0b552f0 | [
"MIT"
] | 153 | 2018-08-16T21:51:33.000Z | 2022-03-28T10:34:48.000Z | include/delfem2/lsmats.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | 63 | 2018-08-16T21:53:34.000Z | 2022-02-22T13:50:34.000Z | include/delfem2/lsmats.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | 18 | 2018-12-17T05:39:15.000Z | 2021-11-16T08:21:16.000Z | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "delfem2/lsmats.h"
#include <cassert>
#include <complex>
namespace delfem2::mats {
DFM2_INLINE double MatNorm_Assym(
const double *V0,
unsigned int n0,
unsigned int m0,
const double *V1) {
double s = 0.0;
for (unsigned int i = 0; i < n0; ++i) {
for (unsigned int j = 0; j < m0; ++j) {
double v0 = V0[i * m0 + j];
double v1 = V1[j * n0 + i];
s += (v0 - v1) * (v0 - v1);
}
}
return s;
}
DFM2_INLINE double MatNorm(
const double *V,
unsigned int n,
unsigned int m) {
double s = 0.0;
for (unsigned int i = 0; i < n; ++i) {
for (unsigned int j = 0; j < m; ++j) {
double v = V[i * m + j];
s += v * v;
}
}
return s;
}
DFM2_INLINE double MatNorm_Assym(
const double *V,
unsigned int n) {
double s = 0.0;
for (unsigned int i = 0; i < n; ++i) {
for (unsigned int j = 0; j < n; ++j) {
double v0 = V[i * n + j];
double v1 = V[j * n + i];
s += (v0 - v1) * (v0 - v1);
}
}
return s;
}
template<typename T>
void MatVec_MatSparseCRS_Blk11(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
y[iblk] += alpha * vcrs[icrs] * x[jblk0];
}
y[iblk] += alpha * vdia[iblk] * x[iblk];
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk22(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
y[iblk * 2 + 0] += alpha * (vcrs[icrs * 4] * x[jblk0 * 2 + 0] + vcrs[icrs * 4 + 1] * x[jblk0 * 2 + 1]);
y[iblk * 2 + 1] += alpha * (vcrs[icrs * 4 + 2] * x[jblk0 * 2 + 0] + vcrs[icrs * 4 + 3] * x[jblk0 * 2 + 1]);
}
y[iblk * 2 + 0] += alpha * (vdia[iblk * 4 + 0] * x[iblk * 2 + 0] + vdia[iblk * 4 + 1] * x[iblk * 2 + 1]);
y[iblk * 2 + 1] += alpha * (vdia[iblk * 4 + 2] * x[iblk * 2 + 0] + vdia[iblk * 4 + 3] * x[iblk * 2 + 1]);
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk33(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
const unsigned int i0 = iblk * 3;
const unsigned int j0 = jblk0 * 3;
const unsigned int k0 = icrs * 9;
y[i0 + 0] += alpha * (vcrs[k0 + 0] * x[j0 + 0] + vcrs[k0 + 1] * x[j0 + 1] + vcrs[k0 + 2] * x[j0 + 2]);
y[i0 + 1] += alpha * (vcrs[k0 + 3] * x[j0 + 0] + vcrs[k0 + 4] * x[j0 + 1] + vcrs[k0 + 5] * x[j0 + 2]);
y[i0 + 2] += alpha * (vcrs[k0 + 6] * x[j0 + 0] + vcrs[k0 + 7] * x[j0 + 1] + vcrs[k0 + 8] * x[j0 + 2]);
}
{
const unsigned int i0 = iblk * 3;
const unsigned int k0 = iblk * 9;
y[i0 + 0] += alpha * (vdia[k0 + 0] * x[i0 + 0] + vdia[k0 + 1] * x[i0 + 1] + vdia[k0 + 2] * x[i0 + 2]);
y[i0 + 1] += alpha * (vdia[k0 + 3] * x[i0 + 0] + vdia[k0 + 4] * x[i0 + 1] + vdia[k0 + 5] * x[i0 + 2]);
y[i0 + 2] += alpha * (vdia[k0 + 6] * x[i0 + 0] + vdia[k0 + 7] * x[i0 + 1] + vdia[k0 + 8] * x[i0 + 2]);
}
}
}
template<typename T>
void MatVec_MatSparseCRS_Blk44(
T *y,
T alpha,
unsigned nrowblk,
const T *vcrs,
const T *vdia,
const unsigned int *colind,
const unsigned int *rowptr,
const T *x) {
for (unsigned int iblk = 0; iblk < nrowblk; iblk++) {
const unsigned int icrs0 = colind[iblk];
const unsigned int icrs1 = colind[iblk + 1];
for (unsigned int icrs = icrs0; icrs < icrs1; icrs++) {
const unsigned int jblk0 = rowptr[icrs];
const unsigned int i0 = iblk * 4;
const unsigned int j0 = jblk0 * 4;
const unsigned int k0 = icrs * 16;
y[i0 + 0] +=
alpha * (
vcrs[k0 + 0] * x[j0 + 0] +
vcrs[k0 + 1] * x[j0 + 1] +
vcrs[k0 + 2] * x[j0 + 2] +
vcrs[k0 + 3] * x[j0 + 3]);
y[i0 + 1] +=
alpha * (
vcrs[k0 + 4] * x[j0 + 0] +
vcrs[k0 + 5] * x[j0 + 1] +
vcrs[k0 + 6] * x[j0 + 2] +
vcrs[k0 + 7] * x[j0 + 3]);
y[i0 + 2] +=
alpha * (
vcrs[k0 + 8] * x[j0 + 0] +
vcrs[k0 + 9] * x[j0 + 1] +
vcrs[k0 + 10] * x[j0 + 2] +
vcrs[k0 + 11] * x[j0 + 3]);
y[i0 + 3] +=
alpha * (
vcrs[k0 + 12] * x[j0 + 0] +
vcrs[k0 + 13] * x[j0 + 1] +
vcrs[k0 + 14] * x[j0 + 2] +
vcrs[k0 + 15] * x[j0 + 3]);
}
{
const unsigned int i0 = iblk * 4;
const unsigned int k0 = iblk * 16;
y[i0 + 0] +=
alpha * (
vdia[k0 + 0] * x[i0 + 0] +
vdia[k0 + 1] * x[i0 + 1] +
vdia[k0 + 2] * x[i0 + 2] +
vdia[k0 + 3] * x[i0 + 3]);
y[i0 + 1] +=
alpha * (
vdia[k0 + 4] * x[i0 + 0] +
vdia[k0 + 5] * x[i0 + 1] +
vdia[k0 + 6] * x[i0 + 2] +
vdia[k0 + 7] * x[i0 + 3]);
y[i0 + 2] +=
alpha * (
vdia[k0 + 8] * x[i0 + 0] +
vdia[k0 + 9] * x[i0 + 1] +
vdia[k0 + 10] * x[i0 + 2] +
vdia[k0 + 11] * x[i0 + 3]);
y[i0 + 3] +=
alpha * (
vdia[k0 + 12] * x[i0 + 0] +
vdia[k0 + 13] * x[i0 + 1] +
vdia[k0 + 14] * x[i0 + 2] +
vdia[k0 + 15] * x[i0 + 3]);
}
}
}
}
// -------------------------------------------------------
// Calc Matrix Vector Product
// {y} = alpha*[A]{x} + beta*{y}
template<typename T>
void delfem2::CMatrixSparse<T>::MatVec(
T *y,
T alpha,
const T *x,
T beta) const {
const unsigned int ndofcol = nrowdim_ * nrowblk_;
for (unsigned int i = 0; i < ndofcol; ++i) { y[i] *= beta; }
// --------
if (nrowdim_ == 1 && ncoldim_ == 1) {
mats::MatVec_MatSparseCRS_Blk11(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 2 && ncoldim_ == 2) {
mats::MatVec_MatSparseCRS_Blk22(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 3 && ncoldim_ == 3) {
mats::MatVec_MatSparseCRS_Blk33(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else if (nrowdim_ == 4 && ncoldim_ == 4) {
mats::MatVec_MatSparseCRS_Blk44(
y,
alpha, nrowblk_, val_crs_.data(), val_dia_.data(),
col_ind_.data(), row_ptr_.data(), x);
} else {
const unsigned int blksize = nrowdim_ * ncoldim_;
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
//
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[iblk * nrowdim_ + idof] +=
alpha * vcrs[icrs * blksize + idof * ncoldim_ + jdof] * x[jblk0 * ncoldim_ + jdof];
}
}
}
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[iblk * nrowdim_ + idof] +=
alpha * vdia[iblk * blksize + idof * ncoldim_ + jdof] * x[iblk * ncoldim_ + jdof];
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatVec(
float *y, float alpha, const float *x, float beta) const;
template void delfem2::CMatrixSparse<double>::MatVec(
double *y, double alpha, const double *x, double beta) const;
template void delfem2::CMatrixSparse<std::complex<double>>::MatVec(
std::complex<double> *y, std::complex<double> alpha,
const std::complex<double> *x, std::complex<double> beta) const;
#endif
// -------------------------------------------------------
/**
* @brief Calc Matrix Vector Product {y} = alpha*[A]{x} + beta*{y}
* the 1x1 sparse matrix is expanded as the len x len sparse matrix
*/
template<typename T>
void delfem2::CMatrixSparse<T>::MatVecDegenerate(
T *y,
unsigned int len,
T alpha,
const T *x,
T beta) const {
assert(nrowdim_ == 1 && ncoldim_ == 1);
const unsigned int ndofcol = len * nrowblk_;
for (unsigned int i = 0; i < ndofcol; ++i) { y[i] *= beta; }
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
const T mval0 = alpha * vcrs[icrs];
for (unsigned int ilen = 0; ilen < len; ilen++) {
y[iblk * len + ilen] += mval0 * x[jblk0 * len + ilen];
}
}
{ // compute diagonal
const T mval0 = alpha * vdia[iblk];
for (unsigned int ilen = 0; ilen < len; ilen++) {
y[iblk * len + ilen] += mval0 * x[iblk * len + ilen];
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatVecDegenerate(
float *y,
unsigned int len,
float alpha,
const float *x,
float beta) const;
template void delfem2::CMatrixSparse<double>::MatVecDegenerate(
double *y,
unsigned int len,
double alpha,
const double *x,
double beta) const;
#endif
// -------------------------------------------------------
// Calc Matrix Vector Product
// {y} = alpha*[A]^T{x} + beta*{y}
template<typename T>
void delfem2::CMatrixSparse<T>::MatTVec(
T *y,
T alpha,
const T *x,
T beta) const {
const unsigned int ndofrow = ncoldim_ * ncolblk_;
for (unsigned int i = 0; i < ndofrow; ++i) { y[i] *= beta; }
const unsigned int blksize = nrowdim_ * ncoldim_;
{
const T *vcrs = val_crs_.data();
const T *vdia = val_dia_.data();
const unsigned int *colind = col_ind_.data();
const unsigned int *rowptr = row_ptr_.data();
//
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) {
const unsigned int colind0 = colind[iblk];
const unsigned int colind1 = colind[iblk + 1];
for (unsigned int icrs = colind0; icrs < colind1; icrs++) {
assert(icrs < row_ptr_.size());
const unsigned int jblk0 = rowptr[icrs];
assert(jblk0 < ncolblk_);
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
y[jblk0 * ncoldim_ + jdof] +=
alpha * vcrs[icrs * blksize + idof * ncoldim_ + jdof] * x[iblk * nrowdim_ + idof];
}
}
}
for (unsigned int jdof = 0; jdof < ncoldim_; jdof++) {
for (unsigned int idof = 0; idof < nrowdim_; idof++) {
y[iblk * ncoldim_ + jdof] +=
alpha * vdia[iblk * blksize + idof * ncoldim_ + jdof] * x[iblk * nrowdim_ + idof];
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::MatTVec(
float *y, float alpha, const float *x, float beta) const;
template void delfem2::CMatrixSparse<double>::MatTVec(
double *y, double alpha, const double *x, double beta) const;
template void delfem2::CMatrixSparse<std::complex<double>>::MatTVec(
std::complex<double> *y, std::complex<double> alpha,
const std::complex<double> *x, std::complex<double> beta) const;
#endif
// -----------------------------------------------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Dia(
const int *bc_flag,
T val_dia) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) { // set diagonal
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
if (bc_flag[iblk * nrowdim_ + ilen] == 0) continue;
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
val_dia_[iblk * blksize + ilen * nrowdim_ + jlen] = 0.0;
val_dia_[iblk * blksize + jlen * nrowdim_ + ilen] = 0.0;
}
val_dia_[iblk * blksize + ilen * nrowdim_ + ilen] = val_dia;
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Dia(
const int *bc_flag, float val_dia);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Dia(
const int *bc_flag, double val_dia);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Dia(
const int *bc_flag, std::complex<double> val_dia);
#endif
// --------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Row(
const int *bc_flag) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int iblk = 0; iblk < nrowblk_; iblk++) { // set row
for (unsigned int icrs = col_ind_[iblk]; icrs < col_ind_[iblk + 1]; icrs++) {
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
if (bc_flag[iblk * nrowdim_ + ilen] == 0) continue;
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
val_crs_[icrs * blksize + ilen * nrowdim_ + jlen] = 0.0;
}
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Row(
const int *bc_flag);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Row(
const int *bc_flag);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Row(
const int *bc_flag);
#endif
// ---------------------------
template<typename T>
void delfem2::CMatrixSparse<T>::SetFixedBC_Col(
const int *bc_flag) {
assert(!this->val_dia_.empty());
assert(this->ncolblk_ == this->nrowblk_);
assert(this->ncoldim_ == this->nrowdim_);
const int blksize = nrowdim_ * ncoldim_;
for (unsigned int icrs = 0; icrs < row_ptr_.size(); icrs++) { // set column
const int jblk1 = row_ptr_[icrs];
for (unsigned int jlen = 0; jlen < ncoldim_; jlen++) {
if (bc_flag[jblk1 * ncoldim_ + jlen] == 0) continue;
for (unsigned int ilen = 0; ilen < nrowdim_; ilen++) {
val_crs_[icrs * blksize + ilen * nrowdim_ + jlen] = 0.0;
}
}
}
}
#ifdef DFM2_STATIC_LIBRARY
template void delfem2::CMatrixSparse<float>::SetFixedBC_Col(const int *bc_flag);
template void delfem2::CMatrixSparse<double>::SetFixedBC_Col(const int *bc_flag);
template void delfem2::CMatrixSparse<std::complex<double>>::SetFixedBC_Col(const int *bc_flag);
#endif
// -----------------------------------------------------------------
DFM2_INLINE void delfem2::MatSparse_ScaleBlk_LeftRight(
delfem2::CMatrixSparse<double> &mat,
const double *scale) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int nblk = mat.nrowblk_;
const unsigned int len = mat.nrowdim_;
const unsigned int blksize = len * len;
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
const unsigned int jno = mat.row_ptr_[icrs0];
const double s0 = scale[ino] * scale[jno];
for (unsigned int i = 0; i < blksize; ++i) { mat.val_crs_[icrs0 * blksize + i] *= s0; }
}
}
if (!mat.val_dia_.empty()) {
for (unsigned int ino = 0; ino < nblk; ++ino) {
double s0 = scale[ino] * scale[ino];
for (unsigned int i = 0; i < blksize; ++i) { mat.val_dia_[ino * blksize + i] *= s0; }
}
}
}
DFM2_INLINE void delfem2::MatSparse_ScaleBlkLen_LeftRight(
delfem2::CMatrixSparse<double> &mat,
const double *scale) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int nblk = mat.nrowblk_;
const unsigned int len = mat.nrowdim_;
const unsigned int blksize = len * len;
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
const unsigned int jno = mat.row_ptr_[icrs0];
for (unsigned int ilen = 0; ilen < len; ++ilen) {
for (unsigned int jlen = 0; jlen < len; ++jlen) {
mat.val_crs_[icrs0 * blksize + ilen * len + jlen] *=
scale[ino * len + ilen] * scale[jno * len + jlen];
}
}
}
}
if (!mat.val_dia_.empty()) {
for (unsigned int ino = 0; ino < nblk; ++ino) {
for (unsigned int ilen = 0; ilen < len; ++ilen) {
for (unsigned int jlen = 0; jlen < len; ++jlen) {
mat.val_dia_[ino * blksize + ilen * len + jlen] *=
scale[ino * len + ilen] * scale[ino * len + jlen];
}
}
}
}
}
DFM2_INLINE double delfem2::CheckSymmetry(
const delfem2::CMatrixSparse<double> &mat) {
assert(mat.ncolblk_ == mat.nrowblk_);
assert(mat.ncoldim_ == mat.nrowdim_);
const unsigned int blksize = mat.nrowdim_ * mat.ncoldim_;
const unsigned int nlen = mat.nrowdim_;
//
double sum = 0;
for (unsigned int ino = 0; ino < mat.nrowblk_; ++ino) {
for (unsigned int icrs0 = mat.col_ind_[ino]; icrs0 < mat.col_ind_[ino + 1]; ++icrs0) {
unsigned int jno = mat.row_ptr_[icrs0];
unsigned int icrs1 = mat.col_ind_[jno];
for (; icrs1 < mat.col_ind_[jno + 1]; ++icrs1) {
if (mat.row_ptr_[icrs1] == ino) { break; }
}
if (icrs1 == mat.col_ind_[jno + 1]) { // no counterpart
sum += mats::MatNorm(
mat.val_crs_.data() + blksize * icrs0, mat.nrowdim_, mat.ncoldim_);
} else {
sum += mats::MatNorm_Assym(
mat.val_crs_.data() + blksize * icrs0, mat.nrowdim_, mat.ncoldim_,
mat.val_crs_.data() + blksize * icrs1);
}
}
sum += mats::MatNorm_Assym(mat.val_dia_.data() + blksize * ino, nlen);
}
return sum;
}
| 34.642984 | 113 | 0.553374 | [
"vector"
] |
b2befc3ba8fb7dbd9072a3efc188f4e189da1586 | 5,405 | cpp | C++ | apps/openmw/mwgui/containeritemmodel.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwgui/containeritemmodel.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwgui/containeritemmodel.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #include "containeritemmodel.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/class.hpp"
#include "../mwbase/world.hpp"
#include "../mwbase/environment.hpp"
namespace
{
bool stacks (const MWWorld::Ptr& left, const MWWorld::Ptr& right)
{
if (left == right)
return true;
// If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure
if (left.getContainerStore() && right.getContainerStore())
return left.getContainerStore()->stacks(left, right)
&& right.getContainerStore()->stacks(left, right);
if (left.getContainerStore())
return left.getContainerStore()->stacks(left, right);
if (right.getContainerStore())
return right.getContainerStore()->stacks(left, right);
MWWorld::ContainerStore store;
return store.stacks(left, right);
}
}
namespace MWGui
{
ContainerItemModel::ContainerItemModel(const std::vector<MWWorld::Ptr>& itemSources, const std::vector<MWWorld::Ptr>& worldItems)
: mItemSources(itemSources)
, mWorldItems(worldItems)
{
assert (mItemSources.size());
}
ContainerItemModel::ContainerItemModel (const MWWorld::Ptr& source)
{
mItemSources.push_back(source);
}
ItemStack ContainerItemModel::getItem (ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t ContainerItemModel::getItemCount()
{
return mItems.size();
}
ItemModel::ModelIndex ContainerItemModel::getIndex (ItemStack item)
{
size_t i = 0;
for (std::vector<ItemStack>::iterator it = mItems.begin(); it != mItems.end(); ++it)
{
if (*it == item)
return i;
++i;
}
return -1;
}
MWWorld::Ptr ContainerItemModel::copyItem (const ItemStack& item, size_t count, bool setNewOwner)
{
const MWWorld::Ptr& source = mItemSources[mItemSources.size()-1];
if (item.mBase.getContainerStore() == &source.getClass().getContainerStore(source))
throw std::runtime_error("Item to copy needs to be from a different container!");
return *source.getClass().getContainerStore(source).add(item.mBase, count, source);
}
void ContainerItemModel::removeItem (const ItemStack& item, size_t count)
{
int toRemove = count;
for (std::vector<MWWorld::Ptr>::iterator source = mItemSources.begin(); source != mItemSources.end(); ++source)
{
MWWorld::ContainerStore& store = source->getClass().getContainerStore(*source);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (stacks(*it, item.mBase))
{
toRemove -= store.remove(*it, toRemove, *source);
if (toRemove <= 0)
return;
}
}
}
for (std::vector<MWWorld::Ptr>::iterator source = mWorldItems.begin(); source != mWorldItems.end(); ++source)
{
if (stacks(*source, item.mBase))
{
int refCount = source->getRefData().getCount();
if (refCount - toRemove <= 0)
MWBase::Environment::get().getWorld()->deleteObject(*source);
else
source->getRefData().setCount(std::max(0, refCount - toRemove));
toRemove -= refCount;
if (toRemove <= 0)
return;
}
}
throw std::runtime_error("Not enough items to remove could be found");
}
void ContainerItemModel::update()
{
mItems.clear();
for (std::vector<MWWorld::Ptr>::iterator source = mItemSources.begin(); source != mItemSources.end(); ++source)
{
MWWorld::ContainerStore& store = source->getClass().getContainerStore(*source);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
std::vector<ItemStack>::iterator itemStack = mItems.begin();
for (; itemStack != mItems.end(); ++itemStack)
{
if (stacks(*it, itemStack->mBase))
{
// we already have an item stack of this kind, add to it
itemStack->mCount += it->getRefData().getCount();
break;
}
}
if (itemStack == mItems.end())
{
// no stack yet, create one
ItemStack newItem (*it, this, it->getRefData().getCount());
mItems.push_back(newItem);
}
}
}
for (std::vector<MWWorld::Ptr>::iterator source = mWorldItems.begin(); source != mWorldItems.end(); ++source)
{
std::vector<ItemStack>::iterator itemStack = mItems.begin();
for (; itemStack != mItems.end(); ++itemStack)
{
if (stacks(*source, itemStack->mBase))
{
// we already have an item stack of this kind, add to it
itemStack->mCount += source->getRefData().getCount();
break;
}
}
if (itemStack == mItems.end())
{
// no stack yet, create one
ItemStack newItem (*source, this, source->getRefData().getCount());
mItems.push_back(newItem);
}
}
}
}
| 31.982249 | 129 | 0.586124 | [
"vector"
] |
b2c3aa918bf43acf925dc6d0554116e8e7e5063b | 1,408 | cpp | C++ | Day 10 - Syntax Scoring/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | 1 | 2021-12-02T19:07:17.000Z | 2021-12-02T19:07:17.000Z | Day 10 - Syntax Scoring/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | Day 10 - Syntax Scoring/Part 1/src/main.cpp | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | //
// main.cpp
// ADVENT OF CODE 2021: Day 10 - Syntax Scoring (Part 1)
//
// Created by diff-arch on 10/12/2021.
//
// Goal: Find the first illegal character in each corrupted line of the navigation subsystem.
// What is the total syntax error score for those errors?
//
// Compile: g++ -std=c++11 -o bin/a.out src/*.cpp
// Run: ./bin/a.out
//
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <deque>
#include <map>
#include "Utils.h"
int main() {
const char* fpath = "../bin/data/syntax-scoring.txt"; // insert your path
std::vector<std::string> lines = readData(fpath);
std::map<char, char> brackets {
{'(', ')'},
{'[', ']'},
{'{', '}'},
{'<', '>'},
};
std::map<char, char> rbrackets;
for (const std::pair<char, char>& p : brackets)
rbrackets.emplace(p.second, p.first);
std::map<char, int> score_table = {
{')', 3 },
{']', 57 },
{'}', 1197 },
{'>', 25137},
};
int score = 0;
for (const std::string& line : lines) {
std::deque<char> dq;
for (const char& c : line) {
if (brackets.find(c) != brackets.end()) {
dq.push_back(c);
} else if (rbrackets.find(c) != rbrackets.end()) {
if (dq.back() != rbrackets[c]) {
score += score_table[c];
break;
} else {
dq.pop_back();
}
}
}
}
std::cout << "Total Syntax Error Score: " << score << "\n";
}
| 20.114286 | 98 | 0.553977 | [
"vector"
] |
b2d3ecd54a294b7b362859c6207cf8ecc24cb8cf | 816 | cpp | C++ | graph/bfs/TargetNumber.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | graph/bfs/TargetNumber.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | graph/bfs/TargetNumber.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | //프로그래머스
//BFS - 타겟 넘버
#include <string>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
int operation[2] = {1, -1};
int solution(vector<int> numbers, int target) {
int answer = 0, idx = 1;
int size = numbers.size();
queue<pair<int,int>> q;
q.push(make_pair(numbers[0],0));
q.push(make_pair(-1 * numbers[0],0));
while(!q.empty()) {
int now = q.front().first, idx = q.front().second;
q.pop();
if(idx == size - 1) {
if(now == target) {
answer++;
}
continue;
}
for(int opIdx = 0; opIdx < 2 && idx < size - 1; opIdx++) {
q.push(make_pair(now + (numbers[idx + 1] * operation[opIdx]),idx + 1));
}
}
return answer;
} | 22.666667 | 83 | 0.488971 | [
"vector"
] |
b2dd4b419f065534ab37907346548ef75d921b5f | 4,962 | hxx | C++ | odb-tests-2.4.0/common/container/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/common/container/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/common/container/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | // file : common/container/basics/test.hxx
// copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC
// license : GNU GPL v2; see accompanying LICENSE file
#ifndef TEST_HXX
#define TEST_HXX
#include <common/config.hxx> // HAVE_CXX11
#include <map>
#include <set>
#include <list>
#include <vector>
#include <deque>
#include <string>
#ifdef HAVE_CXX11
# include <array>
# include <forward_list>
# include <unordered_map>
# include <unordered_set>
#endif
#include <odb/core.hxx>
#pragma db value
struct comp
{
comp () {}
comp (int n, const std::string& s) : num (n), str (s) {}
#pragma db column("number")
int num;
std::string str;
};
inline bool
operator== (const comp& x, const comp& y)
{
return x.num == y.num && x.str == y.str;
}
inline bool
operator!= (const comp& x, const comp& y)
{
return !(x == y);
}
inline bool
operator< (const comp& x, const comp& y)
{
return x.num != y.num ? x.num < y.num : x.str < y.str;
}
typedef std::list<std::string> str_list;
typedef std::deque<int> num_deque;
typedef std::vector<int> num_vector;
typedef std::vector<std::string> str_vector;
typedef std::set<int> num_set;
typedef std::set<std::string> str_set;
typedef std::set<comp> comp_set;
typedef std::map<int, std::string> num_str_map;
typedef std::map<std::string, int> str_num_map;
typedef std::map<int, comp> num_comp_map;
typedef std::map<comp, std::string> comp_str_map;
#ifdef HAVE_CXX11
struct comp_hash
{
std::size_t
operator() (const comp& x) const {return nh (x.num) + sh (x.str);}
std::hash<int> nh;
std::hash<std::string> sh;
};
typedef std::array<int, 3> num_array;
typedef std::array<std::string, 3> str_array;
typedef std::array<comp, 3> comp_array;
typedef std::forward_list<int> num_flist;
typedef std::forward_list<std::string> str_flist;
typedef std::forward_list<comp> comp_flist;
typedef std::unordered_set<int> num_uset;
typedef std::unordered_set<std::string> str_uset;
typedef std::unordered_set<comp, comp_hash> comp_uset;
typedef std::unordered_map<int, std::string> num_str_umap;
typedef std::unordered_map<std::string, int> str_num_umap;
typedef std::unordered_map<int, comp> num_comp_umap;
typedef std::unordered_map<comp, std::string, comp_hash> comp_str_umap;
#endif
#pragma db value
struct cont_comp1
{
// This composite value does not have any columns.
//
num_vector sv; // Have the name "conflic" with the one in the object.
};
#pragma db value
struct cont_comp2
{
cont_comp2 (): num (777), str ("ggg") {}
int num;
str_list sl;
std::string str;
};
#pragma db object
struct object
{
object (): nv (comp1_.sv), sl (comp2_.sl) {}
object (const std::string& id) : id_ (id), nv (comp1_.sv), sl (comp2_.sl) {}
#pragma db id
std::string id_;
int num;
cont_comp1 comp1_;
cont_comp2 comp2_;
// vector
//
#pragma db transient
num_vector& nv;
#pragma db table("object_strings") id_column ("obj_id")
str_vector sv;
#pragma db value_column("")
std::vector<comp> cv;
#pragma db unordered
num_vector uv;
// list
//
#pragma db transient
str_list& sl;
// deque
//
num_deque nd;
// set
//
num_set ns;
str_set ss;
comp_set cs;
// map
//
num_str_map nsm;
str_num_map snm;
num_comp_map ncm;
comp_str_map csm;
#ifdef HAVE_CXX11
// array
//
num_array na;
str_array sa;
comp_array ca;
// forward_list
//
num_flist nfl;
str_flist sfl;
comp_flist cfl;
// unordered_set
//
num_uset nus;
str_uset sus;
comp_uset cus;
// unordered_map
//
num_str_umap nsum;
str_num_umap snum;
num_comp_umap ncum;
comp_str_umap csum;
#else
// Dummy containers to get the equivalent DROP TABLE statements.
//
num_vector na;
num_vector sa;
num_vector ca;
num_vector nfl;
num_vector sfl;
num_vector cfl;
num_set nus;
str_set sus;
comp_set cus;
num_str_map nsum;
str_num_map snum;
num_comp_map ncum;
comp_str_map csum;
#endif
std::string str;
};
inline bool
operator== (const object& x, const object& y)
{
if (x.uv.size () != y.uv.size ())
return false;
int xs (0), ys (0);
for (num_vector::size_type i (0); i < x.uv.size (); ++i)
{
xs += x.uv[i];
ys += y.uv[i];
}
return
x.id_ == y.id_ &&
x.num == y.num &&
x.comp2_.num == y.comp2_.num &&
x.comp2_.str == y.comp2_.str &&
x.nv == y.nv &&
x.sv == y.sv &&
x.cv == y.cv &&
xs == ys &&
x.sl == y.sl &&
x.nd == y.nd &&
x.ns == y.ns &&
x.ss == y.ss &&
x.cs == y.cs &&
x.nsm == y.nsm &&
x.snm == y.snm &&
x.ncm == y.ncm &&
x.csm == y.csm &&
#ifdef HAVE_CXX11
x.na == y.na &&
x.sa == y.sa &&
x.ca == y.ca &&
x.nfl == y.nfl &&
x.sfl == y.sfl &&
x.cfl == y.cfl &&
x.nus == y.nus &&
x.sus == y.sus &&
x.cus == y.cus &&
x.nsum == y.nsum &&
x.snum == y.snum &&
x.ncum == y.ncum &&
x.csum == y.csum &&
#endif
x.str == y.str;
}
#endif // TEST_HXX
| 17.913357 | 78 | 0.6316 | [
"object",
"vector"
] |
b2e4c6b45f3b67d758a53406936404a115a87e42 | 1,618 | cc | C++ | tinyrpc/coroutine/coroutine_pool.cc | Gooddbird/tinyrpc | b87b8ba3ddf3e17b235e29c73131e6912b875b6f | [
"Apache-2.0"
] | 11 | 2022-02-27T17:32:46.000Z | 2022-03-27T04:09:22.000Z | tinyrpc/coroutine/coroutine_pool.cc | Gooddbird/tinyrpc | b87b8ba3ddf3e17b235e29c73131e6912b875b6f | [
"Apache-2.0"
] | 1 | 2022-03-08T05:12:37.000Z | 2022-03-08T05:37:44.000Z | tinyrpc/coroutine/coroutine_pool.cc | Gooddbird/tinyrpc | b87b8ba3ddf3e17b235e29c73131e6912b875b6f | [
"Apache-2.0"
] | 5 | 2022-02-28T07:45:41.000Z | 2022-03-26T06:25:28.000Z | #include <vector>
#include "tinyrpc/comm/config.h"
#include "tinyrpc/coroutine/coroutine_pool.h"
#include "tinyrpc/coroutine/coroutine.h"
namespace tinyrpc {
extern tinyrpc::Config::ptr gRpcConfig;
static thread_local CoroutinePool* t_coroutine_container_ptr = nullptr;
CoroutinePool* GetCoroutinePool() {
if (!t_coroutine_container_ptr) {
t_coroutine_container_ptr = new CoroutinePool(gRpcConfig->m_cor_pool_size, gRpcConfig->m_cor_stack_size);
}
return t_coroutine_container_ptr;
}
CoroutinePool::CoroutinePool(int pool_size, int stack_size /*= 1024 * 128*/) : m_pool_size(pool_size), m_stack_size(stack_size) {
m_index = getCoroutineIndex();
if (m_index == 0) {
// skip main coroutine
m_index = 1;
}
m_free_cors.resize(pool_size + m_index);
for (int i = m_index; i < pool_size + m_index; ++i) {
m_free_cors[i] = std::make_pair(std::make_shared<Coroutine>(stack_size), false);
}
}
CoroutinePool::~CoroutinePool() {
}
Coroutine::ptr CoroutinePool::getCoroutineInstanse() {
for (int i = m_index; i < m_pool_size; ++i) {
if (!m_free_cors[i].first->getIsInCoFunc() && !m_free_cors[i].second) {
m_free_cors[i].second = true;
return m_free_cors[i].first;
}
}
int newsize = (int)(1.5 * m_pool_size);
for (int i = 0; i < newsize - m_pool_size; ++i) {
m_free_cors.push_back(m_free_cors[i] = std::make_pair(std::make_shared<Coroutine>(m_stack_size), false));
}
int tmp = m_pool_size;
m_pool_size = newsize;
return m_free_cors[tmp].first;
}
void CoroutinePool::returnCoroutine(int cor_id) {
m_free_cors[cor_id].second = false;
}
} | 24.892308 | 129 | 0.707664 | [
"vector"
] |
b2ec7097e18eb7745bf7f65d568869480c6e8443 | 3,307 | cpp | C++ | engine/src/wolf.render/directX/w_gui/w_user_controls/w_rounded_rectangle_shape.cpp | SiminBadri/Wolf.Engine | 3da04471ec26e162e1cbb7cc88c7ce37ee32c954 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | 1 | 2020-07-15T13:14:26.000Z | 2020-07-15T13:14:26.000Z | engine/src/wolf.render/directX/w_gui/w_user_controls/w_rounded_rectangle_shape.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | engine/src/wolf.render/directX/w_gui/w_user_controls/w_rounded_rectangle_shape.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | #include "w_directX_pch.h"
#include "w_rounded_rectangle_shape.h"
#include "w_gui/w_widgets_resource_manager.h"
using namespace wolf::gui;
w_rounded_rectangle_shape::w_rounded_rectangle_shape(_In_opt_ w_widget* pParent) :
_super(pParent),
fill_color(128, 57, 123, 255),
mouse_over_color(169,75,162,255),
border_color(w_color::from_hex(w_color::WHITE)),
disabled_color(50, 50, 50, 150),
stroke_width(1),
_rectangle(nullptr)
{
_super::set_class_name(typeid(this).name());
_super::type = W_GUI_CONTROL_SHAPE;
}
w_rounded_rectangle_shape::~w_rounded_rectangle_shape()
{
release();
}
HRESULT w_rounded_rectangle_shape::on_initialize(const std::shared_ptr<wolf::graphics::w_graphics_device>& pGDevice)
{
int _x = 0, _y = 0;
if (parent_widget)
{
parent_widget->get_position(_x, _y);
if (parent_widget->get_is_caption_enabled())
{
_y += parent_widget->get_caption_height();
}
}
this->_rectangle = new wolf::graphics::direct2D::shapes::w_rectangle(pGDevice, _x + this->x, _y + this->y, this->width, this->height);
this->_rectangle->set_stroke_width(this->stroke_width);
return S_OK;
}
bool w_rounded_rectangle_shape::contains_point(_In_ const POINT& pPoint)
{
return PtInRect(&(_super::bounding_box), pPoint) != 0;
}
bool w_rounded_rectangle_shape::can_have_focus()
{
return false;
}
void w_rounded_rectangle_shape::render(_In_ const std::shared_ptr<wolf::graphics::w_graphics_device>& pGDevice, _In_ float pElapsedTime)
{
if (!this->visible) return;
W_GUI_CONTROL_STATE _control_state = W_GUI_STATE_NORMAL;
if (!_super::enabled)
{
_control_state = W_GUI_STATE_DISABLED;
this->_rectangle->set_color(this->disabled_color);
}
else if (this->mouse_over)
{
_control_state = W_GUI_STATE_MOUSEOVER;
this->_rectangle->set_color(this->mouse_over_color);
}
else
{
this->_rectangle->set_color(this->fill_color);
}
this->_rectangle->set_border_color(this->border_color);
if (this->parent_widget)
{
this->parent_widget->draw_shape(this->_rectangle);
}
}
ULONG w_rounded_rectangle_shape::release()
{
if (_super::get_is_released()) return 0;
SAFE_RELEASE(this->_rectangle);
_super::release();
}
#pragma region Setters
void w_rounded_rectangle_shape::set_position_2d(_In_ int pX, _In_ int pY)
{
set_geormetry(pX, pY, this->width, this->height, this->corner_radius.x, this->corner_radius.y);
_super::set_position_2d(pX, pY);
}
void w_rounded_rectangle_shape::set_geormetry(_In_ const float pLeft, _In_ const float pTop,
_In_ float const pWidth, _In_ const float pHeight,
_In_ float const pRadiusX, _In_ const float pRadiusY)
{
this->x = pLeft;
this->y = pTop;
this->width = pWidth;
this->height = pHeight;
this->corner_radius.x = pRadiusX;
this->corner_radius.y = pRadiusY;
if (this->_rectangle)
{
int _x = 0, _y = 0;
if (parent_widget)
{
parent_widget->get_position(_x, _y);
if (parent_widget->get_is_caption_enabled())
{
_y += parent_widget->get_caption_height();
}
}
this->_rectangle->set_geormetry(_x + this->x, _y + this->y, this->width, this->height, pRadiusX, pRadiusY);
_super::update_rects();
}
}
void w_rounded_rectangle_shape::set_stroke_width(_In_ const float pValue)
{
this->stroke_width = pValue;
if (this->_rectangle)
{
this->_rectangle->set_stroke_width(pValue);
}
}
#pragma endregion
| 24.138686 | 136 | 0.740248 | [
"render"
] |
b2ed4cbec4782d461af3a9f1689bc467dab3705e | 896 | hpp | C++ | libadb/include/libadb/api/channel/data/thread-member.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 1 | 2022-03-10T15:14:13.000Z | 2022-03-10T15:14:13.000Z | libadb/include/libadb/api/channel/data/thread-member.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 9 | 2022-03-07T21:00:08.000Z | 2022-03-15T23:14:52.000Z | libadb/include/libadb/api/channel/data/thread-member.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | null | null | null | #pragma once
#include <optional>
#include <cstdint>
#include <nlohmann/json_fwd.hpp>
#include <libadb/types/snowflake.hpp>
#include <libadb/types/time.hpp>
#include <libadb/libadb.hpp>
namespace adb::api
{
/**
* @brief Thread Member
* @details https://discord.com/developers/docs/resources/channel#thread-member-object
*/
struct ThreadMember
{
/// the id of the thread
std::optional<adb::types::SFID> id;
/// the id of the user
std::optional<adb::types::SFID> userId;
/// the time the current user last joined the thread
adb::types::TimePoint joinTimestamp;
/// any user-thread settings, currently only used for notifications
size_t flags;
};
LIBADB_API void to_json(nlohmann::json& j, const ThreadMember& member);
LIBADB_API void from_json(const nlohmann::json& j, ThreadMember& member);
} | 29.866667 | 90 | 0.666295 | [
"object"
] |
b2f191c5f89f72e55efbebe08f501aeb8118e297 | 202,196 | cxx | C++ | main/framework/test/typecfg/xml2xcd.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/framework/test/typecfg/xml2xcd.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/framework/test/typecfg/xml2xcd.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#define VCL_NEED_BASETSD
#include <tools/presys.h>
#include <windows.h>
#include <tools/postsys.h>
#include <classes/servicemanager.hxx>
#include <classes/filtercache.hxx>
#include <macros/generic.hxx>
#include <macros/debug.hxx>
#include <services.h>
#include <filterflags.h>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#include <comphelper/processfactory.hxx>
#include <unotools/processfactory.hxx>
#include <vos/process.hxx>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
using namespace ::framework ;
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// defines
//_________________________________________________________________________________________________________________
/*
Versions: 1) first revision
- one entry for every property
- full loclized values
2) new property "Order" for filters ... but not right set!
all values are 0
3) decrease size of xml file
- don't write full localized values
- use own formatted string for all non localized values
- separate "Installed" flag for filters
4) set right values for "Order" property of filters
5) support for ContentHandler
draft 6) reactivate old filter names
??? draft 7) split xml into standard/optional => use DRAFT_SPLIT_VERSION till this version is well known!
*/
#define DRAFT_SPLIT_VERSION 7
#define ARGUMENT_PACKAGE_STANDARD DECLARE_ASCII("-pas=") // argument for package name of standard filters
#define ARGUMENT_PACKAGE_ADDITIONAL DECLARE_ASCII("-paa=") // argument for package name of additional filters
#define ARGUMENT_WRITEABLE DECLARE_ASCII("-wri=") // argument for "writeable" [true|false]
#define ARGUMENT_VERSION_INPUT DECLARE_ASCII("-vin=") // argument for file version to read [1|2|3]
#define ARGUMENT_VERSION_OUTPUT DECLARE_ASCII("-vou=") // argument for file version to write [1|2|3]
#define ARGUMENTLENGTH 5 // All arguments should have the same length ... it's better to detect it!
#define ARGUMENTFOUND 0 // OUString::compareTo returns 0 if searched string match given one
#define WRITEABLE_ON DECLARE_ASCII("true" )
#define WRITEABLE_OFF DECLARE_ASCII("false")
#define MINARGUMENTCOUNT 5 // no optional arguments allowed yet!
#define LISTFILE_STANDARDTYPES "typelist_standard.txt"
#define LISTFILE_ADDITIONALTYPES "typelist_additional.txt"
#define LISTFILE_STANDARDFILTER "filterlist_standard.txt"
#define LISTFILE_ADDITIONALFILTER "filterlist_additional.txt"
#define SCPFILE_STANDARD "scp_standard.txt"
#define SCPFILE_ADDITIONAL "scp_additional.txt"
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-***************************************************************************************************************/
struct AppMember
{
FilterCache* pFilterCache ; // pointer to configuration
StringHash aOldFilterNamesHash ; // converter tabel to restaurate old filter names
EFilterPackage ePackage ; // specify which package should be used => specify using of file name and buffer too!
// ::rtl::OUString sFileNameStandard ; // file name of our standard filter cfg
// ::rtl::OUString sFileNameAdditional ; // file name of our additional filter cfg
::rtl::OUString sPackageStandard ; // package name of our standard filter cfg
::rtl::OUString sPackageAdditional ; // package name of our additional filter cfg
::rtl::OUStringBuffer sBufferStandard ; // buffer of our standard filter cfg
::rtl::OUStringBuffer sBufferAdditional ; // buffer of our standard filter cfg
::rtl::OUStringBuffer sNew2OldSCPStandard ; // setup script to convert new to old filternames (standard filter)
::rtl::OUStringBuffer sNew2OldSCPAdditional ; // setup script to convert new to old filternames (additional filter)
::rtl::OUStringBuffer sStandardFilterList ;
::rtl::OUStringBuffer sAdditionalFilterList ;
::rtl::OUStringBuffer sStandardTypeList ;
::rtl::OUStringBuffer sAdditionalTypeList ;
sal_Bool bWriteable ; // enable/disable writable configuration items
sal_Int32 nVersionInput ; // format version of input xml file
sal_Int32 nVersionOutput ; // format version of output xcd file
sal_Int32 nOriginalTypes ;
sal_Int32 nOriginalFilters ;
sal_Int32 nOriginalDetectors ;
sal_Int32 nOriginalLoaders ;
sal_Int32 nOriginalContentHandlers ;
sal_Int32 nWrittenTypes ;
sal_Int32 nWrittenFilters ;
sal_Int32 nWrittenDetectors ;
sal_Int32 nWrittenLoaders ;
sal_Int32 nWrittenContentHandlers ;
};
/*-***************************************************************************************************************/
class XCDGenerator : public Application
{
//*************************************************************************************************************
public:
void Main();
//*************************************************************************************************************
private:
void impl_printCopyright ( ); // print copyright to stdout :-)
void impl_printSyntax ( ); // print help to stout for user
void impl_parseCommandLine ( AppMember& rMember ); // parse command line arguments and fill given struct
void impl_generateXCD ( ); // generate all xcd files by using current configuration
void impl_generateCopyright ( ); // generate copyrights
void impl_generateTypeTemplate ( ); // generate templates ...
void impl_generateFilterTemplate ( );
void impl_generateDetectorTemplate ( );
void impl_generateLoaderTemplate ( );
void impl_generateTypeSet ( ); // generate sets
void impl_generateFilterSet ( );
void impl_generateDetectorSet ( );
void impl_generateLoaderSet ( );
void impl_generateDefaults ( ); // generate defaults
void impl_generateContentHandlerTemplate ( );
void impl_generateContentHandlerSet ( );
void impl_generateFilterFlagTemplate ( const ::rtl::OUString& sName , // helper to write atomic elements
sal_Int32 nValue ,
const ::rtl::OString& sDescription = ::rtl::OString() );
void impl_generateIntProperty ( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
sal_Int32 nValue );
void impl_generateBoolProperty ( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
sal_Bool bValue );
void impl_generateStringProperty ( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const ::rtl::OUString& sValue );
void impl_generateStringListProperty ( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const ::framework::StringList& lValue );
void impl_generateUINamesProperty ( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const StringHash& lUINames );
::rtl::OUString impl_getOldFilterName ( const ::rtl::OUString& sNewName ); // convert filter names to old format
static void impl_classifyType ( const AppMember& rData ,
const ::rtl::OUString& sTypeName ,
EFilterPackage& ePackage ); // classify type as STANDARD or ADDITIONAL one
static void impl_classifyFilter ( const AppMember& rData ,
const ::rtl::OUString& sFilterName ,
EFilterPackage& ePackage ,
sal_Int32& nOrder ); // classify filter as STANDARD or ADDITIONAL filter, set order of standard filter too
static ::rtl::OUString impl_encodeSpecialSigns ( const ::rtl::OUString& sValue ); // encode strings for xml
static sal_Unicode impl_defineSeperator ( const ::framework::StringList& lList ); // search seperator for lists
static void impl_initFilterHashNew2Old ( StringHash& aHash ); // initialize converter table to restaurate old filter names
static void impl_orderAlphabetical ( css::uno::Sequence< ::rtl::OUString >& lList ); // sort stringlist of internal type-, filter- ... names in alphabetical order to generate xcd files every time in the same way
static sal_Bool impl_isUsAsciiAlphaDigit ( sal_Unicode c ,
sal_Bool bDigitAllowed = sal_True );
static ::rtl::OUString impl_encodeSetName ( const ::rtl::OUString& rSource );
//*************************************************************************************************************
private:
AppMember m_aData;
}; // class XCDGenerator
//_________________________________________________________________________________________________________________
// global variables
//_________________________________________________________________________________________________________________
XCDGenerator gGenerator;
//*****************************************************************************************************************
void XCDGenerator::Main()
{
// Must be :-)
// impl_printCopyright();
// Init global servicemanager and set it.
// It's necessary for other services ... e.g. configuration.
ServiceManager aManager;
::comphelper::setProcessServiceFactory( aManager.getGlobalUNOServiceManager() );
::utl::setProcessServiceFactory ( aManager.getGlobalUNOServiceManager() );
// Get optional commands from command line.
impl_parseCommandLine( m_aData );
// initialize converter table to match new to old filter names!
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
XCDGenerator::impl_initFilterHashNew2Old( m_aData.aOldFilterNamesHash );
}
// Create access to current set filter configuration.
// Attention: Please use it for a full fat office installation only!!
// We need an installation with ALL filters.
// Member m_pData is used in some impl-methods directly ...
m_aData.pFilterCache = new FilterCache( m_aData.nVersionInput, CONFIG_MODE_ALL_LOCALES );
// Get some statistic informations of current filled filter cache ... (e.g. count of current activae filters)
// because we need it to check if all filters are converted and written to disk.
// May be it's possible to lose some of them during conversion!!!
m_aData.nOriginalTypes = m_aData.pFilterCache->getAllTypeNames().getLength() ;
m_aData.nOriginalFilters = m_aData.pFilterCache->getAllFilterNames().getLength() ;
m_aData.nOriginalDetectors = m_aData.pFilterCache->getAllDetectorNames().getLength() ;
m_aData.nOriginalLoaders = m_aData.pFilterCache->getAllLoaderNames().getLength() ;
if( m_aData.nVersionInput >= 5 )
{
m_aData.nOriginalContentHandlers = m_aData.pFilterCache->getAllContentHandlerNames().getLength() ;
}
// Start generation of xcd file(s).
impl_generateXCD();
// Warn programmer if some items couldn't written to file!
LOG_ASSERT2( m_aData.nOriginalTypes != m_aData.nWrittenTypes , "XCDGenerator::Main()", "Generated xcd file could be invalid ... because I miss some types!" )
LOG_ASSERT2( m_aData.nOriginalFilters != m_aData.nWrittenFilters , "XCDGenerator::Main()", "Generated xcd file could be invalid ... because I miss some filters!" )
LOG_ASSERT2( m_aData.nOriginalDetectors!= m_aData.nWrittenDetectors, "XCDGenerator::Main()", "Generated xcd file could be invalid ... because I miss some detectors!" )
LOG_ASSERT2( m_aData.nOriginalLoaders != m_aData.nWrittenLoaders , "XCDGenerator::Main()", "Generated xcd file could be invalid ... because I miss some loaders!" )
// Free memory.
delete m_aData.pFilterCache;
m_aData.pFilterCache = NULL;
}
/*-************************************************************************************************************//**
@short print some info messages to stderr
@descr We must show an copyright or help for using this file.
This two methods do that.
@seealso -
@param -
@return -
@onerror -
*//*-*************************************************************************************************************/
void XCDGenerator::impl_printCopyright()
{
fprintf( stderr, "\nLicensed to the Apache Software Foundation.\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_printSyntax()
{
// It's not possible to print it out to stdout in a svdem binary :-(
// So we show an assert.
::rtl::OStringBuffer sBuffer( 500 );
sBuffer.append( "\nusing: xml2xcd -fis=<file standard filter> -fia=<file additional filter> -pas=<package standard filter> -paa=<package additional filter> -vin=<version input> -vou=<version output> [-wri=<true|false>]\n\n" );
sBuffer.append( "\tneccessary parameters:\n" );
sBuffer.append( "\t\t-fis\tname of output file in system notation\n" );
sBuffer.append( "\t\t-fia\tname of output file in system notation\n" );
sBuffer.append( "\t\t-pas\tpackage of standard filters\n" );
sBuffer.append( "\t\t-paa\tpackage of additional filters\n" );
sBuffer.append( "\t\t-vin\tformat version of input xml file\n" );
sBuffer.append( "\t\t-vou\tformat version of generated xcd file\n\n" );
sBuffer.append( "\toptional parameters:\n" );
sBuffer.append( "\t\t-wri\tconfig items should be writeable ... [true|false]\n" );
LOG_ERROR( "", sBuffer.makeStringAndClear() )
}
/*-************************************************************************************************************//**
@short analyze command line arguments
@descr Created binary accept different command line arguments. These parameters
regulate creation of xcd file. Follow arguments are supported:
"-fis=<filename of standard xcd>"
"-fia=<filename of additional xcd>"
"-wri=<writeable>[true|false]"
"-vin=<version of input file>[1|2|3]"
"-vou=<version of output file>[1|2|3]"
@seealso -
@param "rMember", reference to struct of global application member to fill arguments in it
@return right filled member struct or unchanged struct if an error occur!
@onerror We do nothing - or warn programmer!
*//*-*************************************************************************************************************/
void XCDGenerator::impl_parseCommandLine( AppMember& rMember )
{
::vos::OStartupInfo aInfo ;
::rtl::OUString sArgument ;
sal_Int32 nArgument = 0 ;
sal_Int32 nCount = aInfo.getCommandArgCount();
sal_Int32 nMinCount = 0 ;
while( nArgument<nCount )
{
aInfo.getCommandArg( nArgument, sArgument );
/*OBSOLETE
//_____________________________________________________________________________________________________
// look for "-fis=..."
if( sArgument.compareTo( ARGUMENT_FILENAME_STANDARD, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
rMember.sFileNameStandard = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
++nMinCount;
}
else
//_____________________________________________________________________________________________________
// look for "-fia=..."
if( sArgument.compareTo( ARGUMENT_FILENAME_ADDITIONAL, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
rMember.sFileNameAdditional = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
++nMinCount;
}
else
*/
//_____________________________________________________________________________________________________
// look for "-pas=..."
if( sArgument.compareTo( ARGUMENT_PACKAGE_STANDARD, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
rMember.sPackageStandard = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
++nMinCount;
}
else
//_____________________________________________________________________________________________________
// look for "-paa=..."
if( sArgument.compareTo( ARGUMENT_PACKAGE_ADDITIONAL, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
rMember.sPackageAdditional = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
++nMinCount;
}
else
//_____________________________________________________________________________________________________
// look for "-wri=..."
if( sArgument.compareTo( ARGUMENT_WRITEABLE, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
::rtl::OUString sWriteable = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
if( sWriteable == WRITEABLE_ON )
{
rMember.bWriteable = sal_True;
}
else
{
rMember.bWriteable = sal_False;
}
++nMinCount;
}
//_____________________________________________________________________________________________________
// look for "-vin=..."
if( sArgument.compareTo( ARGUMENT_VERSION_INPUT, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
::rtl::OUString sVersion = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
rMember.nVersionInput = sVersion.toInt32();
++nMinCount;
}
//_____________________________________________________________________________________________________
// look for "-vou=..."
if( sArgument.compareTo( ARGUMENT_VERSION_OUTPUT, ARGUMENTLENGTH ) == ARGUMENTFOUND )
{
::rtl::OUString sVersion = sArgument.copy( ARGUMENTLENGTH, sArgument.getLength()-ARGUMENTLENGTH );
rMember.nVersionOutput = sVersion.toInt32();
++nMinCount;
}
++nArgument;
}
// Show help if user don't call us right!
if( nMinCount != MINARGUMENTCOUNT )
{
impl_printSyntax();
exit(-1);
}
}
/*-************************************************************************************************************//**
@short regulate generation of complete xcd file(s)
@descr This method is the toppest one and implement the global structure of generated xcd file(s).
We create a unicode string buffer for complete xcd file in memory ...
use different helper methods to fill it ...
and write it to disk at the end of this method!
@seealso struct AppMember
@param -
@return -
@onerror -
*//*-*************************************************************************************************************/
void XCDGenerator::impl_generateXCD()
{
impl_generateCopyright();
// Write header
m_aData.sBufferStandard.appendAscii ( "\n<!-- PLEASE DON'T CHANGE TEMPLATES OR FILE FORMAT BY HAND! USE \"XML2XCD.EXE\" TO DO THAT. THANKS. -->\n\n" );
m_aData.sBufferStandard.appendAscii ( "<!DOCTYPE schema:component SYSTEM \"../../../../schema/schema.description.dtd\">\n" );
m_aData.sBufferStandard.appendAscii ( "<schema:component cfg:name=\"" );
m_aData.sBufferStandard.append ( m_aData.sPackageStandard );
m_aData.sBufferStandard.appendAscii ( "\" cfg:package=\"org.openoffice.Office\" xml:lang=\"en-US\" xmlns:schema=\"http://openoffice.org/2000/registry/schema/description\" xmlns:default=\"http://openoffice.org/2000/registry/schema/default\" xmlns:cfg=\"http://openoffice.org/2000/registry/instance\">\n" );
m_aData.sBufferStandard.appendAscii ( "\t<schema:templates>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii ( "\n<!-- PLEASE DON'T CHANGE TEMPLATES OR FILE FORMAT BY HAND! USE \"XML2XCD.EXE\" TO DO THAT. THANKS. -->\n\n" );
m_aData.sBufferAdditional.appendAscii ( "<!DOCTYPE schema:component SYSTEM \"../../../../schema/schema.description.dtd\">\n" );
m_aData.sBufferAdditional.appendAscii ( "<schema:component cfg:name=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageAdditional );
m_aData.sBufferAdditional.appendAscii ( "\" cfg:package=\"org.openoffice.Office\" xml:lang=\"en-US\" xmlns:schema=\"http://openoffice.org/2000/registry/schema/description\" xmlns:default=\"http://openoffice.org/2000/registry/schema/default\" xmlns:cfg=\"http://openoffice.org/2000/registry/instance\">\n" );
m_aData.sBufferAdditional.appendAscii ( "\t<schema:import cfg:name=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageStandard );
m_aData.sBufferAdditional.appendAscii ( "\"/>\n" );
}
// Follow ...generate... methods to nothing for additional filters!
impl_generateTypeTemplate ();
impl_generateFilterTemplate ();
impl_generateDetectorTemplate();
if( m_aData.nVersionOutput >= 5 )
{
impl_generateContentHandlerTemplate ();
}
impl_generateLoaderTemplate ();
m_aData.sBufferStandard.appendAscii ( "\t</schema:templates>\n" );
m_aData.sBufferStandard.appendAscii ( "<schema:schema cfg:localized=\"false\">\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t<schema:schema cfg:localized=\"false\">\n" );
}
impl_generateTypeSet ();
impl_generateFilterSet ();
impl_generateDetectorSet ();
if( m_aData.nVersionInput >= 5 )
{
impl_generateContentHandlerSet ();
}
impl_generateLoaderSet ();
impl_generateDefaults ();
m_aData.sBufferStandard.appendAscii ( "\t</schema:schema>\n" );
m_aData.sBufferStandard.appendAscii ( "</schema:component>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii ( "\t</schema:schema>\n" );
m_aData.sBufferAdditional.appendAscii ( "</schema:component>\n" );
}
::rtl::OUString sFileName = m_aData.sPackageStandard ;
sFileName += DECLARE_ASCII(".xcd") ;
WRITE_LOGFILE( U2B( sFileName ) , U2B(m_aData.sBufferStandard.makeStringAndClear() ))
WRITE_LOGFILE( LISTFILE_STANDARDFILTER , U2B(m_aData.sStandardFilterList.makeStringAndClear() ))
WRITE_LOGFILE( LISTFILE_STANDARDTYPES , U2B(m_aData.sStandardTypeList.makeStringAndClear() ))
WRITE_LOGFILE( SCPFILE_STANDARD , U2B(m_aData.sNew2OldSCPStandard.makeStringAndClear() ))
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
sFileName = m_aData.sPackageAdditional ;
sFileName += DECLARE_ASCII(".xcd") ;
WRITE_LOGFILE( U2B(sFileName) , U2B(m_aData.sBufferAdditional.makeStringAndClear() ))
WRITE_LOGFILE( LISTFILE_ADDITIONALFILTER, U2B(m_aData.sAdditionalFilterList.makeStringAndClear() ))
WRITE_LOGFILE( LISTFILE_ADDITIONALTYPES , U2B(m_aData.sAdditionalTypeList.makeStringAndClear() ))
WRITE_LOGFILE( SCPFILE_ADDITIONAL , U2B(m_aData.sNew2OldSCPAdditional.makeStringAndClear() ))
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateCopyright()
{
m_aData.sBufferStandard.appendAscii( "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" );
m_aData.sBufferStandard.appendAscii( "<!--***********************************************************\n");
m_aData.sBufferStandard.appendAscii( " *\n");
m_aData.sBufferStandard.appendAscii( " * Licensed to the Apache Software Foundation (ASF) under one\n");
m_aData.sBufferStandard.appendAscii( " * or more contributor license agreements. See the NOTICE file\n");
m_aData.sBufferStandard.appendAscii( " * distributed with this work for additional information\n");
m_aData.sBufferStandard.appendAscii( " * regarding copyright ownership. The ASF licenses this file\n");
m_aData.sBufferStandard.appendAscii( " * to you under the Apache License, Version 2.0 (the\n");
m_aData.sBufferStandard.appendAscii( " * \"License\"); you may not use this file except in compliance\n");
m_aData.sBufferStandard.appendAscii( " * with the License. You may obtain a copy of the License at\n");
m_aData.sBufferStandard.appendAscii( " *\n");
m_aData.sBufferStandard.appendAscii( " * http://www.apache.org/licenses/LICENSE-2.0\n");
m_aData.sBufferStandard.appendAscii( " * \n");
m_aData.sBufferStandard.appendAscii( " * Unless required by applicable law or agreed to in writing,\n");
m_aData.sBufferStandard.appendAscii( " * software distributed under the License is distributed on an\n");
m_aData.sBufferStandard.appendAscii( " * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n");
m_aData.sBufferStandard.appendAscii( " * KIND, either express or implied. See the License for the\n");
m_aData.sBufferStandard.appendAscii( " * specific language governing permissions and limitations\n");
m_aData.sBufferStandard.appendAscii( " * under the License.\n");
m_aData.sBufferStandard.appendAscii( " * \n");
m_aData.sBufferStandard.appendAscii( " ***********************************************************-->\n");
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" );
m_aData.sBufferStandard.appendAscii( "<!--***********************************************************\n");
m_aData.sBufferStandard.appendAscii( " *\n");
m_aData.sBufferStandard.appendAscii( " * Licensed to the Apache Software Foundation (ASF) under one\n");
m_aData.sBufferStandard.appendAscii( " * or more contributor license agreements. See the NOTICE file\n");
m_aData.sBufferStandard.appendAscii( " * distributed with this work for additional information\n");
m_aData.sBufferStandard.appendAscii( " * regarding copyright ownership. The ASF licenses this file\n");
m_aData.sBufferStandard.appendAscii( " * to you under the Apache License, Version 2.0 (the\n");
m_aData.sBufferStandard.appendAscii( " * \"License\"); you may not use this file except in compliance\n");
m_aData.sBufferStandard.appendAscii( " * with the License. You may obtain a copy of the License at\n");
m_aData.sBufferStandard.appendAscii( " *\n");
m_aData.sBufferStandard.appendAscii( " * http://www.apache.org/licenses/LICENSE-2.0\n");
m_aData.sBufferStandard.appendAscii( " * \n");
m_aData.sBufferStandard.appendAscii( " * Unless required by applicable law or agreed to in writing,\n");
m_aData.sBufferStandard.appendAscii( " * software distributed under the License is distributed on an\n");
m_aData.sBufferStandard.appendAscii( " * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n");
m_aData.sBufferStandard.appendAscii( " * KIND, either express or implied. See the License for the\n");
m_aData.sBufferStandard.appendAscii( " * specific language governing permissions and limitations\n");
m_aData.sBufferStandard.appendAscii( " * under the License.\n");
m_aData.sBufferStandard.appendAscii( " * \n");
m_aData.sBufferStandard.appendAscii( " ***********************************************************-->\n");
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateTypeTemplate()
{
//_________________________________________________________________________________________________________________
if( m_aData.nVersionOutput==1 || m_aData.nVersionOutput==2 )
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"Type\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Preferred\" cfg:type=\"boolean\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii("\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the preferred type for an extension if more then one match given URL</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>false</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UIName\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the external name of this type</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"MediaType\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the mime type </schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"ClipboardFormat\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the clipboard format name</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"URLPattern\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the patterns used for URLs. This type is only relevant for HTTP, FTP etc. and is used for internal URL formats like private:factory etc.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Extensions\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the possible file extensions.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"DocumentIconID\" cfg:type=\"int\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the document icon ID of this type</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>0</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
//_________________________________________________________________________________________________________________
else if( m_aData.nVersionOutput>=3 )
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"Type\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UIName\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the external name of this type</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Data\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii("\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Contains all data of a type as an own formatted string.{Preferred, MediaType, ClipboardFormat, URLPattern, Extensions, DocumentIconID}</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>false</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateFilterTemplate()
{
//_________________________________________________________________________________________________________________
if( m_aData.nVersionOutput==1 || m_aData.nVersionOutput==2 )
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"Filter\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Installed\" cfg:type=\"boolean\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Make it possible to enable or disable filter by setup!</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>false</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
if( m_aData.nVersionOutput==2 )
{
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Order\" cfg:type=\"int\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies order of filters for relevant module; don't used for default filter!</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>0</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
}
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UIName\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the external name of the filter which is displayed at the user interface (dialog).</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Type\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the relative type key name of the filter, e.g. Type/T1</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"DocumentService\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the name of the UNO service to implement the document.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"FilterService\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the name of the UNO service for importing the document.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Flags\" cfg:type=\"int\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the properties of the filter</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:type-info>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:value-names>\n" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_IMPORT , FILTERFLAG_IMPORT , "mark filter for import" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_EXPORT , FILTERFLAG_EXPORT , "mark filter for export" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_TEMPLATE , FILTERFLAG_TEMPLATE );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_INTERNAL , FILTERFLAG_INTERNAL );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_TEMPLATEPATH , FILTERFLAG_TEMPLATEPATH );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_OWN , FILTERFLAG_OWN );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_ALIEN , FILTERFLAG_ALIEN );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_USESOPTIONS , FILTERFLAG_USESOPTIONS );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_DEFAULT , FILTERFLAG_DEFAULT , "most important filter, if more then ones available" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_NOTINFILEDIALOG , FILTERFLAG_NOTINFILEDIALOG, "don't show it in file dialogs!" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_NOTINCHOOSER , FILTERFLAG_NOTINCHOOSER , "don't show it in chooser!" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_ASYNCHRON , FILTERFLAG_ASYNCHRON );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_NOTINSTALLED , FILTERFLAG_NOTINSTALLED , "set, if the filter is not installed, but available on CD" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_CONSULTSERVICE , FILTERFLAG_CONSULTSERVICE , "set, if the filter is not installed and not available an CD" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_3RDPARTYFILTER , FILTERFLAG_3RDPARTYFILTER , "must set, if the filter is an external one" );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_PACKED , FILTERFLAG_PACKED );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_SILENTEXPORT , FILTERFLAG_SILENTEXPORT );
impl_generateFilterFlagTemplate( FILTERFLAGNAME_PREFERED , FILTERFLAG_PREFERED );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t</schema:value-names>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:constraints xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"/>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:type-info>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>0</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UserData\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the user-defined data</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data/>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"FileFormatVersion\" cfg:type=\"int\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<!--This should be removed to UserData later-->\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the file format version of the filter</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>0</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"TemplateName\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<!--This should be removed to UserData later-->\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the template used for importing the file with the specified filter.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
//_________________________________________________________________________________________________________________
}
else if( m_aData.nVersionOutput>=3 )
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"Filter\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Installed\" cfg:type=\"boolean\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Make it possible to enable or disable filter by setup!</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<default:data>false</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UIName\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the external name of the filter which is displayed at the user interface (dialog).</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Data\" cfg:type=\"string\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>All data of filter written in own format. {Order, OldName, Type, DocumentService, FilterService, Flags, UserData, FilteFormatVersion, TemplateName}</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateFilterFlagTemplate( const ::rtl::OUString& sName, sal_Int32 nValue, const ::rtl::OString& sDescription )
{
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t\t<schema:named-value name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\" value=\"" );
m_aData.sBufferStandard.append ( nValue );
m_aData.sBufferStandard.appendAscii( "\"" );
if( sDescription.getLength() > 0 )
{
m_aData.sBufferStandard.appendAscii( ">\n\t\t\t\t\t\t\t<schema:description>" );
m_aData.sBufferStandard.appendAscii( sDescription );
m_aData.sBufferStandard.appendAscii( "</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t\t</schema:named-value>\n" );
}
else
{
m_aData.sBufferStandard.appendAscii( "/>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateDetectorTemplate()
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"DetectService\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Types\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>List of types which the service has registered for.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateLoaderTemplate()
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"FrameLoader\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"UIName\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>Specifies the external name of the filter which is displayed at the user interface (dialog).</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Types\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>List of types which the service has registered for.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateContentHandlerTemplate()
{
m_aData.sBufferStandard.appendAscii( "\t\t<schema:group cfg:name=\"ContentHandler\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<schema:value cfg:name=\"Types\" cfg:type=\"string\" cfg:derivedBy=\"list\" cfg:writable=\"" );
m_aData.sBufferStandard.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t<schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t\t<schema:description>List of types which could be handled by this service.</schema:description>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t\t</schema:documentation>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t</schema:value>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:group>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateTypeSet()
{
if( m_aData.pFilterCache->hasTypes() == sal_False )
{
// generate empty set!
m_aData.sBufferStandard.appendAscii ( "\t<schema:set cfg:name=\"Types\" cfg:element-type=\"Type\"/>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t<schema:set cfg:name=\"Types\" cfg:element-type=\"Type\" cfg:component=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageStandard );
m_aData.sBufferAdditional.appendAscii( "\"/>\n" );
}
}
else
{
// generate filled set
// open set
m_aData.sBufferStandard.appendAscii ( "\t<schema:set cfg:name=\"Types\" cfg:element-type=\"Type\">\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t<schema:set cfg:name=\"Types\" cfg:element-type=\"Type\" cfg:component=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageStandard );
m_aData.sBufferAdditional.appendAscii( "\">\n" );
}
css::uno::Sequence< ::rtl::OUString > lNames = m_aData.pFilterCache->getAllTypeNames();
css::uno::Sequence< ::rtl::OUString > lEncNames ( lNames ) ;
sal_Int32 nCount = lNames.getLength() ;
sal_Int32 nItem = 0 ;
XCDGenerator::impl_orderAlphabetical( lNames );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
::rtl::OUString sName ;
::rtl::OUString sEncName;
for( nItem=0; nItem<nCount; ++nItem )
{
sName = lNames[nItem] ;
lEncNames[nItem] = impl_encodeSetName( sName );
}
}
for( nItem=0; nItem<nCount; ++nItem )
{
::rtl::OUString sName = lNames[nItem] ;
FileType aItem = m_aData.pFilterCache->getType( sName );
EFilterPackage ePackage ;
++m_aData.nWrittenTypes;
if( m_aData.nVersionOutput==1 || m_aData.nVersionOutput==2 )
{
// open set entry by using name
m_aData.sBufferStandard.appendAscii( "\t\t<default:group cfg:name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\">\n" );
// write properties
impl_generateBoolProperty ( m_aData.sBufferStandard, SUBKEY_PREFERRED , aItem.bPreferred );
impl_generateUINamesProperty ( m_aData.sBufferStandard, SUBKEY_UINAME , aItem.lUINames );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_MEDIATYPE , aItem.sMediaType );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_CLIPBOARDFORMAT , aItem.sClipboardFormat );
impl_generateStringListProperty ( m_aData.sBufferStandard, SUBKEY_URLPATTERN , aItem.lURLPattern );
impl_generateStringListProperty ( m_aData.sBufferStandard, SUBKEY_EXTENSIONS , aItem.lExtensions );
impl_generateIntProperty ( m_aData.sBufferStandard, SUBKEY_DOCUMENTICONID , aItem.nDocumentIconID );
// close set node
m_aData.sBufferStandard.appendAscii( "\t\t</default:group>\n" );
}
else if( m_aData.nVersionOutput >= 3 )
{
::rtl::OUString sPath = DECLARE_ASCII("org.openoffice.Office.");
::rtl::OUStringBuffer* pXCDBuffer = &(m_aData.sBufferStandard );
::rtl::OUStringBuffer* pSCPBuffer = &(m_aData.sNew2OldSCPStandard );
::rtl::OUStringBuffer* pListBuffer = &(m_aData.sStandardTypeList );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
XCDGenerator::impl_classifyType( m_aData, sName, ePackage );
switch( ePackage )
{
case E_ADDITIONAL : {
sPath += m_aData.sPackageAdditional ;
pXCDBuffer = &(m_aData.sBufferAdditional );
pSCPBuffer = &(m_aData.sNew2OldSCPAdditional);
pListBuffer = &(m_aData.sAdditionalTypeList );
}
}
}
else
{
sPath += m_aData.sPackageStandard;
}
sPath += CFG_PATH_SEPERATOR ;
sPath += DECLARE_ASCII( "Types" );
sPath += CFG_PATH_SEPERATOR ;
pListBuffer->append ( sName );
pListBuffer->appendAscii( "\n" );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
pSCPBuffer->appendAscii( "\"" );
pSCPBuffer->append ( sPath );
pSCPBuffer->append ( lNames[nItem] );
pSCPBuffer->appendAscii( "\"\t\"" );
pSCPBuffer->append ( sPath );
pSCPBuffer->appendAscii( "Type" );
pSCPBuffer->append ( CFG_ENCODING_OPEN );
pSCPBuffer->append ( lNames[nItem] );
pSCPBuffer->append ( CFG_ENCODING_CLOSE );
pSCPBuffer->appendAscii( "\"\n" );
sName = lEncNames[nItem];
aItem.sName = sName;
}
// open set entry by using name
pXCDBuffer->appendAscii( "\t\t<default:group cfg:name=\"" );
pXCDBuffer->append ( sName );
pXCDBuffer->appendAscii( "\">\n" );
// write properties
impl_generateUINamesProperty( *pXCDBuffer, SUBKEY_UINAME, aItem.lUINames );
impl_generateStringProperty ( *pXCDBuffer, SUBKEY_DATA , FilterCFGAccess::encodeTypeData( aItem ) );
// close set node
pXCDBuffer->appendAscii( "\t\t</default:group>\n" );
}
}
// close set
m_aData.sBufferStandard.appendAscii( "\t</schema:set>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t</schema:set>\n" );
}
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateFilterSet()
{
if( m_aData.pFilterCache->hasFilters() == sal_False )
{
// write empty filter set.
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"Filters\" cfg:element-type=\"Filter\"/>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t<schema:set cfg:name=\"Filters\" cfg:element-type=\"Filter\" cfg:component=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageStandard );
m_aData.sBufferAdditional.appendAscii( "\"/>\n" );
}
}
else
{
// open set
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"Filters\" cfg:element-type=\"Filter\">\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t<schema:set cfg:name=\"Filters\" cfg:element-type=\"Filter\" cfg:component=\"" );
m_aData.sBufferAdditional.append ( m_aData.sPackageStandard );
m_aData.sBufferAdditional.appendAscii( "\">\n" );
}
css::uno::Sequence< ::rtl::OUString > lNewNames = m_aData.pFilterCache->getAllFilterNames();
css::uno::Sequence< ::rtl::OUString > lOldNames ( lNewNames ) ;
css::uno::Sequence< ::rtl::OUString > lEncNames ( lNewNames ) ;
sal_Int32 nCount = lNewNames.getLength() ;
sal_Int32 nItem = 0 ;
XCDGenerator::impl_orderAlphabetical( lNewNames );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
::rtl::OUString sNewName;
::rtl::OUString sOldName;
for( nItem=0; nItem<nCount; ++nItem )
{
sNewName = lNewNames[nItem] ;
sOldName = impl_getOldFilterName ( sNewName );
lOldNames[nItem] = sOldName ;
lEncNames[nItem] = impl_encodeSetName ( sOldName );
}
}
for( nItem=0; nItem<nCount; ++nItem )
{
::rtl::OUString sName = lNewNames[nItem] ;
Filter aItem = m_aData.pFilterCache->getFilter( lNewNames[nItem] ) ;
EFilterPackage ePackage ;
++m_aData.nWrittenFilters;
if( m_aData.nVersionOutput==1 || m_aData.nVersionOutput==2 )
{
// open set node by using name
m_aData.sBufferStandard.appendAscii( "\t\t<default:group cfg:name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\">\n" );
// write properties
// Attention:
// We generate "Installed=false" for all entries ... because it's the default for all filters.
// You must work with a full office installation and change this to "true" in generated XML file!!!
impl_generateBoolProperty ( m_aData.sBufferStandard, SUBKEY_INSTALLED , sal_False );
impl_generateIntProperty ( m_aData.sBufferStandard, SUBKEY_ORDER , aItem.nOrder );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_TYPE , aItem.sType );
impl_generateUINamesProperty ( m_aData.sBufferStandard, SUBKEY_UINAME , aItem.lUINames );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_DOCUMENTSERVICE , aItem.sDocumentService );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_FILTERSERVICE , aItem.sFilterService );
impl_generateIntProperty ( m_aData.sBufferStandard, SUBKEY_FLAGS , aItem.nFlags );
impl_generateStringListProperty ( m_aData.sBufferStandard, SUBKEY_USERDATA , aItem.lUserData );
impl_generateIntProperty ( m_aData.sBufferStandard, SUBKEY_FILEFORMATVERSION, aItem.nFileFormatVersion );
impl_generateStringProperty ( m_aData.sBufferStandard, SUBKEY_TEMPLATENAME , aItem.sTemplateName );
// close set node
m_aData.sBufferStandard.appendAscii( "\t\t</default:group>\n" );
}
else if( m_aData.nVersionOutput>=3 )
{
::rtl::OUString sPath = DECLARE_ASCII("org.openoffice.Office.");
::rtl::OUStringBuffer* pXCDBuffer = &(m_aData.sBufferStandard );
::rtl::OUStringBuffer* pSCPBuffer = &(m_aData.sNew2OldSCPStandard );
::rtl::OUStringBuffer* pListBuffer = &(m_aData.sStandardFilterList );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
XCDGenerator::impl_classifyFilter( m_aData, sName, ePackage, aItem.nOrder );
switch( ePackage )
{
case E_ADDITIONAL : {
sPath += m_aData.sPackageAdditional ;
pXCDBuffer = &(m_aData.sBufferAdditional );
pSCPBuffer = &(m_aData.sNew2OldSCPAdditional);
pListBuffer = &(m_aData.sAdditionalFilterList);
}
}
}
else
{
sPath += m_aData.sPackageStandard;
}
sPath += CFG_PATH_SEPERATOR ;
sPath += DECLARE_ASCII( "Filters" );
sPath += CFG_PATH_SEPERATOR ;
pListBuffer->append ( sName );
pListBuffer->appendAscii( "\n" );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
pSCPBuffer->appendAscii( "\"" );
pSCPBuffer->append ( sPath );
pSCPBuffer->append ( lNewNames[nItem] );
pSCPBuffer->appendAscii( "\"\t\"" );
pSCPBuffer->append ( sPath );
pSCPBuffer->appendAscii( "Filter" );
pSCPBuffer->append ( CFG_ENCODING_OPEN );
pSCPBuffer->append ( lOldNames[nItem] );
pSCPBuffer->append ( CFG_ENCODING_CLOSE );
pSCPBuffer->appendAscii( "\"\n" );
sName = lEncNames[nItem];
aItem.sName = sName;
}
// open set node by using name
pXCDBuffer->appendAscii( "\t\t<default:group cfg:name=\"" );
pXCDBuffer->append ( sName );
pXCDBuffer->appendAscii( "\">\n" );
// write properties
// Attention:
// We generate "Installed=false" for all entries ... because it's the default for all filters.
// You must work with a full office installation and change this to "true" in generated XML file!!!
impl_generateBoolProperty ( *pXCDBuffer, SUBKEY_INSTALLED, sal_False );
impl_generateUINamesProperty( *pXCDBuffer, SUBKEY_UINAME , aItem.lUINames );
impl_generateStringProperty ( *pXCDBuffer, SUBKEY_DATA , FilterCFGAccess::encodeFilterData( aItem ) );
// close set node
pXCDBuffer->appendAscii( "\t\t</default:group>\n" );
}
}
// close set
m_aData.sBufferStandard.appendAscii( "\t</schema:set>\n" );
if( m_aData.nVersionOutput >= DRAFT_SPLIT_VERSION )
{
m_aData.sBufferAdditional.appendAscii( "\t</schema:set>\n" );
}
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateDetectorSet()
{
if( m_aData.pFilterCache->hasDetectors() == sal_False )
{
// write empty detector set!
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"DetectServices\" cfg:element-type=\"DetectService\"/>\n" );
}
else
{
// open set
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"DetectServices\" cfg:element-type=\"DetectService\">\n" );
css::uno::Sequence< ::rtl::OUString > lNames = m_aData.pFilterCache->getAllDetectorNames();
css::uno::Sequence< ::rtl::OUString > lEncNames ( lNames ) ;
sal_Int32 nCount = lNames.getLength() ;
sal_Int32 nItem = 0 ;
XCDGenerator::impl_orderAlphabetical( lNames );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
::rtl::OUString sName ;
::rtl::OUString sEncName;
for( nItem=0; nItem<nCount; ++nItem )
{
sName = lNames[nItem] ;
lEncNames[nItem] = impl_encodeSetName( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "org.openoffice.Office." );
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "\torg.openoffice.Office.");
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.appendAscii ( "DetectService" );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_OPEN );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_CLOSE );
m_aData.sNew2OldSCPStandard.appendAscii ( "\n" );
}
}
for( nItem=0; nItem<nCount; ++nItem )
{
::rtl::OUString sName = lNames[nItem] ;
Detector aItem = m_aData.pFilterCache->getDetector( sName );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
sName = lEncNames[nItem];
}
++m_aData.nWrittenDetectors;
// open set node by using name
m_aData.sBufferStandard.appendAscii( "\t\t<default:group cfg:name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\">\n" );
// write properties
impl_generateStringListProperty ( m_aData.sBufferStandard, SUBKEY_TYPES, aItem.lTypes );
// close set node
m_aData.sBufferStandard.appendAscii( "\t\t</default:group>\n" );
}
// close set
m_aData.sBufferStandard.appendAscii( "\t</schema:set>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateLoaderSet()
{
if( m_aData.pFilterCache->hasLoaders() == sal_False )
{
// write empty loader set!
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"FrameLoaders\" cfg:element-type=\"FrameLoader\"/>\n" );
}
else
{
// open set
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"FrameLoaders\" cfg:element-type=\"FrameLoader\">\n" );
css::uno::Sequence< ::rtl::OUString > lNames = m_aData.pFilterCache->getAllLoaderNames();
css::uno::Sequence< ::rtl::OUString > lEncNames ( lNames ) ;
sal_Int32 nCount = lNames.getLength() ;
sal_Int32 nItem = 0 ;
XCDGenerator::impl_orderAlphabetical( lNames );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
::rtl::OUString sName ;
::rtl::OUString sEncName;
for( nItem=0; nItem<nCount; ++nItem )
{
sName = lNames[nItem] ;
lEncNames[nItem] = impl_encodeSetName( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "org.openoffice.Office." );
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "\torg.openoffice.Office.");
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.appendAscii ( "FrameLoader" );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_OPEN );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_CLOSE );
m_aData.sNew2OldSCPStandard.appendAscii ( "\n" );
}
}
for( nItem=0; nItem<nCount; ++nItem )
{
::rtl::OUString sName = lNames[nItem] ;
Loader aItem = m_aData.pFilterCache->getLoader( sName );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
sName = lEncNames[nItem];
}
++m_aData.nWrittenLoaders;
// open set node by using name
m_aData.sBufferStandard.appendAscii( "\t\t<default:group cfg:name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\">\n" );
// write properties
impl_generateUINamesProperty ( m_aData.sBufferStandard, SUBKEY_UINAME, aItem.lUINames );
impl_generateStringListProperty ( m_aData.sBufferStandard, SUBKEY_TYPES , aItem.lTypes );
// close set node
m_aData.sBufferStandard.appendAscii( "\t\t</default:group>\n" );
}
// close set
m_aData.sBufferStandard.appendAscii( "\t</schema:set>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateDefaults()
{
// open group
m_aData.sBufferStandard.appendAscii( "\t<schema:group cfg:name=\"Defaults\">\n" );
// write generic loader
m_aData.sBufferStandard.appendAscii( "\t\t<schema:value cfg:name=\"FrameLoader\" cfg:type=\"string\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<default:data>" );
m_aData.sBufferStandard.append ( m_aData.pFilterCache->getDefaultLoader() );
m_aData.sBufferStandard.appendAscii( "</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:value>\n" );
// write default detector
m_aData.sBufferStandard.appendAscii( "\t\t<schema:value cfg:name=\"DetectService\" cfg:type=\"string\">\n" );
m_aData.sBufferStandard.appendAscii( "\t\t\t<default:data>" );
m_aData.sBufferStandard.append ( m_aData.pFilterCache->getDefaultDetector() );
m_aData.sBufferStandard.appendAscii( "</default:data>\n" );
m_aData.sBufferStandard.appendAscii( "\t\t</schema:value>\n" );
// close group
m_aData.sBufferStandard.appendAscii( "\t</schema:group>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateContentHandlerSet()
{
if( m_aData.pFilterCache->hasContentHandlers() == sal_False )
{
// write empty handler set!
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"ContentHandlers\" cfg:element-type=\"ContentHandler\"/>\n" );
}
else
{
// open set
m_aData.sBufferStandard.appendAscii( "\t<schema:set cfg:name=\"ContentHandlers\" cfg:element-type=\"ContentHandler\">\n" );
css::uno::Sequence< ::rtl::OUString > lNames = m_aData.pFilterCache->getAllContentHandlerNames();
css::uno::Sequence< ::rtl::OUString > lEncNames ( lNames ) ;
sal_Int32 nCount = lNames.getLength() ;
sal_Int32 nItem = 0 ;
XCDGenerator::impl_orderAlphabetical( lNames );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
::rtl::OUString sName ;
::rtl::OUString sEncName;
for( nItem=0; nItem<nCount; ++nItem )
{
sName = lNames[nItem] ;
lEncNames[nItem] = impl_encodeSetName( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "org.openoffice.Office." );
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.appendAscii ( "\torg.openoffice.Office.");
m_aData.sNew2OldSCPStandard.append ( m_aData.sPackageStandard );
m_aData.sNew2OldSCPStandard.append ( CFG_PATH_SEPERATOR );
m_aData.sNew2OldSCPStandard.appendAscii ( "ContentHandler" );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_OPEN );
m_aData.sNew2OldSCPStandard.append ( sName );
m_aData.sNew2OldSCPStandard.append ( CFG_ENCODING_CLOSE );
m_aData.sNew2OldSCPStandard.appendAscii ( "\n" );
}
}
for( nItem=0; nItem<nCount; ++nItem )
{
::rtl::OUString sName = lNames[nItem] ;
ContentHandler aItem = m_aData.pFilterCache->getContentHandler( sName );
if( m_aData.nVersionOutput == 6 && m_aData.nVersionInput < 6 )
{
sName = lEncNames[nItem];
}
++m_aData.nWrittenContentHandlers;
// open set node by using name
m_aData.sBufferStandard.appendAscii( "\t\t<default:group cfg:name=\"" );
m_aData.sBufferStandard.append ( sName );
m_aData.sBufferStandard.appendAscii( "\">\n" );
// write properties
impl_generateStringListProperty( m_aData.sBufferStandard, SUBKEY_TYPES, aItem.lTypes );
// close set node
m_aData.sBufferStandard.appendAscii( "\t\t</default:group>\n" );
}
// close set
m_aData.sBufferStandard.appendAscii( "\t</schema:set>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateIntProperty( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
sal_Int32 nValue )
{
sXCD.appendAscii( "\t\t\t<default:value cfg:name=\"" );
sXCD.append ( sName );
sXCD.appendAscii( "\" cfg:type=\"int\" cfg:writable=\"" );
sXCD.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
sXCD.appendAscii( "\t\t\t\t<default:data>" );
sXCD.append ( (sal_Int32)(nValue) );
sXCD.appendAscii( "</default:data>\n\t\t\t</default:value>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateBoolProperty( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
sal_Bool bValue )
{
sXCD.appendAscii( "\t\t\t<default:value cfg:name=\"" );
sXCD.append ( sName );
sXCD.appendAscii( "\" cfg:type=\"boolean\" cfg:writable=\"" );
sXCD.appendAscii( m_aData.bWriteable==sal_True ? "true\">\n" : "false\">\n" );
sXCD.appendAscii( "\t\t\t\t<default:data>" );
sXCD.appendAscii( bValue==sal_True ? "true" : "false" );
sXCD.appendAscii( "</default:data>\n\t\t\t</default:value>\n" );
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateStringProperty( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const ::rtl::OUString& sValue )
{
sXCD.appendAscii( "\t\t\t<default:value cfg:name=\"" );
sXCD.append ( sName );
sXCD.appendAscii( "\" cfg:type=\"string\" cfg:writable=\"" );
sXCD.appendAscii( m_aData.bWriteable==sal_True ? "true\"" : "false\"" );
if( sValue.getLength() > 0 )
{
sXCD.appendAscii( ">\n\t\t\t\t<default:data>" );
sXCD.append ( XCDGenerator::impl_encodeSpecialSigns( sValue ) );
sXCD.appendAscii( "</default:data>\n\t\t\t</default:value>\n" );
}
else
{
sXCD.appendAscii( "/>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateStringListProperty( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const ::framework::StringList& lValue )
{
sXCD.appendAscii( "\t\t\t<default:value cfg:name=\"" );
sXCD.append ( sName );
sXCD.appendAscii( "\" cfg:type=\"string\" cfg:derivedBy=\"list\"" );
sal_Unicode cSeperator = XCDGenerator::impl_defineSeperator( lValue );
if( cSeperator != ' ' )
{
sXCD.appendAscii( " cfg:separator=\"" );
sXCD.append ( cSeperator );
sXCD.appendAscii( "\"" );
}
sXCD.appendAscii( " cfg:writable=\"" );
sXCD.appendAscii( m_aData.bWriteable==sal_True ? "true\"" : "false\"" );
sal_Int32 nCount = (sal_Int32)(lValue.size());
sal_Int32 nPosition = 1;
if( nCount > 0 )
{
sXCD.appendAscii( ">\n\t\t\t\t<default:data>" );
for( ConstStringListIterator pEntry=lValue.begin(); pEntry!=lValue.end(); ++pEntry )
{
sXCD.append( *pEntry );
if( nPosition < nCount )
{
// Seperator for lists allowed only between two values!
// Don't write leading or leaving seperators ...
sXCD.append( cSeperator );
}
++nPosition;
}
sXCD.appendAscii( "</default:data>\n\t\t\t</default:value>\n" );
}
else
{
sXCD.appendAscii( "/>\n" );
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_generateUINamesProperty( ::rtl::OUStringBuffer& sXCD ,
const ::rtl::OUString& sName ,
const StringHash& lUINames )
{
sXCD.appendAscii( "\t\t\t<default:value cfg:name=\"" );
sXCD.append ( sName );
sXCD.appendAscii( "\" cfg:type=\"string\" cfg:localized=\"true\" cfg:writable=\"" );
sXCD.appendAscii( m_aData.bWriteable==sal_True ? "true\"" : "false\"" );
if( lUINames.size() > 0 )
{
sXCD.appendAscii( ">\n" );
// Search for localized values, which doesn't need full localized set ...
// because all values for all locales are the same!
sal_Bool bDifferent = sal_False ;
ConstStringHashIterator pUIName = lUINames.begin();
::rtl::OUString sUIName = pUIName->second ;
while( pUIName!=lUINames.end() )
{
if( sUIName != pUIName->second )
{
bDifferent = sal_True;
break;
}
++pUIName;
}
// Generate full localized set, if some values are really loclaized.
if( bDifferent == sal_True )
{
for( ConstStringHashIterator pUIName=lUINames.begin(); pUIName!=lUINames.end(); ++pUIName )
{
sXCD.appendAscii( "\t\t\t\t<default:data xml:lang=\"" );
sXCD.append ( pUIName->first );
sXCD.appendAscii( "\">" );
sXCD.append ( XCDGenerator::impl_encodeSpecialSigns( pUIName->second ) );
sXCD.appendAscii( "</default:data>\n" );
}
}
// Generate ONE entry as default for our configuration if all localized values are equal!
else
{
sXCD.appendAscii( "\t\t\t\t<default:data xml:lang=\"" );
sXCD.appendAscii( "en-US" );
sXCD.appendAscii( "\">" );
sXCD.append ( XCDGenerator::impl_encodeSpecialSigns( lUINames.find(DECLARE_ASCII("en-US"))->second ));
sXCD.appendAscii( "</default:data>\n" );
}
sXCD.appendAscii( "\t\t\t</default:value>\n" );
}
else
{
sXCD.appendAscii( "/>\n" );
}
}
//*****************************************************************************************************************
::rtl::OUString XCDGenerator::impl_encodeSpecialSigns( const ::rtl::OUString& sValue )
{
::rtl::OUStringBuffer sSource ( sValue );
::rtl::OUStringBuffer sDestination( 10000 );
sal_Int32 nCount = sValue.getLength();
sal_Int32 i = 0;
for( i=0; i<nCount; ++i )
{
sal_Unicode cSign = sSource.charAt(i);
switch( cSign )
{
// code &, ", ', <, > ...
case '&' : sDestination.appendAscii( "&" );
break;
case '<' : sDestination.appendAscii( "<" );
break;
case '>' : sDestination.appendAscii( ">" );
break;
case '\'': sDestination.appendAscii( "’" );
break;
case '\"': sDestination.appendAscii( """ );
break;
// copy all other letters
default : sDestination.append( cSign );
break;
}
}
return sDestination.makeStringAndClear();
}
//*****************************************************************************************************************
// Step over all elements of list to find one seperator, which isn't used for any value in list.
// We return an empty string if list contains no elements - because we must disable writing of
// "... cfg:seperator="<seperatorvalue> ..."
// => Otherwise we get a Sequence< OUString > with one empty element from configuration!!!
sal_Unicode XCDGenerator::impl_defineSeperator( const ::framework::StringList& lList )
{
static cSeperator1 = ' ';
static cSeperator2 = ';';
static cSeperator3 = '+';
static cSeperator4 = '-';
static cSeperator5 = '*';
// Start with first seperator.
// Step over all list items.
// If one item contains this seperator - try next one!
// If no new one available (5 tests failed!) - show an error message for user.
// => File will be wrong then!
// If seperator was changed start search during list again ... because
// new seperator could exist at already compared elements!
sal_Unicode cSeperator = cSeperator1 ;
sal_Bool bOK = sal_False ;
ConstStringListIterator pItem = lList.begin();
while( bOK == sal_False )
{
if( pItem == lList.end() )
{
bOK = sal_True;
}
else
{
while( pItem!=lList.end() )
{
if( pItem->indexOf( cSeperator, 0 ) != -1 )
{
if( cSeperator == cSeperator1 )
{
cSeperator = cSeperator2;
pItem = lList.begin();
break;
}
else
if( cSeperator == cSeperator2 )
{
cSeperator = cSeperator3;
pItem = lList.begin();
break;
}
else
if( cSeperator == cSeperator3 )
{
cSeperator = cSeperator4;
pItem = lList.begin();
break;
}
else
if( cSeperator == cSeperator4 )
{
cSeperator = cSeperator5;
pItem = lList.begin();
break;
}
else
if( cSeperator == cSeperator5 )
{
LOG_ERROR( "XCDGenerator::impl_defineSeperator()", "Can't find seperator for given list! Generated XCD file will be wrong!" )
exit(-1);
}
}
else
{
++pItem;
}
}
}
}
return cSeperator;
}
//*****************************************************************************************************************
void XCDGenerator::impl_initFilterHashNew2Old( StringHash& aHash )
{
// key = new filter name, value = old name
aHash[DECLARE_ASCII("writer_StarOffice_XML_Writer" )] = DECLARE_ASCII("swriter: StarOffice XML (Writer)" );
aHash[DECLARE_ASCII("writer_StarWriter_50" )] = DECLARE_ASCII("swriter: StarWriter 5.0" );
aHash[DECLARE_ASCII("writer_StarWriter_50_VorlageTemplate" )] = DECLARE_ASCII("swriter: StarWriter 5.0 Vorlage/Template" );
aHash[DECLARE_ASCII("writer_StarWriter_40" )] = DECLARE_ASCII("swriter: StarWriter 4.0" );
aHash[DECLARE_ASCII("writer_StarWriter_40_VorlageTemplate" )] = DECLARE_ASCII("swriter: StarWriter 4.0 Vorlage/Template" );
aHash[DECLARE_ASCII("writer_StarWriter_30" )] = DECLARE_ASCII("swriter: StarWriter 3.0" );
aHash[DECLARE_ASCII("writer_StarWriter_30_VorlageTemplate" )] = DECLARE_ASCII("swriter: StarWriter 3.0 Vorlage/Template" );
aHash[DECLARE_ASCII("writer_StarWriter_20" )] = DECLARE_ASCII("swriter: StarWriter 2.0" );
aHash[DECLARE_ASCII("writer_StarWriter_10" )] = DECLARE_ASCII("swriter: StarWriter 1.0" );
aHash[DECLARE_ASCII("writer_StarWriter_DOS" )] = DECLARE_ASCII("swriter: StarWriter DOS" );
aHash[DECLARE_ASCII("writer_HTML_StarWriter" )] = DECLARE_ASCII("swriter: HTML (StarWriter)" );
aHash[DECLARE_ASCII("writer_Text" )] = DECLARE_ASCII("swriter: Text" );
aHash[DECLARE_ASCII("writer_Text_Unix" )] = DECLARE_ASCII("swriter: Text Unix" );
aHash[DECLARE_ASCII("writer_Text_Mac" )] = DECLARE_ASCII("swriter: Text Mac" );
aHash[DECLARE_ASCII("writer_Text_DOS" )] = DECLARE_ASCII("swriter: Text DOS" );
aHash[DECLARE_ASCII("writer_Rich_Text_Format" )] = DECLARE_ASCII("swriter: Rich Text Format" );
aHash[DECLARE_ASCII("writer_MS_Word_97" )] = DECLARE_ASCII("swriter: MS Word 97" );
aHash[DECLARE_ASCII("writer_MS_Word_95" )] = DECLARE_ASCII("swriter: MS Word 95" );
aHash[DECLARE_ASCII("writer_MS_Word_97_Vorlage" )] = DECLARE_ASCII("swriter: MS Word 97 Vorlage" );
aHash[DECLARE_ASCII("writer_MS_Word_95_Vorlage" )] = DECLARE_ASCII("swriter: MS Word 95 Vorlage" );
aHash[DECLARE_ASCII("writer_MS_WinWord_60" )] = DECLARE_ASCII("swriter: MS WinWord 6.0" );
aHash[DECLARE_ASCII("writer_MS_Word_6x_W4W" )] = DECLARE_ASCII("swriter: MS Word 6.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_WinWord_5" )] = DECLARE_ASCII("swriter: MS WinWord 5" );
aHash[DECLARE_ASCII("writer_MS_WinWord_2x_W4W" )] = DECLARE_ASCII("swriter: MS WinWord 2.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_MacWord_5x_W4W" )] = DECLARE_ASCII("swriter: MS MacWord 5.x (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Win_61_W4W" )] = DECLARE_ASCII("swriter: WordPerfect (Win) 6.1 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Win_70_W4W" )] = DECLARE_ASCII("swriter: WordPerfect (Win) 7.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_Win_1x_20_W4W" )] = DECLARE_ASCII("swriter: WordStar (Win) 1.x-2.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_70_W4W" )] = DECLARE_ASCII("swriter: WordStar 7.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Ami_Pro_11_12_W4W" )] = DECLARE_ASCII("swriter: Ami Pro 1.1-1.2 (W4W)" );
aHash[DECLARE_ASCII("writer_Ami_Pro_20_31_W4W" )] = DECLARE_ASCII("swriter: Ami Pro 2.0-3.1 (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Excel_40_StarWriter" )] = DECLARE_ASCII("swriter: MS Excel 4.0 (StarWriter)" );
aHash[DECLARE_ASCII("writer_MS_Excel_50_StarWriter" )] = DECLARE_ASCII("swriter: MS Excel 5.0 (StarWriter)" );
aHash[DECLARE_ASCII("writer_MS_Excel_95_StarWriter" )] = DECLARE_ASCII("swriter: MS Excel 95 (StarWriter)" );
aHash[DECLARE_ASCII("writer_MS_Works_20_DOS_W4W" )] = DECLARE_ASCII("swriter: MS Works 2.0 DOS (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Works_30_Win_W4W" )] = DECLARE_ASCII("swriter: MS Works 3.0 Win (W4W)" );
aHash[DECLARE_ASCII("writer_Lotus_1_2_3_10_DOS_StarWriter" )] = DECLARE_ASCII("swriter: Lotus 1-2-3 1.0 (DOS) (StarWriter)" );
aHash[DECLARE_ASCII("writer_Lotus_1_2_3_10_WIN_StarWriter" )] = DECLARE_ASCII("swriter: Lotus 1-2-3 1.0 (WIN) (StarWriter)" );
aHash[DECLARE_ASCII("writer_Frame_Maker_MIF_50_W4W" )] = DECLARE_ASCII("swriter: Frame Maker MIF 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Win_Write_3x_W4W" )] = DECLARE_ASCII("swriter: Win Write 3.x (W4W)" );
aHash[DECLARE_ASCII("writer_Text_encoded" )] = DECLARE_ASCII("swriter: Text (encoded)" );
aHash[DECLARE_ASCII("writer_MS_WinWord_1x_W4W" )] = DECLARE_ASCII("swriter: MS WinWord 1.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Word_5x_W4W" )] = DECLARE_ASCII("swriter: MS Word 5.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Word_4x_W4W" )] = DECLARE_ASCII("swriter: MS Word 4.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Word_3x_W4W" )] = DECLARE_ASCII("swriter: MS Word 3.x (W4W)" );
aHash[DECLARE_ASCII("writer_MS_MacWord_40_W4W" )] = DECLARE_ASCII("swriter: MS MacWord 4.0 (W4W)" );
aHash[DECLARE_ASCII("writer_MS_MacWord_30_W4W" )] = DECLARE_ASCII("swriter: MS MacWord 3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Mac_1_W4W" )] = DECLARE_ASCII("swriter: WordPerfect Mac 1 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Mac_2_W4W" )] = DECLARE_ASCII("swriter: WordPerfect Mac 2 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Mac_3_W4W" )] = DECLARE_ASCII("swriter: WordPerfect Mac 3 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Win_51_52_W4W" )] = DECLARE_ASCII("swriter: WordPerfect (Win) 5.1-5.2 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_Win_60_W4W" )] = DECLARE_ASCII("swriter: WordPerfect (Win) 6.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_41_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 4.1 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_42_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 4.2 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_50_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_51_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 5.1 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_60_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 6.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordPerfect_61_W4W" )] = DECLARE_ASCII("swriter: WordPerfect 6.1 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_2000_Rel_30_W4W" )] = DECLARE_ASCII("swriter: WordStar 2000 Rel. 3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_2000_Rel_35_W4W" )] = DECLARE_ASCII("swriter: WordStar 2000 Rel. 3.5 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_33x_W4W" )] = DECLARE_ASCII("swriter: WordStar 3.3x (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_345_W4W" )] = DECLARE_ASCII("swriter: WordStar 3.45 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_40_W4W" )] = DECLARE_ASCII("swriter: WordStar 4.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_50_W4W" )] = DECLARE_ASCII("swriter: WordStar 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_55_W4W" )] = DECLARE_ASCII("swriter: WordStar 5.5 (W4W)" );
aHash[DECLARE_ASCII("writer_WordStar_60_W4W" )] = DECLARE_ASCII("swriter: WordStar 6.0 (W4W)" );
aHash[DECLARE_ASCII("writer_MS_Works_40_Mac_W4W" )] = DECLARE_ASCII("swriter: MS Works 4.0 Mac (W4W)" );
aHash[DECLARE_ASCII("writer_Mac_Write_4x_50_W4W" )] = DECLARE_ASCII("swriter: Mac Write 4.x 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Mac_Write_II_W4W" )] = DECLARE_ASCII("swriter: Mac Write II (W4W)" );
aHash[DECLARE_ASCII("writer_Mac_Write_Pro_W4W" )] = DECLARE_ASCII("swriter: Mac Write Pro (W4W)" );
aHash[DECLARE_ASCII("writer_Lotus_Manuscript_W4W" )] = DECLARE_ASCII("swriter: Lotus Manuscript (W4W)" );
aHash[DECLARE_ASCII("writer_MASS_11_Rel_80_83_W4W" )] = DECLARE_ASCII("swriter: MASS 11 Rel. 8.0-8.3 (W4W)" );
aHash[DECLARE_ASCII("writer_MASS_11_Rel_85_90_W4W" )] = DECLARE_ASCII("swriter: MASS 11 Rel. 8.5-9.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Claris_Works_W4W" )] = DECLARE_ASCII("swriter: Claris Works (W4W)" );
aHash[DECLARE_ASCII("writer_CTOS_DEF_W4W" )] = DECLARE_ASCII("swriter: CTOS DEF (W4W)" );
aHash[DECLARE_ASCII("writer_OfficeWriter_40_W4W" )] = DECLARE_ASCII("swriter: OfficeWriter 4.0 (W4W)" );
aHash[DECLARE_ASCII("writer_OfficeWriter_50_W4W" )] = DECLARE_ASCII("swriter: OfficeWriter 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_OfficeWriter_6x_W4W" )] = DECLARE_ASCII("swriter: OfficeWriter 6.x (W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_III_W4W" )] = DECLARE_ASCII("swriter: XyWrite III ( W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_IIIP_W4W" )] = DECLARE_ASCII("swriter: XyWrite III+ ( W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_Signature_W4W" )] = DECLARE_ASCII("swriter: XyWrite Signature (W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_Sig_Win_W4W" )] = DECLARE_ASCII("swriter: XyWrite Sig. (Win) (W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_IV_W4W" )] = DECLARE_ASCII("swriter: XyWrite IV (W4W)" );
aHash[DECLARE_ASCII("writer_XyWrite_Win_10_W4W" )] = DECLARE_ASCII("swriter: XyWrite (Win) 1.0 (W4W)" );
aHash[DECLARE_ASCII("writer_XEROX_XIF_50_W4W" )] = DECLARE_ASCII("swriter: XEROX XIF 5.0 (W4W)" );
aHash[DECLARE_ASCII("writer_XEROX_XIF_50_Illustrator_W4W" )] = DECLARE_ASCII("swriter: XEROX XIF 5.0 (Illustrator) (W4W)" );
aHash[DECLARE_ASCII("writer_XEROX_XIF_60_Color_Bitmap_W4W" )] = DECLARE_ASCII("swriter: XEROX XIF 6.0 (Color Bitmap) (W4W)" );
aHash[DECLARE_ASCII("writer_XEROX_XIF_60_Res_Graphic_W4W" )] = DECLARE_ASCII("swriter: XEROX XIF 6.0 (Res Graphic) (W4W)" );
aHash[DECLARE_ASCII("writer_WriteNow_30_Macintosh_W4W" )] = DECLARE_ASCII("swriter: WriteNow 3.0 (Macintosh) (W4W)" );
aHash[DECLARE_ASCII("writer_Writing_Assistant_W4W" )] = DECLARE_ASCII("swriter: Writing Assistant (W4W)" );
aHash[DECLARE_ASCII("writer_VolksWriter_Deluxe_W4W" )] = DECLARE_ASCII("swriter: VolksWriter Deluxe (W4W)" );
aHash[DECLARE_ASCII("writer_VolksWriter_3_and_4_W4W" )] = DECLARE_ASCII("swriter: VolksWriter 3 and 4 (W4W)" );
aHash[DECLARE_ASCII("writer_MultiMate_33_W4W" )] = DECLARE_ASCII("swriter: MultiMate 3.3 (W4W)" );
aHash[DECLARE_ASCII("writer_MultiMate_Adv_36_W4W" )] = DECLARE_ASCII("swriter: MultiMate Adv. 3.6 (W4W)" );
aHash[DECLARE_ASCII("writer_MultiMate_Adv_II_37_W4W" )] = DECLARE_ASCII("swriter: MultiMate Adv. II 3.7 (W4W)" );
aHash[DECLARE_ASCII("writer_MultiMate_4_W4W" )] = DECLARE_ASCII("swriter: MultiMate 4 (W4W)" );
aHash[DECLARE_ASCII("writer_NAVY_DIF_W4W" )] = DECLARE_ASCII("swriter: NAVY DIF (W4W)" );
aHash[DECLARE_ASCII("writer_PFS_Write_W4W" )] = DECLARE_ASCII("swriter: PFS Write (W4W)" );
aHash[DECLARE_ASCII("writer_PFS_First_Choice_10_W4W" )] = DECLARE_ASCII("swriter: PFS First Choice 1.0 (W4W)" );
aHash[DECLARE_ASCII("writer_PFS_First_Choice_20_W4W" )] = DECLARE_ASCII("swriter: PFS First Choice 2.0 (W4W)" );
aHash[DECLARE_ASCII("writer_PFS_First_Choice_30_W4W" )] = DECLARE_ASCII("swriter: PFS First Choice 3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Professional_Write_10_W4W" )] = DECLARE_ASCII("swriter: Professional Write 1.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Professional_Write_2x_W4W" )] = DECLARE_ASCII("swriter: Professional Write 2.x (W4W)" );
aHash[DECLARE_ASCII("writer_Professional_Write_Plus_W4W" )] = DECLARE_ASCII("swriter: Professional Write Plus (W4W)" );
aHash[DECLARE_ASCII("writer_Peach_Text_W4W" )] = DECLARE_ASCII("swriter: Peach Text (W4W)" );
aHash[DECLARE_ASCII("writer_DCA_Revisable_Form_Text_W4W" )] = DECLARE_ASCII("swriter: DCA Revisable Form Text (W4W)" );
aHash[DECLARE_ASCII("writer_DCA_with_Display_Write_5_W4W" )] = DECLARE_ASCII("swriter: DCA with Display Write 5 (W4W)" );
aHash[DECLARE_ASCII("writer_DCAFFT_Final_Form_Text_W4W" )] = DECLARE_ASCII("swriter: DCA/FFT-Final Form Text (W4W)" );
aHash[DECLARE_ASCII("writer_DEC_DX_W4W" )] = DECLARE_ASCII("swriter: DEC DX (W4W)" );
aHash[DECLARE_ASCII("writer_DEC_WPS_PLUS_W4W" )] = DECLARE_ASCII("swriter: DEC WPS-PLUS (W4W)" );
aHash[DECLARE_ASCII("writer_DisplayWrite_20_4x_W4W" )] = DECLARE_ASCII("swriter: DisplayWrite 2.0-4.x (W4W)" );
aHash[DECLARE_ASCII("writer_DisplayWrite_5x_W4W" )] = DECLARE_ASCII("swriter: DisplayWrite 5.x (W4W)" );
aHash[DECLARE_ASCII("writer_DataGeneral_CEO_Write_W4W" )] = DECLARE_ASCII("swriter: DataGeneral CEO Write (W4W)" );
aHash[DECLARE_ASCII("writer_EBCDIC_W4W" )] = DECLARE_ASCII("swriter: EBCDIC (W4W)" );
aHash[DECLARE_ASCII("writer_Enable_W4W" )] = DECLARE_ASCII("swriter: Enable (W4W)" );
aHash[DECLARE_ASCII("writer_Frame_Maker_MIF_30_W4W" )] = DECLARE_ASCII("swriter: Frame Maker MIF 3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Frame_Maker_MIF_40_W4W" )] = DECLARE_ASCII("swriter: Frame Maker MIF 4.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Frame_Work_III_W4W" )] = DECLARE_ASCII("swriter: Frame Work III (W4W)" );
aHash[DECLARE_ASCII("writer_Frame_Work_IV_W4W" )] = DECLARE_ASCII("swriter: Frame Work IV (W4W)" );
aHash[DECLARE_ASCII("writer_HP_AdvanceWrite_Plus_W4W" )] = DECLARE_ASCII("swriter: HP AdvanceWrite Plus (W4W)" );
aHash[DECLARE_ASCII("writer_ICL_Office_Power_6_W4W" )] = DECLARE_ASCII("swriter: ICL Office Power 6 (W4W)" );
aHash[DECLARE_ASCII("writer_ICL_Office_Power_7_W4W" )] = DECLARE_ASCII("swriter: ICL Office Power 7 (W4W)" );
aHash[DECLARE_ASCII("writer_Interleaf_W4W" )] = DECLARE_ASCII("swriter: Interleaf (W4W)" );
aHash[DECLARE_ASCII("writer_Interleaf_5_6_W4W" )] = DECLARE_ASCII("swriter: Interleaf 5 - 6 (W4W)" );
aHash[DECLARE_ASCII("writer_Legacy_Winstar_onGO_W4W" )] = DECLARE_ASCII("swriter: Legacy Winstar onGO (W4W)" );
aHash[DECLARE_ASCII("writer_QA_Write_10_30_W4W" )] = DECLARE_ASCII("swriter: Q&A Write 1.0-3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_QA_Write_40_W4W" )] = DECLARE_ASCII("swriter: Q&A Write 4.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Rapid_File_10_W4W" )] = DECLARE_ASCII("swriter: Rapid File 1.0 (W4W)" );
aHash[DECLARE_ASCII("writer_Rapid_File_12_W4W" )] = DECLARE_ASCII("swriter: Rapid File 1.2 (W4W)" );
aHash[DECLARE_ASCII("writer_Samna_Word_IV_IV_Plus_W4W" )] = DECLARE_ASCII("swriter: Samna Word IV-IV Plus (W4W)" );
aHash[DECLARE_ASCII("writer_Total_Word_W4W" )] = DECLARE_ASCII("swriter: Total Word (W4W)" );
aHash[DECLARE_ASCII("writer_Uniplex_onGO_W4W" )] = DECLARE_ASCII("swriter: Uniplex onGO (W4W)" );
aHash[DECLARE_ASCII("writer_Uniplex_V7_V8_W4W" )] = DECLARE_ASCII("swriter: Uniplex V7-V8 (W4W)" );
aHash[DECLARE_ASCII("writer_Wang_PC_W4W" )] = DECLARE_ASCII("swriter: Wang PC (W4W)" );
aHash[DECLARE_ASCII("writer_Wang_II_SWP_W4W" )] = DECLARE_ASCII("swriter: Wang II SWP (W4W)" );
aHash[DECLARE_ASCII("writer_Wang_WP_Plus_W4W" )] = DECLARE_ASCII("swriter: Wang WP Plus (W4W)" );
aHash[DECLARE_ASCII("writer_WITA_W4W" )] = DECLARE_ASCII("swriter: WITA (W4W)" );
aHash[DECLARE_ASCII("writer_WiziWord_30_W4W" )] = DECLARE_ASCII("swriter: WiziWord 3.0 (W4W)" );
aHash[DECLARE_ASCII("writer_web_HTML" )] = DECLARE_ASCII("swriter/web: HTML" );
aHash[DECLARE_ASCII("writer_web_StarWriterWeb_50_VorlageTemplate" )] = DECLARE_ASCII("swriter/web: StarWriter/Web 5.0 Vorlage/Template" );
aHash[DECLARE_ASCII("writer_web_StarWriterWeb_40_VorlageTemplate" )] = DECLARE_ASCII("swriter/web: StarWriter/Web 4.0 Vorlage/Template" );
aHash[DECLARE_ASCII("writer_web_Text_StarWriterWeb" )] = DECLARE_ASCII("swriter/web: Text (StarWriter/Web)" );
aHash[DECLARE_ASCII("writer_web_Text_DOS_StarWriterWeb" )] = DECLARE_ASCII("swriter/web: Text DOS (StarWriter/Web)" );
aHash[DECLARE_ASCII("writer_web_Text_Mac_StarWriterWeb" )] = DECLARE_ASCII("swriter/web: Text Mac (StarWriter/Web)" );
aHash[DECLARE_ASCII("writer_web_Text_Unix_StarWriterWeb" )] = DECLARE_ASCII("swriter/web: Text Unix (StarWriter/Web)" );
aHash[DECLARE_ASCII("writer_web_StarWriter_50" )] = DECLARE_ASCII("swriter/web: StarWriter 5.0" );
aHash[DECLARE_ASCII("writer_web_StarWriter_40" )] = DECLARE_ASCII("swriter/web: StarWriter 4.0" );
aHash[DECLARE_ASCII("writer_web_StarWriter_30" )] = DECLARE_ASCII("swriter/web: StarWriter 3.0" );
aHash[DECLARE_ASCII("writer_web_Text_encoded" )] = DECLARE_ASCII("swriter/web: Text (encoded)" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_60GlobalDocument" )] = DECLARE_ASCII("swriter/GlobalDocument: StarOffice XML (GlobalDocument)" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_50GlobalDocument" )] = DECLARE_ASCII("swriter/GlobalDocument: StarWriter 5.0/GlobalDocument" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_40GlobalDocument" )] = DECLARE_ASCII("swriter/GlobalDocument: StarWriter 4.0/GlobalDocument" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_50" )] = DECLARE_ASCII("swriter/GlobalDocument: StarWriter 5.0" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_40" )] = DECLARE_ASCII("swriter/GlobalDocument: StarWriter 4.0" );
aHash[DECLARE_ASCII("writer_globaldocument_StarWriter_30" )] = DECLARE_ASCII("swriter/GlobalDocument: StarWriter 3.0" );
aHash[DECLARE_ASCII("writer_globaldocument_Text_encoded" )] = DECLARE_ASCII("swriter/GlobalDocument: Text (encoded)" );
aHash[DECLARE_ASCII("chart_StarOffice_XML_Chart" )] = DECLARE_ASCII("schart: StarOffice XML (Chart)" );
aHash[DECLARE_ASCII("chart_StarChart_50" )] = DECLARE_ASCII("schart: StarChart 5.0" );
aHash[DECLARE_ASCII("chart_StarChart_40" )] = DECLARE_ASCII("schart: StarChart 4.0" );
aHash[DECLARE_ASCII("chart_StarChart_30" )] = DECLARE_ASCII("schart: StarChart 3.0" );
aHash[DECLARE_ASCII("calc_StarOffice_XML_Calc" )] = DECLARE_ASCII("scalc: StarOffice XML (Calc)" );
aHash[DECLARE_ASCII("calc_StarCalc_50" )] = DECLARE_ASCII("scalc: StarCalc 5.0" );
aHash[DECLARE_ASCII("calc_StarCalc_50_VorlageTemplate" )] = DECLARE_ASCII("scalc: StarCalc 5.0 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_StarCalc_40" )] = DECLARE_ASCII("scalc: StarCalc 4.0" );
aHash[DECLARE_ASCII("calc_StarCalc_40_VorlageTemplate" )] = DECLARE_ASCII("scalc: StarCalc 4.0 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_StarCalc_30" )] = DECLARE_ASCII("scalc: StarCalc 3.0" );
aHash[DECLARE_ASCII("calc_StarCalc_30_VorlageTemplate" )] = DECLARE_ASCII("scalc: StarCalc 3.0 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_MS_Excel_97" )] = DECLARE_ASCII("scalc: MS Excel 97" );
aHash[DECLARE_ASCII("calc_MS_Excel_97_VorlageTemplate" )] = DECLARE_ASCII("scalc: MS Excel 97 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_MS_Excel_95" )] = DECLARE_ASCII("scalc: MS Excel 95" );
aHash[DECLARE_ASCII("calc_MS_Excel_95_VorlageTemplate" )] = DECLARE_ASCII("scalc: MS Excel 95 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_MS_Excel_5095" )] = DECLARE_ASCII("scalc: MS Excel 5.0/95" );
aHash[DECLARE_ASCII("calc_MS_Excel_5095_VorlageTemplate" )] = DECLARE_ASCII("scalc: MS Excel 5.0/95 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_MS_Excel_40" )] = DECLARE_ASCII("scalc: MS Excel 4.0" );
aHash[DECLARE_ASCII("calc_MS_Excel_40_VorlageTemplate" )] = DECLARE_ASCII("scalc: MS Excel 4.0 Vorlage/Template" );
aHash[DECLARE_ASCII("calc_Rich_Text_Format_StarCalc" )] = DECLARE_ASCII("scalc: Rich Text Format (StarCalc)" );
aHash[DECLARE_ASCII("calc_SYLK" )] = DECLARE_ASCII("scalc: SYLK" );
aHash[DECLARE_ASCII("calc_DIF" )] = DECLARE_ASCII("scalc: DIF" );
aHash[DECLARE_ASCII("calc_HTML_StarCalc" )] = DECLARE_ASCII("scalc: HTML (StarCalc)" );
aHash[DECLARE_ASCII("calc_dBase" )] = DECLARE_ASCII("scalc: dBase" );
aHash[DECLARE_ASCII("calc_Lotus" )] = DECLARE_ASCII("scalc: Lotus" );
aHash[DECLARE_ASCII("calc_StarCalc_10" )] = DECLARE_ASCII("scalc: StarCalc 1.0" );
aHash[DECLARE_ASCII("calc_Text_txt_csv_StarCalc" )] = DECLARE_ASCII("scalc: Text - txt - csv (StarCalc)" );
aHash[DECLARE_ASCII("impress_StarOffice_XML_Impress" )] = DECLARE_ASCII("simpress: StarOffice XML (Impress)" );
aHash[DECLARE_ASCII("impress_StarImpress_50" )] = DECLARE_ASCII("simpress: StarImpress 5.0" );
aHash[DECLARE_ASCII("impress_StarImpress_50_Vorlage" )] = DECLARE_ASCII("simpress: StarImpress 5.0 Vorlage" );
aHash[DECLARE_ASCII("impress_StarImpress_40" )] = DECLARE_ASCII("simpress: StarImpress 4.0" );
aHash[DECLARE_ASCII("impress_StarImpress_40_Vorlage" )] = DECLARE_ASCII("simpress: StarImpress 4.0 Vorlage" );
aHash[DECLARE_ASCII("impress_StarDraw_50_StarImpress" )] = DECLARE_ASCII("simpress: StarDraw 5.0 (StarImpress)" );
aHash[DECLARE_ASCII("impress_StarDraw_50_Vorlage_StarImpress" )] = DECLARE_ASCII("simpress: StarDraw 5.0 Vorlage (StarImpress)" );
aHash[DECLARE_ASCII("impress_StarDraw_30_StarImpress" )] = DECLARE_ASCII("simpress: StarDraw 3.0 (StarImpress)" );
aHash[DECLARE_ASCII("impress_StarDraw_30_Vorlage_StarImpress" )] = DECLARE_ASCII("simpress: StarDraw 3.0 Vorlage (StarImpress)" );
aHash[DECLARE_ASCII("impress_MS_PowerPoint_97" )] = DECLARE_ASCII("simpress: MS PowerPoint 97" );
aHash[DECLARE_ASCII("impress_MS_PowerPoint_97_Vorlage" )] = DECLARE_ASCII("simpress: MS PowerPoint 97 Vorlage" );
aHash[DECLARE_ASCII("impress_CGM_Computer_Graphics_Metafile" )] = DECLARE_ASCII("simpress: CGM - Computer Graphics Metafile" );
aHash[DECLARE_ASCII("impress_StarImpress_50_packed" )] = DECLARE_ASCII("simpress: StarImpress 5.0 (packed)" );
aHash[DECLARE_ASCII("draw_StarOffice_XML_Draw" )] = DECLARE_ASCII("sdraw: StarOffice XML (Draw)" );
aHash[DECLARE_ASCII("draw_GIF_Graphics_Interchange" )] = DECLARE_ASCII("sdraw: GIF - Graphics Interchange" );
aHash[DECLARE_ASCII("draw_PCD_Photo_CD" )] = DECLARE_ASCII("sdraw: PCD - Photo CD" );
aHash[DECLARE_ASCII("draw_PCX_Zsoft_Paintbrush" )] = DECLARE_ASCII("sdraw: PCX - Zsoft Paintbrush" );
aHash[DECLARE_ASCII("draw_PSD_Adobe_Photoshop" )] = DECLARE_ASCII("sdraw: PSD - Adobe Photoshop" );
aHash[DECLARE_ASCII("draw_PNG_Portable_Network_Graphic" )] = DECLARE_ASCII("sdraw: PNG - Portable Network Graphic" );
aHash[DECLARE_ASCII("draw_StarDraw_50" )] = DECLARE_ASCII("sdraw: StarDraw 5.0" );
aHash[DECLARE_ASCII("draw_PBM_Portable_Bitmap" )] = DECLARE_ASCII("sdraw: PBM - Portable Bitmap" );
aHash[DECLARE_ASCII("draw_PGM_Portable_Graymap" )] = DECLARE_ASCII("sdraw: PGM - Portable Graymap" );
aHash[DECLARE_ASCII("draw_PPM_Portable_Pixelmap" )] = DECLARE_ASCII("sdraw: PPM - Portable Pixelmap" );
aHash[DECLARE_ASCII("draw_RAS_Sun_Rasterfile" )] = DECLARE_ASCII("sdraw: RAS - Sun Rasterfile" );
aHash[DECLARE_ASCII("draw_TGA_Truevision_TARGA" )] = DECLARE_ASCII("sdraw: TGA - Truevision TARGA" );
aHash[DECLARE_ASCII("draw_SGV_StarDraw_20" )] = DECLARE_ASCII("sdraw: SGV - StarDraw 2.0" );
aHash[DECLARE_ASCII("draw_TIF_Tag_Image_File" )] = DECLARE_ASCII("sdraw: TIF - Tag Image File" );
aHash[DECLARE_ASCII("draw_SGF_StarOffice_Writer_SGF" )] = DECLARE_ASCII("sdraw: SGF - StarOffice Writer SGF" );
aHash[DECLARE_ASCII("draw_XPM" )] = DECLARE_ASCII("sdraw: XPM" );
aHash[DECLARE_ASCII("gif_Graphics_Interchange" )] = DECLARE_ASCII("sdraw: GIF - Graphics Interchange" );
aHash[DECLARE_ASCII("pcd_Photo_CD" )] = DECLARE_ASCII("sdraw: PCD - Photo CD" );
aHash[DECLARE_ASCII("pcx_Zsoft_Paintbrush" )] = DECLARE_ASCII("sdraw: PCX - Zsoft Paintbrush" );
aHash[DECLARE_ASCII("psd_Adobe_Photoshop" )] = DECLARE_ASCII("sdraw: PSD - Adobe Photoshop" );
aHash[DECLARE_ASCII("png_Portable_Network_Graphic" )] = DECLARE_ASCII("sdraw: PNG - Portable Network Graphic" );
aHash[DECLARE_ASCII("pbm_Portable_Bitmap" )] = DECLARE_ASCII("sdraw: PBM - Portable Bitmap" );
aHash[DECLARE_ASCII("pgm_Portable_Graymap" )] = DECLARE_ASCII("sdraw: PGM - Portable Graymap" );
aHash[DECLARE_ASCII("ppm_Portable_Pixelmap" )] = DECLARE_ASCII("sdraw: PPM - Portable Pixelmap" );
aHash[DECLARE_ASCII("ras_Sun_Rasterfile" )] = DECLARE_ASCII("sdraw: RAS - Sun Rasterfile" );
aHash[DECLARE_ASCII("tga_Truevision_TARGA" )] = DECLARE_ASCII("sdraw: TGA - Truevision TARGA" );
aHash[DECLARE_ASCII("sgv_StarDraw_20" )] = DECLARE_ASCII("sdraw: SGV - StarDraw 2.0" );
aHash[DECLARE_ASCII("tif_Tag_Image_File" )] = DECLARE_ASCII("sdraw: TIF - Tag Image File" );
aHash[DECLARE_ASCII("sgf_StarOffice_Writer_SGF" )] = DECLARE_ASCII("sdraw: SGF - StarOffice Writer SGF" );
aHash[DECLARE_ASCII("xpm_XPM" )] = DECLARE_ASCII("sdraw: XPM" );
aHash[DECLARE_ASCII("draw_StarDraw_50_Vorlage" )] = DECLARE_ASCII("sdraw: StarDraw 5.0 Vorlage" );
aHash[DECLARE_ASCII("draw_StarImpress_50_StarDraw" )] = DECLARE_ASCII("sdraw: StarImpress 5.0 (StarDraw)" );
aHash[DECLARE_ASCII("draw_StarImpress_50_Vorlage_StarDraw" )] = DECLARE_ASCII("sdraw: StarImpress 5.0 Vorlage (StarDraw)" );
aHash[DECLARE_ASCII("draw_StarImpress_40_StarDraw" )] = DECLARE_ASCII("sdraw: StarImpress 4.0 (StarDraw)" );
aHash[DECLARE_ASCII("draw_StarImpress_40_Vorlage_StarDraw" )] = DECLARE_ASCII("sdraw: StarImpress 4.0 Vorlage (StarDraw)" );
aHash[DECLARE_ASCII("draw_StarDraw_30" )] = DECLARE_ASCII("sdraw: StarDraw 3.0" );
aHash[DECLARE_ASCII("draw_StarDraw_30_Vorlage" )] = DECLARE_ASCII("sdraw: StarDraw 3.0 Vorlage" );
aHash[DECLARE_ASCII("draw_EMF_MS_Windows_Metafile" )] = DECLARE_ASCII("sdraw: EMF - MS Windows Metafile" );
aHash[DECLARE_ASCII("draw_MET_OS2_Metafile" )] = DECLARE_ASCII("sdraw: MET - OS/2 Metafile" );
aHash[DECLARE_ASCII("draw_DXF_AutoCAD_Interchange" )] = DECLARE_ASCII("sdraw: DXF - AutoCAD Interchange" );
aHash[DECLARE_ASCII("draw_EPS_Encapsulated_PostScript" )] = DECLARE_ASCII("sdraw: EPS - Encapsulated PostScript" );
aHash[DECLARE_ASCII("draw_WMF_MS_Windows_Metafile" )] = DECLARE_ASCII("sdraw: WMF - MS Windows Metafile" );
aHash[DECLARE_ASCII("draw_PCT_Mac_Pict" )] = DECLARE_ASCII("sdraw: PCT - Mac Pict" );
aHash[DECLARE_ASCII("draw_SVM_StarView_Metafile" )] = DECLARE_ASCII("sdraw: SVM - StarView Metafile" );
aHash[DECLARE_ASCII("draw_BMP_MS_Windows" )] = DECLARE_ASCII("sdraw: BMP - MS Windows" );
aHash[DECLARE_ASCII("draw_JPG_JPEG" )] = DECLARE_ASCII("sdraw: JPG - JPEG" );
aHash[DECLARE_ASCII("draw_XBM_X_Consortium" )] = DECLARE_ASCII("sdraw: XBM - X-Consortium" );
aHash[DECLARE_ASCII("emf_MS_Windows_Metafile" )] = DECLARE_ASCII("sdraw: EMF - MS Windows Metafile" );
aHash[DECLARE_ASCII("met_OS2_Metafile" )] = DECLARE_ASCII("sdraw: MET - OS/2 Metafile" );
aHash[DECLARE_ASCII("dxf_AutoCAD_Interchange" )] = DECLARE_ASCII("sdraw: DXF - AutoCAD Interchange" );
aHash[DECLARE_ASCII("eps_Encapsulated_PostScript" )] = DECLARE_ASCII("sdraw: EPS - Encapsulated PostScript" );
aHash[DECLARE_ASCII("wmf_MS_Windows_Metafile" )] = DECLARE_ASCII("sdraw: WMF - MS Windows Metafile" );
aHash[DECLARE_ASCII("pct_Mac_Pict" )] = DECLARE_ASCII("sdraw: PCT - Mac Pict" );
aHash[DECLARE_ASCII("svm_StarView_Metafile" )] = DECLARE_ASCII("sdraw: SVM - StarView Metafile" );
aHash[DECLARE_ASCII("bmp_MS_Windows" )] = DECLARE_ASCII("sdraw: BMP - MS Windows" );
aHash[DECLARE_ASCII("jpg_JPEG" )] = DECLARE_ASCII("sdraw: JPG - JPEG" );
aHash[DECLARE_ASCII("xbm_X_Consortium" )] = DECLARE_ASCII("sdraw: XBM - X-Consortium" );
aHash[DECLARE_ASCII("math_StarOffice_XML_Math" )] = DECLARE_ASCII("smath: StarOffice XML (Math)" );
aHash[DECLARE_ASCII("math_MathML_XML_Math" )] = DECLARE_ASCII("smath: MathML XML (Math)" );
aHash[DECLARE_ASCII("math_StarMath_50" )] = DECLARE_ASCII("smath: StarMath 5.0" );
aHash[DECLARE_ASCII("math_StarMath_40" )] = DECLARE_ASCII("smath: StarMath 4.0" );
aHash[DECLARE_ASCII("math_StarMath_30" )] = DECLARE_ASCII("smath: StarMath 3.0" );
aHash[DECLARE_ASCII("math_StarMath_20" )] = DECLARE_ASCII("smath: StarMath 2.0" );
aHash[DECLARE_ASCII("math_MathType_3x" )] = DECLARE_ASCII("smath: MathType 3.x" );
}
//*****************************************************************************************************************
::rtl::OUString XCDGenerator::impl_getOldFilterName( const ::rtl::OUString& sNewName )
{
::rtl::OUString sOldName;
ConstStringHashIterator pEntry = m_aData.aOldFilterNamesHash.find(sNewName);
if( pEntry==m_aData.aOldFilterNamesHash.end() )
{
sOldName = sNewName;
}
else
{
sOldName = m_aData.aOldFilterNamesHash[sNewName];
}
return sOldName;
}
//*****************************************************************************************************************
void XCDGenerator::impl_classifyType( const AppMember& rData, const ::rtl::OUString& sTypeName, EFilterPackage& ePackage )
{
ePackage = E_STANDARD;
// Step over all registered filters for this type ...
// Classify all of these filters. If one of them a standard filter ...
// type must be a standard type too - otherwise not!
CheckedStringListIterator pIterator ;
::rtl::OUString sFilterName ;
sal_Int32 nOrder ;
while( rData.pFilterCache->searchFilterForType( sTypeName, pIterator, sFilterName ) == sal_True )
{
EFilterPackage eFilterPackage;
XCDGenerator::impl_classifyFilter( rData, sFilterName, eFilterPackage, nOrder );
if( eFilterPackage == E_STANDARD )
{
ePackage = E_STANDARD;
break;
}
}
}
//*****************************************************************************************************************
void XCDGenerator::impl_classifyFilter( const AppMember& rData, const ::rtl::OUString& sFilterName, EFilterPackage& ePackage, sal_Int32& nOrder )
{
// a) For versions less then 4 => use hard coded list of filter names to differ between standard or additional filters.
// Why? This version don't support the order flag or hasn't set it right!
// b) For version greater then 3 => use order of currently cached types in FilterCache!
ePackage = E_STANDARD;
nOrder = 0;
// writer
if( sFilterName == DECLARE_ASCII("writer_StarOffice_XML_Writer" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("writer_StarOffice_XML_Writer_Template" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_50" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_50_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_40" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_40_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_30" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_30_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("writer_StarWriter_20" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_97" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_97_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_95" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_95_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 13; } else
if( sFilterName == DECLARE_ASCII("writer_MS_WinWord_2x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 14; } else
if( sFilterName == DECLARE_ASCII("writer_MS_WinWord_1x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 15; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_6x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 16; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_5x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 17; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_4x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 18; } else
if( sFilterName == DECLARE_ASCII("writer_MS_Word_3x_W4W" ) ) { ePackage = E_STANDARD; nOrder = 19; } else
if( sFilterName == DECLARE_ASCII("writer_WordPerfect_Win_70_W4W" ) ) { ePackage = E_STANDARD; nOrder = 20; } else
if( sFilterName == DECLARE_ASCII("writer_WordPerfect_Win_61_W4W" ) ) { ePackage = E_STANDARD; nOrder = 21; } else
if( sFilterName == DECLARE_ASCII("writer_WordPerfect_Win_60_W4W" ) ) { ePackage = E_STANDARD; nOrder = 22; } else
if( sFilterName == DECLARE_ASCII("writer_WordPerfect_Win_51_52_W4W" ) ) { ePackage = E_STANDARD; nOrder = 23; } else
if( sFilterName == DECLARE_ASCII("writer_HTML_StarWriter" ) ) { ePackage = E_STANDARD; nOrder = 24; } else
if( sFilterName == DECLARE_ASCII("writer_Text" ) ) { ePackage = E_STANDARD; nOrder = 25; } else
if( sFilterName == DECLARE_ASCII("writer_Text_encoded" ) ) { ePackage = E_STANDARD; nOrder = 26; } else
if( sFilterName == DECLARE_ASCII("writer_Text_DOS" ) ) { ePackage = E_STANDARD; nOrder = 27; } else
if( sFilterName == DECLARE_ASCII("writer_Text_Unix" ) ) { ePackage = E_STANDARD; nOrder = 28; } else
if( sFilterName == DECLARE_ASCII("writer_Text_Mac" ) ) { ePackage = E_STANDARD; nOrder = 29; } else
if( sFilterName == DECLARE_ASCII("writer_Rich_Text_Format" ) ) { ePackage = E_STANDARD; nOrder = 30; }
// writer web
if( sFilterName == DECLARE_ASCII("writer_web_HTML" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarOffice_XML_Writer" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarOffice_XML_Writer_Web_Template" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarWriter_50" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarWriterWeb_50_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarWriter_40" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarWriterWeb_40_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("writer_web_StarWriter_30" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("writer_web_Text_StarWriterWeb" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("writer_web_Text_encoded" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("writer_web_Text_DOS_StarWriterWeb" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("writer_web_Text_Unix_StarWriterWeb" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("writer_web_Text_Mac_StarWriterWeb" ) ) { ePackage = E_STANDARD; nOrder = 13; }
// global document
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarOffice_XML_Writer_GlobalDocument" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarOffice_XML_Writer" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarWriter_50" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarWriter_50GlobalDocument" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarWriter_40" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarWriter_40GlobalDocument" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_StarWriter_30" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("writer_globaldocument_Text_encoded" ) ) { ePackage = E_STANDARD; nOrder = 8; }
// calc
if( sFilterName == DECLARE_ASCII("calc_StarOffice_XML_Calc" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("calc_StarOffice_XML_Calc_Template" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_50" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_50_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_40" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_40_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_30" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_30_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("calc_StarCalc_10" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_97" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_97_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_95" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_95_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 13; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_5095" ) ) { ePackage = E_STANDARD; nOrder = 14; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_5095_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 15; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_40" ) ) { ePackage = E_STANDARD; nOrder = 16; } else
if( sFilterName == DECLARE_ASCII("calc_MS_Excel_40_VorlageTemplate" ) ) { ePackage = E_STANDARD; nOrder = 17; } else
if( sFilterName == DECLARE_ASCII("calc_HTML_StarCalc" ) ) { ePackage = E_STANDARD; nOrder = 18; } else
if( sFilterName == DECLARE_ASCII("calc_HTML_WebQuery" ) ) { ePackage = E_STANDARD; nOrder = 19; } else
if( sFilterName == DECLARE_ASCII("calc_Rich_Text_Format_StarCalc" ) ) { ePackage = E_STANDARD; nOrder = 20; } else
if( sFilterName == DECLARE_ASCII("calc_Text_txt_csv_StarCalc" ) ) { ePackage = E_STANDARD; nOrder = 21; } else
if( sFilterName == DECLARE_ASCII("calc_dBase" ) ) { ePackage = E_STANDARD; nOrder = 22; } else
if( sFilterName == DECLARE_ASCII("calc_Lotus" ) ) { ePackage = E_STANDARD; nOrder = 23; } else
if( sFilterName == DECLARE_ASCII("calc_SYLK" ) ) { ePackage = E_STANDARD; nOrder = 24; } else
if( sFilterName == DECLARE_ASCII("calc_DIF" ) ) { ePackage = E_STANDARD; nOrder = 25; }
// impress
if( sFilterName == DECLARE_ASCII("impress_StarOffice_XML_Impress" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("impress_StarOffice_XML_Impress_Template" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("impress_StarImpress_50" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("impress_StarImpress_50_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("impress_StarImpress_50_packed" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("impress_StarImpress_40" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("impress_StarImpress_40_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("impress_MS_PowerPoint_97" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("impress_MS_PowerPoint_97_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("impress_StarOffice_XML_Draw" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("impress_StarDraw_50_StarImpress" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("impress_StarDraw_50_Vorlage_StarImpress" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("impress_StarDraw_30_StarImpress" ) ) { ePackage = E_STANDARD; nOrder = 13; } else
if( sFilterName == DECLARE_ASCII("impress_StarDraw_30_Vorlage_StarImpress" ) ) { ePackage = E_STANDARD; nOrder = 14; } else
if( sFilterName == DECLARE_ASCII("impress_CGM_Computer_Graphics_Metafile" ) ) { ePackage = E_STANDARD; nOrder = 15; }
// draw
if( sFilterName == DECLARE_ASCII("draw_StarOffice_XML_Draw" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("draw_StarOffice_XML_Draw_Template" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("draw_StarDraw_50" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("draw_StarDraw_50_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("draw_StarDraw_30" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("draw_StarDraw_30_Vorlage" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("draw_StarOffice_XML_Impress" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("draw_StarImpress_50_StarDraw" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("draw_StarImpress_50_Vorlage_StarDraw" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("draw_StarImpress_40_StarDraw" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("draw_StarImpress_40_Vorlage_StarDraw" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("draw_SGV_StarDraw_20" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("draw_SGF_StarOffice_Writer_SGF" ) ) { ePackage = E_STANDARD; nOrder = 13; } else
if( sFilterName == DECLARE_ASCII("draw_SVM_StarView_Metafile" ) ) { ePackage = E_STANDARD; nOrder = 14; } else
if( sFilterName == DECLARE_ASCII("draw_WMF_MS_Windows_Metafile" ) ) { ePackage = E_STANDARD; nOrder = 15; } else
if( sFilterName == DECLARE_ASCII("draw_EMF_MS_Windows_Metafile" ) ) { ePackage = E_STANDARD; nOrder = 16; } else
if( sFilterName == DECLARE_ASCII("draw_EPS_Encapsulated_PostScript" ) ) { ePackage = E_STANDARD; nOrder = 17; } else
if( sFilterName == DECLARE_ASCII("draw_DXF_AutoCAD_Interchange" ) ) { ePackage = E_STANDARD; nOrder = 18; } else
if( sFilterName == DECLARE_ASCII("draw_BMP_MS_Windows" ) ) { ePackage = E_STANDARD; nOrder = 19; } else
if( sFilterName == DECLARE_ASCII("draw_GIF_Graphics_Interchange" ) ) { ePackage = E_STANDARD; nOrder = 20; } else
if( sFilterName == DECLARE_ASCII("draw_JPG_JPEG" ) ) { ePackage = E_STANDARD; nOrder = 21; } else
if( sFilterName == DECLARE_ASCII("draw_MET_OS2_Metafile" ) ) { ePackage = E_STANDARD; nOrder = 22; } else
if( sFilterName == DECLARE_ASCII("draw_PBM_Portable_Bitmap" ) ) { ePackage = E_STANDARD; nOrder = 23; } else
if( sFilterName == DECLARE_ASCII("draw_PCD_Photo_CD_Base" ) ) { ePackage = E_STANDARD; nOrder = 24; } else
if( sFilterName == DECLARE_ASCII("draw_PCD_Photo_CD_Base4" ) ) { ePackage = E_STANDARD; nOrder = 25; } else
if( sFilterName == DECLARE_ASCII("draw_PCD_Photo_CD_Base16" ) ) { ePackage = E_STANDARD; nOrder = 26; } else
if( sFilterName == DECLARE_ASCII("draw_PCT_Mac_Pict" ) ) { ePackage = E_STANDARD; nOrder = 27; } else
if( sFilterName == DECLARE_ASCII("draw_PCX_Zsoft_Paintbrush" ) ) { ePackage = E_STANDARD; nOrder = 28; } else
if( sFilterName == DECLARE_ASCII("draw_PGM_Portable_Graymap" ) ) { ePackage = E_STANDARD; nOrder = 29; } else
if( sFilterName == DECLARE_ASCII("draw_PNG_Portable_Network_Graphic" ) ) { ePackage = E_STANDARD; nOrder = 30; } else
if( sFilterName == DECLARE_ASCII("draw_PPM_Portable_Pixelmap" ) ) { ePackage = E_STANDARD; nOrder = 31; } else
if( sFilterName == DECLARE_ASCII("draw_PSD_Adobe_Photoshop" ) ) { ePackage = E_STANDARD; nOrder = 32; } else
if( sFilterName == DECLARE_ASCII("draw_RAS_Sun_Rasterfile" ) ) { ePackage = E_STANDARD; nOrder = 33; } else
if( sFilterName == DECLARE_ASCII("draw_TGA_Truevision_TARGA" ) ) { ePackage = E_STANDARD; nOrder = 34; } else
if( sFilterName == DECLARE_ASCII("draw_TIF_Tag_Image_File" ) ) { ePackage = E_STANDARD; nOrder = 35; } else
if( sFilterName == DECLARE_ASCII("draw_XBM_X_Consortium" ) ) { ePackage = E_STANDARD; nOrder = 36; } else
if( sFilterName == DECLARE_ASCII("draw_XPM" ) ) { ePackage = E_STANDARD; nOrder = 37; }
// chart
if( sFilterName == DECLARE_ASCII("chart_StarOffice_XML_Chart" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("chart_StarChart_50" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("chart_StarChart_40" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("chart_StarChart_30" ) ) { ePackage = E_STANDARD; nOrder = 4; }
// math
if( sFilterName == DECLARE_ASCII("math_StarOffice_XML_Math" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("math_StarMath_50" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("math_StarMath_40" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("math_StarMath_30" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("math_StarMath_20" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("math_MathML_XML_Math" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("math_MathType_3x" ) ) { ePackage = E_STANDARD; nOrder = 7; }
// graphics
if( sFilterName == DECLARE_ASCII("bmp_Import" ) ) { ePackage = E_STANDARD; nOrder = 1; } else
if( sFilterName == DECLARE_ASCII("bmp_Export" ) ) { ePackage = E_STANDARD; nOrder = 2; } else
if( sFilterName == DECLARE_ASCII("dxf_Import" ) ) { ePackage = E_STANDARD; nOrder = 3; } else
if( sFilterName == DECLARE_ASCII("emf_Import" ) ) { ePackage = E_STANDARD; nOrder = 4; } else
if( sFilterName == DECLARE_ASCII("emf_Export" ) ) { ePackage = E_STANDARD; nOrder = 5; } else
if( sFilterName == DECLARE_ASCII("eps_Import" ) ) { ePackage = E_STANDARD; nOrder = 6; } else
if( sFilterName == DECLARE_ASCII("eps_Export" ) ) { ePackage = E_STANDARD; nOrder = 7; } else
if( sFilterName == DECLARE_ASCII("gif_Import" ) ) { ePackage = E_STANDARD; nOrder = 8; } else
if( sFilterName == DECLARE_ASCII("gif_Export" ) ) { ePackage = E_STANDARD; nOrder = 9; } else
if( sFilterName == DECLARE_ASCII("jpg_Import" ) ) { ePackage = E_STANDARD; nOrder = 10; } else
if( sFilterName == DECLARE_ASCII("jpg_Export" ) ) { ePackage = E_STANDARD; nOrder = 11; } else
if( sFilterName == DECLARE_ASCII("met_Import" ) ) { ePackage = E_STANDARD; nOrder = 12; } else
if( sFilterName == DECLARE_ASCII("met_Export" ) ) { ePackage = E_STANDARD; nOrder = 13; } else
if( sFilterName == DECLARE_ASCII("pbm_Import" ) ) { ePackage = E_STANDARD; nOrder = 14; } else
if( sFilterName == DECLARE_ASCII("pbm_Export" ) ) { ePackage = E_STANDARD; nOrder = 15; } else
if( sFilterName == DECLARE_ASCII("pcd_Import_Base16" ) ) { ePackage = E_STANDARD; nOrder = 16; } else
if( sFilterName == DECLARE_ASCII("pcd_Import_Base4" ) ) { ePackage = E_STANDARD; nOrder = 17; } else
if( sFilterName == DECLARE_ASCII("pcd_Import_Base" ) ) { ePackage = E_STANDARD; nOrder = 18; } else
if( sFilterName == DECLARE_ASCII("pct_Import" ) ) { ePackage = E_STANDARD; nOrder = 19; } else
if( sFilterName == DECLARE_ASCII("pct_Export" ) ) { ePackage = E_STANDARD; nOrder = 20; } else
if( sFilterName == DECLARE_ASCII("pcx_Import" ) ) { ePackage = E_STANDARD; nOrder = 21; } else
if( sFilterName == DECLARE_ASCII("pgm_Import" ) ) { ePackage = E_STANDARD; nOrder = 22; } else
if( sFilterName == DECLARE_ASCII("pgm_Export" ) ) { ePackage = E_STANDARD; nOrder = 23; } else
if( sFilterName == DECLARE_ASCII("png_Import" ) ) { ePackage = E_STANDARD; nOrder = 24; } else
if( sFilterName == DECLARE_ASCII("png_Export" ) ) { ePackage = E_STANDARD; nOrder = 25; } else
if( sFilterName == DECLARE_ASCII("ppm_Import" ) ) { ePackage = E_STANDARD; nOrder = 26; } else
if( sFilterName == DECLARE_ASCII("ppm_Export" ) ) { ePackage = E_STANDARD; nOrder = 27; } else
if( sFilterName == DECLARE_ASCII("psd_Import" ) ) { ePackage = E_STANDARD; nOrder = 28; } else
if( sFilterName == DECLARE_ASCII("ras_Import" ) ) { ePackage = E_STANDARD; nOrder = 29; } else
if( sFilterName == DECLARE_ASCII("ras_Export" ) ) { ePackage = E_STANDARD; nOrder = 30; } else
if( sFilterName == DECLARE_ASCII("sgf_Import" ) ) { ePackage = E_STANDARD; nOrder = 31; } else
if( sFilterName == DECLARE_ASCII("sgv_Import" ) ) { ePackage = E_STANDARD; nOrder = 32; } else
if( sFilterName == DECLARE_ASCII("svg_Export" ) ) { ePackage = E_STANDARD; nOrder = 33; } else
if( sFilterName == DECLARE_ASCII("svm_Import" ) ) { ePackage = E_STANDARD; nOrder = 34; } else
if( sFilterName == DECLARE_ASCII("svm_Export" ) ) { ePackage = E_STANDARD; nOrder = 35; } else
if( sFilterName == DECLARE_ASCII("tga_Import" ) ) { ePackage = E_STANDARD; nOrder = 36; } else
if( sFilterName == DECLARE_ASCII("tif_Import" ) ) { ePackage = E_STANDARD; nOrder = 37; } else
if( sFilterName == DECLARE_ASCII("tif_Export" ) ) { ePackage = E_STANDARD; nOrder = 38; } else
if( sFilterName == DECLARE_ASCII("wmf_Import" ) ) { ePackage = E_STANDARD; nOrder = 39; } else
if( sFilterName == DECLARE_ASCII("wmf_Export" ) ) { ePackage = E_STANDARD; nOrder = 40; } else
if( sFilterName == DECLARE_ASCII("xbm_Import" ) ) { ePackage = E_STANDARD; nOrder = 41; } else
if( sFilterName == DECLARE_ASCII("xpm_Import" ) ) { ePackage = E_STANDARD; nOrder = 42; } else
if( sFilterName == DECLARE_ASCII("xpm_Export" ) ) { ePackage = E_STANDARD; nOrder = 43; }
}
//*****************************************************************************************************************
void XCDGenerator::impl_orderAlphabetical( css::uno::Sequence< ::rtl::OUString >& lList )
{
::std::vector< ::rtl::OUString > lSortedList;
sal_Int32 nCount ;
sal_Int32 nItem ;
// Copy sequence to vector
nCount = lList.getLength();
for( nItem=0; nItem<nCount; ++nItem )
{
lSortedList.push_back( lList[nItem] );
}
// sort in a alphabetical order
::std::sort( lSortedList.begin(), lSortedList.end() );
// copy sorted list back to sequence
nItem = 0;
for( ::std::vector< ::rtl::OUString >::iterator pIterator=lSortedList.begin(); pIterator!=lSortedList.end(); ++pIterator )
{
lList[nItem] = *pIterator;
++nItem;
}
}
//*****************************************************************************************************************
class ModifiedUTF7Buffer
{
rtl::OUStringBuffer & m_rBuffer;
sal_uInt32 m_nValue;
int m_nFilled;
public:
ModifiedUTF7Buffer(rtl::OUStringBuffer * pTheBuffer):
m_rBuffer(*pTheBuffer), m_nFilled(0) {}
inline void write(sal_Unicode c);
void flush();
};
inline void ModifiedUTF7Buffer::write(sal_Unicode c)
{
switch (m_nFilled)
{
case 0:
m_nValue = sal_uInt32(c) << 8;
m_nFilled = 2;
break;
case 1:
m_nValue |= sal_uInt32(c);
m_nFilled = 3;
flush();
break;
case 2:
m_nValue |= sal_uInt32(c) >> 8;
m_nFilled = 3;
flush();
m_nValue = (sal_uInt32(c) & 0xFF) << 16;
m_nFilled = 1;
break;
}
}
void ModifiedUTF7Buffer::flush()
{
static sal_Unicode const aModifiedBase64[64]
= { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.' };
switch (m_nFilled)
{
case 1:
m_rBuffer.append(aModifiedBase64[m_nValue >> 18]);
m_rBuffer.append(aModifiedBase64[m_nValue >> 12 & 63]);
break;
case 2:
m_rBuffer.append(aModifiedBase64[m_nValue >> 18]);
m_rBuffer.append(aModifiedBase64[m_nValue >> 12 & 63]);
m_rBuffer.append(aModifiedBase64[m_nValue >> 6 & 63]);
break;
case 3:
m_rBuffer.append(aModifiedBase64[m_nValue >> 18]);
m_rBuffer.append(aModifiedBase64[m_nValue >> 12 & 63]);
m_rBuffer.append(aModifiedBase64[m_nValue >> 6 & 63]);
m_rBuffer.append(aModifiedBase64[m_nValue & 63]);
break;
}
m_nFilled = 0;
m_nValue = 0;
}
sal_Bool XCDGenerator::impl_isUsAsciiAlphaDigit(sal_Unicode c, sal_Bool bDigitAllowed)
{
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'
|| bDigitAllowed && c >= '0' && c <= '9';
}
::rtl::OUString XCDGenerator::impl_encodeSetName( const ::rtl::OUString& rSource )
{
return impl_encodeSpecialSigns( rSource );
/*
rtl::OUStringBuffer aTarget;
sal_Unicode const * pBegin = rSource.getStr();
sal_Unicode const * pEnd = pBegin + rSource.getLength();
sal_Unicode const * pCopyEnd = pBegin;
sal_Unicode const * p = pBegin;
while (p != pEnd)
{
sal_Unicode c = *p;
if (!impl_isUsAsciiAlphaDigit(c,p != pBegin))
switch (c)
{
case '-':
case '.':
if (p != pBegin)
break;
default:
aTarget.append(pCopyEnd, p - pCopyEnd);
aTarget.append(sal_Unicode('_'));
ModifiedUTF7Buffer aBuffer(&aTarget);
for (;;)
{
aBuffer.write(c);
++p;
if (p == pEnd)
break;
c = *p;
if (impl_isUsAsciiAlphaDigit(c) || c == '-' || c == '.')
break;
}
aBuffer.flush();
aTarget.append(sal_Unicode('_'));
pCopyEnd = p;
continue;
}
++p;
}
if (pCopyEnd == pBegin)
return rSource;
else
{
aTarget.append(pCopyEnd, pEnd - pCopyEnd);
return aTarget.makeStringAndClear();
}
*/
}
| 86.187553 | 319 | 0.460716 | [
"vector"
] |
b2fab6f1b6b84a458efe7f2df8ef56fd2230037f | 1,461 | cpp | C++ | code/1136.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/1136.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/1136.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
int du[5005], dis[5005];
vector<int> to[5005];
int minimumSemesters(int N, vector<vector<int>>& relations) {
for (auto& p: relations)
++du[p[1]], to[p[0]].push_back(p[1]);
queue<int> q;
int cnt = 0, ans = 1;
for (int i = 1; i <= N; ++i)
if (!du[i])
dis[i] = 1, q.push(i);
while (!q.empty()){
int h = q.front();
q.pop(), ++cnt;
for (int v: to[h]){
--du[v], dis[v] = max(dis[v], dis[h] + 1);
if (!du[v]) q.push(v), ans = max(ans, dis[v]);
}
}
if (cnt < N) return -1;
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 22.136364 | 67 | 0.46475 | [
"vector"
] |
b2fb4e6c19298d4d8d1a9885a42f021ca30884e4 | 134 | hh | C++ | inc/Vector3D.hh | KPO-2020-2021/zad5_1-262703 | 82d8ec01ce69d8c108adaae9a6ed46f467093bd0 | [
"Unlicense"
] | null | null | null | inc/Vector3D.hh | KPO-2020-2021/zad5_1-262703 | 82d8ec01ce69d8c108adaae9a6ed46f467093bd0 | [
"Unlicense"
] | null | null | null | inc/Vector3D.hh | KPO-2020-2021/zad5_1-262703 | 82d8ec01ce69d8c108adaae9a6ed46f467093bd0 | [
"Unlicense"
] | null | null | null | #ifndef VECTOR3D_HH
#define VECTOR3D_HH
#include "vector.hh"
#include "../src/vektor.cpp"
typedef Vector<double,3> Vector3D;
#endif | 14.888889 | 34 | 0.753731 | [
"vector"
] |
b2fe1f5cd91d60c635e30116ba6a826a1a40c60d | 519 | cpp | C++ | BaekJoon/1181.cpp | falconlee236/Algorithm_Practice | 4e6e380a0e6c840525ca831a05c35253eeaaa25c | [
"MIT"
] | null | null | null | BaekJoon/1181.cpp | falconlee236/Algorithm_Practice | 4e6e380a0e6c840525ca831a05c35253eeaaa25c | [
"MIT"
] | null | null | null | BaekJoon/1181.cpp | falconlee236/Algorithm_Practice | 4e6e380a0e6c840525ca831a05c35253eeaaa25c | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string a, string b){
if(a.size() == b.size()) return a < b;
return a.size() < b.size() ? true : false;
}
int main() {
int t; cin >> t;
getchar();
set<string> s;
while(t--){
string str; getline(cin, str);
s.insert(str);
}
vector<string> v(s.begin(), s.end());
sort(v.begin(), v.end(), cmp);
for(string x : v) cout << x << "\n";
return 0;
} | 20.76 | 46 | 0.547206 | [
"vector"
] |
65134ffb1d46d368bf7d8f6fd7ef423d693fd88e | 9,582 | hpp | C++ | include/parseCSV_CIS_pointCloud.hpp | ahundt/cis | bd55e8c77ec78994454247ffe7d67f537710a53f | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2018-12-17T03:13:01.000Z | 2018-12-17T03:13:01.000Z | include/parseCSV_CIS_pointCloud.hpp | ahundt/cis | bd55e8c77ec78994454247ffe7d67f537710a53f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | include/parseCSV_CIS_pointCloud.hpp | ahundt/cis | bd55e8c77ec78994454247ffe7d67f537710a53f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #ifndef _PARSE_CSV_CIS_POINTCLOUD_HPP_
#define _PARSE_CSV_CIS_POINTCLOUD_HPP_
#include "parse.hpp"
/// Stores the parsed data from the csv text files
struct csvCIS_pointCloudData {
typedef Eigen::MatrixXd TrackerPoints;
typedef std::vector<TrackerPoints> TrackerDevices;
typedef std::vector<TrackerDevices> TrackerFrames;
/// filename of the file
std::string title;
/// the number of elements in each "cloud"
std::vector<int> firstLine;
/// "output" only field for testing
/// @todo check if we need to do something special for these eigen values in a struct
Eigen::Vector3d estElectromagneticPostPos;
/// "output" only field for testing
/// @todo check if we need to do something special for these eigen values in a struct
Eigen::Vector3d estOpticalPostPos;
/// vector containing each cloud
TrackerFrames frames;
public:
/// avoid issues with eigen alignment
/// @see http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
/// parse the CIS HW1 point cloud string that was loaded directly from a txt file into a simpler struct
/// @see DataFileFormatDescription.svg for a visual explanation of the file format
///
///
/// There are additional special cases:
/// - 2 numbers -> trackerpoints1, numframes, filename
/// - 3 numbers -> trackerpoints1, trackerpoints2, numframes, filename
/// - 4 numbers -> trackerpoints1, trackerpoints2, trackerpoints3, numframes, filename
/// - "calbody" filename is different: 3 numbers -> trackerpoints1, trackerpoints2, trackerpoints3, filename
/// - "output" filename is differeint: first line is the same but next 2 lines are special points of estimated postion
csvCIS_pointCloudData parseCSV_CIS_pointCloud(std::string csv, bool debug = false){
csvCIS_pointCloudData outputData;
if(csv.empty()) return outputData;
std::vector<std::string> strs;
// by default if no frame count is specified, there is only one frame
int numFrames = 1;
// split into separate strings by newlines
boost::split(strs, csv, boost::is_any_of("\n"));
if(debug) {
//std::cout << "\n\n FULL FILE CONTENTS:\n\n" << csv; // original file string
std::cout << "\n\nNewly split vector of strings:\n\n"; // file string post split on newlines
printStringVector(strs);
}
// parse first line differently
std::vector<std::string>::iterator currentStringLineIterator = strs.begin();
std::vector<std::string> firstLineStrings;
/// @todo the file format could be improved and shouldn't require these special cases
bool isCtFiducials = boost::algorithm::contains(*strs.begin(), std::string("ct-fiducials"));
bool isCalBody = boost::algorithm::contains(*strs.begin(), std::string("calbody"));
// only isCalBody and is CtFiducials do not specify numframes, they assume a fixed value instead.
bool isNumFramesSpecified = !(isCalBody || isCtFiducials);
boost::split(firstLineStrings, *currentStringLineIterator, boost::is_any_of(", "), boost::token_compress_on);
int firstLineIndex = 0;
for(std::vector<std::string>::iterator beginFL = firstLineStrings.begin();
beginFL != firstLineStrings.end(); ++beginFL, ++firstLineIndex ){
if(boost::algorithm::contains(*beginFL, std::string("txt"))){
// the first 3 numbers are the number of trackers on each object
// there are expected to be 3 of these numbers (as opposed to trackers) as of HW1
outputData.title = *beginFL;
} else if(isNumFramesSpecified && firstLineIndex == firstLineStrings.size()-2) {
// the number of Frames containing all the tracker markers,
// essentially like timesteps, in each file.
// This is the last number and second to last item in the line, except in the "calbody" case.
if(debug) std::cout << *beginFL <<"\n";
numFrames = boost::lexical_cast<int>(*beginFL);
} else {
if(debug) std::cout << *beginFL <<"\n";
outputData.firstLine.push_back(boost::lexical_cast<int>(*beginFL));
}
}
// if the filename contains the string output,
// the first two lines are special estimated positions
/// @todo the file format could be improved and shouldn't require these special cases
if(boost::algorithm::contains(*strs.begin(), std::string("output1"))){
++currentStringLineIterator;
outputData.estElectromagneticPostPos = readPointString(*currentStringLineIterator);
++currentStringLineIterator;
outputData.estOpticalPostPos = readPointString(*currentStringLineIterator);
} else if(boost::algorithm::contains(*strs.begin(), std::string("output2"))){
// output2 does not specify number of elements per data frame, assume 1
outputData.firstLine.push_back(1);
}
// move to second line
++currentStringLineIterator;
// parse remaining lines
// need to decrement each point cloud in the file using the number of points specified in the first line
/// @bug this isn't accounted for correctly, somehow the values end up huge or negative
std::vector<int> trackerCounterVec;
// start out on a new frame
std::vector<int>::iterator trackerCounterVecPointsRemainingIterator = trackerCounterVec.end();
std::size_t currentPointIndexInThisTracker = 0;
std::size_t trackerDeviceIndex = 0;
csvCIS_pointCloudData::TrackerFrames::iterator currentFrameIterator(outputData.frames.end());
/// @todo remove isNewFrame, it is confusing
bool isNewFrame = true;
// go through every string
/// @todo there is a potential code safety issue here where if the sizes specified in the file don't match up with the length then we could run over the end of arrays.
for(int stringVectorIndex = 0; currentStringLineIterator != strs.end(); ++currentStringLineIterator, ++stringVectorIndex){
////////////////////
// Skip Empty lines
////////////////////
if(currentStringLineIterator->empty()){
// no data on this line, skip it
continue; // skip empty lines, consider finding a way to remove the continue
}
/////////////////////////////////////////
// Move to next Frame if needed
/////////////////////////////////////////
if(trackerCounterVecPointsRemainingIterator == trackerCounterVec.end() || (trackerCounterVecPointsRemainingIterator == trackerCounterVec.end()-1 && *trackerCounterVecPointsRemainingIterator == 0)){
// done with this frame, move on to next one
// back to the first tracker device for this new frame
trackerDeviceIndex = 0;
// create the counters for the next set of trackers
trackerCounterVec = outputData.firstLine;
trackerCounterVecPointsRemainingIterator = trackerCounterVec.begin();
// add the next frame to the vector, which starts out empty
csvCIS_pointCloudData::TrackerDevices tf;
outputData.frames.push_back(tf);
currentFrameIterator = outputData.frames.end()-1;
isNewFrame = true;
// add the next tracker point cloud to fill out, currently empty
Eigen::MatrixXd nextCloud(*trackerCounterVecPointsRemainingIterator,3);
currentFrameIterator->push_back(nextCloud);
currentPointIndexInThisTracker = 0;
}
/////////////////////////////////////////
// move to next Tracker if needed
/////////////////////////////////////////
if(!isNewFrame && *trackerCounterVecPointsRemainingIterator == 0 ) {
// go to next tracker
++trackerCounterVecPointsRemainingIterator;
BOOST_VERIFY(trackerCounterVecPointsRemainingIterator!=trackerCounterVec.end());
// create a matrix large enough to store all the points for this tracker
// and insert it into the vector
/// @bug the length isn't accounted for correctly, somehow the values in *currentTrackerPointsRemainingIterato end up huge or negative
Eigen::MatrixXd nextCloud(*trackerCounterVecPointsRemainingIterator,3);
currentFrameIterator->push_back(nextCloud);
++trackerDeviceIndex;
currentPointIndexInThisTracker = 0;
}
/////////////////////////////////////////
// Add point to this tracker
/////////////////////////////////////////
if(*trackerCounterVecPointsRemainingIterator > 0 ){
(*currentFrameIterator)[trackerDeviceIndex].block<1,3>(currentPointIndexInThisTracker,0) = readPointString(*currentStringLineIterator);
(*trackerCounterVecPointsRemainingIterator)--; // decrement point cloud counter for this cloud
currentPointIndexInThisTracker++;
}
// s
isNewFrame = false;
}
if(debug) std::cout << "numframes: " <<numFrames << " outputdata.frames.size(): " << outputData.frames.size() << std::endl;
BOOST_VERIFY(numFrames==outputData.frames.size());
return outputData;
}
void loadPointCloudFromFile(std::string fullFilePath, csvCIS_pointCloudData& pointCloud, bool debug = false){
std::stringstream ss;
ss << std::ifstream( fullFilePath ).rdbuf();
pointCloud = parseCSV_CIS_pointCloud(ss.str(),debug);
}
#endif // _PARSE_CSV_CIS_POINTCLOUD_HPP_ | 44.775701 | 205 | 0.656439 | [
"object",
"vector"
] |
fb948fd141ab1395099f53c8f85a333ba1335322 | 1,695 | cpp | C++ | Math/1041. Robot Bounded In Circle.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Math/1041. Robot Bounded In Circle.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Math/1041. Robot Bounded In Circle.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | /*
If the robot doesn't face north at the end of the first cycle, then that's the limit cycle trajectory.
First, let's check which direction the robot faces after 4 cycles.
Let's use numbers from 0 to 3 to mark the directions: north = 0, east = 1, south = 2, west = 3.
After one cycle the robot is facing direction k != 0.
After 4 cycles, the robot faces direction (k * 4) % 4 = 0, i.e. after 4 cycles, the robot is always facing north.
Second, let's find the robot coordinates after 4 cycles.
After one cycle, the new coordinates are x_1 = x + d_x, y_1 = y + d_y where d_x and d_y could be both positive or negative
1. After one cycle, the robot faces north.
x_1 = x + d_x + d_x + d_x + d_x = x + 4 d_x
y_1 = y + d_y + d_y + d_y + d_y = y + 4 d_y
2. After one cycle, the robot faces east.
x_1 = x + d_x - d_y - d_x + d_y = x
y_1 = y + d_y + d_x - d_y - d_x = y
3. After one cycle, the robot faces south.
x_1 = x + d_x - d_x + d_x - d_x = x
y_1 = y + d_y + d_y - d_y + d_y = y
4. After one cycle, the robot faces west.
x_1 = x + d_x + d_y - d_x - d_y = x
y_1 = y + d_y - d_x - d_y + d_x = y
*/
class Solution {
public:
bool isRobotBounded(string instructions) {
vector<vector<int>>direction = {{0,1},{-1,0}, {0,-1},{1,0}};
int x = 0, y = 0, idx = 0;
for(auto i: instructions){
if(i == 'L' )
idx = (idx + 1 )%4;
else if(i == 'R')
idx = (idx + 3) % 4;
else{
x += direction[idx][0];
y += direction[idx][1];
}
}
return (x == 0 && y == 0) || idx != 0;
}
}; | 26.904762 | 124 | 0.538053 | [
"vector"
] |
fb98c643931c72aa94178b515290d97c22abf587 | 1,941 | cpp | C++ | frontends/p4/insertProtectedState.cpp | mcnevesinf/p4c | 43d47fddb718a4de8779c1fa51400a3fe2395fc1 | [
"Apache-2.0"
] | 1 | 2021-03-07T09:03:25.000Z | 2021-03-07T09:03:25.000Z | frontends/p4/insertProtectedState.cpp | mcnevesinf/p4box | 43d47fddb718a4de8779c1fa51400a3fe2395fc1 | [
"Apache-2.0"
] | null | null | null | frontends/p4/insertProtectedState.cpp | mcnevesinf/p4box | 43d47fddb718a4de8779c1fa51400a3fe2395fc1 | [
"Apache-2.0"
] | 3 | 2017-02-16T16:41:13.000Z | 2018-08-29T01:00:21.000Z |
#include "p4box.h"
#include "ir/ir.h"
namespace P4 {
const IR::Node* InsertProtectedState::postorder(IR::Type_Struct* origStruct){
//Check if the struct is a candidate type to receive P4box protected state
std::string structName = origStruct->toString().c_str();
structName.replace(0, 7, "");
bool isCandidateType = false;
for( std::vector<cstring>::iterator it = P4boxIR->candidateTypes.begin() ; it != P4boxIR->candidateTypes.end(); ++it ){
if ( *it == structName ){
isCandidateType = true;
}
}
if( isCandidateType ){
if( not P4boxIR->pStateInserted ){
//printf("Candidate struct: %s\n", structName.c_str());
IR::IndexedVector<IR::StructField> newFields;
//Insert original struct fields
for( auto field : origStruct->fields ){
newFields.push_back( field );
}
/* Insert P4box protected state */
//FOR each protected struct
for(std::map<cstring,const IR::Type_ProtectedStruct*>::iterator it=P4boxIR->pStructMap.begin(); it!=P4boxIR->pStructMap.end(); ++it){
//FOR each field in the protected struct
for( auto pField : it->second->fields ){
//printf("Protected field: %s\n", pField->toString().c_str());
newFields.push_back( pField );
}
}//End for each protected struct
/* Instrument original program with P4box protected state */
auto newStruct = new IR::Type_Struct( origStruct->srcInfo, origStruct->name, origStruct->annotations, newFields );
P4boxIR->pStateInserted = true;
P4boxIR->hostStructType = structName;
return newStruct;
}//End if protected state not inserted yet
}//End if is candidate type
return origStruct;
}
}//End P4 namespace
| 26.589041 | 145 | 0.588357 | [
"vector"
] |
fba17fc858a05030e7f6e609734ffca91afb03ae | 1,677 | cpp | C++ | Bridger/bridger.cpp | pampas93/ProjectDependency | f0ff9caea2e5065a125148378554d8d58f34bfac | [
"MIT"
] | null | null | null | Bridger/bridger.cpp | pampas93/ProjectDependency | f0ff9caea2e5065a125148378554d8d58f34bfac | [
"MIT"
] | null | null | null | Bridger/bridger.cpp | pampas93/ProjectDependency | f0ff9caea2e5065a125148378554d8d58f34bfac | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////
// bridger.cpp //
// //
// Language: Visual C++ 2015 //
// Platform: Dell Inspiron, Windows 8.1 //
// Application: ProjectDependency- PempPassionProjects //
// Author: Abhijit Srikanth SUID:864888072 //
/////////////////////////////////////////////////////////////////////
#include "../Bridger/bridger.h"
#include <string>
#include <thread>
#include <iostream>
#include "../Analyzer/Executive.h"
class Bridger : public IBridger
{
public:
void start(char* path);
void open();
void stop();
private:
};
void Bridger::start(char* path)
{
char * argvArray[7];
std::string temp = "simbly";
argvArray[0] = _strdup(temp.c_str());
argvArray[1] = path;
std::string x[] = { "simbly","pathActually","*.h","*.cpp","/m","/f","/r" };
for (int i = 2; i < 7; i++) {
const char* xx = x[i].c_str();
argvArray[i] = _strdup(xx);
}
CodeAnalysis::CodeAnalysisExecutive exexec;
exexec.ProcessCommandLine(7, argvArray);
std::unordered_map<std::string, std::vector<std::string>> xx = exexec.ExecutiveMain4GUI();
return;
//std::cout << "Tester";
}
void Bridger::open()
{
std::string f = "file:///" + FileSystem::Path::getFullFileSpec("../VisualizationFiles/projectVisualization.html");
std::wstring ff = std::wstring(f.begin(), f.end());
LPCWSTR lpcff = ff.c_str();
LPCWSTR a = L"open";
LPCWSTR browser = L"chrome.exe";
ShellExecute(NULL, a, browser, lpcff, NULL, SW_SHOWDEFAULT);
}
void Bridger::stop()
{
}
IBridger* ObjectFactory::createBridger()
{
return new Bridger();
}
| 25.409091 | 115 | 0.559928 | [
"vector"
] |
fba3ceac892a74dccd41eec1bcb108347319fd1c | 1,833 | cpp | C++ | examples/google-code-jam/rabbit125/google_2011_1.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/rabbit125/google_2011_1.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/rabbit125/google_2011_1.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include<iostream>
#include<stdlib.h>
#include<vector>
#include<string.h>
#include<queue>
#define MAXSIZE 120
using namespace std ;
struct G
{
int r , s ;
};
G c ;
vector<G> total ;
int main( )
{
int T , t , n , p , ans1 , ans2 , ans , now1 , now2 , i , j ;
bool A[MAXSIZE] , B[MAXSIZE] ;
vector<int> a , b ;
char r ;
FILE *in = fopen( "A-large.in" , "r" ) ;
fscanf( in , "%d" , &T ) ;
t = T ;
FILE *file = fopen( "output.txt" , "w" ) ;
while( t-- )
{
ans = ans1 = ans2 = 0 ;
now1 = now2 = 1 ;
a.clear( ) ;
b.clear( ) ;
total.clear( ) ;
memset( A , false , sizeof( A ) ) ;
memset( B , false , sizeof( B ) ) ;
fscanf( in , "%d" , &n ) ;
for( i = 0 ; i < n ; i++ )
{
fscanf( in , " %c%d" , &r , &p ) ;
if( r == 'O' )
{
A[p] = true ;
c.r = 1 ;
c.s = p ;
total.push_back( c ) ;
}
if( r == 'B' )
{
B[p] = true ;
c.r = 2 ;
c.s = p ;
total.push_back( c ) ;
}
}
for( i = 1 ; i <= 100 ; i++ )
{
if( A[i] == true )
a.push_back( i ) ;
if( B[i] == true )
b.push_back( i ) ;
}
for( i = 0 ; i < total.size( ) ; i++ )
{
if( total[i].r == 1 )
{
ans1 += max( total[i].s , now1 ) - min( total[i].s , now1 ) + 1 ;
if( total[i-1].r == 2 && i != 0 )
{
if( ans1 <= ans2 )
ans1 = ans2 + 1 ;
}
now1 = total[i].s ;
}
if( total[i].r == 2 )
{
ans2 += max( total[i].s , now2 ) - min( total[i].s , now2 ) + 1 ;
if( total[i-1].r == 1 && i != 0 )
{
if( ans2 <= ans1 )
ans2 = ans1 + 1 ;
}
now2 = total[i].s ;
}
//printf( "%d : %d %d\n" , i , ans1 , ans2 ) ;
}
fprintf( file , "Case #%d: " , T-t ) ;
fprintf( file , "%d\n" , max( ans1 , ans2 ) ) ;
}
return 0 ;
}
| 20.595506 | 70 | 0.401528 | [
"vector"
] |
fba3f0e4c1dccf19ddef07e88994c49b1053cd5f | 6,536 | cpp | C++ | src/text/Text.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | src/text/Text.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | src/text/Text.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | #include "Text.h"
#include <iostream>
#include <cmath>
#include "textdefs.h"
#include GLFW_INCLUDE_HEADER_LOCATION
Text::Text(): Text(getDefaultFont(), getDefaultTextShader()) {
}
Text::Text(const Font::type &font, const nafy::shader_t &shader):
font(font),
wrappingWidth(0), overflowHeight(0),
lineSpacingMod(1.0f), textAlign(Font::textAlign::left),
fontSize(Font::defaultSize), stopsIndex(0) {
bindShader(shader);
}
// Memory manegemet
void Text::textSteal(Text &other) {
font = std::move(other.font);
image = std::move(other.image);
color = std::move(other.color);
str = std::move(other.str);
stops = std::move(other.stops);
textCopyIL(other);
textCopyPOD(other);
}
void Text::textCopy(const Text &other) {
font = other.font;
image = other.image;
color = other.color;
str = other.str;
stops = other.stops;
textCopyIL(other);
textCopyPOD(other);
}
void Text::textCopyIL(const Text &other) {
// https://stackoverflow.com/questions/11021764/does-moving-a-vector-invalidate-iterators
// So iterators _might_ be invalidated...
// I saw another post saying that they aren't as long as
// the allocaters are the same or something, but I'm just
// going to stay on the safe side.
index = other.index;
lines = other.lines;
for (Font::line &ln : lines) {
ln.start = index.begin() + (ln.start - other.index.begin());
ln.end = index.begin() + (ln.end - other.index.begin());
}
for (Font::line_iterator &it : stops) {
it = lines.begin() + (it - other.lines.begin());
}
}
void Text::textCopyPOD(const Text &other) {
wrappingWidth = other.wrappingWidth;
overflowHeight = other.overflowHeight;
lineSpacingMod = other.lineSpacingMod;
stopsIndex = other.stopsIndex;
textAlign = other.textAlign;
}
Text::Text(const Text &other) {
textCopy(other);
// Only render the bimap if there are lines to render
if (lines.size()) {
loadStops();
}
}
Text::Text(Text &&other) {
textSteal(other);
}
Text &Text::operator=(const Text &other) {
textCopy(other);
if (lines.size()) {
loadStops();
}
return *this;
}
Text &Text::operator=(Text &&other) {
textSteal(other);
return *this;
}
// End memory manegemet
void Text::configureFont() {
font->setSize(fontSize);
}
void Text::bindShader(const nafy::shader_t &shader) {
image.bindShader(shader);
}
nafy::shader_t Text::getShader() {
return image.getShader();
}
void Text::clear() {
// Clear the image of all data,
// and wipe the lines so that no mistakes are
// made
image.setImage(GL_RGBA, 0, 0, nullptr);
image.setWidth(0);
image.setHeight(0);
lines.clear();
}
void Text::generate() {
if (!str.size()) {
clear();
return;
}
// Determine if the string contains only whitespace.
// If so, a clear() would have the same effect,
// and would prevent a crash fron allocating a zero
// length array later on in Font.
for (std::string::size_type i = 0;; i++) {
if (i >= str.size()) {
clear();
return;
}
if (str[i] != ' ' && str[i] != '\n') {
break;
}
}
// Setup font for rendering operations
configureFont();
index = font->indexString(str.cbegin(), str.cend());
if (wrappingWidth) {
lines = font->getLines(index.cbegin(), index.cend(), wrappingWidth, textAlign);
if (overflowHeight) {
stops = font->breakupLines(lines.cbegin(), lines.cend(), lineSpacingMod, overflowHeight);
} else {
stops.clear();
stops.push_back(lines.cend());
}
} else {
// If wrapping width has been turned off (set to zero), then
// make a dummy line from the entire index.
lines.clear();
lines.push_back(font->makeLine(index.cbegin(), index.cend()));
// If wrapping width is disabled, then overflow height is
// irrelevant because the line height is constant.
stops.clear();
stops.push_back(lines.cend());
}
// Render lines up until the first stop
loadLines(lines.cbegin(), stops[0]);
}
void Text::loadLines(const Font::line_iterator &start, const Font::line_iterator &end) {
configureFont();
unsigned int width, height;
unsigned char *bitmap = font->renderLines(start, end, 4, color.get(), lineSpacingMod, width, height);
image.setWidth(width);
image.setHeight(height);
image.setImage(GL_RGBA, width, height, bitmap);
delete[] bitmap;
}
void Text::loadStops() {
Font::line_iterator start;
if (stopsIndex != 0) {
start = stops[stopsIndex - 1];
} else {
start = lines.begin();
}
loadLines(start, stops[stopsIndex]);
}
void Text::render() {
image.render();
}
bool Text::nextOverflow() {
if (stopsIndex + 1 < overflowSize()) {
stopsIndex++;
loadStops();
return true;
}
return false;
}
Font::line_str::size_type Text::overflowSize() {
return stops.size();
}
void Text::seekOverflow(Font::line_str::size_type i) {
if (i < overflowSize()) {
stopsIndex = i;
loadStops();
}
}
/* Setter bloat */
nafy::Color &Text::getColor() {
return color;
}
Font::type Text::getFont() {
return font;
}
void Text::setFont(const Font::type &font) {
this->font = font;
}
int Text::getX() {
return image.getX();
}
int Text::getY() {
return image.getY();
}
std::string &Text::getString() {
return str;
}
Font::textAlign Text::getAlign() {
return textAlign;
}
void Text::setX(int x) {
image.setX(x);
}
void Text::setY(int y) {
image.setY(y);
}
void Text::setString(const std::string &str) {
this->str = str;
}
void Text::setAlign(Font::textAlign textAlign) {
this->textAlign = textAlign;
}
void Text::setWrappingWidth(unsigned int width) {
wrappingWidth = width;
}
void Text::setOverflowHeight(unsigned int height) {
overflowHeight = height;
}
void Text::setLineSpacingMod(float mod) {
lineSpacingMod = mod;
}
unsigned int Text::getWrappingWidth() {
return wrappingWidth;
}
float Text::getLineSpacingMod() {
return lineSpacingMod;
}
void Text::setFontSize(unsigned int size) {
fontSize = size;
}
unsigned int Text::getFontSize() {
return fontSize;
}
unsigned int Text::getWidth() {
return image.getWidth();
}
unsigned int Text::getHeight() {
return image.getHeight();
}
| 22.307167 | 105 | 0.620716 | [
"render",
"vector"
] |
fbab1f1b7566df5ae026f63ccde269816e285270 | 1,098 | cpp | C++ | advanced/1024.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | advanced/1024.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | advanced/1024.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <map>
#include <set>
using namespace std;
//是回文数返回1,不是回文数返回0
bool is_palindromic(string num)
{
string s_num = num;
string t = s_num;
reverse(s_num.begin(), s_num.end());
if (s_num == t)
{
return 1;
}
else
{
return 0;
}
}
string add(string a, string b)
{
int flag = 0;
string res = "";
for (int i = a.size() - 1; i >= 0; i--)
{
int t = a[i] - '0' + b[i] - '0' + flag;
int g = t % 10;
res += to_string(g);
flag = t / 10;
}
if (flag)
{
res += to_string(flag);
}
reverse(res.begin(), res.end());
return res;
}
int main()
{
string num;
int k;
cin >> num >> k;
int t = k;
string res = num;
while (!is_palindromic(res) && k)
{
string rev_res = res;
reverse(rev_res.begin(), rev_res.end());
res = add(res, rev_res);
k--;
}
cout << res << endl
<< t - k;
system("pause");
return 0;
} | 17.15625 | 48 | 0.486339 | [
"vector"
] |
fbcfeb69113cf3daf8daa78e4c28d2e42bc55b3b | 9,602 | cpp | C++ | src/Pegasus/ProviderManager2/tests/OperationResponseHandler/TestOperationResponseHandler.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | null | null | null | src/Pegasus/ProviderManager2/tests/OperationResponseHandler/TestOperationResponseHandler.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | null | null | null | src/Pegasus/ProviderManager2/tests/OperationResponseHandler/TestOperationResponseHandler.cpp | ncultra/Pegasus-2.5 | 4a0b9a1b37e2eae5c8105fdea631582dc2333f9a | [
"MIT"
] | 1 | 2022-03-07T22:54:02.000Z | 2022-03-07T22:54:02.000Z | //%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// 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.
//
//==============================================================================
//
// Author: Chip Vincent
//
// Modified By:
//
//%/////////////////////////////////////////////////////////////////////////////
#include <Pegasus/ProviderManager2/OperationResponseHandler.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
static const char * verbose = 0;
// test null object checks
void Test1(void)
{
if(verbose)
{
cout << "Test1()" << endl;
}
try
{
// create dummy request and response messages
CIMGetInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMObjectPath("dummy"),
false,
false,
false,
CIMPropertyList(),
QueueIdStack());
CIMGetInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMInstance());
GetInstanceResponseHandler handler(&request, &response);
handler.processing();
CIMInstance cimInstance;
handler.deliver(cimInstance);
handler.complete();
throw Exception("Failed to detect null object in CIMGetInstanceResponseHandler::deliver().");
}
catch(CIMException &)
{
// do nothing expected
}
try
{
// create dummy request and response messages
CIMEnumerateInstancesRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMName("dummy"),
false,
false,
false,
false,
CIMPropertyList(),
QueueIdStack());
CIMEnumerateInstancesResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
Array<CIMInstance>());
EnumerateInstancesResponseHandler handler(&request, &response);
handler.processing();
CIMInstance cimInstance;
handler.deliver(cimInstance);
handler.complete();
throw Exception("Failed to detect null object in CIMEnumerateInstancesResponseHandler::deliver().");
}
catch(CIMException &)
{
// do nothing expected
}
try
{
// create dummy request and response messages
CIMEnumerateInstanceNamesRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMName("dummy"),
QueueIdStack());
CIMEnumerateInstanceNamesResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
Array<CIMObjectPath>());
EnumerateInstanceNamesResponseHandler handler(&request, &response);
handler.processing();
CIMObjectPath cimObjectPath;
handler.deliver(cimObjectPath);
handler.complete();
throw Exception("Failed to detect null object in CIMEnumerateInstanceNamesResponseHandler::deliver().");
}
catch(CIMException &)
{
// do nothing expected
}
try
{
// create dummy request and response messages
CIMCreateInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMInstance("dummy"),
QueueIdStack());
CIMCreateInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMObjectPath());
CreateInstanceResponseHandler handler(&request, &response);
handler.processing();
CIMObjectPath cimObjectPath;
handler.deliver(cimObjectPath);
handler.complete();
throw Exception("Failed to detect null object in CIMCreateInstanceResponseHandler::deliver().");
}
catch(CIMException &)
{
}
}
// test too many or too few objects delivered
void Test2(void)
{
if(verbose)
{
cout << "Test2()" << endl;
}
try
{
// create dummy request and response messages
CIMGetInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMObjectPath("dummy"),
false,
false,
false,
CIMPropertyList(),
QueueIdStack());
CIMGetInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMInstance());
GetInstanceResponseHandler handler(&request, &response);
handler.processing();
handler.complete();
throw Exception("Failed to detect too few objects in CIMGetInstanceResponseHandler::complete().");
}
catch(CIMException &)
{
// do nothing expected
}
try
{
// create dummy request and response messages
CIMGetInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMObjectPath("dummy"),
false,
false,
false,
CIMPropertyList(),
QueueIdStack());
CIMGetInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMInstance());
GetInstanceResponseHandler handler(&request, &response);
handler.processing();
CIMInstance cimInstance1("dummy");
handler.deliver(cimInstance1);
CIMInstance cimInstance2("dummy");
handler.deliver(cimInstance2);
handler.complete();
throw Exception("Failed to detect too many objects in CIMGetInstanceResponseHandler::deliver().");
}
catch(CIMException &)
{
// do nothing expected
}
try
{
// create dummy request and response messages
CIMCreateInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMInstance("dummy"),
QueueIdStack());
CIMCreateInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMObjectPath());
CreateInstanceResponseHandler handler(&request, &response);
handler.processing();
handler.complete();
throw Exception("Failed to detect too few objects in CIMCreateInstanceResponseHandler::complete().");
}
catch(CIMException &)
{
}
try
{
// create dummy request and response messages
CIMCreateInstanceRequestMessage request(
String::EMPTY,
CIMNamespaceName(),
CIMInstance("dummy"),
QueueIdStack());
CIMCreateInstanceResponseMessage response(
String::EMPTY,
CIMException(),
QueueIdStack(),
CIMObjectPath());
CreateInstanceResponseHandler handler(&request, &response);
handler.processing();
CIMObjectPath cimObjectPath1("dummy");
handler.deliver(cimObjectPath1);
CIMObjectPath cimObjectPath2("dummy");
handler.deliver(cimObjectPath2);
handler.complete();
throw Exception("Failed to detect too many objects in CIMGetInstanceResponseHandler::deliver().");
}
catch(CIMException &)
{
// do nothing expected
}
}
int main(int argc, char** argv)
{
const char * verbose = getenv("PEGASUS_TEST_VERBOSE");
try
{
Test1();
Test2();
}
catch(CIMException & e)
{
cout << "CIMException: " << e.getCode() << " " << e.getMessage() << endl;
return(-1);
}
catch(Exception & e)
{
cout << "Exception: " << e.getMessage() << endl;
return(-1);
}
catch(...)
{
cout << "unknown exception" << endl;
return(-1);
}
cout << argv[0] << " +++++ passed all tests" << endl;
return(0);
}
| 26.379121 | 112 | 0.58894 | [
"object"
] |
fbe18627c5f98e984f022dd2feac38761513ded2 | 1,668 | cpp | C++ | _Ray.cpp | MrApfel1994/Ray | 31ae807ee6a0406c30c08fa0d38b3a44224f86b6 | [
"WTFPL"
] | 60 | 2018-10-24T08:31:22.000Z | 2019-04-28T20:14:04.000Z | _Ray.cpp | MrApfel1994/Ray | 31ae807ee6a0406c30c08fa0d38b3a44224f86b6 | [
"WTFPL"
] | 1 | 2018-12-17T16:18:00.000Z | 2018-12-18T15:32:52.000Z | _Ray.cpp | MrApfel1994/Ray | 31ae807ee6a0406c30c08fa0d38b3a44224f86b6 | [
"WTFPL"
] | 5 | 2020-01-22T08:54:00.000Z | 2021-11-21T16:23:46.000Z |
#include "RendererFactory.cpp"
#include "SceneBase.cpp"
#include "internal/BVHSplit.cpp"
#include "internal/TextureSplitter.cpp"
#include "internal/Core.cpp"
#include "internal/CoreRef.cpp"
#include "internal/FramebufferRef.cpp"
#include "internal/RendererRef.cpp"
#include "internal/SceneRef.cpp"
#include "internal/TextureAtlasRef.cpp"
#include "internal/TextureUtilsRef.cpp"
#if defined(__ARM_NEON__) || defined(__aarch64__)
#include "internal/RendererNEON.cpp"
#endif
#if defined(__ANDROID__) || defined(DISABLE_OCL)
#else
#include "internal/RendererOCL.cpp"
#include "internal/SceneOCL.cpp"
#include "internal/TextureAtlasOCL.cpp"
#endif
// TODO:
// consider transparency in shadow from punctual lights
// add deletion functions for OpenCL backend
// add tests for intersection
// add more validation tests (use Cycles)
// DONE:
// add SH lightmap generation
// add lightmap generation (simple)
// add geometry camera (for lightmapping)
// add hdr env map
// add punctual lights support
// try using image for node buffer (utilize texture cache)
// compare traversal algorithm with stack
// add tent filter
// add depth of field
// try again with spatial splits or remove unnecessary indirection
// proper Ray termination
// add validation tests (use Cycles)
// make camera fov work
// add neon support
// add android build
// add shading to cpu implementations
// catch up CPU backends
// fix precision issues
// add deletion functions for CPU backends
// macro tree for OpenCL
// split shade kernel
// simple textures
// texture atlas
// rethink 'shapes' in mesh description
// Ray differentials
// sky and sun colors
// make render process incremental
| 26.903226 | 66 | 0.766187 | [
"mesh",
"geometry",
"render"
] |
fbfa19a6d7dddb5bdb13a055b8bd94fda991e288 | 3,692 | cpp | C++ | examples/google-code-jam/sprea/gcj3A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/sprea/gcj3A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/sprea/gcj3A.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#include <cctype>
#include <cassert>
#include <cmath>
#include <set>
#include <stack>
#include <utility>
#include <map>
#include <string>
#include <sstream>
using namespace std;
#define SIZE 109
#define eps 1e-10
//typedef pair<int,int> pi;
typedef pair<double, double> pd;
pd Larr[SIZE], Uarr[SIZE];
int L, U, W;
double segarea;
double getArea(vector<pd> poly, int flag = 0){
double ret = 0;
int i;
poly.push_back(poly[0]);
for( i = 0; i+1<(int)poly.size(); ++i){
ret += (poly[i].first * poly[i+1].second) - (poly[i].second*poly[i+1].first);
// if(flag)<<ret<< " ";
}
// if(flag)<<endl;
if ( ret < 0) ret = -ret;
return ret;
}
bool eq(double a, double b){
return fabs(a-b) < eps;
}
bool ok(double mid, int lidx, int uidx){
vector<pd> poly, temp;
int i;
double cury;
for( i = lidx; i<L; ++i){
if( Larr[i].first <= mid){
poly.push_back(Larr[i]);
}
else{
// i to i-1
if( !eq(Larr[i].first-Larr[i-1].first, 0)){
cury = (Larr[i].second - Larr[i-1].second)/(Larr[i].first-Larr[i-1].first)*(mid - Larr[i].first) + Larr[i].second;
poly.push_back(pd(mid, cury));
}
}
}
for( i = uidx; i<U; ++i){
if(Uarr[i].first <= mid){
temp.push_back(Uarr[i]);
}
else{
if( !eq(Uarr[i].first-Uarr[i-1].first, 0)){
cury = (Uarr[i].second - Uarr[i-1].second)/(Uarr[i].first-Uarr[i-1].first)*(mid - Uarr[i].first) + Uarr[i].second;
temp.push_back(pd(mid, cury));
}
}
}
for( i = (int)temp.size()-1; i>=0; --i){
poly.push_back(temp[i]);
}
// <<mid<< " "<<poly.size()<< " "<<segarea<<endl;
return getArea(poly)>=segarea;
}
double getSeg(int &lidx, int &uidx){
double low = Larr[lidx].first, high = W, mid;
int lp;
for( lp = 0; lp<100; ++lp){
mid = (low+high)/2;
if(ok(mid, lidx, uidx)){
high = mid;
}
else low = mid;
}
double cury;
for( ; lidx<L; ++lidx){
if( Larr[lidx+1].first>mid){
if( !eq(Larr[lidx+1].first-Larr[lidx].first, 0)){
cury = (Larr[lidx+1].second - Larr[lidx].second)/(Larr[lidx+1].first-Larr[lidx].first)*(mid - Larr[lidx+1].first) + Larr[lidx+1].second;
Larr[lidx] = pd(mid, cury);
}
else ++lidx;
break;
}
}
for( ; uidx<U; ++uidx){
if( Uarr[uidx+1].first > mid){
if( !eq(Uarr[uidx+1].first-Uarr[uidx].first, 0)){
cury = (Uarr[uidx+1].second - Uarr[uidx].second)/(Uarr[uidx+1].first-Uarr[uidx].first)*(mid - Uarr[uidx+1].first) + Uarr[uidx+1].second;
Uarr[uidx] = pd(mid, cury);
}
else ++uidx;
break;
}
}
// <<mid<< " "<<lidx<<" "<<uidx<<endl;
assert(lidx<L && uidx<U);
return mid;
}
int main() {
int T, cs, G, i, li, ui;
double totarea, curret;
// freopen("/home/user/Desktop/B-large.in", "r", stdin);
freopen("/home/user/Desktop/A-large.in", "r", stdin);
freopen("/home/user/Desktop/a-large.out", "w", stdout);
scanf("%d", &T);
for( cs = 1; cs<=T; ++cs){
scanf("%d%d%d%d", &W, &L, &U, &G);
vector<pd> poly;
poly.clear();
for( i = 0; i<L; ++i){
scanf("%lf%lf", &Larr[i].first, &Larr[i].second);
poly.push_back(Larr[i]);
}
for( i = 0; i<U; ++i){
scanf("%lf%lf", &Uarr[i].first, &Uarr[i].second);
}
for( i = U-1; i>=0; --i){
poly.push_back(Uarr[i]);
}
totarea = getArea(poly,1);
segarea = totarea/G;
printf("Case #%d:\n", cs);
li = ui = 0;
// printf("%d %d %lf %lf %d\n", L, U, segarea, totarea, poly.size());
// for( i = 0; i<poly.size(); ++i){
// printf("(%.2lf %.2lf) ", poly[i].first, poly[i].second);
// }puts("");
for( i = 1; i<G; ++i){
curret = getSeg(li, ui);
printf("%.10lf\n", curret);
}
}
return 0;
}
| 20.741573 | 140 | 0.557151 | [
"vector"
] |
22040332602bd3ed94fd404a59242d478de8dd8a | 2,774 | cpp | C++ | src/modules/meshmodels/softrenderer/softrenderer_scene.cpp | reneruhr/kipod | 5860f1730049a7901d4825be9af00d99aa99b8fa | [
"Apache-2.0",
"MIT"
] | null | null | null | src/modules/meshmodels/softrenderer/softrenderer_scene.cpp | reneruhr/kipod | 5860f1730049a7901d4825be9af00d99aa99b8fa | [
"Apache-2.0",
"MIT"
] | null | null | null | src/modules/meshmodels/softrenderer/softrenderer_scene.cpp | reneruhr/kipod | 5860f1730049a7901d4825be9af00d99aa99b8fa | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "softrenderer_scene.h"
#include "../meshmodel_scene.h"
#include "../../../render/softrenderer/softrenderer_layout.h"
namespace kipod::MeshModels{
void SoftRendererScene::Setup()
{
}
void SoftRendererScene::PrepareScreen()
{
softrenderer_->ClearBuffer();
scene_->framebuffer_->Bind();
glViewport(0, 0, scene_->width_, scene_->height_);
glClearColor(0.1f, 0.1f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void SoftRendererScene::Draw()
{
for(const auto& model : scene_->render_objects_){
softrenderer_->SetUniforms(scene_->GetActiveCamera(), mat4( model->Transform() ));
if(scene_->Toggle("Colors") || scene_->Toggle("Emissive"))
softrenderer_->DrawColoredTriangles(model.get(), scene_->lights_, scene_->Toggle("Emissive") );
else
softrenderer_->DrawTriangles(model.get(), scene_->Toggle("Wireframe"), scene_->Toggle("Normals") );
// if(box_mode){
// mat4 m = mat4( &model->TansformBoundingBox()[0][0] ); //to be changed
// softrenderer_->SetObjectMatrices(m, mat3(1.0));
// boundingBox.draw(softrenderer_, true,false);
// }
}
softrenderer_->DrawToOpenGL();
}
void SoftRendererScene::DrawBoundingBox(MeshModel *model, RenderCamera *camera)
{
}
void SoftRendererScene::DrawGrid(RenderCamera *camera)
{
}
void SoftRendererScene::DrawCoordinateAxis(RenderCamera *camera)
{
}
void SoftRendererScene::CreateMeshModelLayout(MeshModel *model)
{
std::string name = "SoftLayout";
auto layout = new kipod::SoftRenderLayout();
layout->SetSoftRenderer(softrenderer_.get());
layout->SetBuffer(model->vertices_vector,
model->indices_vector,
model->normals_vector,
model->nindices_vector);
model->AddLayout(name, std::move(*layout));
}
void SoftRendererScene::CreatePrimitiveModelLayout(PrimMeshModel *model)
{
std::string name = "SoftLayout";
auto layout = new kipod::SoftRenderLayout();
layout->SetSoftRenderer(softrenderer_.get());
layout->SetBuffer(model->vertices_vector,
model->indices_vector,
model->normals_vector,
model->nindices_vector);
model->AddLayout(name, std::move(*layout));
}
void SoftRendererScene::CreateCoordinateAxisLayout(std::vector<glm::vec3> &vertices, std::vector<glm::vec3> &colors)
{
}
void SoftRendererScene::CreateBoundingBoxLayout()
{
}
void SoftRendererScene::CreateGridLayout(std::vector<glm::vec3> &vertices)
{
}
SoftRendererScene::SoftRendererScene(MeshModelScene *scene) :
MeshModelAPIScene(scene),
softrenderer_(std::make_unique<SoftRenderer>(scene->width_, scene->height_))
{
}
}
| 28.020202 | 116 | 0.673035 | [
"render",
"vector",
"model",
"transform"
] |
2209bd04434d4dc74465901ab9cfb3e4814afca3 | 9,626 | cpp | C++ | text_renderer.cpp | thegedge/vogl | e5ba49a0d328ae0a839d9d4a18d187ae5e6c587c | [
"MIT"
] | null | null | null | text_renderer.cpp | thegedge/vogl | e5ba49a0d328ae0a839d9d4a18d187ae5e6c587c | [
"MIT"
] | 1 | 2015-04-28T14:36:38.000Z | 2015-04-28T14:37:41.000Z | text_renderer.cpp | thegedge/vogl | e5ba49a0d328ae0a839d9d4a18d187ae5e6c587c | [
"MIT"
] | null | null | null | #include "text_renderer.hpp"
#include <iostream>
#include <vector>
#include <OpenGL/gl3ext.h>
//----------------------------------------------------------------------------
namespace {
const char *VSHADER =
"#version 410 core\n"
""
"in vec4 position;\n"
"out vec2 texCoords;\n"
""
"void main(void) {\n"
" gl_Position = vec4(position.xy, 0, 1);\n"
" texCoords = position.zw;\n"
"}\n";
const char *FSHADER =
"#version 410 core\n"
"precision highp float;\n"
""
"uniform sampler2D sampler;\n"
"uniform vec4 color;\n"
"in vec2 texCoords;\n"
"out vec4 fragColor;\n"
""
"void main(void) {\n"
" fragColor = vec4(1, 1, 1, texture(sampler, texCoords).r) * color;\n"
"}\n";
bool getShaderLog(GLuint shader, std::string &error) {
char log[1024];
GLsizei len = 0;
glGetShaderInfoLog(shader, 1024, &len, log);
error = std::string(log, log + len);
return (len > 0);
}
struct GlyphVBOData {
float x;
float y;
float s;
float t;
GlyphVBOData() : x(0), y(0), s(0), t(0) {}
GlyphVBOData(float x, float y, float s, float t) : x(x), y(y), s(s), t(t) {}
};
}
namespace vogl {
//----------------------------------------------------------------------------
TextRenderer::TextRenderer(const std::string &fontPath, unsigned int height)
: texture_(0)
, sampler_(0)
, vbo_(0)
, vao_(0)
, vertexShader_(0)
, fragmentShader_(0)
, program_(0)
, colorUniform_(0)
, textureUniform_(0)
, face_(0)
, ft_(0)
, height_(height)
, sx_(1)
, sy_(1)
{
if(FT_Init_FreeType(&ft_) != 0) {
std::cerr << "Unable to initialize FreeType library\n";
return; // TODO throw exception
}
if(FT_New_Face(ft_, fontPath.c_str(), 0, &face_) != 0) {
std::cerr << "Unlable to load font: " << fontPath << '\n';
return; // TODO throw exception
}
// Initialize OpenGL objects
std::string shaderLog;
vertexShader_ = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader_, 1, &VSHADER, 0);
glCompileShader(vertexShader_);
if(getShaderLog(vertexShader_, shaderLog)) {
std::cerr << "Unable to compile vertex shader: " << shaderLog << '\n';
return; // TODO throw exception
}
fragmentShader_ = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader_, 1, &FSHADER, 0);
glCompileShader(fragmentShader_);
if(getShaderLog(fragmentShader_, shaderLog)) {
std::cerr << "Unable to compile fragment shader: " << shaderLog << '\n';
return; // TODO throw exception
}
program_ = glCreateProgram();
glAttachShader(program_, vertexShader_);
glAttachShader(program_, fragmentShader_);
glBindAttribLocation(program_, 0, "position");
glLinkProgram(program_);
glUseProgram(program_);
{
colorUniform_ = glGetUniformLocation(program_, "color");
textureUniform_ = glGetUniformLocation(program_, "sampler");
}
glUseProgram(0);
glGenTextures(1, &texture_);
glGenSamplers(1, &sampler_);
glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler_, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(sampler_, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenBuffers(1, &vbo_);
glGenVertexArrays(1, &vao_);
createAtlas();
}
TextRenderer::~TextRenderer() {
FT_Done_Face(face_);
FT_Done_FreeType(ft_);
glDeleteTextures(1, &texture_);
glDeleteSamplers(1, &sampler_);
glDeleteBuffers(1, &vbo_);
glDeleteVertexArrays(1, &vao_);
glDeleteProgram(program_);
glDeleteShader(vertexShader_);
glDeleteShader(fragmentShader_);
}
//----------------------------------------------------------------------------
void TextRenderer::createAtlas() {
glyphs_.clear();
if(face_) {
FT_Set_Pixel_Sizes(face_, 0, height_);
const FT_GlyphSlot g = face_->glyph;
// First get the size of the atlas so we can initialize the texture
int atlasWidth = 0, atlasHeight = 0;
for(unsigned char charIndex = 32; charIndex < 128; charIndex++) {
if(FT_Load_Char(face_, charIndex, FT_LOAD_RENDER) == 0) {
atlasWidth += g->bitmap.width;
atlasHeight = std::max(atlasHeight, static_cast<int>(g->bitmap.rows));
} else {
std::cerr << "Could not load character: " << charIndex << '\n';
// TODO throw exception
}
}
// Prepare the texture
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, atlasWidth, atlasHeight, 0,
GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer);
// Initialize texture and glyph data
const float invWidth = 1.0f / atlasWidth;
const float invHeight = 1.0f / atlasHeight;
int x = 0;
for(unsigned int charIndex = 32; charIndex < 128; ++charIndex) {
if(FT_Load_Char(face_, charIndex, FT_LOAD_RENDER) == 0) {
// Set texture data
glTexSubImage2D(GL_TEXTURE_2D, 0, x, 0, g->bitmap.width,
g->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE,
g->bitmap.buffer);
// Set glyph data
glyphs_[charIndex].x = g->bitmap_left;
glyphs_[charIndex].y = g->bitmap_top;
glyphs_[charIndex].width = g->bitmap.width;
glyphs_[charIndex].height = g->bitmap.rows;
glyphs_[charIndex].advanceX = g->advance.x >> 6;
glyphs_[charIndex].advanceY = g->advance.y >> 6;
glyphs_[charIndex].textureLeft = x * invWidth;
glyphs_[charIndex].textureRight = (x + g->bitmap.width)*invWidth;
glyphs_[charIndex].textureTop = g->bitmap.rows*invHeight;
glyphs_[charIndex].textureBottom = 0.0f;
x += g->bitmap.width;
}
}
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}
}
//----------------------------------------------------------------------------
void TextRenderer::setScale(float sx, float sy) {
this->sx_ = sx;
this->sy_ = sy;
}
//----------------------------------------------------------------------------
void TextRenderer::bind() {
if(vao_) {
glEnable(GL_BLEND);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_);
glBindSampler(0, sampler_);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindBuffer(GL_ARRAY_BUFFER, vbo_);
glBindVertexArray(vao_);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glUseProgram(program_);
glUniform4f(colorUniform_, 0, 0, 0, 1);
glUniform1i(textureUniform_, 0);
}
}
void TextRenderer::unbind() {
if(vao_) {
glDisable(GL_BLEND);
glBindTexture(GL_TEXTURE_2D, 0);
glBindSampler(0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glUseProgram(0);
}
}
//----------------------------------------------------------------------------
void TextRenderer::drawText(const std::string &text, float x, float y,
const Color &color) const
{
if(!vao_)
return;
glUniform4fv(colorUniform_, 1, color.rgba);
std::vector<GlyphVBOData> vboData(text.length() * 6);
size_t numVerts = 0;
const float initialX = x;
for(std::string::const_iterator iter = text.begin(); iter != text.end(); ++iter) {
const char p = *iter;
if(p == '\n') {
x = initialX;
y -= height_*sy_;
} else {
const GlyphMap::const_iterator glyphIter = glyphs_.find(static_cast<unsigned int>(p));
if(glyphIter != glyphs_.end()) {
const GlyphData &glyph = glyphIter->second;
const float x2 = x + glyph.x * sx_;
const float y2 = y + glyph.y * sy_;
const float w = glyph.width * sx_;
const float h = glyph.height * sy_;
const float tl = glyph.textureLeft;
const float tr = glyph.textureRight;
const float tt = glyph.textureTop;
const float tb = glyph.textureBottom;
vboData[numVerts++] = GlyphVBOData(x2 , y2 , tl, tb);
vboData[numVerts++] = GlyphVBOData(x2 , y2 - h, tl, tt);
vboData[numVerts++] = GlyphVBOData(x2 + w, y2 , tr, tb);
vboData[numVerts++] = GlyphVBOData(x2 + w, y2 , tr, tb);
vboData[numVerts++] = GlyphVBOData(x2 , y2 - h, tl, tt);
vboData[numVerts++] = GlyphVBOData(x2 + w, y2 - h, tr, tt);
x += glyph.advanceX * sx_;
y += glyph.advanceY * sy_;
}
}
}
glBufferData(GL_ARRAY_BUFFER,
static_cast<GLint>(vboData.size()*sizeof(GlyphVBOData)),
vboData.data(), GL_DYNAMIC_DRAW);
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLint>(numVerts));
}
//----------------------------------------------------------------------------
} | 33.307958 | 98 | 0.545294 | [
"vector"
] |
220bae924004a81dc4c698eb18e2f117de990c4f | 4,608 | hpp | C++ | projects/AMReX-Translation/src/f2cxx_analyzer.hpp | ouankou/rose | 76f2a004bd6d8036bc24be2c566a14e33ba4f825 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | projects/AMReX-Translation/src/f2cxx_analyzer.hpp | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | projects/AMReX-Translation/src/f2cxx_analyzer.hpp | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z |
#ifndef _F2CXX_ANALYZER_HPP
#define _F2CXX_ANALYZER_HPP 1
#include <set>
#include "rose.h"
namespace f2cxx
{
enum ParamAttr
{
none = (0),
param = (1 << 0), // parameter
data = (1 << 1), // 3D-data
dataparam = (data | param),
space_lower = (1 << 2), // marks parameters that are part of space bounds
space_upper = (1 << 3),
loop_lower = (1 << 4), // marks parameters that are part of loop bounds
loop_upper = (1 << 5),
normal_expr = (1 << 6), // unrelated expression
induction = (1 << 7), // marks induction variables (curr. only loop variables)
amrex_loop = (1 << 8) // marks loops that require translations
};
struct AnalyzerAttribute : AstAttribute
{
// implicit
AnalyzerAttribute(ParamAttr attr = none)
: AstAttribute(), val(attr), data_upper(), data_lower(),
iter_upper(), iter_lower(), transl(NULL), data_bounds(NULL)
{}
/** returns a set with associated declarations
* \todo basic correctness is a 1:1 mapping, thus only one entry
* is expected at this time. */
std::set<SgInitializedName*>& associates(ParamAttr relation);
/** records the role @p attr of an variable/parameter */
AnalyzerAttribute& role(ParamAttr attr);
/** tests whether the role @p attr is set */
bool hasRole(ParamAttr attr) const;
/** records a relationship described by @p attr with @p other */
AnalyzerAttribute& associate(ParamAttr attr, SgInitializedName* other);
/** records an indexing relationship at dimension @p dim with @p idx */
AnalyzerAttribute& access_dim(size_t dim, SgInitializedName* idx);
/** returns the array access of this induction variable. */
std::pair<size_t, SgInitializedName*> array_access() const;
/** removes all stored array accesses */
void clear_array_access();
/** returns the role */
ParamAttr flags() const { return val; }
/** sets a node prototype for the C++ code. */
AnalyzerAttribute& setTranslated(SgLocatedNode& cppnode)
{
transl = &cppnode;
return *this;
}
/** Retrieves the C++ prototype. */
SgLocatedNode* translated() const { return transl; }
/** sets a node prototype for the C++ code. */
AnalyzerAttribute& setBounds(SgInitializedName& cppnode)
{
data_bounds = &cppnode;
return *this;
}
/** Retrieves the C++ prototype for the bounds. */
SgInitializedName* bounds() const { return data_bounds; }
private:
/** stores the discovered role in the fortran code */
ParamAttr val;
/** stores all space upper bounds associated with this datablock */
std::set<SgInitializedName*> data_upper;
/** stores all space lower bounds associated with this datablock */
std::set<SgInitializedName*> data_lower;
/** stores all loop upper bounds associated with this datablock */
std::set<SgInitializedName*> iter_upper;
/** stores all loop lower bounds associated with this datablock */
std::set<SgInitializedName*> iter_lower;
/** stores all datablocks associated with this bound value */
std::set<SgInitializedName*> datablocks;
/** stores all variables used for indexing into a dimension of this datablock */
std::map<size_t, std::set<SgInitializedName*> > indexvars;
/** the translated node in C++ */
SgLocatedNode* transl;
SgInitializedName* data_bounds;
};
/** retrieves attribute on n
* \details
* if the attribute is not yet set, it will be created. */
AnalyzerAttribute& getAttribute(SgNode& n);
struct Analyzer
{
/** @brief
* Analyzes the procedure parameters and its uses in order to
* determine whether they need to be translated to special Amrex
* types.
* @details
* Supported type migration:
* * any three dimensional array in Fortran will be translated
* to an amrex::Box
* * a combination of four 3-element arrays will be translated
* into amrex::FArrayBox. The four arrays describe:
* - lower bounds on a 3D array
* - upper bounds on a 3D array
* - lower bounds on an iteration space over a 3D array
* - upper bounds on an iteration space over a 3D array
*/
void operator()(SgProcedureHeaderStatement* n);
};
void print_param_tags(SgProcedureHeaderStatement* proc);
}
#endif /* _F2CXX_ANALYZER_HPP */
| 33.391304 | 86 | 0.629123 | [
"3d"
] |
220c9327b1394f6f8a450eed3e3fade1ec32ec93 | 1,421 | cpp | C++ | solved/conquest.cpp | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | solved/conquest.cpp | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | solved/conquest.cpp | AudreyFelicio/Kattis-Solutions | bc5856e1c7d9b8d8c2677e2af5e84a37110200e8 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
#define rep(a, b) for (int a = 0; a < b; a++)
bool cmp(const pii &p1, const pii &p2) {
return p1.second > p2.second;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vi> al(n + 1, vi{});
vi sizes(n + 1, 0);
vector<bool> visited(n + 1, false);
rep(i, m) {
int u, v;
cin >> u >> v;
al[u].push_back(v);
al[v].push_back(u);
}
rep(i, n) {
cin >> sizes[i + 1];
}
int totalSize = sizes[1];
priority_queue<pii, vector<pii>, decltype(*cmp)> pq(*cmp);
queue<int> bfs;
bfs.push(1);
visited[1] = true;
while (!bfs.empty()) {
int curr = bfs.front(); bfs.pop();
while (!pq.empty()) {
auto [index, count] = pq.top();
if (totalSize <= count) {
break;
} else {
pq.pop();
bfs.push(index);
visited[index] = true;
totalSize += count;
}
}
for (auto neighbour : al[curr]) {
if (visited[neighbour]) {
continue;
}
if (totalSize > sizes[neighbour]) {
visited[neighbour] = true;
bfs.push(neighbour);
totalSize += sizes[neighbour];
} else {
pq.push({ neighbour, sizes[neighbour] });
}
}
}
cout << totalSize << endl;
}
| 21.861538 | 60 | 0.535538 | [
"vector"
] |
220cb2c3420e8d5ab8bb0d9f9958f198318331fc | 16,738 | hpp | C++ | ClassPath/include/Variant/UTI.hpp | X-Ryl669/Frost | 5eefa4d4d73ecb0985389bc142609221047b0e6b | [
"MIT"
] | 24 | 2015-03-23T19:16:56.000Z | 2022-02-02T01:55:55.000Z | ClassPath/include/Variant/UTI.hpp | X-Ryl669/Frost | 5eefa4d4d73ecb0985389bc142609221047b0e6b | [
"MIT"
] | 12 | 2015-03-22T03:49:01.000Z | 2019-04-10T08:08:54.000Z | ClassPath/include/Variant/UTI.hpp | X-Ryl669/Frost | 5eefa4d4d73ecb0985389bc142609221047b0e6b | [
"MIT"
] | 2 | 2016-03-14T08:09:38.000Z | 2020-08-07T11:40:23.000Z | #ifndef hpp_UTI_hpp
#define hpp_UTI_hpp
// Need general type definitions
#include "../Types.hpp"
// Need Data Source declarations
#include "DataSource.hpp"
// We need AVL tree to store UIDs
#include "../Tree/AVL.hpp"
/** The universal type identifier - should be the same on all platform
They are based stored on 128 bits
@warning The object file compiled from the CPP file including UTIImpl.hpp must be the first in the link order */
namespace UniversalTypeIdentifier
{
/** Runtime interface */
struct ModifiableTypeID
{
virtual const uint32 getID1() const = 0;
virtual const uint32 getID2() const = 0;
virtual const uint32 getID3() const = 0;
virtual const uint32 getID4() const = 0;
inline bool isEqual(ModifiableTypeID const * other) const { if (other) return getID1() == other->getID1() && getID2() == other->getID2() && getID3() == other->getID3() && getID4() == other->getID4(); return false; }
virtual ~ModifiableTypeID(){}
};
/** The constant typeID type */
typedef const ModifiableTypeID ConstTypeID;
/** The TypeID type the typebase is using for keys */
typedef ConstTypeID * TypeID;
/** Declare the Comparable policy for the type ID */
struct TypeIDComparator
{
/** TypeID comparators */
inline static bool LessThan(TypeID a, TypeID b)
{
return (bool)
(a->getID1() == b->getID1() ?
(a->getID2() == b->getID2() ?
(a->getID3() == b->getID3() ?
(a->getID4() == b->getID4() ?
false
: a->getID4() < b->getID4())
: a->getID3() < b->getID3())
: a->getID2() < b->getID2())
: a->getID1() < b->getID1()
);
}
/** Check if 2 types are equals */
inline static bool Equal(TypeID a, TypeID b) { return (bool)(a->getID1() == b->getID1() && a->getID2() == b->getID2() && a->getID3() == b->getID3() && a->getID4() == b->getID4()); }
};
/** Generic implementation for a TypeID
This should be used as a reference for manual implementation.
The implemented behavior here is to not compile
(there is no default constructor and const members)
*/
template <typename T>
struct TypeIDImpl : public ModifiableTypeID
{
const uint32 & ID1;
const uint32 & ID2;
const uint32 & ID3;
const uint32 & ID4;
typedef Type::Var type;
/** Runtime interface */
const uint32 getID1() const { return ID1; }
const uint32 getID2() const { return ID2; }
const uint32 getID3() const { return ID3; }
const uint32 getID4() const { return ID4; }
// If the compilation stops here, it's because you must specialize the type ID for the type you are using
// If it breaks for usual type, you've probably forgotten to include UTIImpl.hpp
private:
TypeIDImpl();
};
/** The type ID parser */
class TypeIDParser
{
// Members
private:
uint32 ID1, ID2, ID3, ID4;
// Construction and destruction
private:
/** Private default constructor with identifiers */
TypeIDParser(const uint32 _ID1 = 0, const uint32 _ID2 = 0, const uint32 _ID3 = 0, const uint32 _ID4 = 0) : ID1(_ID1), ID2(_ID2), ID3(_ID3), ID4(_ID4) {}
public:
/** The minimal TypeID length in a string */
enum { MinimumTypeIDLength = 35 };
/** The only allowed construction is through char array */
TypeIDParser(const char * typeName) : ID1(0), ID2(0), ID3(0), ID4(0)
{
if (typeName && strlen(typeName) == 35)
{
if (sscanf(typeName, "%08X-%08X-%08X-%08X", &ID1, &ID2, &ID3, &ID4) != 4)
ID1 = ID2 = ID3 = ID4 = 0;
}
}
/** Or other TypeID */
TypeIDParser(TypeID type) : ID1(type ? type->getID1() : 0), ID2(type ? type->getID2() : 0), ID3(type ? type->getID3() : 0), ID4(type ? type->getID4() : 0) {}
/** Save the current TypeID identifier to a char array */
inline bool saveTo(char * typeName, const uint32 typeSize)
{
if (typeSize < 36 || !typeName) return false;
return sprintf(typeName, "%08X-%08X-%08X-%08X", ID1, ID2, ID3, ID4) > 0;
}
/** Check if the read TypeID is valid */
inline bool isValid() { return !(ID1 == 0 && ID2 == 0 && ID3 == 0 && ID4 == 0); }
/** Check if the parsed type is the same as the one given */
inline const bool operator == (TypeID type) const { if (!type) return false; return type->getID1() == ID1 && type->getID2() == ID2 && type->getID3() == ID3 && type->getID4() == ID4; }
/** Check if the parsed type is the same as the one given */
inline const bool operator == (const char * typeName) const { if (!typeName) return false; TypeIDParser other(typeName); return ID1 == other.ID1 && ID2 == other.ID2 && ID3 == other.ID3 && ID4 == other.ID4; }
};
/** Qualifier cleaning template
@cond Private
*/
namespace Private
{
// Type1 has sizeof != sizeof(Type2)
typedef char Type1;
typedef struct { char some[2]; } Type2;
// Our type differentiator
Type1 isConst(const volatile void *);
Type2 isConst(volatile void *);
template<typename A, typename B>
struct isSame { };
template<typename A>
struct isSame<A, A> { typedef void type; };
template<typename> struct toVoid { typedef void type; };
template<typename T, typename = void>
struct isClass { enum { Result = false }; };
template<typename C>
struct isClass<C, typename toVoid<int C::*>::type> { enum { Result = true }; };
template<typename T>
struct isFloat { enum { Result = false }; typedef Type2 Type; };
template<> struct isFloat<float> { enum { Result = true }; typedef Type1 Type; };
template<> struct isFloat<double> { enum { Result = true }; typedef Type1 Type; };
template<> struct isFloat<long double> { enum { Result = true }; typedef Type1 Type; };
// Check for enum type, typically anything that's not a class, function, reference, array, but can be converted to int
template<typename E, typename = void>
struct isEnum
{
struct nullsink {};
static Type2 checkI(nullsink*); // accept null pointer constants
static Type1 checkI(...);
static Type1 checkE(int);
static Type2 checkE(...);
static Type2 checkFISink(const Type1 * );
static Type1 checkFISink(const Type2 * );
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion-null"
#endif
enum { Result = sizeof(checkI(E())) == sizeof(Type1)
&& sizeof(checkFISink((typename isFloat<E>::Type*)0)) == sizeof(Type1)
&& sizeof(checkE(E())) == sizeof(Type1) };
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
};
// class
template<typename E>
struct isEnum<E, typename toVoid<int E::*>::type> { enum { Result = false }; };
// reference
template<typename R>
struct isEnum<R&, void> { enum { Result = false }; };
// function (FuntionType() will error out).
template<typename F>
struct isEnum<F, typename isSame<void(F), void(F*)>::type> { enum { Result = false }; };
// array (ArrayType() will error out)
template<typename E>
struct isEnum<E[], void> { enum { Result = false }; };
template<typename E, int N>
struct isEnum<E[N], void> { enum { Result = false }; };
}
/** @endcond*/
// Check for enum type, typically anything that's not a class, function, reference, array, but can be converted to int
template<typename E, typename V = void>
struct IsEnum
{
enum { Result = Private::isEnum<E, V>::Result };
};
// Extract and test for enum value
template<typename E, typename V = void>
class IfEnum
{
struct ImpossibleTypeToInstantiate {};
template <bool, int N> struct Test { typedef E Type; };
template <int N> struct Test<false, N> { typedef ImpossibleTypeToInstantiate Type; };
public:
typedef typename Test< IsEnum<E, V> :: Result, 0> :: Type Type;
};
template <typename T>
struct IsConst
{
// Avoid building T
// (this will simply avoid compile error when T's constructor is private)
static T* t;
// The selector
enum { Result = (sizeof(Private::Type1) == sizeof(Private::isConst( t )) )};
};
template <typename T>
struct WithoutConst
{
struct PleaseDontTryToRegisterConstType;
typedef PleaseDontTryToRegisterConstType type;
};
template <typename T>
struct WarpType
{
typedef T type;
};
/** The binder static function that create the type ID at compile time. */
template <typename T>
// If compilation breaks here it is because you are trying to get a type id of a const type
// Try without const
TypeID getTypeIDImpl(T*, Bool2Type< true > * );
template <typename T>
// If compilation break here, it is because you've forgotten to add this
// in your code (must be in global namespace):
// RegisterClassForVariant(YourClassHere, SomeUniqueID1, SomeUniqueID2, SomeUniqueID3, SomeUniqueID4);
// RegisterClassFunctions(YourClassHere, GetCode, SetCode);
TypeID getTypeIDImpl(T*, Bool2Type< false > * );
// If you get linker error related to getTypeIDImpl, it can be hard to spot where the given type is referenced in your code
// In that case, you can use this macro, on the FIRST line of the file to force the compiler to break on a specific implementation type T
// So, for example, if you get Undefined reference error for type A in file X.o
// Put this at the very top of the X.cpp file:
// #include "path/to/UTI.hpp"
// PreventTypeIDImpl(A)
// Then compile. This will result in compiler noise, from which you extract the location where the symbol is being used (in the previous example,
// it gives:
// path/to/X.cpp:580:80: note: in instantiation of function template specialization 'Type::VarT<Type::ObjectCopyPolicy>::extractIf<A>' requested here
// Reference * _ref = initialiser->getResult(environment).extractIf((A*)0);
#define PreventTypeIDImpl(T) \
namespace UniversalTypeIdentifier { void getTypeID(T *); }
#define PreventTypeIDImplForwardDecl(N,type,T) \
namespace N { type T; } \
namespace UniversalTypeIdentifier { void getTypeID(N::T *); }
/** This links a type known at compile time to a runtime instance of TypeID */
template <typename T>
static TypeID getTypeID(T* t) { return getTypeIDImpl(t, (Bool2Type< IsConst<T>::Result > *)0); }
enum { PODBaseID = 0x00000000, };
/** An item in the type factory */
struct CreationMethods
{
/** This method create the default object as a Var variable */
Type::Var * (*createDefaultObject)(void);
/** Return the Object's Universal Type Identifier */
TypeID (*registerObjectUTI)(void);
/** Get the data source for this object */
Type::DataSource* (*getDataSource)(const void *);
/** Set the data source for this object */
void (*setDataSource)(Type::DataSource *, void *);
/** Return the type name */
const char * (*getTypeName)(void);
CreationMethods(Type::Var * (*pFunc1)(), TypeID (*pFunc2)(), Type::DataSource * (*pFunc3)(const void *), void (*pFunc4)(Type::DataSource *, void*), const char* (*pFunc5)()) : createDefaultObject(pFunc1), registerObjectUTI(pFunc2), getDataSource(pFunc3), setDataSource(pFunc4), getTypeName(pFunc5) {}
CreationMethods(const CreationMethods & xCM) : createDefaultObject(xCM.createDefaultObject), registerObjectUTI(xCM.registerObjectUTI), getDataSource(xCM.getDataSource), setDataSource(xCM.setDataSource), getTypeName(xCM.getTypeName) {}
CreationMethods & operator = (const CreationMethods & xCM) { memcpy(this, &xCM, sizeof(*this)); return *this; }
};
typedef const CreationMethods ConstCreationMethods;
typedef ConstCreationMethods * PCreationMethods;
struct ConstCreationMethodsDeleter
{
/** Used for cleaning const object */
inline static void deleter(PCreationMethods pObj, TypeID tID) { delete const_cast<CreationMethods *>(pObj); delete const_cast<ModifiableTypeID*>(tID); }
};
template <typename T>
struct CMImpl : public CreationMethods
{
};
/** The data source type definition */
typedef Type::DataSource * (*PGetDataSourceFunc)(const void *);
typedef void (*PSetDataSourceFunc)(Type::DataSource *, void *);
/** The factory itself */
class TypeFactory
{
private:
/** Private shortcut to the tree type */
typedef Tree::AVL::Tree<PCreationMethods, TypeID, TypeIDComparator, ConstCreationMethodsDeleter> TreeT;
/** The factory holder */
TreeT mlTree;
public:
/** Not found enum */
enum { NotFound = 0 };
/** Add a type to the factory
@return true on success, false if already exists */
bool registerType(TypeID typeID, PCreationMethods pMethod)
{
return mlTree.insertObject(pMethod, typeID);
}
/** Find a type from the factory
@return The creation methods or NULL on failure */
inline PCreationMethods findType(TypeID typeID) const
{
// Find the object in the tree
TreeT::IterT iter = mlTree.searchFor(typeID);
if (iter.isValid()) return (PCreationMethods)*iter;
return NULL;
}
/** Check if this type is already registered.
Compile-time version */
template <typename T>
inline bool isRegistered(T* t) const { return isRegistered(UniversalTypeIdentifier::getTypeID(t)); }
/** Check if this type is already registered.
Run-time version */
inline bool isRegistered(TypeID typeID) const { return (findType(typeID) != (PCreationMethods)NotFound); }
/** Get the type name.
Run-time version */
inline const char * getTypeName(TypeID typeID) const { PCreationMethods ptr = findType(typeID); return ptr ? (*ptr->getTypeName)() : ""; }
/** Return the data source export and import function */
inline PGetDataSourceFunc getDataSourceOutFunc(TypeID typeID) const
{
PCreationMethods pxCM = findType(typeID);
if (pxCM == NULL) return NULL;
return pxCM->getDataSource;
}
/** Return the data source export and import function */
inline PSetDataSourceFunc getDataSourceInFunc(TypeID typeID) const
{
PCreationMethods pxCM = findType(typeID);
if (pxCM == NULL) return NULL;
return pxCM->setDataSource;
}
};
/** The factory singleton */
extern TypeFactory * getTypeFactory();
/** The automatic register object at startup */
struct AutoRegister
{
PCreationMethods mpCM;
#ifdef DelayTypeRegistering
// Debug here
// Delay registering
static Stack::PlainOldData::FIFO<PCreationMethods> mlFifo;
AutoRegister(const PCreationMethods & pCM) : mpCM(pCM) { mlFifo.Push(pCM); }
// Register all the pending registration
static void registerAllTypeAtOnce()
{
while (mlFifo.getSize())
{
const PCreationMethods & pCM = mlFifo.Pop();
getTypeFactory()->registerType(pCM->registerObjectUTI(), pCM);
}
}
#else
AutoRegister(const PCreationMethods & pCM) : mpCM(pCM) { getTypeFactory()->registerType(pCM->registerObjectUTI(), pCM); }
#endif
// ~AutoRegister() { delete const_cast<CreationMethods*>(mpCM); }
};
/* You'll need to enable this if you want to delay type registering
namespace UniversalTypeIdentifier
{
#ifdef DelayTypeRegistering
Stack::PlainOldData::FIFO<PCreationMethods> AutoRegister::mlFifo;
#endif
}
*/
}
#endif
| 38.835267 | 307 | 0.607719 | [
"object"
] |
220cc25c71f847e9b3bdc4193bcc37353ecb39af | 2,063 | cpp | C++ | WordBreakII.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | WordBreakII.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | WordBreakII.cpp | hgfeaon/leetcode | 1e2a562bd8341fc57a02ecff042379989f3361ea | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
void print_strings(vector<string>& v);
void print_ints(vector<vector<int> >& dp);
class Solution {
private:
vector<string> result;
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<vector<int> > dp;
result.clear();
int len = s.length();
dp.resize(len + 1);
dp[0].push_back(-1);
for (int i=1; i<=len; i++) {
for (int j=i-1; j>=0; j--) {
string str = s.substr(j, i - j);
if (dict.find(str) != dict.end()) {
if (dp[j].empty()) continue;
dp[i].push_back(j);
}
}
}
print_ints(dp);
dfs_build(dp, s, len, "");
return result;
}
void dfs_build(vector<vector<int> >& dp, string& s, int len, string sent) {
vector<int> indices = dp[len];
for (int i=0; i<indices.size(); i++) {
int prefix_len = indices[i];
if (prefix_len <= 0) {
result.push_back(s.substr(0, len) + sent);
} else {
string suffix = s.substr(prefix_len, len - prefix_len);
dfs_build(dp, s, prefix_len, " " + suffix + sent);
}
}
}
};
void print_strings(vector<string>& v) {
for (int i=0; i<v.size(); i++) {
cout<<v[i]<<endl;
}
}
void print_ints(vector<vector<int> >& dp) {
for (int i=0; i<dp.size(); i++) {
for (int j=0; j<dp[i].size(); j++) {
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
}
int main() {
Solution s;
unordered_set<string> dict;
const char* words[] = {"cat", "cats", "sand", "and", "dog"};
for (int i=0; i<sizeof(words)/sizeof(const char*); i++) {
dict.insert(words[i]);
}
vector<string> ret = s.wordBreak("catsanddog", dict);
print_strings(ret);
system("pause");
return 0;
}
| 24.559524 | 79 | 0.492002 | [
"vector"
] |
81fc99da924e945e146a93500ca44b597d567b27 | 351 | cpp | C++ | API/GameEngineContents/TitleTimeObject.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | API/GameEngineContents/TitleTimeObject.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | API/GameEngineContents/TitleTimeObject.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | #include "TitleTimeObject.h"
#include <GameEngineBase/GameEngineTime.h>
float TitleTimeObject::TimeLine_ = 0.0f;
TitleTimeObject::TitleTimeObject()
{
}
TitleTimeObject::~TitleTimeObject()
{
}
void TitleTimeObject::Start()
{
}
void TitleTimeObject::Update()
{
TimeLine_ += GameEngineTime::GetDeltaTime();
}
void TitleTimeObject::Render()
{
}
| 13 | 45 | 0.740741 | [
"render"
] |
c301bb590ce38cf72997773d1c46fd54d3489644 | 175 | hpp | C++ | include/engine.hpp | fedor-rusak/chickpea | c59ecce4c606f1508b28ebfe5d6d7e2e3529ae1c | [
"MIT"
] | 1 | 2017-08-09T13:04:51.000Z | 2017-08-09T13:04:51.000Z | include/engine.hpp | fedor-rusak/chickpea | c59ecce4c606f1508b28ebfe5d6d7e2e3529ae1c | [
"MIT"
] | null | null | null | include/engine.hpp | fedor-rusak/chickpea | c59ecce4c606f1508b28ebfe5d6d7e2e3529ae1c | [
"MIT"
] | null | null | null | namespace engine {
int init();
int terminate();
double getTime();
void processInput();
bool shouldExit();
void render();
void other();
void swapBuffers();
} | 8.333333 | 21 | 0.634286 | [
"render"
] |
c30312b92e71f47e49396daecbf8da3a5ccb8949 | 6,197 | cpp | C++ | tests/src/MustacheTemplateEngineTests.cpp | nemu-cpp/mustache-template-engine | 8666e5fd3affe04978a4007ad69d3657c9558147 | [
"MIT"
] | null | null | null | tests/src/MustacheTemplateEngineTests.cpp | nemu-cpp/mustache-template-engine | 8666e5fd3affe04978a4007ad69d3657c9558147 | [
"MIT"
] | null | null | null | tests/src/MustacheTemplateEngineTests.cpp | nemu-cpp/mustache-template-engine | 8666e5fd3affe04978a4007ad69d3657c9558147 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2022 Xavier Leclercq
Released under the MIT License
See https://github.com/nemu-cpp/mustache-template-engine/blob/main/LICENSE.txt
*/
#include "MustacheTemplateEngineTests.hpp"
#include "Nemu/MustacheTemplateEngine/MustacheTemplateEngine.hpp"
#include <Ishiko/FileSystem.hpp>
using namespace Ishiko;
using namespace Nemu;
MustacheTemplateEngineTests::MustacheTemplateEngineTests(const TestNumber& number, const TestContext& context)
: TestSequence(number, "MustacheTemplateEngine tests", context)
{
append<HeapAllocationErrorsTest>("Creation test 1", ConstructorTest1);
append<HeapAllocationErrorsTest>("render test 1", RenderTest1);
append<HeapAllocationErrorsTest>("render test 2", RenderTest2);
append<HeapAllocationErrorsTest>("render test 3", RenderTest3);
append<HeapAllocationErrorsTest>("render with layout test 1", RenderWithLayoutTest1);
append<HeapAllocationErrorsTest>("render with layout test 2", RenderWithLayoutTest2);
}
void MustacheTemplateEngineTests::ConstructorTest1(Test& test)
{
MustacheTemplateEngine templatingEngine(MustacheTemplateEngine::Options("."));
ISHIKO_TEST_PASS();
}
void MustacheTemplateEngineTests::RenderTest1(Test& test)
{
boost::filesystem::path templateRootDir = test.context().getTestDataPath("templates");
MustacheTemplateEngine templatingEngine(MustacheTemplateEngine::Options(templateRootDir.string()));
ViewContext context;
std::string renderedView = templatingEngine.render("MustacheTemplateEngineTests_RenderTest1.html", context);
boost::filesystem::path outputPath =
test.context().getTestOutputPath("MustacheTemplateEngineTests_RenderTest1.html");
Error error; // TODO: use exception
BinaryFile outputFile = BinaryFile::Create(outputPath, error);
outputFile.write(renderedView.c_str(), renderedView.size());
outputFile.close();
ISHIKO_TEST_FAIL_IF_FILES_NEQ("MustacheTemplateEngineTests_RenderTest1.html",
"MustacheTemplateEngineTests_RenderTest1.html");
ISHIKO_TEST_PASS();
}
void MustacheTemplateEngineTests::RenderTest2(Test& test)
{
boost::filesystem::path templateRootDir = test.context().getTestDataPath("templates");
MustacheTemplateEngine templatingEngine(MustacheTemplateEngine::Options(templateRootDir.string()));
ViewContext context;
context["name"] = "John";
std::string renderedView = templatingEngine.render("MustacheTemplateEngineTests_RenderTest2.html", context);
boost::filesystem::path outputPath =
test.context().getTestOutputPath("MustacheTemplateEngineTests_RenderTest2.html");
Error error; // TODO: use exception
BinaryFile outputFile = BinaryFile::Create(outputPath, error);
outputFile.write(renderedView.c_str(), renderedView.size());
outputFile.close();
ISHIKO_TEST_FAIL_IF_FILES_NEQ("MustacheTemplateEngineTests_RenderTest2.html",
"MustacheTemplateEngineTests_RenderTest2.html");
ISHIKO_TEST_PASS();
}
void MustacheTemplateEngineTests::RenderTest3(Test& test)
{
boost::filesystem::path templateRootDir = test.context().getTestDataPath("templates");
MustacheTemplateEngine templatingEngine(MustacheTemplateEngine::Options(templateRootDir.string()));
ViewContext context;
context["name"] = "<John>";
std::string renderedView = templatingEngine.render("MustacheTemplateEngineTests_RenderTest2.html", context);
boost::filesystem::path outputPath =
test.context().getTestOutputPath("MustacheTemplateEngineTests_RenderTest3.html");
Error error; // TODO: use exception
BinaryFile outputFile = BinaryFile::Create(outputPath, error);
outputFile.write(renderedView.c_str(), renderedView.size());
outputFile.close();
ISHIKO_TEST_FAIL_IF_FILES_NEQ("MustacheTemplateEngineTests_RenderTest3.html",
"MustacheTemplateEngineTests_RenderTest3.html");
ISHIKO_TEST_PASS();
}
void MustacheTemplateEngineTests::RenderWithLayoutTest1(Test& test)
{
boost::filesystem::path templateRootDir = test.context().getTestDataPath("templates");
boost::filesystem::path layoutRootDir = test.context().getTestDataPath("layouts");
MustacheTemplateEngine templatingEngine(
MustacheTemplateEngine::Options(templateRootDir.string(), layoutRootDir.string()));
ViewContext context;
context["name"] = "John";
std::string renderedView = templatingEngine.render("MustacheTemplateEngineTests_RenderWithLayoutTest1.html", context, "MustacheTemplateEngineTests_RenderWithLayoutTest1.html");
boost::filesystem::path outputPath =
test.context().getTestOutputPath("MustacheTemplateEngineTests_RenderWithLayoutTest1.html");
Error error; // TODO: use exception
BinaryFile outputFile = BinaryFile::Create(outputPath, error);
outputFile.write(renderedView.c_str(), renderedView.size());
outputFile.close();
ISHIKO_TEST_FAIL_IF_FILES_NEQ("MustacheTemplateEngineTests_RenderWithLayoutTest1.html",
"MustacheTemplateEngineTests_RenderWithLayoutTest1.html");
ISHIKO_TEST_PASS();
}
void MustacheTemplateEngineTests::RenderWithLayoutTest2(Test& test)
{
boost::filesystem::path templateRootDir = test.context().getTestDataPath("templates");
boost::filesystem::path layoutRootDir = test.context().getTestDataPath("layouts");
MustacheTemplateEngine templatingEngine(
MustacheTemplateEngine::Options(templateRootDir.string(), layoutRootDir.string()));
ViewContext context;
context["name"] = "<John>";
std::string renderedView = templatingEngine.render("MustacheTemplateEngineTests_RenderWithLayoutTest1.html", context, "MustacheTemplateEngineTests_RenderWithLayoutTest1.html");
boost::filesystem::path outputPath =
test.context().getTestOutputPath("MustacheTemplateEngineTests_RenderWithLayoutTest2.html");
Error error; // TODO: use exception
BinaryFile outputFile = BinaryFile::Create(outputPath, error);
outputFile.write(renderedView.c_str(), renderedView.size());
outputFile.close();
ISHIKO_TEST_FAIL_IF_FILES_NEQ("MustacheTemplateEngineTests_RenderWithLayoutTest2.html",
"MustacheTemplateEngineTests_RenderWithLayoutTest2.html");
ISHIKO_TEST_PASS();
}
| 44.582734 | 180 | 0.775052 | [
"render"
] |
c30324a82914a65e6c0fa269e6c1dd7c3b552cc3 | 4,891 | cpp | C++ | box2d/native/src/shape/circle_shape.cpp | d954mas/defold-box2d | c21fb0d8bfc4f70e1d837351b0c06bb1bc9195b4 | [
"MIT"
] | 12 | 2021-06-27T11:34:47.000Z | 2021-11-25T15:01:46.000Z | box2d/native/src/shape/circle_shape.cpp | d954mas/defold-box2d | c21fb0d8bfc4f70e1d837351b0c06bb1bc9195b4 | [
"MIT"
] | 6 | 2021-07-13T20:36:30.000Z | 2021-07-21T17:57:54.000Z | box2d/native/src/shape/circle_shape.cpp | d954mas/defold-box2d | c21fb0d8bfc4f70e1d837351b0c06bb1bc9195b4 | [
"MIT"
] | 3 | 2021-06-28T12:12:30.000Z | 2021-11-19T06:13:03.000Z | #include "shape/circle_shape.h"
#include "utils.h"
#include "extra_utils.h"
#include "allocators.h"
#define META_NAME_CIRCLE_SHAPE "Box2d::CircleShapeClass"
namespace box2dDefoldNE {
CircleShape* CircleShape_get_userdata(lua_State* L, int index){
if(luaL_checkudata(L, index, META_NAME_CIRCLE_SHAPE) == NULL){
utils::error(L,"not circle shape");
}
CircleShape *shape = *static_cast<CircleShape**>(luaL_checkudata(L, index, META_NAME_CIRCLE_SHAPE));
return shape;
}
static int CircleShape_destroy(lua_State* L){
delete *static_cast<CircleShape**>(luaL_checkudata(L, 1, META_NAME_CIRCLE_SHAPE));
return 0;
}
//region BASE METHODS
static int GetType(lua_State* L){
utils::check_arg_count(L, 1);
CircleShape *shape = CircleShape_get_userdata(L,1);
lua_pushnumber(L, shape->shape->GetType());
return 1;
}
static int GetRadius(lua_State* L){
utils::check_arg_count(L, 1);
CircleShape *shape = CircleShape_get_userdata(L,1);
lua_pushnumber(L, shape->shape->m_radius);
return 1;
}
static int SetRadius(lua_State* L){
utils::check_arg_count(L, 2);
CircleShape *shape = CircleShape_get_userdata(L,1);
shape->shape->m_radius = luaL_checknumber(L,2);
return 0;
}
static int Clone(lua_State* L){
utils::check_arg_count(L, 1);
CircleShape *shape = CircleShape_get_userdata(L,1);
b2CircleShape_push(L,shape->shape);
return 1;
}
static int GetChildCount(lua_State* L){
utils::check_arg_count(L, 1);
CircleShape *shape = CircleShape_get_userdata(L,1);
lua_pushnumber(L, shape->shape->GetChildCount());
return 1;
}
static int TestPoint(lua_State* L){
utils::check_arg_count(L, 3);
CircleShape *shape = CircleShape_get_userdata(L,1);
b2Transform transform = extra_utils::get_b2Transform_safe(L,2,"not transform");
b2Vec2 point = extra_utils::get_b2vec_safe(L,3,"point not vector3");
lua_pushboolean(L, shape->shape->TestPoint(transform, point));
return 1;
}
static int RayCast(lua_State* L){
utils::check_arg_count(L, 3,4);
CircleShape *shape = CircleShape_get_userdata(L,1);
b2RayCastInput input = extra_utils::get_b2RayCastInput_safe(L,2);
b2Transform transform = extra_utils::get_b2Transform_safe(L,3,"not transform");
b2RayCastOutput output;
output.fraction = -1;
output.normal.x = 0;
output.normal.y = 0;
bool result = shape->shape->RayCast(&output,input,transform,0);
if(result){
extra_utils::b2RayCastOutput_push(L,output);
}else{
lua_pushnil(L);
}
return 1;
}
static int ComputeAABB(lua_State* L){
utils::check_arg_count(L, 2, 3);
CircleShape *shape = CircleShape_get_userdata(L,1);
b2Transform transform = extra_utils::get_b2Transform_safe(L,2,"not transform");
b2AABB aabb;
shape->shape->ComputeAABB(&aabb,transform,0);
extra_utils::b2AABB_push(L,aabb);
return 1;
}
static int ComputeMass(lua_State* L){
utils::check_arg_count(L, 2);
CircleShape *shape = CircleShape_get_userdata(L,1);
float density = luaL_checknumber(L,2);
b2MassData massData;
shape->shape->ComputeMass(&massData,density);
extra_utils::massData_to_table(L,massData);
return 1;
}
//endregion
//region functions
static int SetPosition(lua_State* L){
utils::check_arg_count(L, 2);
CircleShape *shape = CircleShape_get_userdata(L,1);
shape->shape->m_p = extra_utils::get_b2vec_safe(L,2, "position not vector");
return 0;
}
static int GetPosition(lua_State* L){
utils::check_arg_count(L, 1);
CircleShape *shape = CircleShape_get_userdata(L,1);
b2Vec2 position = shape->shape->m_p;
utils::push_vector(L, position.x, position.y, 0);
return 1;
}
//endregion
CircleShape* b2CircleShape_push(lua_State *L, b2CircleShape* b2Shape){
CircleShape *shape = new CircleShape(b2Shape);
*static_cast<CircleShape**>(lua_newuserdata(L, sizeof(CircleShape*))) = shape;
if(luaL_newmetatable(L, META_NAME_CIRCLE_SHAPE)){
static const luaL_Reg functions[] =
{
{"GetType", GetType},
{"GetRadius", GetRadius},
{"Clone", Clone},
{"GetChildCount", GetChildCount},
{"TestPoint", TestPoint},
{"RayCast", RayCast},
{"ComputeAABB", ComputeAABB},
{"ComputeMass", ComputeMass},
{"SetRadius", SetRadius},
{"SetPosition", SetPosition},
{"GetPosition", GetPosition},
{"__gc", CircleShape_destroy},
{0, 0}
};
luaL_register(L, NULL,functions);
lua_pushvalue(L, -1);
lua_setfield(L, -1, "__index");
}
lua_setmetatable(L, -2);
return shape;
}
CircleShape::CircleShape(b2CircleShape* shape){
this->shape = (b2CircleShape*) b2Shape_clone(shape);
}
CircleShape::~CircleShape() {
b2Shape_free(this->shape);
}
} | 29.823171 | 105 | 0.674913 | [
"shape",
"vector",
"transform"
] |
c3086e72f1e06641b968a4335825fec49839c1f3 | 12,671 | cpp | C++ | HW8_v0/src/main.cpp | hansenbeast/2019-SYSU-CG | 8be1affc82f76a7fa1c1b1d5f72f4c4e0f889987 | [
"MIT"
] | 1 | 2021-09-16T15:53:03.000Z | 2021-09-16T15:53:03.000Z | HW8_v0/src/main.cpp | hansenbeast/2019-SYSU-CG | 8be1affc82f76a7fa1c1b1d5f72f4c4e0f889987 | [
"MIT"
] | null | null | null | HW8_v0/src/main.cpp | hansenbeast/2019-SYSU-CG | 8be1affc82f76a7fa1c1b1d5f72f4c4e0f889987 | [
"MIT"
] | null | null | null | //
// main.cpp
// HW8_Bezier_Curve
//
// Created by hansen on 2019/5/22.
// Copyright © 2019 hansen. All rights reserved.
//
// system headers
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
// third-party headers
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
// local headers
#include "Shader.hpp"
#include "ImGUI/imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
// Function prototypes
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
vector<glm::vec3>::iterator findNearestControlPoint(const float xpos, const float ypos, const float threshold);
vector<GLfloat> controlPoints2floatVector(vector<glm::vec3> controlPoints);
glm::vec3 glfwPos2ndcPos(const glm::vec3 point);
void draw_process(vector<glm::vec3> points, float t);
void renderPointsLines(Shader &shader,const vector<GLfloat> &nodeData, float pointSize);
static void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "Glfw Error %d: %s\n", error, description);
}
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// Global variable
vector<glm::vec3> controlPoints;
vector<glm::vec3>::iterator currPointIter;
bool isLeftButtonPressed = false;
bool isDrawing = false;
GLuint pointVAO, pointVBO;
Shader pointShader;
int main(int argc, const char * argv[]) {
// glfw: initialize and configure
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
return 1;
// Decide GL+GLSL versions
#if __APPLE__
// GL 3.2 + GLSL 150
const char* glsl_version = "#version 150";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac
#else
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Bezier Curve", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// load the shader program
pointShader = Shader("Shader/point.vs","Shader/point.fs");
Shader curveShader = Shader("Shader/curve.vs","Shader/curve.fs");
// vertex data
float step = 0.001;
vector<float> data;
data.resize(int(1 / step));
for (int i = 0; i < data.size(); ++i) {
data[i] = i * step;
}
GLuint VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenVertexArrays(1, &pointVAO);
glGenBuffers(1, &pointVBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 1 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
// control variables in render loop
ImVec4 clear_color = ImVec4(0.1f, 0.1f, 0.1f, 0.1f);
float current_t = 0.0;
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// clear the colorbuffer
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
// unbind VAO every time
glBindVertexArray(0);
// Render Control Points
if (isLeftButtonPressed) {
// record the selected point index
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
// check if can selected the nearest control point
currPointIter = findNearestControlPoint(xpos, ypos, 100);
if (currPointIter != controlPoints.end()){
// update position
*currPointIter = glm::vec3(xpos, ypos, 0.0f);
}
}
auto pointdata = controlPoints2floatVector(controlPoints);
renderPointsLines(pointShader, pointdata, 5.0f);
// Render Beizer Curve
curveShader.use();
curveShader.setInt("size", int(controlPoints.size()));
for (auto index = 0; index < controlPoints.size(); index++){
curveShader.setFloat3(("points[" + std::to_string(index) + "]").c_str(),glm::value_ptr(glfwPos2ndcPos(controlPoints[index])));
}
if(!controlPoints.empty()){
glBindVertexArray(VAO);
glPointSize(2.0f);
glDrawArrays(GL_POINTS, 0, int(data.size()));
glBindVertexArray(0);
}
// dynamic draw
if(isDrawing){
// deactivate the mouse movement
glfwSetMouseButtonCallback(window, NULL);
if (current_t <= 1.0) {
current_t += 0.0005;
draw_process(controlPoints, current_t);
}
} else {
current_t = 0.0;
// reactivate the mouse movement
glfwSetMouseButtonCallback(window, mouse_button_callback);
}
// render ImGui
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS){
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){
isDrawing = !isDrawing;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
// add one point on the canvas && move the selected points
if (action == GLFW_PRESS) {
isLeftButtonPressed = true;
if (findNearestControlPoint(xpos, ypos, 100) == controlPoints.end()) {
// add the selected point
controlPoints.push_back(glm::vec3(xpos, ypos, 0.0f));
}
}
if (action == GLFW_RELEASE) {
currPointIter = controlPoints.end();
isLeftButtonPressed = false;
}
}
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
// delete the last control point on the canvas
if(!controlPoints.empty()){
controlPoints.pop_back();
}
}
}
vector<glm::vec3>::iterator findNearestControlPoint(const float xpos, const float ypos, const float threshold) {
// 粗略查找点击范围中是否有可以控制的点
vector<glm::vec3>::iterator res = controlPoints.end();
auto dist = [&xpos, &ypos](const vector<glm::vec3>::iterator iter) -> float {
return pow((xpos - iter->x), 2) + pow((ypos - iter->y), 2);
};
for (auto iter = controlPoints.begin(); iter != controlPoints.end(); ++iter) {
auto dis = dist(iter);
if (dis < threshold) {
if (res == controlPoints.end()) {
res = iter;
}
else {
res = (dist(res) < dis) ? res : iter;
}
}
}
return res;
}
vector<GLfloat> controlPoints2floatVector(vector<glm::vec3> cp){
vector<GLfloat> res;
res.clear();
for (auto iter = cp.begin(); iter != cp.end(); iter++){
res.push_back(iter->x);
res.push_back(iter->y);
res.push_back(iter->z);
}
// normalize to [-1, 1]
for (unsigned int i = 0; i < res.size(); i = i + 3) {
auto norx = (2 * res[i]) / SCR_WIDTH - 1;
auto nory = 1 - (2 * res[i + 1]) / SCR_HEIGHT;
res[i] = norx;
res[i + 1] = nory;
}
return res;
}
glm::vec3 glfwPos2ndcPos(const glm::vec3 point){
glm::vec3 res;
res.x = (2 * point.x) / SCR_WIDTH - 1;
res.y = 1 - (2 * point.y) / SCR_HEIGHT;
res.z = 0.0f;
return res;
}
void draw_process(vector<glm::vec3> points, float t){
if (points.size() < 2){
return;
}
vector<glm::vec3> next_nodes;
for (int i = 0; i < points.size() - 1; ++i)
{
float x = (1 - t) * points[i].x + t * points[i + 1].x;
float y = (1 - t) * points[i].y + t * points[i + 1].y;
next_nodes.push_back(glm::vec3(x, y, 0.0f));
}
auto nodeData = controlPoints2floatVector(next_nodes);
renderPointsLines(pointShader, nodeData, 3.5f);
draw_process(next_nodes, t);
}
void renderPointsLines(Shader &shader,const vector<GLfloat> &nodeData, float pointSize){
shader.use();
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(pointVAO);
glBindBuffer(GL_ARRAY_BUFFER,pointVBO);
glBufferData(GL_ARRAY_BUFFER, nodeData.size() * sizeof(GLfloat), nodeData.data(), GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glPointSize(pointSize);
glDrawArrays(GL_POINTS, 0, int(nodeData.size() / 3));
// Render lines between control points
glLineWidth(1.0f);
glDrawArrays(GL_LINE_STRIP, 0, int(nodeData.size() / 3));
glBindVertexArray(0);
}
| 33.879679 | 138 | 0.604688 | [
"render",
"object",
"vector"
] |
c31270001325d146721dad0649934fd739e5ae00 | 2,719 | cpp | C++ | cgi_module/cgi_module.cpp | ADKosm/Lagush | e71dc82ccea54cf307b37c328c3bd08b53f0735f | [
"MIT"
] | null | null | null | cgi_module/cgi_module.cpp | ADKosm/Lagush | e71dc82ccea54cf307b37c328c3bd08b53f0735f | [
"MIT"
] | 1 | 2016-03-01T10:59:38.000Z | 2016-03-01T10:59:38.000Z | cgi_module/cgi_module.cpp | ADKosm/Lagush | e71dc82ccea54cf307b37c328c3bd08b53f0735f | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <iostream>
#include <string>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <vector>
#include <limits.h>
#define COMMAND strtol(argv[1], NULL, 10)
#define JAIL_PATH argv[2]
#define SCRIPT_PATH argv[3]
void signal_identificate() {
sigset_t sigset;
siginfo_t sig;
sigemptyset(&sigset);
sigaddset(&sigset, SIGUSR1);
sigprocmask(SIG_BLOCK, &sigset, NULL);
struct timespec limit;
limit.tv_sec = 10; // 10 секунд на подумать
limit.tv_nsec = 0;
pid_t ppid = getppid();
kill(ppid, SIGUSR1);
int status = sigtimedwait(&sigset, &sig, &limit);
if(status == -1) {
std::cerr << "Can't launch cgi_script! Server is not responding " << std::endl;
exit(0);
}
}
int main(int argc, char ** argv) {
signal_identificate();
int user_id = getuid();
if(user_id == 0) {
std::cerr << "Don't launch server with root permitions!" << std::endl;
exit(0);
}
int st = setuid(0);
if(st == -1) {
std::cerr << "Impossible to create jail! Please set SUID flag on this server" << std::endl;
exit(0);
}
std::string path_to_lexe = "/proc/"+std::to_string(getpid())+"/exe";
std::string path_to_pexe = "/proc/"+std::to_string(getppid())+"/exe";
std::string path_to_real_exe;
std::string path_to_real_pexe;
char linkname[PATH_MAX+1];
size_t r = readlink(path_to_lexe.c_str(), linkname, PATH_MAX+1);
linkname[r] = '\0';
path_to_real_exe = std::string(linkname);
r = readlink(path_to_pexe.c_str(), linkname, PATH_MAX+1);
linkname[r] = '\0';
path_to_real_pexe = std::string(linkname);
if(path_to_real_exe.substr(0, path_to_real_exe.rfind('/')) != path_to_real_pexe.substr(0, path_to_real_pexe.rfind('/'))) {
std::cerr << "Only original server can launch this module!" << std::endl;
exit(0);
}
if(COMMAND == 0) {
chroot(JAIL_PATH);
chdir("/");
setuid(user_id);
execle(SCRIPT_PATH, SCRIPT_PATH, NULL, environ);
} else if (COMMAND == 1) {
mkdir((std::string(JAIL_PATH)+"/dev").c_str(), 0777);
std::vector< std::string > devices {
"/dev/random",
"/dev/urandom",
"/dev/zero",
"/dev/null",
"/dev/tty"
};
int user_id = getuid();
setuid(0);
for(auto dev : devices) {
struct stat buf;
stat(dev.c_str(), &buf);
mknod( (std::string(JAIL_PATH)+dev).c_str(), S_IFCHR | 0777, buf.st_rdev );
}
setuid(user_id);
exit(0);
}
return 0;
}
| 26.656863 | 126 | 0.581832 | [
"vector"
] |
c31f8cd57b9581576587007e5a0c993df670f5d6 | 26,433 | cc | C++ | third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_metrics_helper.h"
#include <memory>
#include "base/macros.h"
#include "base/test/histogram_tester.h"
#include "base/test/simple_test_tick_clock.h"
#include "components/viz/test/ordered_simple_task_runner.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/page/launching_process_state.h"
#include "third_party/blink/renderer/platform/scheduler/base/test/task_queue_manager_for_test.h"
#include "third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/test/fake_frame_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/test/fake_page_scheduler.h"
using base::sequence_manager::TaskQueue;
namespace blink {
namespace scheduler {
namespace {
class MainThreadSchedulerImplForTest : public MainThreadSchedulerImpl {
public:
MainThreadSchedulerImplForTest(
std::unique_ptr<base::sequence_manager::TaskQueueManager>
task_queue_manager,
base::Optional<base::Time> initial_virtual_time)
: MainThreadSchedulerImpl(std::move(task_queue_manager),
initial_virtual_time){};
using MainThreadSchedulerImpl::SetCurrentUseCaseForTest;
};
} // namespace
using QueueType = MainThreadTaskQueue::QueueType;
using base::Bucket;
using testing::ElementsAre;
using testing::UnorderedElementsAre;
class MainThreadMetricsHelperTest : public testing::Test {
public:
MainThreadMetricsHelperTest() = default;
~MainThreadMetricsHelperTest() override = default;
void SetUp() override {
histogram_tester_.reset(new base::HistogramTester());
clock_.Advance(base::TimeDelta::FromMilliseconds(1));
mock_task_runner_ =
base::MakeRefCounted<cc::OrderedSimpleTaskRunner>(&clock_, true);
scheduler_ = std::make_unique<MainThreadSchedulerImplForTest>(
base::sequence_manager::TaskQueueManagerForTest::Create(
nullptr, mock_task_runner_, &clock_),
base::nullopt);
metrics_helper_ = &scheduler_->main_thread_only().metrics_helper;
}
void TearDown() override {
scheduler_->Shutdown();
scheduler_.reset();
}
void RunTask(MainThreadTaskQueue::QueueType queue_type,
base::TimeTicks start,
base::TimeDelta duration) {
DCHECK_LE(clock_.NowTicks(), start);
clock_.SetNowTicks(start + duration);
scoped_refptr<MainThreadTaskQueueForTest> queue;
if (queue_type != MainThreadTaskQueue::QueueType::kDetached) {
queue = scoped_refptr<MainThreadTaskQueueForTest>(
new MainThreadTaskQueueForTest(queue_type));
}
// Pass an empty task for recording.
TaskQueue::PostedTask posted_task(base::OnceClosure(), FROM_HERE);
TaskQueue::Task task(std::move(posted_task), base::TimeTicks());
metrics_helper_->RecordTaskMetrics(queue.get(), task, start,
start + duration, base::nullopt);
}
void RunTask(FrameScheduler* scheduler,
base::TimeTicks start,
base::TimeDelta duration) {
DCHECK_LE(clock_.NowTicks(), start);
clock_.SetNowTicks(start + duration);
scoped_refptr<MainThreadTaskQueueForTest> queue(
new MainThreadTaskQueueForTest(QueueType::kDefault));
queue->SetFrameSchedulerForTest(scheduler);
// Pass an empty task for recording.
TaskQueue::PostedTask posted_task(base::OnceClosure(), FROM_HERE);
TaskQueue::Task task(std::move(posted_task), base::TimeTicks());
metrics_helper_->RecordTaskMetrics(queue.get(), task, start,
start + duration, base::nullopt);
}
void RunTask(UseCase use_case,
base::TimeTicks start,
base::TimeDelta duration) {
DCHECK_LE(clock_.NowTicks(), start);
clock_.SetNowTicks(start + duration);
scoped_refptr<MainThreadTaskQueueForTest> queue(
new MainThreadTaskQueueForTest(QueueType::kDefault));
scheduler_->SetCurrentUseCaseForTest(use_case);
// Pass an empty task for recording.
TaskQueue::PostedTask posted_task(base::OnceClosure(), FROM_HERE);
TaskQueue::Task task(std::move(posted_task), base::TimeTicks());
metrics_helper_->RecordTaskMetrics(queue.get(), task, start,
start + duration, base::nullopt);
}
base::TimeTicks Milliseconds(int milliseconds) {
return base::TimeTicks() + base::TimeDelta::FromMilliseconds(milliseconds);
}
void ForceUpdatePolicy() { scheduler_->ForceUpdatePolicy(); }
std::unique_ptr<FakeFrameScheduler> CreateFakeFrameSchedulerWithType(
FrameStatus frame_status) {
FakeFrameScheduler::Builder builder;
switch (frame_status) {
case FrameStatus::kNone:
case FrameStatus::kDetached:
return nullptr;
case FrameStatus::kMainFrameVisible:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetIsPageVisible(true)
.SetIsFrameVisible(true);
break;
case FrameStatus::kMainFrameVisibleService:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetPageScheduler(playing_view_.get())
.SetIsFrameVisible(true);
break;
case FrameStatus::kMainFrameHidden:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetIsPageVisible(true);
break;
case FrameStatus::kMainFrameHiddenService:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetPageScheduler(playing_view_.get());
break;
case FrameStatus::kMainFrameBackground:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame);
break;
case FrameStatus::kMainFrameBackgroundExemptSelf:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetIsExemptFromThrottling(true);
break;
case FrameStatus::kMainFrameBackgroundExemptOther:
builder.SetFrameType(FrameScheduler::FrameType::kMainFrame)
.SetPageScheduler(throtting_exempt_view_.get());
break;
case FrameStatus::kSameOriginVisible:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsPageVisible(true)
.SetIsFrameVisible(true);
break;
case FrameStatus::kSameOriginVisibleService:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetPageScheduler(playing_view_.get())
.SetIsFrameVisible(true);
break;
case FrameStatus::kSameOriginHidden:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsPageVisible(true);
break;
case FrameStatus::kSameOriginHiddenService:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetPageScheduler(playing_view_.get());
break;
case FrameStatus::kSameOriginBackground:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe);
break;
case FrameStatus::kSameOriginBackgroundExemptSelf:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsExemptFromThrottling(true);
break;
case FrameStatus::kSameOriginBackgroundExemptOther:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetPageScheduler(throtting_exempt_view_.get());
break;
case FrameStatus::kCrossOriginVisible:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetIsPageVisible(true)
.SetIsFrameVisible(true);
break;
case FrameStatus::kCrossOriginVisibleService:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetPageScheduler(playing_view_.get())
.SetIsFrameVisible(true);
break;
case FrameStatus::kCrossOriginHidden:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetIsPageVisible(true);
break;
case FrameStatus::kCrossOriginHiddenService:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetPageScheduler(playing_view_.get());
break;
case FrameStatus::kCrossOriginBackground:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true);
break;
case FrameStatus::kCrossOriginBackgroundExemptSelf:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetIsExemptFromThrottling(true);
break;
case FrameStatus::kCrossOriginBackgroundExemptOther:
builder.SetFrameType(FrameScheduler::FrameType::kSubframe)
.SetIsCrossOrigin(true)
.SetPageScheduler(throtting_exempt_view_.get());
break;
case FrameStatus::kCount:
NOTREACHED();
return nullptr;
}
return builder.Build();
}
base::SimpleTestTickClock clock_;
scoped_refptr<cc::OrderedSimpleTaskRunner> mock_task_runner_;
std::unique_ptr<MainThreadSchedulerImplForTest> scheduler_;
MainThreadMetricsHelper* metrics_helper_; // NOT OWNED
std::unique_ptr<base::HistogramTester> histogram_tester_;
std::unique_ptr<FakePageScheduler> playing_view_ =
FakePageScheduler::Builder().SetIsAudioPlaying(true).Build();
std::unique_ptr<FakePageScheduler> throtting_exempt_view_ =
FakePageScheduler::Builder().SetIsThrottlingExempt(true).Build();
DISALLOW_COPY_AND_ASSIGN(MainThreadMetricsHelperTest);
};
TEST_F(MainThreadMetricsHelperTest, Metrics_PerQueueType) {
// QueueType::kDefault is checking sub-millisecond task aggregation,
// FRAME_* tasks are checking normal task aggregation and other
// queue types have a single task.
// Make sure that it starts in a foregrounded state.
if (kLaunchingProcessIsBackgrounded)
scheduler_->SetRendererBackgrounded(false);
RunTask(QueueType::kDefault, Milliseconds(1),
base::TimeDelta::FromMicroseconds(700));
RunTask(QueueType::kDefault, Milliseconds(2),
base::TimeDelta::FromMicroseconds(700));
RunTask(QueueType::kDefault, Milliseconds(3),
base::TimeDelta::FromMicroseconds(700));
RunTask(QueueType::kControl, Milliseconds(400),
base::TimeDelta::FromMilliseconds(30));
RunTask(QueueType::kFrameLoading, Milliseconds(800),
base::TimeDelta::FromMilliseconds(70));
RunTask(QueueType::kFramePausable, Milliseconds(1000),
base::TimeDelta::FromMilliseconds(20));
RunTask(QueueType::kCompositor, Milliseconds(1200),
base::TimeDelta::FromMilliseconds(25));
RunTask(QueueType::kTest, Milliseconds(1600),
base::TimeDelta::FromMilliseconds(85));
scheduler_->SetRendererBackgrounded(true);
RunTask(QueueType::kControl, Milliseconds(2000),
base::TimeDelta::FromMilliseconds(25));
RunTask(QueueType::kFrameThrottleable, Milliseconds(2600),
base::TimeDelta::FromMilliseconds(175));
RunTask(QueueType::kUnthrottled, Milliseconds(2800),
base::TimeDelta::FromMilliseconds(25));
RunTask(QueueType::kFrameLoading, Milliseconds(3000),
base::TimeDelta::FromMilliseconds(35));
RunTask(QueueType::kFrameThrottleable, Milliseconds(3200),
base::TimeDelta::FromMilliseconds(5));
RunTask(QueueType::kCompositor, Milliseconds(3400),
base::TimeDelta::FromMilliseconds(20));
RunTask(QueueType::kIdle, Milliseconds(3600),
base::TimeDelta::FromMilliseconds(50));
RunTask(QueueType::kFrameLoadingControl, Milliseconds(4000),
base::TimeDelta::FromMilliseconds(5));
RunTask(QueueType::kControl, Milliseconds(4200),
base::TimeDelta::FromMilliseconds(20));
RunTask(QueueType::kFrameThrottleable, Milliseconds(4400),
base::TimeDelta::FromMilliseconds(115));
RunTask(QueueType::kFramePausable, Milliseconds(4600),
base::TimeDelta::FromMilliseconds(175));
RunTask(QueueType::kIdle, Milliseconds(5000),
base::TimeDelta::FromMilliseconds(1600));
RunTask(QueueType::kDetached, Milliseconds(8000),
base::TimeDelta::FromMilliseconds(150));
std::vector<base::Bucket> expected_samples = {
{static_cast<int>(QueueType::kControl), 75},
{static_cast<int>(QueueType::kDefault), 2},
{static_cast<int>(QueueType::kUnthrottled), 25},
{static_cast<int>(QueueType::kFrameLoading), 105},
{static_cast<int>(QueueType::kCompositor), 45},
{static_cast<int>(QueueType::kIdle), 1650},
{static_cast<int>(QueueType::kTest), 85},
{static_cast<int>(QueueType::kFrameLoadingControl), 5},
{static_cast<int>(QueueType::kFrameThrottleable), 295},
{static_cast<int>(QueueType::kFramePausable), 195},
{static_cast<int>(QueueType::kDetached), 150},
};
EXPECT_THAT(histogram_tester_->GetAllSamples(
"RendererScheduler.TaskDurationPerQueueType2"),
testing::ContainerEq(expected_samples));
EXPECT_THAT(histogram_tester_->GetAllSamples(
"RendererScheduler.TaskDurationPerQueueType2.Foreground"),
UnorderedElementsAre(
Bucket(static_cast<int>(QueueType::kControl), 30),
Bucket(static_cast<int>(QueueType::kDefault), 2),
Bucket(static_cast<int>(QueueType::kFrameLoading), 70),
Bucket(static_cast<int>(QueueType::kCompositor), 25),
Bucket(static_cast<int>(QueueType::kTest), 85),
Bucket(static_cast<int>(QueueType::kFramePausable), 20)));
EXPECT_THAT(histogram_tester_->GetAllSamples(
"RendererScheduler.TaskDurationPerQueueType2.Background"),
UnorderedElementsAre(
Bucket(static_cast<int>(QueueType::kControl), 45),
Bucket(static_cast<int>(QueueType::kUnthrottled), 25),
Bucket(static_cast<int>(QueueType::kFrameLoading), 35),
Bucket(static_cast<int>(QueueType::kFrameThrottleable), 295),
Bucket(static_cast<int>(QueueType::kFramePausable), 175),
Bucket(static_cast<int>(QueueType::kCompositor), 20),
Bucket(static_cast<int>(QueueType::kIdle), 1650),
Bucket(static_cast<int>(QueueType::kFrameLoadingControl), 5),
Bucket(static_cast<int>(QueueType::kDetached), 150)));
}
TEST_F(MainThreadMetricsHelperTest, Metrics_PerUseCase) {
RunTask(UseCase::kNone, Milliseconds(500),
base::TimeDelta::FromMilliseconds(4000));
RunTask(UseCase::kTouchstart, Milliseconds(7000),
base::TimeDelta::FromMilliseconds(25));
RunTask(UseCase::kTouchstart, Milliseconds(7050),
base::TimeDelta::FromMilliseconds(25));
RunTask(UseCase::kTouchstart, Milliseconds(7100),
base::TimeDelta::FromMilliseconds(25));
RunTask(UseCase::kCompositorGesture, Milliseconds(7150),
base::TimeDelta::FromMilliseconds(5));
RunTask(UseCase::kCompositorGesture, Milliseconds(7200),
base::TimeDelta::FromMilliseconds(30));
RunTask(UseCase::kMainThreadCustomInputHandling, Milliseconds(7300),
base::TimeDelta::FromMilliseconds(2));
RunTask(UseCase::kSynchronizedGesture, Milliseconds(7400),
base::TimeDelta::FromMilliseconds(250));
RunTask(UseCase::kMainThreadCustomInputHandling, Milliseconds(7700),
base::TimeDelta::FromMilliseconds(150));
RunTask(UseCase::kLoading, Milliseconds(7900),
base::TimeDelta::FromMilliseconds(50));
RunTask(UseCase::kMainThreadGesture, Milliseconds(8000),
base::TimeDelta::FromMilliseconds(60));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskDurationPerUseCase"),
UnorderedElementsAre(
Bucket(static_cast<int>(UseCase::kNone), 4000),
Bucket(static_cast<int>(UseCase::kCompositorGesture), 35),
Bucket(static_cast<int>(UseCase::kMainThreadCustomInputHandling),
152),
Bucket(static_cast<int>(UseCase::kSynchronizedGesture), 250),
Bucket(static_cast<int>(UseCase::kTouchstart), 75),
Bucket(static_cast<int>(UseCase::kLoading), 50),
Bucket(static_cast<int>(UseCase::kMainThreadGesture), 60)));
}
TEST_F(MainThreadMetricsHelperTest, GetFrameStatusTest) {
DCHECK_EQ(GetFrameStatus(nullptr), FrameStatus::kNone);
FrameStatus frame_statuses_tested[] = {
FrameStatus::kMainFrameVisible,
FrameStatus::kSameOriginHidden,
FrameStatus::kCrossOriginHidden,
FrameStatus::kSameOriginBackground,
FrameStatus::kMainFrameBackgroundExemptSelf,
FrameStatus::kSameOriginVisibleService,
FrameStatus::kCrossOriginHiddenService,
FrameStatus::kMainFrameBackgroundExemptOther};
for (FrameStatus frame_status : frame_statuses_tested) {
std::unique_ptr<FakeFrameScheduler> frame =
CreateFakeFrameSchedulerWithType(frame_status);
EXPECT_EQ(GetFrameStatus(frame.get()), frame_status);
}
}
TEST_F(MainThreadMetricsHelperTest, BackgroundedRendererTransition) {
scheduler_->SetFreezingWhenBackgroundedEnabled(true);
typedef BackgroundedRendererTransition Transition;
int backgrounding_transitions = 0;
int foregrounding_transitions = 0;
if (!kLaunchingProcessIsBackgrounded) {
scheduler_->SetRendererBackgrounded(true);
backgrounding_transitions++;
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(Bucket(static_cast<int>(Transition::kBackgrounded),
backgrounding_transitions)));
scheduler_->SetRendererBackgrounded(false);
foregrounding_transitions++;
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(Bucket(static_cast<int>(Transition::kBackgrounded),
backgrounding_transitions),
Bucket(static_cast<int>(Transition::kForegrounded),
foregrounding_transitions)));
} else {
scheduler_->SetRendererBackgrounded(false);
foregrounding_transitions++;
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(Bucket(static_cast<int>(Transition::kForegrounded),
foregrounding_transitions)));
}
scheduler_->SetRendererBackgrounded(true);
backgrounding_transitions++;
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(Bucket(static_cast<int>(Transition::kBackgrounded),
backgrounding_transitions),
Bucket(static_cast<int>(Transition::kForegrounded),
foregrounding_transitions)));
// Waste 5+ minutes so that the delayed stop is triggered
RunTask(QueueType::kDefault, Milliseconds(1),
base::TimeDelta::FromSeconds(5 * 61));
// Firing ForceUpdatePolicy multiple times to make sure that the
// metric is only recorded upon an actual change.
ForceUpdatePolicy();
ForceUpdatePolicy();
ForceUpdatePolicy();
EXPECT_THAT(histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(
Bucket(static_cast<int>(Transition::kBackgrounded),
backgrounding_transitions),
Bucket(static_cast<int>(Transition::kForegrounded),
foregrounding_transitions),
Bucket(static_cast<int>(Transition::kFrozenAfterDelay), 1)));
scheduler_->SetRendererBackgrounded(false);
foregrounding_transitions++;
ForceUpdatePolicy();
ForceUpdatePolicy();
EXPECT_THAT(histogram_tester_->GetAllSamples(
"RendererScheduler.BackgroundedRendererTransition"),
UnorderedElementsAre(
Bucket(static_cast<int>(Transition::kBackgrounded),
backgrounding_transitions),
Bucket(static_cast<int>(Transition::kForegrounded),
foregrounding_transitions),
Bucket(static_cast<int>(Transition::kFrozenAfterDelay), 1),
Bucket(static_cast<int>(Transition::kResumed), 1)));
}
TEST_F(MainThreadMetricsHelperTest, TaskCountPerFrameStatus) {
int task_count = 0;
struct CountPerFrameStatus {
FrameStatus frame_status;
int count;
};
CountPerFrameStatus test_data[] = {
{FrameStatus::kNone, 4},
{FrameStatus::kMainFrameVisible, 8},
{FrameStatus::kMainFrameBackgroundExemptSelf, 5},
{FrameStatus::kCrossOriginHidden, 3},
{FrameStatus::kCrossOriginHiddenService, 7},
{FrameStatus::kCrossOriginVisible, 1},
{FrameStatus::kMainFrameBackgroundExemptOther, 2},
{FrameStatus::kSameOriginVisible, 10},
{FrameStatus::kSameOriginBackground, 9},
{FrameStatus::kSameOriginVisibleService, 6}};
for (const auto& data : test_data) {
std::unique_ptr<FakeFrameScheduler> frame =
CreateFakeFrameSchedulerWithType(data.frame_status);
for (int i = 0; i < data.count; ++i) {
RunTask(frame.get(), Milliseconds(++task_count),
base::TimeDelta::FromMicroseconds(100));
}
}
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kNone), 4),
Bucket(static_cast<int>(FrameStatus::kMainFrameVisible), 8),
Bucket(static_cast<int>(FrameStatus::kMainFrameBackgroundExemptSelf),
5),
Bucket(static_cast<int>(FrameStatus::kMainFrameBackgroundExemptOther),
2),
Bucket(static_cast<int>(FrameStatus::kSameOriginVisible), 10),
Bucket(static_cast<int>(FrameStatus::kSameOriginVisibleService), 6),
Bucket(static_cast<int>(FrameStatus::kSameOriginBackground), 9),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisible), 1),
Bucket(static_cast<int>(FrameStatus::kCrossOriginHidden), 3),
Bucket(static_cast<int>(FrameStatus::kCrossOriginHiddenService), 7)));
}
TEST_F(MainThreadMetricsHelperTest, TaskCountPerFrameTypeLongerThan) {
int total_duration = 0;
struct TasksPerFrameStatus {
FrameStatus frame_status;
std::vector<int> durations;
};
TasksPerFrameStatus test_data[] = {
{FrameStatus::kSameOriginHidden,
{2, 15, 16, 20, 25, 30, 49, 50, 73, 99, 100, 110, 140, 150, 800, 1000,
1200}},
{FrameStatus::kCrossOriginVisibleService,
{5, 10, 18, 19, 20, 55, 75, 220}},
{FrameStatus::kMainFrameBackground,
{21, 31, 41, 51, 61, 71, 81, 91, 101, 1001}},
};
for (const auto& data : test_data) {
std::unique_ptr<FakeFrameScheduler> frame =
CreateFakeFrameSchedulerWithType(data.frame_status);
for (size_t i = 0; i < data.durations.size(); ++i) {
RunTask(frame.get(), Milliseconds(++total_duration),
base::TimeDelta::FromMilliseconds(data.durations[i]));
total_duration += data.durations[i];
}
}
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 10),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 17),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisibleService),
8)));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType."
"LongerThan16ms"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 10),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 15),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisibleService),
6)));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType."
"LongerThan50ms"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 7),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 10),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisibleService),
3)));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType."
"LongerThan100ms"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 2),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 7),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisibleService),
1)));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType."
"LongerThan150ms"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 1),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 4),
Bucket(static_cast<int>(FrameStatus::kCrossOriginVisibleService),
1)));
EXPECT_THAT(
histogram_tester_->GetAllSamples(
"RendererScheduler.TaskCountPerFrameType.LongerThan1s"),
UnorderedElementsAre(
Bucket(static_cast<int>(FrameStatus::kMainFrameBackground), 1),
Bucket(static_cast<int>(FrameStatus::kSameOriginHidden), 2)));
}
// TODO(crbug.com/754656): Add tests for NthMinute and
// AfterNthMinute histograms.
// TODO(crbug.com/754656): Add tests for
// TaskDuration.Hidden/Visible histograms.
// TODO(crbug.com/754656): Add tests for non-TaskDuration
// histograms.
} // namespace scheduler
} // namespace blink
| 43.120718 | 97 | 0.691787 | [
"vector"
] |
c32f5ae0205c14e63685ab3a0ce4aecb912eadd1 | 2,818 | cpp | C++ | MeshUtil/MeshIO.cpp | minhpvo/MRef | ecd4c6cafe9c800c76e4f7853fda2ffd7771fb67 | [
"BSD-3-Clause"
] | 2 | 2020-05-26T14:22:25.000Z | 2020-06-11T09:41:13.000Z | MeshUtil/MeshIO.cpp | minhpvo/MRef | ecd4c6cafe9c800c76e4f7853fda2ffd7771fb67 | [
"BSD-3-Clause"
] | null | null | null | MeshUtil/MeshIO.cpp | minhpvo/MRef | ecd4c6cafe9c800c76e4f7853fda2ffd7771fb67 | [
"BSD-3-Clause"
] | 1 | 2020-07-14T19:07:40.000Z | 2020-07-14T19:07:40.000Z | // Copyright ETHZ 2017
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/IO/writer/PLYWriter.hh>
#include <OpenMesh/Core/IO/writer/OBJWriter.hh>
#include <OpenMesh/Core/IO/reader/PLYReader.hh>
#include <OpenMesh/Core/IO/reader/OBJReader.hh>
#include "MyMesh.h"
#include <string>
#include <boost/filesystem.hpp>
#include <iostream>
#include "MeshIO.h"
namespace MeshIO
{
void readMesh( MyMesh &ommesh, std::string savename, bool hasvertcolor, bool hasfacecolor, bool hasvertnormal, bool hasfacetexture )
{
// Check which extension
std::string extension=boost::filesystem::extension(savename);
if(extension==".obj") { OpenMesh::IO::_OBJWriter_(); }
else if (extension==".ply") { OpenMesh::IO::_PLYWriter_(); }
else { std::cout << "\n MeshUtil::readReadMeshVFN: could not figure extension. " << extension; exit(1); }
OpenMesh::IO::Options ropt, wopt;
if (hasfacecolor)
{
ommesh.request_face_colors();
ropt += OpenMesh::IO::Options::FaceColor;
}
if (hasvertcolor)
{
ommesh.request_vertex_colors();
ropt += OpenMesh::IO::Options::VertexColor;
}
if( hasvertnormal)
{
ommesh.request_vertex_normals();
ropt += OpenMesh::IO::Options::VertexNormal;
}
if( hasfacetexture )
{
ommesh.request_halfedge_texcoords2D();
ommesh.request_face_texture_index();
ropt += OpenMesh::IO::Options::FaceTexCoord;
}
if(extension==".obj") {
OpenMesh::IO::_OBJReader_();
if ( ! OpenMesh::IO::read_mesh(ommesh, savename.c_str(), ropt ))
{
std::cerr << "Error loading mesh from file " << savename << std::endl;
}
}
else if(extension==".ply")
{
OpenMesh::IO::_PLYReader_();
ropt+=OpenMesh::IO::Options::Binary;
if ( ! OpenMesh::IO::read_mesh(ommesh, savename.c_str(), ropt ))
{
std::cerr << "Error loading mesh from file " << savename << std::endl;
}
}
}
void writeMesh( const MyMesh &mesh, const std::string &savename, const bool hasvertcolor, const bool hasfacecolor, const bool hasvertnormal, const bool hasfacetexture )
{
// Check which extension
std::string extension=boost::filesystem::extension(savename);
if(extension==".obj") { /*OpenMesh::IO::_OBJWriter_();*/ }
else if (extension==".ply") { /*OpenMesh::IO::_PLYWriter_();*/ }
else {std::cout<<"\n MeshIO::writeMesh: could not figure extension."; exit(1); }
OpenMesh::IO::Options wopt;
if(hasfacecolor) wopt += OpenMesh::IO::Options::FaceColor;
if(hasvertcolor) wopt += OpenMesh::IO::Options::VertexColor;
if(hasvertnormal) wopt += OpenMesh::IO::Options::VertexNormal;
if(hasfacetexture) wopt += OpenMesh::IO::Options::FaceTexCoord;
if (!OpenMesh::IO::write_mesh(mesh, savename.c_str(), wopt))
{
std::cerr << "MeshUtil: Write error\n";
exit(1);
}
}
}
| 29.978723 | 168 | 0.664656 | [
"mesh"
] |
c3351259b155fc427f19611a6531d336db5da213 | 2,002 | cpp | C++ | kattis/set1/C.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | 5 | 2019-03-17T01:33:19.000Z | 2021-06-25T09:50:45.000Z | kattis/set1/C.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | kattis/set1/C.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | /**
Those who do not understand true pain can never understand true peace.
*/
#include <bits/stdc++.h>
#define forn(i, l, r) for(int i=l;i<=r;i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define nd second
#define st first
#define debug(x) cout<<#x<<" -> "<<x<< endl
#define kakimasu(x) cout << x << '\n'
#define sseuda(x) cout << x
#define sz(x) (int)x.size()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<long long> vll;
typedef vector<vector<int> > vvi;
typedef vector<vll> vvll;
typedef vector<pair<int, int> > vpi;
typedef vector<vpi> vvpi;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
const int INF = 1 << 30;
/**
Start coding from here
*/
const int MOD=1e9+7;
const double EPS = 1e-9;
int determinant(vector<vector<double> >& a, int n) {
ld det = 1.0;
for (int i=0; i<n; ++i) {
int k = i;
for (int j=i+1; j<n; ++j)
if (abs (a[j][i]) > abs (a[k][i]))
k = j;
if (abs (a[k][i]) < EPS) {
det = 0;
break;
}
swap (a[i], a[k]);
if (i != k)
det = -det;
det*=a[i][i];
for (int j=i+1; j<n; ++j)
a[i][j] /= a[i][i];
for (int j=0; j<n; ++j)
if (j != i && abs (a[j][i]) > EPS)
for (int k=i+1; k<n; ++k)
a[j][k] -= a[i][k] * a[j][i];
}
det=fmod(det, MOD);
return det;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
#ifdef LOCAL_PROJECT
freopen("input.txt","r",stdin);
#endif
int tc;
cin>>tc;
while(tc--) {
int n, m;
cin>>n>>m;
vector<vector<double> > degree(n, vector<double>(n, 0.0));
vector<vector<double> > adjmat(n, vector<double>(n, 0.0));
forn(i, 0, m-1) {
int a, b;
cin>>a>>b;
degree[a-1][a-1]+=1;
degree[b-1][b-1]+=1;
adjmat[a-1][b-1]=1.0;
adjmat[b-1][a-1]=1.0;
}
forn(i, 0, n-1) forn(j,0,n-1)
degree[i][j]-=adjmat[i][j];
cout << determinant(degree, n - 1) <<'\n';
}
return 0;
}
| 22 | 78 | 0.572428 | [
"vector"
] |
c335e130d5f8cff3a821bdf5dace6b4456d9d3db | 3,768 | cpp | C++ | 4b.cpp | coolcomputery/Advent-of-Code-2020 | 4e9606a8e2383a10914da4ed632943c9eca3afc1 | [
"MIT"
] | null | null | null | 4b.cpp | coolcomputery/Advent-of-Code-2020 | 4e9606a8e2383a10914da4ed632943c9eca3afc1 | [
"MIT"
] | null | null | null | 4b.cpp | coolcomputery/Advent-of-Code-2020 | 4e9606a8e2383a10914da4ed632943c9eca3afc1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<string> vs;
typedef vector<vll> vvll;
typedef pair<ll,ll> pll;
typedef pair<string,string> pss;
#define PB push_back
vs fields{"byr","iyr","eyr","hgt","hcl","ecl","pid"};//,"cid"}
set<string> ecls={"amb","blu","brn","gry","grn","hzl","oth"};
/*
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
*/
bool btwn(ll x, ll a, ll b) {
return a<=x && x<=b;
}
bool isnum(string s, int base) {
//https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c
char *p;
strtol(s.c_str(),&p,base);
return *p==0;
}
int main() {
vector<vector<string>> ports;
for (vector<string> port{}; true; ) {
string lin;
getline(cin,lin);
if (lin.size()<=2) {
vector<string> tmp;
for (string s:port)
tmp.PB(s);
ports.PB(tmp);
port.clear();
//break;
if (lin.size()==0) break;
}
else
port.PB(lin);
}
ll ans=0;
for (vs port:ports) {
//cout<<"port\n";
/*
for (string s:port)
cout<<s<<"\n";*/
map<string,string> info;
for (string s:port) {
while (true) {
ll c=s.find(':');
ll sp=s.find(' ');
string val="";
for (ll i=c+1; i<(sp==-1?s.size():sp) && btwn(s.at(i),33,126); i++)
val+=s.at(i);
//string val=s.substr(c+1,(sp==-1?s.size():sp)-(c+1));
if (val.at(val.size()-1)=='\n')
val=val.substr(0,val.size()-2);
info.insert(pair<string,string>(
s.substr(0,c),val
));
if (sp==-1) break;
s=s.substr(s.find(' ')+1);
}
}
/*for (pss p:info)
cout<<p.first<<":"<<p.second<<"--";
cout<<"\n";*/
bool good=true;
for (string s:fields) {
if (info.find(s)==info.end()) good=false;
}
if (good) {
string h=info["hgt"];
string e=h.substr(h.size()-2);
if (e!="cm" && e!="in") good=false;
for (ll i=0; i<h.size()-2; i++)
if (!btwn(h.at(i),'0','9')) good=false;
if (good) {
ll hi=stoi(h.substr(0,h.size()-2));
good=good&&(e=="cm"?btwn(hi,150,193):btwn(hi,59,76));
}
}
good=good&&btwn(stoi(info["byr"]),1920,2002)
&&btwn(stoi(info["iyr"]),2010,2020)
&&btwn(stoi(info["eyr"]),2020,2030);
if (good) {
string c=info["hcl"];
good=good&&c.at(0)=='#'&&c.size()==7&&isnum(c.substr(1),16);
}
good=good&&(ecls.find(info["ecl"])!=ecls.end());
if (good) {
string h=info["pid"];
for (ll i=0; i<h.size(); i++)
if (!btwn(h.at(i),'0','9')) good=false;
good=good&&h.size()==9;
}
ans+=good;
}
cout<<ans;
}
| 32.205128 | 97 | 0.485934 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.