blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4b19958a8a2cbfe59bb815164ff03bf4a393c3ab | 267150742ef2b9c58c15f2139f7e41cb9c6970a5 | /Workspace/Example/readonly/entities/Barrel_readonly.cpp | 2c57c5eaa3f41b209af2f2ff1b7663aa7a8a2196 | [] | no_license | rouviecy/CG_generator | 85319ad2517e6206cb94989519388a049f30b264 | 0d41d73a7207aa1c5639eca28ffebb432a97d861 | refs/heads/master | 2021-01-20T00:29:18.126981 | 2017-05-11T02:56:23 | 2017-05-11T02:56:23 | 89,139,363 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | cpp | Barrel_readonly.cpp | #include "Barrel_readonly.h"
Barrel_readonly::Barrel_readonly() : Entity(){
}
void Barrel_readonly::Update(int id, int x, int y, int rhum){
Entity::Update(id, x, y);
this->rhum = rhum;
}; |
93bc90e52a6cf63b460f8e91699abf79c3c60675 | 949f567272fd11ac3c227f641faaf574adb640b1 | /Code/Don'tFuckUp/Don'tFuckUp/BIRDS.cpp | 445c295d4ce5e56e411bffb198f944a2b7efa95d | [] | no_license | ShoGanKing/Game-Jam-2015 | b14904531497ed2bac1300d7e48196d79393fd8e | 952b0592cb9954e180be45ae3d349f3f3eafeae5 | refs/heads/master | 2020-07-03T12:29:34.908635 | 2015-01-27T19:44:59 | 2015-01-27T19:44:59 | 29,752,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,727 | cpp | BIRDS.cpp | #include"BIRDS.h"
#include "ActiveGameObject.h"
#include "MyVec2.h"
#include "Scene.h"
#include "ButtonObject.h"
BirdObject::BirdObject(Scene* aScene, MyVec2 aPos, float aAngle, MyVec2 aVelocity) : ActiveGameObject(aScene, aPos, aAngle)
{
m_Scene = aScene;
m_Frame = 0;
m_Time = m_Time.Zero;
m_Velocity = aVelocity;
m_Window = m_Scene->GetWindow();
m_Sprite.setRotation(m_Angle);
m_Sprite.setPosition(m_Position.X(), m_Position.Y());
}
BirdObject::~BirdObject()
{
}
bool BirdObject::Load()
{
if (!m_Texture.loadFromFile("../../../Assets/Models/Bird1.png")) // ./ current directory, ../ back one
{
// Handle Loading Error
m_Texture.loadFromFile("../../../Assets/Models/Missing.png");
}
m_Sprite.setTexture(m_Texture);
if (!m_Texture2.loadFromFile("../../../Assets/Models/Bird2.png")) // ./ current directory, ../ back one
{
// Handle Loading Error
m_Texture2.loadFromFile("../../../Assets/Models/Missing.png");
}
if (!m_Texture3.loadFromFile("../../../Assets/Models/Bird3.png")) // ./ current directory, ../ back one
{
// Handle Loading Error
m_Texture3.loadFromFile("../../../Assets/Models/Missing.png");
}
if (!m_Texture4.loadFromFile("../../../Assets/Models/Bird4.png")) // ./ current directory, ../ back one
{
// Handle Loading Error
m_Texture4.loadFromFile("../../../Assets/Models/Missing.png");
}
return true;
}
void BirdObject::Update(sf::Time aDelta)
{
MyVec2 translation(0.0f, 0.0f);
translation.AddToMe(m_Velocity);
translation.MultiplyMeBy(aDelta.asSeconds());
m_Position.AddToMe(translation);
SetPosition(m_Position);
m_Time += aDelta;
if (m_Time.asSeconds() >= 0.2f)
{
m_Frame++;
if (m_Frame >= 4)
{
m_Frame = 0;
}
m_Time = m_Time.Zero;
}
}
void BirdObject::Draw()
{
if (m_Active)
{
switch (m_Frame)
{
case 0:
m_Sprite.setTexture(m_Texture);
break;
case 1:
m_Sprite.setTexture(m_Texture2);
break;
case 2:
m_Sprite.setTexture(m_Texture3);
break;
case 3:
m_Sprite.setTexture(m_Texture4);
break;
}
m_Window->draw(m_Sprite);
}
}
void BirdObject::SetPosition(MyVec2 aPosition)
{
m_Position = aPosition;
m_Sprite.setPosition(aPosition.X(), aPosition.Y());
m_PressedSprite.setPosition(aPosition.X(), aPosition.Y());
}
MyVec2 BirdObject::GetVelocity()
{
return m_Velocity;
}
void BirdObject::SetVelocity(MyVec2 aVelocity)
{
m_Velocity = aVelocity;
} |
bab088e1d514b547acc40e0ee6cfc28972f38e37 | ac5eb7df8515fb92071f9e0f64d1cf6467f4042d | /C++/candy.cpp | 3ac7119cca63e959e120a57f81bc040937811c56 | [] | no_license | Litao439420999/LeetCodeAlgorithm | 6ea8060d56953bff6c03c95cf6b94901fbfbe395 | 9aee4fa0ea211d28ff1e5d9b70597421f9562959 | refs/heads/master | 2023-07-08T06:17:20.310470 | 2021-08-08T08:12:23 | 2021-08-08T08:12:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,079 | cpp | candy.cpp | /**
* @File : candy.cpp
* @Brief : 分发糖果 贪心策略
* @Link : https://leetcode-cn.com/problems/candy/
* @Author : Wei Li
* @Date : 2021-07-04
*/
//![include]
#include <iostream>
#include <numeric>
#include <vector>
#include <memory>
//![include]
//![solution]
/**
* 0、只需要简单的两次遍历即可:把所有孩子的糖果数初始化为 1;
* 1、先从左往右遍历一遍,如果右边孩子的评分比左边的高,
* 则右边孩子的糖果数更新为左边孩子的糖果数加 1;
* 2、再从右往左遍历一遍,如果左边孩子的评分比右边的高,且左边孩子当前的糖果数不大于右边孩子的糖果数,
* 则左边孩子的糖果数更新为右边孩子的糖果数加 1。
* 3、通过这两次遍历,分配的糖果就可以满足题目要求了。
*
* 这里的贪心策略即为,在每次遍历中,只考虑并更新相邻一侧的大小关系。
*/
class Solution
{
public:
int candy(std::vector<int> &ratings)
{
size_t size = ratings.size();
// 若只有一个人,则最少需要一个糖果
if (size < 2)
{
return size;
}
// 初始化每个人一个糖果
std::vector<int> num(size, 1);
// 第一次遍历,从左往右
for (unsigned int i = 1; i < size; ++i)
{
// 如果右边的评分高于左边,则其糖果数量等于其左边的糖果数量 + 1
if (ratings[i] > ratings[i - 1])
{
num[i] = num[i - 1] + 1;
}
}
// 第二次遍历,从右往左
for (unsigned int i = size - 1; i > 0; --i)
{
// 如果左边的评分高于右边,且左边孩子当前的糖果数不大于右边孩子的糖果数,
// 则左边孩子的糖果数更新为右边孩子的糖果数 + 1
if (ratings[i] < ratings[i - 1])
{
num[i - 1] = std::max(num[i - 1], num[i] + 1);
}
}
// 经过两次遍历之后,则满足题目要求了
// 贪心策略即为,在每次遍历中,只考虑并更新相邻一侧的大小关系
return std::accumulate(num.begin(), num.end(), 0); // std::accumulate 可以很方便的求和
}
};
// ----------------------------------
int main(int argc, char** argv)
{
// std::vector<int> ratings = {2, 3, 1, 3, 7, 3};
// std::vector<int> ratings = {1, 0, 2};
std::vector<int> ratings = {1, 2, 2};
// auto solution = Solution(); // 基于堆实例化类对象,但是没有智能指针
auto solution = std::make_unique<Solution>(); // 基于堆实例化类对象,同时使用智能指针
// Solution solution; // 基于堆栈实例化类对象
// auto array_candy = solution.candy(ratings);
// auto array_candy = (*solution).candy(ratings);
auto array_candy = solution->candy(ratings);
std::cout << "The solution of this porblem is : " << array_candy << std::endl;
return 0;
} |
113803888af00f1a01376d184013aa0d83ac4a8a | e71ebf5118040fdbfb6bbd62ad6b7a434eea2c0a | /LabWorks/Lab6Version1/pbDeliveredFromCashRegister.h | b4b04fe1b927468affef083ec5493c102e62ecf5 | [] | no_license | sviatoslav-vilkovych/OOP-NU-LP | ce577525aa12d941d0db3b7b9621d201f9742ace | 50c75ffd98c4635b5bfd5d2f765380833fb3e5ea | refs/heads/master | 2021-08-27T16:19:46.255774 | 2016-12-26T03:46:48 | 2016-12-26T03:46:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | h | pbDeliveredFromCashRegister.h | #pragma once
#include "CashRegister.h"
class pbDeliveredFromCashRegister : public CashRegister
{
public:
pbDeliveredFromCashRegister();
~pbDeliveredFromCashRegister();
};
|
3d1500b0d0e308395633b1f9dec2ebdea4b3f2aa | 4a3e5419e89dfbd9788a4539740b8ea7321ee7ef | /c/35.cpp | bae2827f2c1e46522f357da6b180606eb7f69176 | [] | no_license | tars0x9752/atcoder | d3cbfefeb5164edab72d87f8feb16e1160c231a2 | 0e54c9a34055e47ae6bb19d4493306e974a50eee | refs/heads/master | 2022-11-19T15:36:17.711849 | 2020-07-19T12:56:31 | 2020-07-19T12:56:31 | 182,626,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | cpp | 35.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n, q;
cin >> n >> q;
vector<int> l(q), r(q);
for (int i = 0; i < q; i++) {
cin >> l[i] >> r[i];
l[i]--;
r[i]--;
}
vector<int> sum(n + 1);
for (int i = 0; i < q; i++) {
sum[l[i]]++;
sum[r[i] + 1]--;
}
for (int i = 1; i < n; i++) {
sum[i] += sum[i - 1];
}
for (int i = 0; i < n; i++) {
cout << (sum[i] % 2 == 0 ? 0 : 1);
}
cout << endl;
return 0;
} |
cffcde2fa660764d4d1847f5de35e1a0ecb4bf1d | bf9770bcc23894a737f4b29f34f6426400d5fa32 | /src/record.hpp | a938b63783f294deafa0f515e831f3238e059039 | [] | no_license | Pablenko/csvparser | 72c96799998dd5dc093eb0afb696e3abc3311e4e | 29bb5874f27903d2ab65177d8644d470c28b4a62 | refs/heads/master | 2021-05-12T13:52:53.670667 | 2018-01-16T23:48:18 | 2018-01-16T23:48:18 | 116,942,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,357 | hpp | record.hpp | #ifndef CSV_PARSER_RECORD_HPP
#define CSV_PARSER_RECORD_HPP
#include <ostream>
#include <string>
namespace csv_parser
{
struct record
{
struct r_date
{
unsigned int year;
unsigned short month;
unsigned short day;
unsigned short hour;
unsigned short minutes;
unsigned short seconds;
};
r_date date;
std::string source_account, dest_account;
float ammount;
};
inline bool operator==(const record::r_date& lhs, const record::r_date& rhs)
{
return lhs.year == rhs.year &&
lhs.month == rhs.month &&
lhs.day == rhs.day &&
lhs.hour == rhs.hour &&
lhs.minutes == rhs.minutes &&
lhs.seconds == rhs.seconds;
}
inline bool operator!=(const record::r_date& lhs, const record::r_date& rhs)
{
return not (lhs == rhs);
}
inline bool operator==(const record& lhs, const record& rhs)
{
return lhs.date == rhs.date &&
lhs.source_account == rhs.source_account &&
lhs.dest_account == rhs.dest_account &&
lhs.ammount == rhs.ammount;
}
inline bool operator!=(const record& lhs, const record& rhs)
{
return not (lhs == rhs);
}
std::ostream& operator <<(std::ostream& str, const record& r);
std::ostream& operator <<(std::ostream& str, const record::r_date& d);
} // namespace csv_parser
#endif |
01c05a7064f147f927fd175ae4b6739984a78449 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /essbasic/include/tencentcloud/essbasic/v20201222/model/Caller.h | 9c4962f2e401ad643816e27c3252ded7562e2bbc | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,602 | h | Caller.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* 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 TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CALLER_H_
#define TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CALLER_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Essbasic
{
namespace V20201222
{
namespace Model
{
/**
* 此结构体 (Caller) 用于描述调用方属性。
*/
class Caller : public AbstractModel
{
public:
Caller();
~Caller() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取应用号
* @return ApplicationId 应用号
*
*/
std::string GetApplicationId() const;
/**
* 设置应用号
* @param _applicationId 应用号
*
*/
void SetApplicationId(const std::string& _applicationId);
/**
* 判断参数 ApplicationId 是否已赋值
* @return ApplicationId 是否已赋值
*
*/
bool ApplicationIdHasBeenSet() const;
/**
* 获取下属机构ID
* @return SubOrganizationId 下属机构ID
*
*/
std::string GetSubOrganizationId() const;
/**
* 设置下属机构ID
* @param _subOrganizationId 下属机构ID
*
*/
void SetSubOrganizationId(const std::string& _subOrganizationId);
/**
* 判断参数 SubOrganizationId 是否已赋值
* @return SubOrganizationId 是否已赋值
*
*/
bool SubOrganizationIdHasBeenSet() const;
/**
* 获取经办人的用户ID
* @return OperatorId 经办人的用户ID
*
*/
std::string GetOperatorId() const;
/**
* 设置经办人的用户ID
* @param _operatorId 经办人的用户ID
*
*/
void SetOperatorId(const std::string& _operatorId);
/**
* 判断参数 OperatorId 是否已赋值
* @return OperatorId 是否已赋值
*
*/
bool OperatorIdHasBeenSet() const;
private:
/**
* 应用号
*/
std::string m_applicationId;
bool m_applicationIdHasBeenSet;
/**
* 下属机构ID
*/
std::string m_subOrganizationId;
bool m_subOrganizationIdHasBeenSet;
/**
* 经办人的用户ID
*/
std::string m_operatorId;
bool m_operatorIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ESSBASIC_V20201222_MODEL_CALLER_H_
|
fc78f0b4d1001de7b4b1e1c857a0fde823cb7694 | c507b259841a43910e94c20e58073eaa8937288b | /deform_control/bullet_helpers/include/bullet_helpers/bullet_eigen_conversions.hpp | 2837227f3ed4221f89d205c82ab4c345da1fc0bf | [
"BSD-2-Clause"
] | permissive | UM-ARM-Lab/mab_ms | 5024c4d696cb35bc69fce71e85e1be1da66a30b5 | f199f05b88060182cfbb47706bd1ff3479032c43 | refs/heads/master | 2020-03-07T11:18:25.199893 | 2018-03-30T23:47:39 | 2018-03-30T23:47:39 | 127,452,258 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | hpp | bullet_eigen_conversions.hpp | #ifndef BULLET_EIGEN_CONVERSIONS_HPP
#define BULLET_EIGEN_CONVERSIONS_HPP
#include <btBulletDynamicsCommon.h>
#include <Eigen/Dense>
namespace BulletHelpers
{
inline Eigen::Affine3d toEigenAffine3d(btTransform&& bt)
{
const btVector3& bt_origin = bt.getOrigin();
const btQuaternion& bt_rot = bt.getRotation();
const Eigen::Translation3d trans(bt_origin.getX(), bt_origin.getY(), bt_origin.getZ());
const Eigen::Quaterniond rot(bt_rot.getW(), bt_rot.getX(), bt_rot.getY(), bt_rot.getZ());
return trans*rot;
}
inline Eigen::Affine3d toEigenAffine3d(const btTransform& bt)
{
const btVector3& bt_origin = bt.getOrigin();
const btQuaternion& bt_rot = bt.getRotation();
const Eigen::Translation3d trans(bt_origin.getX(), bt_origin.getY(), bt_origin.getZ());
const Eigen::Quaterniond rot(bt_rot.getW(), bt_rot.getX(), bt_rot.getY(), bt_rot.getZ());
return trans*rot;
}
}
#endif // BULLET_EIGEN_CONVERSIONS_HPP
|
42144e640e09ff14644769928fb230fef61ae006 | 70f5890c920a01de2e67427b25317d38070cdaf7 | /FX/B.cpp | f87d1e7ccdf60524c5169802feaf2b196c4f5768 | [] | no_license | DiasDogalakov/ADS_FALL_2020 | fc359010332139d9b4e56c7e550c888de697febc | 715b27e5b555b77fd34f45454d50f5b75f9050de | refs/heads/master | 2023-06-22T17:37:03.627139 | 2021-07-26T17:35:19 | 2021-07-26T17:35:19 | 297,119,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | B.cpp | #include <iostream> //ok
#include <string>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <deque>
using namespace std;
int main () {
int n, h;
cin >> n >> h;
int a[n];
for(int i = 0; i < n; ++i)
cin >> a[i];
int l = 1;
int r = (int)1e9 + 1;
int f = -1;
while (l <= r) {
int k = (l + r) / 2;
long long ans = 0;
for(int i = 0; i < n; ++i) {
int cur = a[i] / k;
if(a[i] % k != 0)
cur ++;
ans += cur;
}
if(ans <= h) {
r = k - 1;
f = k;
}else {
l = k + 1;
}
}
cout << f << '\n';
} |
d8a668426b2e2d43ebb1c4cf5e8ebaa26d5b5c39 | e6b0006949ed9d21efce8c4fd18fd6e371cd4bf9 | /util/unittest/testpageTable.cpp | b80394a10442b15613e5eb8437c87aeca3193f01 | [] | no_license | liweiliv/DBStream | ced5a25e934ab64e0986a8a4230767e12f04bdab | 584f20f938530bb52bf38faa832992bfb59e7dbb | refs/heads/master | 2021-07-21T02:58:20.442685 | 2021-06-07T12:57:34 | 2021-06-07T13:04:33 | 182,390,627 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | cpp | testpageTable.cpp | #include "../pageTable.h"
#include <thread>
#include <chrono>
pageTable<uint64_t> p;
uint64_t *base;
uint64_t** to;
#define c 10000000
void testThread(uint64_t id)
{
std::this_thread::sleep_for(std::chrono::nanoseconds(rand()%100000));
for (unsigned int i = 1; i < c; i++)
{
uint64_t v = ((id << 32) | i);
uint64_t rtv = p.set(i, v);
if (rtv != v)
{
to[id][i] = rtv ;
if ((rtv & 0xffffffffu) != i)
{
abort();
}
}
else
{
base[i] = v;
to[id][i] = v;
}
//rtv = p.get(i);
//assert(rtv==(void*)to[id][i]);
}
}
int main()
{
std::thread *t[10];
to = new uint64_t*[sizeof(t) / sizeof(std::thread*)];
base = new uint64_t[c];
for (unsigned int i = 0; i < sizeof(t) / sizeof(std::thread*); i++)
{
to[i] = new uint64_t[c];
memset(to[i], 0, c);
t[i] = new std::thread(testThread, i);
}
for (unsigned int i = 0; i < sizeof(t) / sizeof(std::thread*); i++)
t[i]->join();
for (unsigned int i = 0; i < sizeof(t) / sizeof(std::thread*); i++)
{
for (int j = 1; j < c; j++)
{
uint64_t v = p.get(j);
if (base[j] != to[i][j]||v!=base[j])
abort();
}
delete t[i];
delete to[i];
}
delete base;
delete []to;
return 0;
}
|
fb4799f40c175186683703d38e1aade9b3ef987b | e49e892e58e005ec8b6c07a0b16afeff88b161d8 | /5_cpp_examples/6_hackerrank_com/03_basic_data_types.cpp | f0e3e253c1952b1dcf5153f2c55e4440ef127c98 | [] | no_license | zyavuz610/learnCPP_inKTU | e59676e250f011ff9b5dec86203a0b069c02219f | c6195793bf3464e10d022b852ef486e0c4e3f6da | refs/heads/master | 2020-05-17T08:15:36.754448 | 2020-03-28T16:27:25 | 2020-03-28T16:27:25 | 183,598,702 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | 03_basic_data_types.cpp | /*
Sample Input
3 12345678912345 a 334.23 14049.30493
Sample Output
3
12345678912345
a
334.230
14049.304930000
*/
//------------------------------------------------------------------------------
#include <iostream>
#include <cstdio>
#include <iomanip>
using namespace std;
int main() {
int i;
long int l;
char c;
float f;
double d;
cin>>i>>l>>c>>f>>d;
cout<<i<<endl;
cout<<l<<endl;
cout<<c<<endl;
cout<<fixed<<setprecision(3)<<f<<endl;
cout<<d<<endl;
return 0;
} |
ebd77bf7f0a6e59bbc48ecd00e90143e34120e8e | adcd4911da022685e22178d0c598ff213117205e | /src/main.cpp | df6004b7fb8d2a22e2dadd9af318bec2250624e2 | [
"MIT"
] | permissive | giraugh/reaction-diffusion | 51186dabd54a4ab8c92c5fa16be18e24ed4445e8 | 9662cbe25f1a473d6d2625992d48d18728fc6c30 | refs/heads/main | 2023-03-07T04:45:59.845262 | 2021-02-14T06:28:52 | 2021-02-14T06:28:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | main.cpp | #include <iostream>
#include "core.h"
int main(int argc, char* argv[])
{
// Construct grid data
GridData* gd = new GridData();
RDConfig* config = new RDConfig();
for (int i = 0; i < 9999; i++)
gd->update(config);
gd->print();
return 0;
}
|
432c5824fcbc7b6a092ef238bfce16a0bc932355 | 3a025072af237effce7c89dd0249106bae40a801 | /cpp-cc189_lcci/lcci02.05-add-two-numbers(linked-list)-solution1.cpp | c0401bf2a6b49796653a99f6587775ea8d1a1a0b | [] | no_license | 88b67391/AlgoSolutions | d1ad2002b319489044627b67939d5b5eeade9934 | 0951b0f9990eadd307091c7853f6df5fd432b11c | refs/heads/master | 2023-08-18T18:01:12.569245 | 2021-10-11T00:43:48 | 2021-10-11T00:43:48 | 518,107,160 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | lcci02.05-add-two-numbers(linked-list)-solution1.cpp | #include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
ListNode *fakeHead = new ListNode(-1); //定义输出链表
ListNode *p = fakeHead;
int carry = 0; //进位数字
int x = 0; //记录l1链表的值
int y = 0; //记录12链表的值
//遍历两个链表
while (l1 != NULL || l2 != NULL)
{
x = l1 == NULL ? 0 : l1->val;
y = l2 == NULL ? 0 : l2->val;
int sum = x + y + carry;
if (sum < 10)
{
p->next = new ListNode(sum);
carry = 0;
}
else
{
p->next = new ListNode(sum % 10);
carry = sum / 10;
}
if (l1 != NULL)
l1 = l1->next;
if (l2 != NULL)
l2 = l2->next;
p = p->next;
}
if (carry != 0)
p->next = new ListNode(carry);
return fakeHead->next;
}
};
// Test
int main()
{
Solution sol;
ListNode *l1;
ListNode *l2;
l1 = new ListNode(7);
l1->next = new ListNode(1);
l1->next->next = new ListNode(6);
l2 = new ListNode(5);
l2->next = new ListNode(9);
l2->next->next = new ListNode(2);
ListNode *resHead = sol.addTwoNumbers(l1, l2);
while (resHead != NULL)
{
cout << resHead->val << endl;
resHead = resHead -> next;
}
return 0;
} |
0538b5612d9d797de8948fa16a27ae8ecef841f3 | 31901aa3cefde7392b8eb92f3948cb3c99acce45 | /src/WiegandAnalyzerResults.cpp | 1bf3d89d71efdafaa0de9e52c45a10567bfb7c79 | [] | no_license | xkentr/wiegand-analyzer | 42617ff9555aeed9d68b3306989f5170d6f74578 | a6ffd7ef3f5e3532207d82abe648db330abe480b | refs/heads/master | 2020-05-21T13:01:47.163376 | 2019-05-10T21:59:27 | 2019-05-10T21:59:27 | 186,059,049 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,851 | cpp | WiegandAnalyzerResults.cpp | #include "WiegandAnalyzerResults.h"
#include <AnalyzerHelpers.h>
#include "WiegandAnalyzer.h"
#include "WiegandAnalyzerSettings.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
WiegandAnalyzerResults::WiegandAnalyzerResults( WiegandAnalyzer* analyzer, WiegandAnalyzerSettings* settings )
: AnalyzerResults(),
mSettings( settings ),
mAnalyzer( analyzer )
{
}
WiegandAnalyzerResults::~WiegandAnalyzerResults()
{
}
void WiegandAnalyzerResults::GenerateBubbleText( U64 frame_index, Channel& /*channel*/, DisplayBase display_base ) //unrefereced vars commented out to remove warnings.
{
//we only need to pay attention to 'channel' if we're making bubbles for more than one channel (as set by AddChannelBubblesWillAppearOn)
ClearResultStrings();
Frame frame = GetFrame( frame_index );
char number_str[128];
AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 8, number_str, 128 );
AddResultString( number_str );
}
void WiegandAnalyzerResults::GenerateExportFile( const char* file, DisplayBase display_base, U32 /*export_type_user_id*/ )
{
//export_type_user_id is only important if we have more than one export type.
std::stringstream ss;
void* f = AnalyzerHelpers::StartFile( file );;
U64 trigger_sample = mAnalyzer->GetTriggerSample();
U32 sample_rate = mAnalyzer->GetSampleRate();
ss << "Time [s],Data" << std::endl;
U64 num_frames = GetNumFrames();
for( U32 i=0; i < num_frames; i++ )
{
Frame frame = GetFrame( i );
char time[128];
AnalyzerHelpers::GetTimeString( frame.mStartingSampleInclusive, trigger_sample, sample_rate, time, 128 );
char data[128];
AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 8, data, 128);
ss << time << "," << data << std::endl;
AnalyzerHelpers::AppendToFile( (U8*)ss.str().c_str(), ss.str().length(), f );
ss.str(std::string());
if( UpdateExportProgressAndCheckForCancel( i, num_frames ) == true )
{
AnalyzerHelpers::EndFile( f );
return;
}
}
UpdateExportProgressAndCheckForCancel( num_frames, num_frames );
AnalyzerHelpers::EndFile( f );
}
void WiegandAnalyzerResults::GenerateFrameTabularText( U64 frame_index, DisplayBase display_base )
{
ClearTabularText();
Frame frame = GetFrame( frame_index );
char number_str[128];
AnalyzerHelpers::GetNumberString( frame.mData1, display_base, 8, number_str, 128 );
AddTabularText(number_str);
}
void WiegandAnalyzerResults::GeneratePacketTabularText( U64 /*packet_id*/, DisplayBase /*display_base*/ ) //unrefereced vars commented out to remove warnings.
{
ClearResultStrings();
AddResultString( "not supported" );
}
void WiegandAnalyzerResults::GenerateTransactionTabularText( U64 /*transaction_id*/, DisplayBase /*display_base*/ ) //unrefereced vars commented out to remove warnings.
{
ClearResultStrings();
AddResultString( "not supported" );
}
|
a0f0d06131ccd4df329707c1d9e3aebd4b1f1510 | d26a306d0dc07a6a239e0f1e87e83e8d96712681 | /1382_A/main.cpp | 61fc2e1e50a6f17b803fffe69d2e0252df51a4b9 | [] | no_license | umar-07/Competitive-Programming-questions-with-solutions | e08f8dbbebed7ab48c658c3f0ead19baf966f140 | 39353b923638dff2021923a8ea2f426cd94d2204 | refs/heads/main | 2023-05-19T03:05:48.669470 | 2021-06-16T18:36:22 | 2021-06-16T18:36:22 | 377,588,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | main.cpp | #include <bits/stdc++.h>
#define ll long long int
#define debug(x) cerr << #x << " is " << x << " ";
#define mod 1000000007
#define endl "\n"
#define fast_input ios_base::sync_with_stdio(false); cin.tie(NULL);
using namespace std;
int main()
{
ll t;
cin >> t;
while(t--)
{
ll n, m;
cin >> n >> m;
ll a[n];
ll b[m];
for(int i=0; i<n; i++)
cin >> a[i];
for(int i=0; i<m; i++)
cin >> b[i];
sort(a, a+n);
sort(b, b+m);
int flag=0;
ll idx=-1;
for(int i=0; i<n; i++)
{
if(binary_search(b, b+m, a[i]))
{
idx=a[i];
flag=1;
break;
}
continue;
}
if(flag)
{
cout << "YES" << endl;
cout << 1 << " " << idx << endl;
}
else
cout << "NO" << endl;
}
return 0;
}
|
77b813ff74623f16a1277bbd685551176b99c88f | fad2094689d89eea189631b327cb67690b3ce5a8 | /verilog/formatting/align.cc | 1fc64be5f2b3a64780558dde75e4dbbd97c47521 | [
"Apache-2.0"
] | permissive | dpretet/verible | dfea857c63efc4624463684ae54dede10155a9c5 | 617b40419adc1c39f5ad553c0ec50843abd0fb1a | refs/heads/master | 2022-11-23T21:12:51.564072 | 2020-07-29T21:39:29 | 2020-07-29T21:54:49 | 284,467,391 | 1 | 0 | Apache-2.0 | 2020-08-02T13:30:32 | 2020-08-02T13:30:31 | null | UTF-8 | C++ | false | false | 12,513 | cc | align.cc | // Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "verilog/formatting/align.h"
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <vector>
#include "common/formatting/align.h"
#include "common/formatting/format_token.h"
#include "common/formatting/unwrapped_line.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/token_info.h"
#include "common/text/tree_utils.h"
#include "common/util/casts.h"
#include "common/util/logging.h"
#include "common/util/value_saver.h"
#include "verilog/CST/verilog_nonterminals.h"
#include "verilog/parser/verilog_token_classifications.h"
#include "verilog/parser/verilog_token_enum.h"
namespace verilog {
namespace formatter {
using verible::AlignmentCellScannerGenerator;
using verible::AlignmentColumnProperties;
using verible::ByteOffsetSet;
using verible::ColumnSchemaScanner;
using verible::down_cast;
using verible::FormatTokenRange;
using verible::MutableFormatTokenRange;
using verible::PreFormatToken;
using verible::Symbol;
using verible::SyntaxTreeLeaf;
using verible::SyntaxTreeNode;
using verible::SyntaxTreePath;
using verible::TokenPartitionTree;
using verible::TreeContextPathVisitor;
using verible::TreePathFormatter;
using verible::ValueSaver;
static const AlignmentColumnProperties FlushLeft(true);
static const AlignmentColumnProperties FlushRight(false);
template <class T>
static bool TokensAreAllComments(const T& tokens) {
return std::find_if(
tokens.begin(), tokens.end(),
[](const typename T::value_type& token) {
return !IsComment(verilog_tokentype(token.token->token_enum()));
}) == tokens.end();
}
template <class T>
static bool TokensHaveParenthesis(const T& tokens) {
return std::any_of(tokens.begin(), tokens.end(),
[](const typename T::value_type& token) {
return token.TokenEnum() == '(';
});
}
static bool IgnorePortDeclarationPartition(
const TokenPartitionTree& partition) {
const auto& uwline = partition.Value();
const auto token_range = uwline.TokensRange();
CHECK(!token_range.empty());
// ignore lines containing only comments
if (TokensAreAllComments(token_range)) return true;
// ignore partitions belonging to preprocessing directives
if (IsPreprocessorKeyword(verilog_tokentype(token_range.front().TokenEnum())))
return true;
// Ignore .x or .x(x) port declarations.
// These can appear in a list_of_port_or_port_declarations.
if (verible::SymbolCastToNode(*uwline.Origin()).MatchesTag(NodeEnum::kPort)) {
return true;
}
return false;
}
static bool IgnoreActualNamedPortPartition(
const TokenPartitionTree& partition) {
const auto& uwline = partition.Value();
const auto token_range = uwline.TokensRange();
CHECK(!token_range.empty());
// ignore lines containing only comments
if (TokensAreAllComments(token_range)) return true;
// ignore partitions belonging to preprocessing directives
if (IsPreprocessorKeyword(verilog_tokentype(token_range.front().TokenEnum())))
return true;
// ignore wildcard connections .*
if (verilog_tokentype(token_range.front().TokenEnum()) ==
verilog_tokentype::TK_DOTSTAR) {
return true;
}
// ignore implicit connections .aaa
if (verible::SymbolCastToNode(*uwline.Origin())
.MatchesTag(NodeEnum::kActualNamedPort) &&
!TokensHaveParenthesis(token_range)) {
return true;
}
// ignore positional port connections
if (verible::SymbolCastToNode(*uwline.Origin())
.MatchesTag(NodeEnum::kActualPositionalPort)) {
return true;
}
return false;
}
class ActualNamedPortColumnSchemaScanner : public ColumnSchemaScanner {
public:
ActualNamedPortColumnSchemaScanner() = default;
void Visit(const SyntaxTreeNode& node) override {
auto tag = NodeEnum(node.Tag().tag);
VLOG(2) << __FUNCTION__ << ", node: " << tag << " at "
<< TreePathFormatter(Path());
switch (tag) {
case NodeEnum::kParenGroup:
if (Context().DirectParentIs(NodeEnum::kActualNamedPort)) {
ReserveNewColumn(node, FlushLeft);
}
break;
default:
break;
}
TreeContextPathVisitor::Visit(node);
VLOG(2) << __FUNCTION__ << ", leaving node: " << tag;
}
void Visit(const SyntaxTreeLeaf& leaf) override {
VLOG(2) << __FUNCTION__ << ", leaf: " << leaf.get() << " at "
<< TreePathFormatter(Path());
const int tag = leaf.get().token_enum();
switch (tag) {
case verilog_tokentype::SymbolIdentifier:
if (Context().DirectParentIs(NodeEnum::kActualNamedPort)) {
ReserveNewColumn(leaf, FlushLeft);
}
break;
default:
break;
}
VLOG(2) << __FUNCTION__ << ", leaving leaf: " << leaf.get();
}
};
class PortDeclarationColumnSchemaScanner : public ColumnSchemaScanner {
public:
PortDeclarationColumnSchemaScanner() = default;
void Visit(const SyntaxTreeNode& node) override {
auto tag = NodeEnum(node.Tag().tag);
VLOG(2) << __FUNCTION__ << ", node: " << tag << " at "
<< TreePathFormatter(Path());
if (new_column_after_open_bracket_) {
ReserveNewColumn(node, FlushRight);
new_column_after_open_bracket_ = false;
TreeContextPathVisitor::Visit(node);
return;
}
switch (tag) {
case NodeEnum::kPackedDimensions: {
// Kludge: kPackedDimensions can appear in paths [2,1] and [2,0,2],
// but we want them to line up in the same column. Make it so.
if (current_path_ == SyntaxTreePath{2, 1}) {
SyntaxTreePath new_path{2, 0, 2};
const ValueSaver<SyntaxTreePath> path_saver(¤t_path_, new_path);
// TODO(fangism): a swap-based saver would be more efficient
// for vectors.
TreeContextPathVisitor::Visit(node);
return;
}
break;
}
case NodeEnum::kDataType:
// appears in path [2,0]
case NodeEnum::kDimensionRange:
case NodeEnum::kDimensionScalar:
case NodeEnum::kDimensionSlice:
case NodeEnum::kDimensionAssociativeType:
// all of these cases cover packed and unpacked
ReserveNewColumn(node, FlushLeft);
break;
case NodeEnum::kUnqualifiedId:
if (Context().DirectParentIs(NodeEnum::kPortDeclaration)) {
ReserveNewColumn(node, FlushLeft);
}
break;
case NodeEnum::kExpression:
// optional: Early termination of tree traversal.
// This also helps reduce noise during debugging of this visitor.
return;
// case NodeEnum::kConstRef: possible in CST, but should be
// syntactically illegal in module ports context.
default:
break;
}
// recursive visitation
TreeContextPathVisitor::Visit(node);
VLOG(2) << __FUNCTION__ << ", leaving node: " << tag;
}
void Visit(const SyntaxTreeLeaf& leaf) override {
VLOG(2) << __FUNCTION__ << ", leaf: " << leaf.get() << " at "
<< TreePathFormatter(Path());
if (new_column_after_open_bracket_) {
ReserveNewColumn(leaf, FlushRight);
new_column_after_open_bracket_ = false;
return;
}
const int tag = leaf.get().token_enum();
switch (tag) {
// port directions
case verilog_tokentype::TK_inout:
case verilog_tokentype::TK_input:
case verilog_tokentype::TK_output:
case verilog_tokentype::TK_ref: {
ReserveNewColumn(leaf, FlushLeft);
break;
}
// net types
case verilog_tokentype::TK_wire:
case verilog_tokentype::TK_tri:
case verilog_tokentype::TK_tri1:
case verilog_tokentype::TK_supply0:
case verilog_tokentype::TK_wand:
case verilog_tokentype::TK_triand:
case verilog_tokentype::TK_tri0:
case verilog_tokentype::TK_supply1:
case verilog_tokentype::TK_wor:
case verilog_tokentype::TK_trior:
case verilog_tokentype::TK_wone:
case verilog_tokentype::TK_uwire: {
// Effectively merge/re-map this into the next node slot,
// which is kDataType of kPortDeclaration.
// This works-around a quirk in the CST construction where net_types
// like 'wire' appear positionally before kDataType variable types
// like 'reg'.
ReserveNewColumn(leaf, FlushLeft, verible::NextSiblingPath(Path()));
break;
}
// For now, treat [...] as a single column per dimension.
case '[': {
if (ContextAtDeclarationDimensions()) {
// FlushLeft vs. Right doesn't matter, this is a single character.
ReserveNewColumn(leaf, FlushLeft);
new_column_after_open_bracket_ = true;
}
break;
}
case ']': {
if (ContextAtDeclarationDimensions()) {
// FlushLeft vs. Right doesn't matter, this is a single character.
ReserveNewColumn(leaf, FlushLeft);
}
break;
}
// TODO(b/70310743): Treat "[...:...]" as 5 columns.
// Treat "[...]" (scalar) as 3 columns.
// TODO(b/70310743): Treat the ... as a multi-column cell w.r.t.
// the 5-column range format.
default:
break;
}
VLOG(2) << __FUNCTION__ << ", leaving leaf: " << leaf.get();
}
protected:
bool ContextAtDeclarationDimensions() const {
// Alternatively, could check that grandparent is
// kDeclarationDimensions.
return current_context_.DirectParentIsOneOf(
{NodeEnum::kDimensionRange, NodeEnum::kDimensionScalar,
NodeEnum::kDimensionSlice, NodeEnum::kDimensionAssociativeType});
}
private:
// Set this to force the next syntax tree node/leaf to start a new column.
// This is useful for aligning after punctation marks.
bool new_column_after_open_bracket_ = false;
};
static const verible::AlignedFormattingHandler kPortDeclarationAligner{
.extract_alignment_groups = &verible::GetSubpartitionsBetweenBlankLines,
.ignore_partition_predicate = &IgnorePortDeclarationPartition,
.alignment_cell_scanner =
AlignmentCellScannerGenerator<PortDeclarationColumnSchemaScanner>(),
};
static const verible::AlignedFormattingHandler kActualNamedPortAligner{
.extract_alignment_groups = &verible::GetSubpartitionsBetweenBlankLines,
.ignore_partition_predicate = &IgnoreActualNamedPortPartition,
.alignment_cell_scanner =
AlignmentCellScannerGenerator<ActualNamedPortColumnSchemaScanner>(),
};
void TabularAlignTokenPartitions(TokenPartitionTree* partition_ptr,
std::vector<PreFormatToken>* ftokens,
absl::string_view full_text,
const ByteOffsetSet& disabled_byte_ranges,
int column_limit) {
VLOG(1) << __FUNCTION__;
auto& partition = *partition_ptr;
auto& uwline = partition.Value();
const auto* origin = uwline.Origin();
VLOG(1) << "origin is nullptr? " << (origin == nullptr);
if (origin == nullptr) return;
const auto* node = down_cast<const SyntaxTreeNode*>(origin);
VLOG(1) << "origin is node? " << (node != nullptr);
if (node == nullptr) return;
// Dispatch aligning function based on syntax tree node type.
static const auto* kAlignHandlers =
new std::map<NodeEnum, verible::AlignedFormattingHandler>{
{NodeEnum::kPortDeclarationList, kPortDeclarationAligner},
{NodeEnum::kPortActualList, kActualNamedPortAligner},
};
const auto handler_iter = kAlignHandlers->find(NodeEnum(node->Tag().tag));
if (handler_iter == kAlignHandlers->end()) return;
verible::TabularAlignTokens(partition_ptr, handler_iter->second, ftokens,
full_text, disabled_byte_ranges, column_limit);
VLOG(1) << "end of " << __FUNCTION__;
}
} // namespace formatter
} // namespace verilog
|
302e7d90c36c7d0469f75ff3a4ca553fc4490c92 | 8722f71ac68dbb0cc2dcb96c473a0eb38df63449 | /src/controller/torquePositionController.cpp | a958e43d55c3a38419118b8e3476c6448bb6800e | [
"BSD-3-Clause"
] | permissive | CARDSflow/kindyn | 390122725b24229cbd4ddf85adab5e1501456aec | 80e9201ab2d3fba5534ae9a188e482a28bdc5eee | refs/heads/brain | 2023-04-14T05:13:14.927637 | 2021-08-20T17:20:57 | 2021-08-20T17:20:57 | 153,008,249 | 5 | 3 | BSD-3-Clause | 2021-09-08T11:50:59 | 2018-10-14T18:59:40 | C++ | UTF-8 | C++ | false | false | 6,112 | cpp | torquePositionController.cpp | /*
BSD 3-Clause License
Copyright (c) 2018, Roboy
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 copyright holder 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.
author: Simon Trendel ( st@gi.ai ), 2018
description: A Torque controller for joint position targets using PD control
*/
#include <type_traits>
#include <controller_interface/controller.h>
#include <hardware_interface/joint_command_interface.h>
#include <pluginlib/class_list_macros.h>
#include "kindyn/robot.hpp"
#include "kindyn/controller/cardsflow_command_interface.hpp"
#include <roboy_simulation_msgs/ControllerType.h>
#include <std_msgs/Float32.h>
#include <roboy_control_msgs/SetControllerParameters.h>
using namespace std;
class TorquePositionController : public controller_interface::Controller<hardware_interface::EffortJointInterface> {
public:
/**
* Constructor
*/
TorquePositionController() {};
/**
* Initializes the controller. Will be call by controller_manager when loading this controller
* @param hw pointer to the hardware interface
* @param n the nodehandle
* @return success
*/
bool init(hardware_interface::EffortJointInterface *hw, ros::NodeHandle &n) {
nh = n;
// get joint name from the parameter server
if (!n.getParam("joint", joint_name)) {
ROS_ERROR("No joint given (namespace: %s)", n.getNamespace().c_str());
return false;
}
spinner.reset(new ros::AsyncSpinner(0));
spinner->start();
controller_state = nh.advertise<roboy_simulation_msgs::ControllerType>("/controller_type",1);
ros::Rate r(10);
while(controller_state.getNumSubscribers()==0)
r.sleep();
joint = hw->getHandle(joint_name); // throws on failure
joint_command = nh.subscribe((joint_name+"/target").c_str(),1,&TorquePositionController::JointCommand, this);
controller_parameter_srv = nh.advertiseService((joint_name+"/params").c_str(),& TorquePositionController::setControllerParameters, this);
return true;
}
/**
* Called regularily by controller manager. The torque for a joint wrt to a PD controller on the joint target
* position is calculated.
* @param time current time
* @param period period since last control
*/
void update(const ros::Time &time, const ros::Duration &period) {
double q = joint.getPosition();
double qd = joint.getVelocity();
double p_error = q - q_target;
double cmd = Kp * p_error + Kd *qd;
joint.setCommand(cmd);
// ROS_INFO_THROTTLE(1, "%s target %lf current %lf", joint_name.c_str(), q_target, q);
}
/**
* Called by controller manager when the controller is about to be started
* @param time current time
*/
void starting(const ros::Time& time) {
ROS_WARN("torque position controller started for %s", joint_name.c_str());
roboy_simulation_msgs::ControllerType msg;
msg.joint_name = joint_name;
msg.type = CARDSflow::ControllerType::torque_position_controller;
controller_state.publish(msg);
}
/**
* Called by controller manager when the controller is about to be stopped
* @param time current time
*/
void stopping(const ros::Time& time) { ROS_WARN("cable length controller stopped for %s", joint_name.c_str());}
/**
* Joint position command callback for this joint
* @param msg joint position target in radians
*/
void JointCommand(const std_msgs::Float32ConstPtr &msg){
q_target = msg->data;
}
/**
* Controller Parameters service
* @param req requested gains
* @param res success
* @return success
*/
bool setControllerParameters( roboy_control_msgs::SetControllerParameters::Request &req,
roboy_control_msgs::SetControllerParameters::Response &res){
Kp = req.kp;
Kd = req.kd;
res.success = true;
return true;
}
private:
double q_target = 0; /// joint position target
double Kp = 3000, Kd = 5; /// PD gains
ros::NodeHandle nh; /// ROS nodehandle
ros::Publisher controller_state; /// publisher for controller state
ros::ServiceServer controller_parameter_srv; /// service for controller parameters
boost::shared_ptr<ros::AsyncSpinner> spinner;
hardware_interface::JointHandle joint;
ros::Subscriber joint_command; /// joint command subscriber
string joint_name; /// name of the controlled joint
};
PLUGINLIB_EXPORT_CLASS(TorquePositionController, controller_interface::ControllerBase);
|
3487fa362a15c4261c5aff7313d9b08745e9c32c | eb729586972e784492fdffc9be8e6cb70698f75d | /archive/2017/Round2/D.cpp | 462762672e71d4e2965540a52dad63acf2a2a8d6 | [] | no_license | mkleesiek/google-codejam | af637805d086bbf9e4042c3715b431a8c88d4a95 | 9a7993bba538d92dd7eac04d47e57665ad84f037 | refs/heads/master | 2023-03-25T15:21:24.919726 | 2021-03-26T08:53:51 | 2021-03-26T09:03:48 | 109,621,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp | D.cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int T = 0;
cin >> T;
for (int t = 1; t <= T; ++t)
{
cout << "Case #" << t << ": " << setprecision(12) << 0.0 << endl;
}
return 0;
} |
c1574cdc30e7a05d60d4877c31d29141a713e7b7 | 6db695715a1edd02c20705137af171a1fd94a625 | /cses/removedigits.cpp | 23728f8e4095988cf26a530f793550d74a46ab74 | [] | no_license | arora-ansh/CP-Repository | 0991190507fef779e196193635248be8fb85e5de | 3629a0c0ea92e47bd419b011be518b5feb9781ea | refs/heads/master | 2023-06-19T02:53:26.018511 | 2021-07-08T19:02:00 | 2021-07-08T19:02:00 | 282,615,965 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 680 | cpp | removedigits.cpp | #include <iostream>
#include <vector>
using namespace std;
int solver(int n, int *dp){
//cout<<n<<endl;
if(n==0){
return 0;
}
if(dp[n]!=-1){
return dp[n];
}
vector<int> arr;
int x = n;
while(x!=0){
//cout<<x%10<<" ";
arr.push_back(x%10);
x = x/10;
}
//cout<<endl;
dp[n] = 100000000;
for(int i=0;i<arr.size();i++){
if(n-arr[i]>=0){
dp[n] = min(dp[n],1+solver(n-arr[i],dp));
}
}
return dp[n];
}
int main(){
int n;
cin>>n;
int *dp = new int[n+1];
for(int i=0;i<=n;i++){
dp[i] = -1;
}
cout<<solver(n,dp)<<endl;
return 0;
} |
d50e1d9a3a285398d364c6c3037468e44fbaf6a6 | ca170d96a960e95a7822eb69c65179898a601329 | /libs/stream_vis/stream_vis_context.h | 924329f3325696a36b17e0dbf85dfa871e0c5709 | [] | permissive | sgumhold/cgv | fbd67e9612d4380714467d161ce264cf8c544b96 | cd1eb14564280f12bac35d6603ec2bfe6016faed | refs/heads/master | 2023-08-17T02:30:27.528703 | 2023-01-04T12:50:38 | 2023-01-04T12:50:38 | 95,436,980 | 17 | 29 | BSD-3-Clause | 2023-04-20T20:54:52 | 2017-06-26T10:49:07 | C++ | UTF-8 | C++ | false | false | 3,805 | h | stream_vis_context.h | #pragma once
#include "plot_info.h"
#include "view_info.h"
#include "offset_info.h"
#include "view_overlay.h"
#include "streaming_time_series.h"
#include "streaming_aabb.h"
#include <cgv/base/node.h>
#include <cgv/os/thread.h>
#include <cgv/os/mutex.h>
#include <cgv/render/drawable.h>
#include <cgv/render/vertex_buffer.h>
#include <cgv_app/application_plugin.h>
#include <cgv/gui/event_handler.h>
#include <cgv/gui/provider.h>
#include <plot/plot2d.h>
#include <plot/plot3d.h>
#include <atomic>
#include "lib_begin.h"
namespace stream_vis {
/// ringbuffer
struct time_series_ringbuffer
{
uint16_t time_series_index;
TimeSeriesAccessor time_series_access;
uint16_t nr_time_series_components;
uint16_t time_series_ringbuffer_size;
size_t nr_samples;
uint16_t storage_buffer_index;
size_t storage_buffer_offset;
streaming_aabb_base<float>* streaming_aabb;
};
struct time_series_info
{
TimeSeriesAccessor time_series_access;
std::vector<uint16_t> ringbuffer_indices;
std::vector<uint16_t> component_indices;
};
class CGV_API stream_vis_context :
public cgv::app::application_plugin,
public view_update_handler
{
protected:
std::vector<view_overlay_ptr> view_overlays;
std::atomic<bool> outofdate;
bool use_vbo, last_use_vbo, plot_attributes_initialized;
AABBMode aabb_mode, last_aabb_mode;
/// maps name to time series indices
std::map<std::string, uint16_t> name2index;
/// vector with all time series
std::vector<stream_vis::streaming_time_series*> typed_time_series;
/// vector with all offset infos
std::vector<offset_info> offset_infos;
/// keep track if there are uninitialized offset definitions
size_t nr_uninitialized_offsets;
/// vector of all plots
std::vector<plot_info> plot_pool;
/// vector of view infos
std::vector<view_info> view_infos;
/// vector of all layouts
// std::vector<layout_info> layouts;
bool paused;
unsigned sleep_ms;
/// store view pointer and last view
cgv::render::view* view_ptr = 0;
cgv::render::view last_view;
/// store for each typed time series and each of its components a list of references where the time series component is stored in the storage buffers/vbos
std::vector<std::vector<component_reference>> time_series_component_references;
///
std::vector<std::vector<component_reference>> time_series_ringbuffer_references;
std::vector<time_series_ringbuffer> time_series_ringbuffers;
std::vector<std::vector<float>> storage_buffers;
std::vector<cgv::render::vertex_buffer*> storage_vbos;
static size_t get_component_index(TimeSeriesAccessor accessor, TimeSeriesAccessor accessors);
void construct_streaming_aabbs();
void construct_storage_buffer();
bool is_paused() const { return paused; }
unsigned get_sleep_ms() const { return sleep_ms; }
public:
stream_vis_context(const std::string& name);
~stream_vis_context();
virtual size_t get_first_composed_index() const = 0;
void announce_values(uint16_t num_values, indexed_value* values, double timestamp, const uint16_t* val_idx_from_ts_idx);
void on_set(void* member_ptr);
std::string get_type_name() const { return "stream_vis_context"; }
virtual void extract_time_series() = 0;
void parse_declarations(const std::string& declarations);
void show_time_series() const;
void show_plots() const;
void show_ringbuffers() const;
bool is_outofdate() const { return outofdate; }
bool handle_event(cgv::gui::event& e);
void stream_help(std::ostream& os);
bool init(cgv::render::context& ctx);
void clear(cgv::render::context& ctx);
void update_plot_samples(cgv::render::context& ctx);
void update_plot_domains();
void init_frame(cgv::render::context& ctx);
void draw(cgv::render::context& ctx);
void create_gui();
};
}
#include <cgv/config/lib_end.h> |
ea82787a90b47db38b43ec121b37d662946253c3 | bb9b83b2526d3ff8a932a1992885a3fac7ee064d | /src/modules/osgAnimation/generated_code/RigGeometry.pypp.cpp | fca70e04fb6b3bd938ce15dc434b7118a7c9ed63 | [] | no_license | JaneliaSciComp/osgpyplusplus | 4ceb65237772fe6686ddc0805b8c77d7b4b61b40 | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | refs/heads/master | 2021-01-10T19:12:31.756663 | 2015-09-09T19:10:16 | 2015-09-09T19:10:16 | 23,578,052 | 20 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 20,861 | cpp | RigGeometry.pypp.cpp | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osganimation.h"
#include "wrap_referenced.h"
#include "riggeometry.pypp.hpp"
namespace bp = boost::python;
struct RigGeometry_wrapper : osgAnimation::RigGeometry, bp::wrapper< osgAnimation::RigGeometry > {
RigGeometry_wrapper( )
: osgAnimation::RigGeometry( )
, bp::wrapper< osgAnimation::RigGeometry >(){
// null constructor
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osgAnimation::RigGeometry::className( );
}
}
char const * default_className( ) const {
return osgAnimation::RigGeometry::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osgAnimation::RigGeometry::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osgAnimation::RigGeometry::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osgAnimation::RigGeometry::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osgAnimation::RigGeometry::cloneType( );
}
virtual void drawImplementation( ::osg::RenderInfo & renderInfo ) const {
if( bp::override func_drawImplementation = this->get_override( "drawImplementation" ) )
func_drawImplementation( boost::ref(renderInfo) );
else{
this->osgAnimation::RigGeometry::drawImplementation( boost::ref(renderInfo) );
}
}
void default_drawImplementation( ::osg::RenderInfo & renderInfo ) const {
osgAnimation::RigGeometry::drawImplementation( boost::ref(renderInfo) );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osgAnimation::RigGeometry::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osgAnimation::RigGeometry::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osgAnimation::RigGeometry::libraryName( );
}
}
char const * default_libraryName( ) const {
return osgAnimation::RigGeometry::libraryName( );
}
virtual void accept( ::osg::Drawable::AttributeFunctor & af ) {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(af) );
else{
this->osg::Geometry::accept( boost::ref(af) );
}
}
void default_accept( ::osg::Drawable::AttributeFunctor & af ) {
osg::Geometry::accept( boost::ref(af) );
}
virtual void accept( ::osg::Drawable::ConstAttributeFunctor & af ) const {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(af) );
else{
this->osg::Geometry::accept( boost::ref(af) );
}
}
void default_accept( ::osg::Drawable::ConstAttributeFunctor & af ) const {
osg::Geometry::accept( boost::ref(af) );
}
virtual void accept( ::osg::PrimitiveFunctor & pf ) const {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(pf) );
else{
this->osg::Geometry::accept( boost::ref(pf) );
}
}
void default_accept( ::osg::PrimitiveFunctor & pf ) const {
osg::Geometry::accept( boost::ref(pf) );
}
virtual void accept( ::osg::PrimitiveIndexFunctor & pf ) const {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(pf) );
else{
this->osg::Geometry::accept( boost::ref(pf) );
}
}
void default_accept( ::osg::PrimitiveIndexFunctor & pf ) const {
osg::Geometry::accept( boost::ref(pf) );
}
virtual ::osg::Geometry * asGeometry( ) {
if( bp::override func_asGeometry = this->get_override( "asGeometry" ) )
return func_asGeometry( );
else{
return this->osg::Geometry::asGeometry( );
}
}
::osg::Geometry * default_asGeometry( ) {
return osg::Geometry::asGeometry( );
}
virtual ::osg::Geometry const * asGeometry( ) const {
if( bp::override func_asGeometry = this->get_override( "asGeometry" ) )
return func_asGeometry( );
else{
return this->osg::Geometry::asGeometry( );
}
}
::osg::Geometry const * default_asGeometry( ) const {
return osg::Geometry::asGeometry( );
}
virtual void compileGLObjects( ::osg::RenderInfo & renderInfo ) const {
if( bp::override func_compileGLObjects = this->get_override( "compileGLObjects" ) )
func_compileGLObjects( boost::ref(renderInfo) );
else{
this->osg::Geometry::compileGLObjects( boost::ref(renderInfo) );
}
}
void default_compileGLObjects( ::osg::RenderInfo & renderInfo ) const {
osg::Geometry::compileGLObjects( boost::ref(renderInfo) );
}
virtual ::osg::BoundingBox computeBound( ) const {
if( bp::override func_computeBound = this->get_override( "computeBound" ) )
return func_computeBound( );
else{
return this->osg::Drawable::computeBound( );
}
}
::osg::BoundingBox default_computeBound( ) const {
return osg::Drawable::computeBound( );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Drawable::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Drawable::computeDataVariance( );
}
virtual void dirtyDisplayList( ) {
if( bp::override func_dirtyDisplayList = this->get_override( "dirtyDisplayList" ) )
func_dirtyDisplayList( );
else{
this->osg::Geometry::dirtyDisplayList( );
}
}
void default_dirtyDisplayList( ) {
osg::Geometry::dirtyDisplayList( );
}
virtual unsigned int getGLObjectSizeHint( ) const {
if( bp::override func_getGLObjectSizeHint = this->get_override( "getGLObjectSizeHint" ) )
return func_getGLObjectSizeHint( );
else{
return this->osg::Geometry::getGLObjectSizeHint( );
}
}
unsigned int default_getGLObjectSizeHint( ) const {
return osg::Geometry::getGLObjectSizeHint( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void resizeGLObjectBuffers( unsigned int maxSize ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( maxSize );
else{
this->osg::Geometry::resizeGLObjectBuffers( maxSize );
}
}
void default_resizeGLObjectBuffers( unsigned int maxSize ) {
osg::Geometry::resizeGLObjectBuffers( maxSize );
}
virtual void setCullCallback( ::osg::Drawable::CullCallback * cc ) {
if( bp::override func_setCullCallback = this->get_override( "setCullCallback" ) )
func_setCullCallback( boost::python::ptr(cc) );
else{
this->osg::Drawable::setCullCallback( boost::python::ptr(cc) );
}
}
void default_setCullCallback( ::osg::Drawable::CullCallback * cc ) {
osg::Drawable::setCullCallback( boost::python::ptr(cc) );
}
virtual void setDrawCallback( ::osg::Drawable::DrawCallback * dc ) {
if( bp::override func_setDrawCallback = this->get_override( "setDrawCallback" ) )
func_setDrawCallback( boost::python::ptr(dc) );
else{
this->osg::Drawable::setDrawCallback( boost::python::ptr(dc) );
}
}
void default_setDrawCallback( ::osg::Drawable::DrawCallback * dc ) {
osg::Drawable::setDrawCallback( boost::python::ptr(dc) );
}
virtual void setEventCallback( ::osg::Drawable::EventCallback * ac ) {
if( bp::override func_setEventCallback = this->get_override( "setEventCallback" ) )
func_setEventCallback( boost::python::ptr(ac) );
else{
this->osg::Drawable::setEventCallback( boost::python::ptr(ac) );
}
}
void default_setEventCallback( ::osg::Drawable::EventCallback * ac ) {
osg::Drawable::setEventCallback( boost::python::ptr(ac) );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Drawable::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Drawable::setThreadSafeRefUnref( threadSafe );
}
virtual void setUpdateCallback( ::osg::Drawable::UpdateCallback * ac ) {
if( bp::override func_setUpdateCallback = this->get_override( "setUpdateCallback" ) )
func_setUpdateCallback( boost::python::ptr(ac) );
else{
this->osg::Drawable::setUpdateCallback( boost::python::ptr(ac) );
}
}
void default_setUpdateCallback( ::osg::Drawable::UpdateCallback * ac ) {
osg::Drawable::setUpdateCallback( boost::python::ptr(ac) );
}
virtual void setUseVertexBufferObjects( bool flag ) {
if( bp::override func_setUseVertexBufferObjects = this->get_override( "setUseVertexBufferObjects" ) )
func_setUseVertexBufferObjects( flag );
else{
this->osg::Geometry::setUseVertexBufferObjects( flag );
}
}
void default_setUseVertexBufferObjects( bool flag ) {
osg::Geometry::setUseVertexBufferObjects( flag );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
virtual bool supports( ::osg::Drawable::AttributeFunctor const & arg0 ) const {
if( bp::override func_supports = this->get_override( "supports" ) )
return func_supports( boost::ref(arg0) );
else{
return this->osg::Geometry::supports( boost::ref(arg0) );
}
}
bool default_supports( ::osg::Drawable::AttributeFunctor const & arg0 ) const {
return osg::Geometry::supports( boost::ref(arg0) );
}
virtual bool supports( ::osg::Drawable::ConstAttributeFunctor const & arg0 ) const {
if( bp::override func_supports = this->get_override( "supports" ) )
return func_supports( boost::ref(arg0) );
else{
return this->osg::Geometry::supports( boost::ref(arg0) );
}
}
bool default_supports( ::osg::Drawable::ConstAttributeFunctor const & arg0 ) const {
return osg::Geometry::supports( boost::ref(arg0) );
}
virtual bool supports( ::osg::PrimitiveFunctor const & arg0 ) const {
if( bp::override func_supports = this->get_override( "supports" ) )
return func_supports( boost::ref(arg0) );
else{
return this->osg::Geometry::supports( boost::ref(arg0) );
}
}
bool default_supports( ::osg::PrimitiveFunctor const & arg0 ) const {
return osg::Geometry::supports( boost::ref(arg0) );
}
virtual bool supports( ::osg::PrimitiveIndexFunctor const & arg0 ) const {
if( bp::override func_supports = this->get_override( "supports" ) )
return func_supports( boost::ref(arg0) );
else{
return this->osg::Geometry::supports( boost::ref(arg0) );
}
}
bool default_supports( ::osg::PrimitiveIndexFunctor const & arg0 ) const {
return osg::Geometry::supports( boost::ref(arg0) );
}
};
void register_RigGeometry_class(){
bp::class_< RigGeometry_wrapper, bp::bases< ::osg::Geometry >, osg::ref_ptr< RigGeometry_wrapper >, boost::noncopyable >( "RigGeometry", bp::init< >() )
.def(
"buildVertexInfluenceSet"
, (void ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::buildVertexInfluenceSet ) )
.def(
"className"
, (char const * ( ::osgAnimation::RigGeometry::* )( )const)(&::osgAnimation::RigGeometry::className)
, (char const * ( RigGeometry_wrapper::* )( )const)(&RigGeometry_wrapper::default_className) )
.def(
"clone"
, (::osg::Object * ( ::osgAnimation::RigGeometry::* )( ::osg::CopyOp const & )const)(&::osgAnimation::RigGeometry::clone)
, (::osg::Object * ( RigGeometry_wrapper::* )( ::osg::CopyOp const & )const)(&RigGeometry_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"cloneType"
, (::osg::Object * ( ::osgAnimation::RigGeometry::* )( )const)(&::osgAnimation::RigGeometry::cloneType)
, (::osg::Object * ( RigGeometry_wrapper::* )( )const)(&RigGeometry_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"computeMatrixFromRootSkeleton"
, (void ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::computeMatrixFromRootSkeleton ) )
.def(
"copyFrom"
, (void ( ::osgAnimation::RigGeometry::* )( ::osg::Geometry & ))( &::osgAnimation::RigGeometry::copyFrom )
, ( bp::arg("from") ) )
.def(
"drawImplementation"
, (void ( ::osgAnimation::RigGeometry::* )( ::osg::RenderInfo & )const)(&::osgAnimation::RigGeometry::drawImplementation)
, (void ( RigGeometry_wrapper::* )( ::osg::RenderInfo & )const)(&RigGeometry_wrapper::default_drawImplementation)
, ( bp::arg("renderInfo") ) )
.def(
"getInfluenceMap"
, (::osgAnimation::VertexInfluenceMap const * ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getInfluenceMap )
, bp::return_internal_reference< >() )
.def(
"getInfluenceMap"
, (::osgAnimation::VertexInfluenceMap * ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::getInfluenceMap )
, bp::return_internal_reference< >() )
.def(
"getInvMatrixFromSkeletonToGeometry"
, (::osg::Matrix const & ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getInvMatrixFromSkeletonToGeometry )
, bp::return_internal_reference< >() )
.def(
"getMatrixFromSkeletonToGeometry"
, (::osg::Matrix const & ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getMatrixFromSkeletonToGeometry )
, bp::return_internal_reference< >() )
.def(
"getNeedToComputeMatrix"
, (bool ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getNeedToComputeMatrix ) )
.def(
"getRigTransformImplementation"
, (::osgAnimation::RigTransform * ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::getRigTransformImplementation )
, bp::return_internal_reference< >() )
.def(
"getSkeleton"
, (::osgAnimation::Skeleton const * ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getSkeleton )
, bp::return_internal_reference< >() )
.def(
"getSkeleton"
, (::osgAnimation::Skeleton * ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::getSkeleton )
, bp::return_internal_reference< >() )
.def(
"getSourceGeometry"
, (::osg::Geometry * ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::getSourceGeometry )
, bp::return_internal_reference< >() )
.def(
"getSourceGeometry"
, (::osg::Geometry const * ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getSourceGeometry )
, bp::return_internal_reference< >() )
.def(
"getVertexInfluenceSet"
, (::osgAnimation::VertexInfluenceSet const & ( ::osgAnimation::RigGeometry::* )( )const)( &::osgAnimation::RigGeometry::getVertexInfluenceSet )
, bp::return_internal_reference< >() )
.def(
"isSameKindAs"
, (bool ( ::osgAnimation::RigGeometry::* )( ::osg::Object const * )const)(&::osgAnimation::RigGeometry::isSameKindAs)
, (bool ( RigGeometry_wrapper::* )( ::osg::Object const * )const)(&RigGeometry_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) )
.def(
"libraryName"
, (char const * ( ::osgAnimation::RigGeometry::* )( )const)(&::osgAnimation::RigGeometry::libraryName)
, (char const * ( RigGeometry_wrapper::* )( )const)(&RigGeometry_wrapper::default_libraryName) )
.def(
"setInfluenceMap"
, (void ( ::osgAnimation::RigGeometry::* )( ::osgAnimation::VertexInfluenceMap * ))( &::osgAnimation::RigGeometry::setInfluenceMap )
, ( bp::arg("vertexInfluenceMap") ) )
.def(
"setNeedToComputeMatrix"
, (void ( ::osgAnimation::RigGeometry::* )( bool ))( &::osgAnimation::RigGeometry::setNeedToComputeMatrix )
, ( bp::arg("state") ) )
.def(
"setRigTransformImplementation"
, (void ( ::osgAnimation::RigGeometry::* )( ::osgAnimation::RigTransform * ))( &::osgAnimation::RigGeometry::setRigTransformImplementation )
, ( bp::arg("arg0") ) )
.def(
"setSkeleton"
, (void ( ::osgAnimation::RigGeometry::* )( ::osgAnimation::Skeleton * ))( &::osgAnimation::RigGeometry::setSkeleton )
, ( bp::arg("arg0") ) )
.def(
"setSourceGeometry"
, (void ( ::osgAnimation::RigGeometry::* )( ::osg::Geometry * ))( &::osgAnimation::RigGeometry::setSourceGeometry )
, ( bp::arg("geometry") ) )
.def(
"update"
, (void ( ::osgAnimation::RigGeometry::* )( ))( &::osgAnimation::RigGeometry::update ) );
}
|
f6e9582116882b90941c4abcd0848c8a0bf64fb7 | 6c756d53535a85da6bcbfba4049f98568cc120bf | /ML_project/evalForest_mex.cpp | c9acee1c22ac1885fc6b2c5075bd977e530f9de1 | [] | no_license | adinutzyc21/MachineLearning | 71c15d87cec8997785bbf3a133ad594a2fe0bcc4 | 8061f133cf02c7efc20f29d3b8f599912879bb47 | refs/heads/master | 2021-01-16T00:28:45.885521 | 2014-04-23T22:13:57 | 2014-04-23T22:13:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | cpp | evalForest_mex.cpp | /* decisionTree.c
* fast decision tree algorithms
*
*
*/
#include "mex.h"
#include "randomForest.hpp"
void evalForest(const double *x, const mwSize nsamples, const mwSize ndims,
const size_t *features, const double *values, const double *leaves,
const mwSize ntrees, const size_t depth,
double *y) {
//x is 2D: (nsamples)x(ndims) (row-major order)
//features, values are 2D: (ntrees)x(2^(depth-1)-1)
//leaves is 2D: (ntrees)x(2^(depth-1))
//y is 2D: (nsamples)x(ntrees)
//compute (2^nlevels - 1
mwSize nodes_len = (1 << (depth-1))-1;
mwSize leaves_len = (1 << (depth-1));
//loop over all the samples:
for(mwSize s = 0; s < nsamples; ++s) {
//index into x and y for the current sample:
const double *xs = x + s*ndims;
double *ys = y + s*ntrees;
//loop over all the trees:
for(mwSize t = 0; t < ntrees; ++t) {
//index into dims and vals for the current tree:
const size_t *ft = features + t*nodes_len;
const double *vt = values + t*nodes_len;
const double *lt = leaves + t*leaves_len;
//evaluate the current tree:
ys[t] = evaluateTree(xs, makeConstTree(depth,ft,vt,lt));
}
}
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
//usage: [y] = evalTree(x, features, values, leaves, depth)
// x is 2D: (nsamples)x(ndims) (row-major order)
// depth is scalar
// features is 2D: (ntrees)x(2^(depth-1) - 1)
// values is 2D: (ntrees)x(2^(depth-1) - 1)
// leaves is 2D: (ntrees)x(2^(depth-1))
// y is 2D: (nsamples)x(ntrees)
//assume that we've checked the arguments in the calling .m file
//get pointer to x array:
const mxArray *x_arr = prhs[0];
//get x array's size:
const mwSize *sx = mxGetDimensions(x_arr);
mwSize ndims = sx[0]; //matlab reports dimensions in column-major order :(
mwSize nsamples = sx[1];
//get pointers to decision tree stuff:
const mxArray *features_arr = prhs[1];
const mxArray *values_arr = prhs[2];
const mxArray *leaves_arr = prhs[3];
const mxArray *depth_arr = prhs[4];
//get depth of trees
size_t depth = *(size_t*)(mxGetPr(depth_arr));
//get number of trees
sx = mxGetDimensions(features_arr);
mwSize ntrees = sx[1]; //matlab reports dimensions in column-major order :(
//make output array
mxArray* y_arr = plhs[0] = mxCreateDoubleMatrix(ntrees, nsamples, mxREAL);
//evaluate trees:
evalForest(mxGetPr(x_arr), nsamples, ndims,
(size_t*)mxGetData(features_arr), mxGetPr(values_arr), mxGetPr(leaves_arr),
ntrees, depth,
mxGetPr(y_arr));
}
|
b6becf28dff4b10021bafd765557f820fee1c5ef | 0433a98aa6a22efbbf59e047fcae1894475a4c26 | /lksh_2017/Практика/139 Задача Очень Важный Объект (бинпоиск).cpp | 0ab928f1f3966930a30409179418dade1b6834e2 | [] | no_license | MrDonaldoWorking/School-Codes | a4336c1425122b746f4508cf80d5315a515525ed | 6aa3aca03e63bb1666e2f1a1d75752826de93255 | refs/heads/master | 2022-11-14T09:37:42.484431 | 2020-07-14T21:25:57 | 2020-07-14T21:25:57 | 279,339,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,641 | cpp | 139 Задача Очень Важный Объект (бинпоиск).cpp | #define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/STACK:108777216")
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
#define forn(i, a, b) for (int i = a; i < b; i++)
#define form(i, a, b) for (int i = a - 1; i >= b; i--)
#define all(a) a.begin(), a.end()
template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if (x < y) x = y; }
using namespace std;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-7;
struct point {
int x;
int y;
};
int n, k;
ld l;
set<int> holes;
vector<int> holev;
vector<ld> holelength;
vector<ld> length;
vector<ld> sumlength;
ld f(int i) {
///Circumvention
int left = i, right = 2 * n, middle;
while (right - left > 1) {
middle = (left + right) / 2;
if (l - sumlength[middle] + sumlength[i] > EPS)
left = middle;
else
right = middle;
}
//left = left % n;
ld ans = 0;
//it's works slowly
/*if (i > left) {
forn(j, 0, k) {
if (hole[j] - 1 < left || hole[j] - 1 >= i)
ans += length[hole[j] - 1];
if (hole[j] - 1 == left)
ans += l - sumlength[left + n] + sumlength[i];
}
}
else {
forn(j, 0, k) {
if (hole[j] - 1 < left && hole[j] - 1 >= i)
ans += length[hole[j] - 1];
if (hole[j] - 1 == left)
ans += l - sumlength[left] + sumlength[i];
}
}*/
//it's works wrongly
/*forn(j, 0, k) {
if (hole[j] - 1 < left && hole[j] - 1 >= i && left > i || !(hole[j] - 1 < i && hole[j] - 1 > left) && left < i)
ans += length[hole[j] - 1];
if (hole[j] - 1 == left)
part_of_fence = true;
}*/
//if (part_of_fence)
//ans += l - sumlength[left] + sumlength[i];
ans = holelength[left] - holelength[i];
if (holes.count(left % n + 1))
ans += l - sumlength[left] + sumlength[i];
///Opposite Circumvention
left = i, right = 2 * n;
while (right - left > 1) {
middle = (left + right) / 2;
if (l - sumlength[i + n] + sumlength[middle] > EPS)
right = middle;
else
left = middle;
}
ld ans1 = 0;
ans1 = holelength[i + n] - holelength[left];
if (holes.count(left % n + 1))
ans1 += l - sumlength[i + n] + sumlength[left];
return max(ans, ans1);
}
int main() {
ios::sync_with_stdio(false);
ifstream in("fence.in");
ofstream out("fence.out");
//scanf("%d%d%d", &n, &l, &k);
in >> n >> l >> k;
//out << "n = " << n << " k = " << k << " l = " << l << '\n';
//printf("n = %d l = %f k = %d\n", n, l, k);
holev.resize(k);
forn(i, 0, k) {
//scanf("%d", &hole[i]);
int x;
in >> x;
holes.insert(x);
holev[i] = x;
}
vector<point> polygon(n);
forn(i, 0, n)
//scanf("%d%d", polygon[i].x, polygon[i].y);
in >> polygon[i].x >> polygon[i].y;
polygon.push_back(polygon[0]);
//out << "---length---\n";
length.resize(n, 0);
forn(i, 0, n) {
length[i] = (polygon[i].x - polygon[i + 1].x) * (polygon[i].x - polygon[i + 1].x);
length[i] += (polygon[i].y - polygon[i + 1].y) * (polygon[i].y - polygon[i + 1].y);
length[i] = sqrt(length[i]);
//printf("%f ", length[i]);
//out << length[i] << ' ';
}
//printf("\n");
//out << '\n';
//out << "---sumlength---\n";
sumlength.resize(2 * n + 1);
sumlength[0] = 0;
forn(i, 1, n + 1)
sumlength[i] = sumlength[i - 1] + length[i - 1];
forn(i, n + 1, 2 * n + 1)
sumlength[i] = sumlength[i - 1] + length[i - n - 1];
/*forn(i, 0, 2 * n + 1)
out << sumlength[i] << ' ';
out << '\n';*/
//out << "---holelength---\n";
holelength.resize(2 * n + 1, 0);
holelength[0] = 0;
int j = 0;
forn(i, 1, n + 1) {
holelength[i] = holelength[i - 1];
if (j < k && holev[j] == i) {
holelength[i] += length[i - 1];
j++;
}
}
forn(i, n + 1, 2 * n + 1)
holelength[i] = holelength[i - n] + holelength[n];
/*forn(i, 0, 2 * n + 1)
out << holelength[i] << ' ';
out << '\n';*/
ld sumhole = 0;
for (int i : holes)//i -> hole[i]
sumhole += length[i - 1];
//out << "sumhole = " << sumhole << '\n';
ld sum = sumlength[n - 1];
//out << "sum = " << sum << '\n';
out.precision(20);
out << fixed;
if (l - sum > EPS) {
//printf("0.00000000000000000000000");
out << EPS / EPS - 1;
return 0;
}
ld max_ = 0;
forn(i, 0, n)
amax(max_, f(i));
//printf("%.20f\n%f", sumhole - max_, max_);
//printf("%.20f", sumhole - max_);
//out << "---ans---\n";
out << sumhole - max_;
return 0;
} |
03dab8fff86702633721e139137c2ced15245822 | bc19894b684d82260b2536395ea5e5a06a879cda | /MergeSort.cpp | a01af2a7cff097c8183e713d7004a6f5fc42fd85 | [] | no_license | Coder-Goo/SortMehods | 709d932f4779a41fdff8746aa536c1828cff6af6 | e8330539d3843bf4d7bf5c896ae03dcdb72a6bfa | refs/heads/master | 2023-06-05T21:04:08.097185 | 2021-06-30T09:34:16 | 2021-06-30T09:34:16 | 375,530,710 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | cpp | MergeSort.cpp | #include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
vector<int>temp;
//归并排序;后序遍历
void MergeSort(vector<int> &vec, int l, int r) {
if(l >= r) return;
int mid = l+(r-l)/2;
MergeSort(vec, l, mid); //如何划分区间,即mid属于左半部分还是右半部分?!!!!
MergeSort(vec, mid +1, r);
//此时左右两部分都已经分排好序了;将左右两部分合成一部分
int i= l, j = mid +1;
int count= l;
while(i<= mid && j <= r) {
if(vec[i]<= vec[j]) {
temp[count++] = vec[i++];
}else {
temp[count++] = vec[j++];
}
}
while(i<= mid) {
temp[count++] = vec[i++];
}
while(j<=r) {
temp[count ++] = vec[j++];
}
for(int k= l; k<= r; k++) {
vec[k] = temp[k];
}
}
int main() {
//vector<int> vec = {3,2,4,7,3,5,3,5,9,13};
vector<int> vec = {-2,3,-5};
temp.resize(vec.size());
MergeSort(vec, 0, vec.size()-1);
for(auto v:vec) cout<<v<<endl;
return 0;
} |
b37660263ead6806363577b21e1bcbf552bcf508 | 0272f2e67a09432d22e4f382125723777c27044d | /tutorials/multi-linkedlist/sw/part_build/Config.h | dc4a72f6fde17278b89d718c1cb8dccec502be7a | [
"BSD-3-Clause"
] | permissive | intel/rapid-design-methods-for-developing-hardware-accelerators | 027545835fef8daac9d43e731c09b9873fabb989 | 9a0afe216626b6d345b436ee4dce71511e8275f4 | refs/heads/master | 2023-05-27T13:25:30.640965 | 2023-01-07T00:07:05 | 2023-01-07T00:07:05 | 76,606,002 | 94 | 19 | BSD-3-Clause | 2019-06-01T20:30:48 | 2016-12-16T00:03:48 | C++ | UTF-8 | C++ | false | false | 1,451 | h | Config.h | // See LICENSE for license details.
#ifndef __CONFIG_H__
#define __CONFIG_H__
class Node {
public:
Node *next;
unsigned long long val;
Node *get_next() const {
return next;
}
void set_next( Node *val) {
next = val;
}
};
class HeadPtr {
public:
Node *head;
Node *get_head() const {
return head;
}
void set_head( Node *val) {
head = val;
}
bool get_found() const {
unsigned long long bits = reinterpret_cast<unsigned long long>( head);
return bits & 0x1ULL;
}
void set_found( bool val) {
unsigned long long bits = reinterpret_cast<unsigned long long>( head);
if ( val) {
head = reinterpret_cast<Node *>( bits | 0x1ULL);
} else {
head = reinterpret_cast<Node *>( bits & ~0x1ULL);
}
}
};
typedef unsigned long long AddrType;
class Config {
public:
AddrType aInp;
AddrType aOut;
unsigned long long m;
AddrType get_aInp() const {
return aInp;
}
AddrType get_aOut() const {
return aOut;
}
unsigned long long get_m() const {
return m;
}
void set_aInp( AddrType val) {
aInp = val;
}
void set_aOut( AddrType val) {
aOut = val;
}
void set_m( unsigned long long val) {
m = val;
}
HeadPtr *getInpPtr() const {
return reinterpret_cast<HeadPtr*>( aInp);
}
HeadPtr *getOutPtr() const {
return reinterpret_cast<HeadPtr*>( aOut);
}
Config() {
aInp = aOut = m = 0;
}
};
#endif //__CONFIG_H__
|
588f74cb7c166b643932b6ec1a6f670123a168cd | 4d6b65d04f367678563f48771bf918f5e609c86a | /commands/startapp/startapp.cpp | 7f39d377d0efe6a3e099cee33a0d12075fb48192 | [] | no_license | xdsh/FShell | 3bdb79d690de00efeac2d727fda9ed413d07621d | 3f2cf79601f53c9435c8f957e06a4067085320c3 | refs/heads/master | 2020-12-28T14:22:03.942434 | 2020-02-05T04:42:32 | 2020-02-05T04:42:32 | 238,367,577 | 2 | 0 | null | 2020-02-05T04:27:58 | 2020-02-05T04:27:57 | null | UTF-8 | C++ | false | false | 2,575 | cpp | startapp.cpp | // startapp.cpp
//
// Copyright (c) 2011 Accenture. All rights reserved.
// This component and the accompanying materials are made available
// under the terms of the "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Accenture - Initial contribution
//
#include <fshell/ioutils.h>
#include <fshell/common.mmh>
#include <apgcli.h>
#include <apacmdln.h>
using namespace IoUtils;
class CCmdStartApp : public CCommandBase
{
public:
static CCommandBase* NewLC();
~CCmdStartApp();
private:
CCmdStartApp();
private: // From CCommandBase.
virtual const TDesC& Name() const;
virtual void DoRunL();
virtual void ArgumentsL(RCommandArgumentList& aArguments);
virtual void OptionsL(RCommandOptionList& aOptions);
private:
HBufC* iAppName;
TFileName2 iDocument;
TBool iBackground;
TInt iScreen;
//TBool iWait;
};
EXE_BOILER_PLATE(CCmdStartApp)
CCommandBase* CCmdStartApp::NewLC()
{
CCmdStartApp* self = new(ELeave) CCmdStartApp();
CleanupStack::PushL(self);
self->BaseConstructL();
return self;
}
CCmdStartApp::~CCmdStartApp()
{
delete iAppName;
}
CCmdStartApp::CCmdStartApp()
{
}
const TDesC& CCmdStartApp::Name() const
{
_LIT(KName, "startapp");
return KName;
}
void CCmdStartApp::ArgumentsL(RCommandArgumentList& aArguments)
{
aArguments.AppendStringL(iAppName, _L("appname"));
}
void CCmdStartApp::OptionsL(RCommandOptionList& aOptions)
{
aOptions.AppendBoolL(iBackground, _L("background"));
aOptions.AppendFileNameL(iDocument, _L("document"));
aOptions.AppendIntL(iScreen, _L("screen"));
//aOptions.AppendBoolL(iWait, _L("wait"));
}
void CCmdStartApp::DoRunL()
{
RApaLsSession lsSession;
LeaveIfErr(lsSession.Connect(), _L("Couldn't connect to AppArc"));
CleanupClosePushL(lsSession);
TThreadId threadId;
CApaCommandLine* cl = CApaCommandLine::NewLC();
cl->SetExecutableNameL(*iAppName);
if (iBackground)
{
cl->SetCommandL(EApaCommandBackground);
}
if (iDocument.Length())
{
cl->SetDocumentNameL(iDocument);
}
if (iScreen)
{
cl->SetDefaultScreenL(iScreen);
}
TRequestStatus stat;
LeaveIfErr(lsSession.StartApp(*cl, threadId, &stat), _L("Couldn't start app %S"), iAppName);
User::WaitForRequest(stat);
LeaveIfErr(stat.Int(), _L("Failed to rendezvous with application %S"), iAppName);
CleanupStack::PopAndDestroy(cl);
CleanupStack::PopAndDestroy(&lsSession);
}
|
78a8eddce2e699d91fbe4aa95e5ef2838c4d4624 | 24b362affe54f9015e94ee91be6558b8305d6873 | /include/CommsManager.hpp | 25ddf5aa184def6e04bf57ec5f6e430099c47c69 | [] | no_license | RicardoRagel/comms_manager | 234078aac5d32e5ea5cbddbfd634fd68537dea2f | ab4e658d975e852954329348f503f80921d555eb | refs/heads/master | 2022-07-03T15:23:55.715202 | 2020-05-16T19:08:05 | 2020-05-16T19:08:05 | 260,712,251 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,668 | hpp | CommsManager.hpp | /*************************************************
* Description:
* ------------
* Class to create a channel, and to point it in the Bb,
* or to subscribe to it, creating (only at the first
* creating channel) the Bb, if not exist, and all
* necessary semaphores.
*
* Author:
* -------
* Ricardo Ragel de la Torre
* E-mail: ricardoragel4@gmail.com
* GitHub: RicardoRagel
*************************************************/
#ifndef __COMMSMANAGER_HPP__
#define __COMMSMANAGER_HPP__
#include "SharedMemory.hpp"
// BlackBoard (Bb) data struct
struct CBbData
{
char channel[256]; // Channel name (= Shared memory reference)
int id; // Channel id (Bb: 0, Channels: 1~100). The Bb is other special shared memory
int size; // Size of channel/SharedMemory in bytes
};
#define BLACKBOARD_ID 0
#define BLACKBOARD_MAX_CH 100
#define BLACKBOARD_SIZE BLACKBOARD_MAX_CH*sizeof(CBbData)+sizeof(int)
// The Bb will have in the first position one integer which value is the actual channel number pointed in the Bb and space to 100 channels (save as CBbData).
class CommsManager
{
public:
// Constructor. Just initialize blackboard and semaphores.
// initChannel(...) must be used to initialize channel
CommsManager(void);
// Constructor. Args: Channel name (as a path), pointer to the data where write
// or read the data channel, and the data channel size in bytes
CommsManager(const char *channel, void *data, int size);
// Destructor
~CommsManager(void);
// Initialize a channel. Channel name (as a path), pointer to the data where write
// or read the data channel, and the data channel size in bytes
bool initChannel(const char *channel, void *data, int size);
// Write to the channel
bool write(void);
// Read from the channel.
// Arg: true for blocking read, waiting to new data.
bool read(bool block = false);
CBbData getChannelInfo(const char *channel);
private:
// Wait until receive a synch
void waitSynch(void);
// Send a synch
void synch(void);
// BlackBoard shared memory
SharedMemory bb;
// Channel shared memory
SharedMemory ch;
// Pointer to the data to read or write
void *pData;
// Identification data channel (as a Bb struct)
CBbData chData;
// Semaphore variables for channel synchronization
int semid; // Id semaphores set (unique id for the channel group)
key_t key; // Key for the semaphores set
int lastCount; // Variable for the blocking read
};
#endif
|
ad45b65dbfdacb8dd87dccd8e568564ade4819e9 | 168b9963c510b84f1978e6a7602202aebd5adb5e | /streaming-pointcloud/examples/td/top-plugin/MqttToTex.h | 8e8b7edd236b9a4e9f2b1f734577626e6c2ecb60 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | PieMyth/Azure-Kinect-Samples | e226b94912a9c932b6bdaa5d0be77b5e38e41d00 | c7949aee5dea0231f4cb8ea212a6f2fe40373d6b | refs/heads/master | 2022-12-13T01:01:04.652633 | 2020-09-08T18:07:54 | 2020-09-08T18:07:54 | 288,911,663 | 0 | 0 | MIT | 2020-08-20T05:08:02 | 2020-08-20T05:08:02 | null | UTF-8 | C++ | false | false | 2,825 | h | MqttToTex.h | /* Shared Use License: This file is owned by Derivative Inc. (Derivative)
* and can only be used, and/or modified for use, in conjunction with
* Derivative's TouchDesigner software, and only if you are a licensee who has
* accepted Derivative's TouchDesigner license or assignment agreement
* (which also govern the use of this file). You may share or redistribute
* a modified version of this file provided the following conditions are met:
*
* 1. The shared file or redistribution must retain the information set out
* above and this list of conditions.
* 2. Derivative's name (Derivative Inc.) or its trademarks may not be used
* to endorse or promote products derived from this file without specific
* prior written permission from Derivative.
*/
#include "TOP_CPlusPlusBase.h"
#include "FrameQueue.h"
#include <thread>
#include <atomic>
#include "MQTTClient.cpp"
class MqttToTex : public TOP_CPlusPlusBase
{
public:
MqttToTex(const OP_NodeInfo *info);
virtual ~MqttToTex();
virtual void getGeneralInfo(TOP_GeneralInfo *, const OP_Inputs*, void*) override;
virtual bool getOutputFormat(TOP_OutputFormat*, const OP_Inputs*, void*) override;
virtual void execute(TOP_OutputFormatSpecs*,
const OP_Inputs*,
TOP_Context* context,
void* reserved1) override;
virtual void fillBuffer(float * mem, int width, int height);
virtual int32_t getNumInfoCHOPChans(void *reserved1) override;
virtual void getInfoCHOPChan(int32_t index,
OP_InfoCHOPChan *chan, void* reserved1) override;
virtual bool getInfoDATSize(OP_InfoDATSize *infoSize, void *reserved1) override;
virtual void getInfoDATEntries(int32_t index,
int32_t nEntries,
OP_InfoDATEntries *entries,
void *reserved1) override;
virtual void setupParameters(OP_ParameterManager *manager, void *reserved1) override;
virtual void pulsePressed(const char *name, void *reserved1) override;
private:
// We don't need to store this pointer, but we do for the example.
// The OP_NodeInfo class store information about the node that's using
// this instance of the class (like its name).
const OP_NodeInfo* myNodeInfo;
// In this example this value will be incremented each time the execute()
// function is called, then passes back to the TOP
int myExecuteCount;
int myPointCount;
std::unique_ptr<MQTTClient> mqttClient;
//mqtt broker ip address and port in this format: tcp://127.0.0.1:1883
std::string broker;
//mqtt client id
std::string client;
//mqtt topic
std::string topic;
//color fil;
double fillR;
double fillG;
double fillB;
double fillA;
int32_t outputWidth;
int32_t outputHeight;
//TD pulse
bool reconnect;
//buffer to receive mqtt data in
TextureData databuffer;
int textureMemoryLocation;
};
|
2eee483a4f8a2ac8dc72a427aff1126f7b59feb9 | 1b4ef06460dee1faa27ef5568fb6e3d8b3db7cfb | /kmp/main.cpp | 3a827757d7ed989e8d589324fd787052dbb2dde4 | [] | no_license | imoverflow/mycode | 3efb4d3663334ca7d96feaefbaa07cac4b4e2076 | 6ca89e1df775dbf351b5a7590f6a6af5167a46e9 | refs/heads/master | 2020-04-01T23:06:39.017093 | 2018-12-02T04:40:02 | 2018-12-02T04:40:02 | 153,742,417 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,193 | cpp | main.cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
void kmp_pre(char x[],int m,int next[]) //两种处理方法
{
int i,j;
j=next[0]=-1;
i=0;
while(i<m)
{
while(-1!=j&&x[i]!=x[j]) j=next[j];
next[++i]=++j;
}
}
void preKMP(char x[],int m,int kmpNext[])
{
int i,j;
j=kmpNext[0]=-1;
i=0;
while(i<m)
{
while(-1!=j&&x[i]!=x[j]) j=kmpNext[j];
if(x[++i]==x[++j]) kmpNext[i]=kmpNext[j];
else kmpNext[i]=j;
}
}
int next[10010];
int kmp_count(char x[],int m,char y[],int n)
{
int i,j;
int ans=0;
kmp_pre(x,m,next);
i=j=0;
while(i<n)
{
while(-1!=j&&y[i]!=x[j])
j=next[j];
i++;
j++;
if(j>=m)
{
ans++;
j=next[j];
}
}
return ans;
}
int main()
{
char T[] = "ababxbababcadfdsss";
char P[] = "ab";
printf("%s\n",T);
printf("%s\n",P );
int len1=strlen(T);
int len2=strlen(P);
int k=kmp_count(P,len2,T,len1);
for (int i = 0; i < strlen(P); ++i)
{
printf("%d ",next[i]);
}
printf("\n num is%d\n",k);
printf("\n");
return 0;
}
|
e190da27a4c02e289bd9677451ec3765a5166934 | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp | ad2eadca3500a19c093d9ac08f982a9a41856a7a | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 11,301 | cpp | InspectorConsoleAgent.cpp | /*
* Copyright (C) 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "core/inspector/InspectorConsoleAgent.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/ConsoleMessageStorage.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptManager.h"
#include "core/inspector/InspectorDebuggerAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptAsyncCallStack.h"
#include "core/inspector/V8Debugger.h"
#include "wtf/text/WTFString.h"
namespace blink {
namespace ConsoleAgentState {
static const char consoleMessagesEnabled[] = "consoleMessagesEnabled";
}
InspectorConsoleAgent::InspectorConsoleAgent(InjectedScriptManager* injectedScriptManager)
: InspectorBaseAgent<InspectorConsoleAgent, InspectorFrontend::Console>("Console")
, m_injectedScriptManager(injectedScriptManager)
, m_debuggerAgent(nullptr)
, m_enabled(false)
{
}
InspectorConsoleAgent::~InspectorConsoleAgent()
{
#if !ENABLE(OILPAN)
m_instrumentingAgents->setInspectorConsoleAgent(0);
#endif
}
DEFINE_TRACE(InspectorConsoleAgent)
{
visitor->trace(m_injectedScriptManager);
visitor->trace(m_debuggerAgent);
InspectorBaseAgent::trace(visitor);
}
void InspectorConsoleAgent::enable(ErrorString*)
{
if (m_enabled)
return;
m_instrumentingAgents->setInspectorConsoleAgent(this);
m_enabled = true;
enableStackCapturingIfNeeded();
m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, true);
ConsoleMessageStorage* storage = messageStorage();
if (storage->expiredCount()) {
RefPtrWillBeRawPtr<ConsoleMessage> expiredMessage = ConsoleMessage::create(OtherMessageSource, WarningMessageLevel, String::format("%d console messages are not shown.", storage->expiredCount()));
expiredMessage->setTimestamp(0);
sendConsoleMessageToFrontend(expiredMessage.get(), false);
}
size_t messageCount = storage->size();
for (size_t i = 0; i < messageCount; ++i)
sendConsoleMessageToFrontend(storage->at(i), false);
}
void InspectorConsoleAgent::disable(ErrorString*)
{
if (!m_enabled)
return;
m_instrumentingAgents->setInspectorConsoleAgent(nullptr);
m_enabled = false;
disableStackCapturingIfNeeded();
m_state->setBoolean(ConsoleAgentState::consoleMessagesEnabled, false);
}
void InspectorConsoleAgent::restore()
{
if (m_state->getBoolean(ConsoleAgentState::consoleMessagesEnabled)) {
frontend()->messagesCleared();
ErrorString error;
enable(&error);
}
}
void InspectorConsoleAgent::addMessageToConsole(ConsoleMessage* consoleMessage)
{
sendConsoleMessageToFrontend(consoleMessage, true);
if (consoleMessage->type() != AssertMessageType)
return;
if (!m_debuggerAgent || !m_debuggerAgent->enabled())
return;
if (m_debuggerAgent->debugger().pauseOnExceptionsState() != V8Debugger::DontPauseOnExceptions)
m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::Assert, nullptr);
}
void InspectorConsoleAgent::consoleMessagesCleared()
{
m_injectedScriptManager->releaseObjectGroup("console");
frontend()->messagesCleared();
}
static TypeBuilder::Console::ConsoleMessage::Source::Enum messageSourceValue(MessageSource source)
{
switch (source) {
case XMLMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Xml;
case JSMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Javascript;
case NetworkMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Network;
case ConsoleAPIMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Console_api;
case StorageMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Storage;
case AppCacheMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Appcache;
case RenderingMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Rendering;
case SecurityMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Security;
case OtherMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Other;
case DeprecationMessageSource: return TypeBuilder::Console::ConsoleMessage::Source::Deprecation;
}
return TypeBuilder::Console::ConsoleMessage::Source::Other;
}
static TypeBuilder::Console::ConsoleMessage::Type::Enum messageTypeValue(MessageType type)
{
switch (type) {
case LogMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Log;
case ClearMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Clear;
case DirMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Dir;
case DirXMLMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Dirxml;
case TableMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Table;
case TraceMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Trace;
case StartGroupMessageType: return TypeBuilder::Console::ConsoleMessage::Type::StartGroup;
case StartGroupCollapsedMessageType: return TypeBuilder::Console::ConsoleMessage::Type::StartGroupCollapsed;
case EndGroupMessageType: return TypeBuilder::Console::ConsoleMessage::Type::EndGroup;
case AssertMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Assert;
case TimeEndMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Log;
case CountMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Log;
}
return TypeBuilder::Console::ConsoleMessage::Type::Log;
}
static TypeBuilder::Console::ConsoleMessage::Level::Enum messageLevelValue(MessageLevel level)
{
switch (level) {
case DebugMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Debug;
case LogMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Log;
case WarningMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Warning;
case ErrorMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Error;
case InfoMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Info;
case RevokedErrorMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::RevokedError;
}
return TypeBuilder::Console::ConsoleMessage::Level::Log;
}
void InspectorConsoleAgent::sendConsoleMessageToFrontend(ConsoleMessage* consoleMessage, bool generatePreview)
{
if (consoleMessage->workerGlobalScopeProxy())
return;
RefPtr<TypeBuilder::Console::ConsoleMessage> jsonObj = TypeBuilder::Console::ConsoleMessage::create()
.setSource(messageSourceValue(consoleMessage->source()))
.setLevel(messageLevelValue(consoleMessage->level()))
.setText(consoleMessage->message())
.setTimestamp(consoleMessage->timestamp());
// FIXME: only send out type for ConsoleAPI source messages.
jsonObj->setType(messageTypeValue(consoleMessage->type()));
jsonObj->setLine(static_cast<int>(consoleMessage->lineNumber()));
jsonObj->setColumn(static_cast<int>(consoleMessage->columnNumber()));
if (consoleMessage->scriptId())
jsonObj->setScriptId(String::number(consoleMessage->scriptId()));
jsonObj->setUrl(consoleMessage->url());
ScriptState* scriptState = consoleMessage->scriptState();
if (scriptState)
jsonObj->setExecutionContextId(m_injectedScriptManager->injectedScriptIdFor(scriptState));
if (consoleMessage->source() == NetworkMessageSource && consoleMessage->requestIdentifier())
jsonObj->setNetworkRequestId(IdentifiersFactory::requestId(consoleMessage->requestIdentifier()));
RefPtrWillBeRawPtr<ScriptArguments> arguments = consoleMessage->scriptArguments();
if (arguments && arguments->argumentCount()) {
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(arguments->scriptState());
if (!injectedScript.isEmpty()) {
RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::RemoteObject> > jsonArgs = TypeBuilder::Array<TypeBuilder::Runtime::RemoteObject>::create();
if (consoleMessage->type() == TableMessageType && generatePreview && arguments->argumentCount()) {
ScriptValue table = arguments->argumentAt(0);
ScriptValue columns = arguments->argumentCount() > 1 ? arguments->argumentAt(1) : ScriptValue();
RefPtr<TypeBuilder::Runtime::RemoteObject> inspectorValue = injectedScript.wrapTable(table, columns);
if (!inspectorValue) {
ASSERT_NOT_REACHED();
return;
}
jsonArgs->addItem(inspectorValue);
} else {
for (unsigned i = 0; i < arguments->argumentCount(); ++i) {
RefPtr<TypeBuilder::Runtime::RemoteObject> inspectorValue = injectedScript.wrapObject(arguments->argumentAt(i), "console", generatePreview);
if (!inspectorValue) {
ASSERT_NOT_REACHED();
return;
}
jsonArgs->addItem(inspectorValue);
}
}
jsonObj->setParameters(jsonArgs);
}
}
if (consoleMessage->callStack()) {
jsonObj->setStackTrace(consoleMessage->callStack()->buildInspectorArray());
RefPtrWillBeRawPtr<ScriptAsyncCallStack> asyncCallStack = consoleMessage->callStack()->asyncCallStack();
if (asyncCallStack)
jsonObj->setAsyncStackTrace(asyncCallStack->buildInspectorObject());
}
if (consoleMessage->messageId())
jsonObj->setMessageId(consoleMessage->messageId());
if (consoleMessage->relatedMessageId())
jsonObj->setRelatedMessageId(consoleMessage->relatedMessageId());
frontend()->messageAdded(jsonObj);
frontend()->flush();
}
} // namespace blink
|
553b5c6b1339addfd4248373097aac9105550697 | f8211d24d758f2a4af9244e66a2ac86a1c2031a9 | /231_A.cpp | 77b4411a125291a0f08baa55cf4015e5dfc625d8 | [] | no_license | kowshik24/Codeforces | 7bdb6a933cda5e27b97b4b5764598cbd91648493 | f265752dbade9ef8d06e064ae8009200ec01cbad | refs/heads/main | 2022-02-18T23:30:57.415200 | 2022-02-09T19:43:28 | 2022-02-09T19:43:28 | 237,670,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | 231_A.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,a,b,c,sum=0,count=0;
cin>>n;
for(int i=0; i<n ;i++)
{
cin>>a>>b>>c;
sum=a+b+c;
if(sum>=2)
{
count++;
}
}
cout<<count<<endl;
return 0;
}
|
e9477b4e6310607d9346566500f1ad83f0f87b15 | b54882cf89639ad5a6d289fb478e90e95311ad39 | /largestFibonacciSubsequence.cpp | 89cf1ae183829e9e311600356f0b043ac866bd56 | [] | no_license | kk77777/geeksForGeeksSolutions | 16111f7c39686db17e06e4213ab68159437900d0 | 4b51dd9699550b55b68766c6e22ff5cb9b205a7c | refs/heads/master | 2021-08-07T09:36:49.380647 | 2021-08-01T08:37:08 | 2021-08-01T08:37:08 | 249,911,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | largestFibonacciSubsequence.cpp | #include <iostream>
#include <unordered_map>
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
using namespace std;
int fib(unordered_map<int, int> &mp)
{
mp[0] = 0, mp[1] = 1, mp[2] = 2;
for (int i = 3; i < 20; i++)
{
mp[i] = mp[i - 1] + mp[i - 2];
}
}
int main()
{
fast
unordered_map<int, int>
mp;
fib(mp);
int tc;
cin >> tc;
while (tc--)
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
for (auto it = mp.begin(); it != mp.end(); it++)
{
if (it->second == x)
{
cout << x << " ";
continue;
}
}
}
cout << "\n";
}
} |
72b8254cc86682205ee3af4dd88fa4f07ea4c230 | 820c61849a45ed69f3e4636e2d3f0486304b5d46 | /Contest Participations/IPC 4/g.cpp | 9a492406a5434c834bdbf2c99ef459f02c1be4ac | [] | no_license | Tanmoytkd/programming-projects | 1d842c994b6e2c546ab37a5378a823f9c9443c39 | 42c6f741d6da1e4cf787b1b4971a72ab2c2919e1 | refs/heads/master | 2021-08-07T18:00:43.530215 | 2021-06-04T11:18:27 | 2021-06-04T11:18:27 | 42,516,841 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,544 | cpp | g.cpp | #include<cstdio>
#include<sstream>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<iostream>
#include<fstream>
#include<numeric>
#include<string>
#include<vector>
#include<cstring>
#include<map>
#include<iterator>
#include<limits.h>
using namespace std;
#define N 100007
#define level 18
long long n;
vector<long long> edge[N], cost[N];
long long dist[N], parent[N][level], depth[N];
void dfs(long long node, long long currentparent, long long dst) {
if(node==0) depth[node]=0;
else depth[node]=depth[currentparent]+1;
//cout << node << " " << currentparent << " parentcall " << endl;
parent[node][0]=currentparent;
dist[node]=dst;
std::vector<long long> & e = edge[node];
std::vector<long long> & c = cost[node];
for(long long i=0; i<e.size(); i++) {
long long nxt=e[i];
if(nxt==currentparent) continue;
dfs(nxt, node, dst+c[i]);
}
}
void preprocess() {
for (long long i=1; i<level; i++) {
for (long long node = 1; node <= n; node++) {
if (parent[node][i-1] != -1) {
parent[node][i] = parent[parent[node][i-1]][i-1];
}
}
}
}
long long LCA(long long u, long long v)
{
//cout << "depth of " << u << " " << depth[u] << endl;
//cout << "depth of " << v << " " << depth[v] << endl;
if (depth[v] < depth[u])
swap(u, v);
long long diff = depth[v] - depth[u];
for (long long i=0; i<level; i++)
if ((diff>>i)&1)
v = parent[v][i];
//cout << u << " " << v << " u v final" << endl;
if (u == v)
return u;
for (long long i=level-1; i>=0; i--)
if (parent[u][i] != parent[v][i])
{
u = parent[u][i];
v = parent[v][i];
}
//cout << u << " " << v << " uv morefinal" << endl;
return parent[u][0];
}
int main() {
while(scanf("%lld", &n)==1 && n) {
for(long long i=0; i<n; i++) {
edge[i].clear();
cost[i].clear();
}
for(long long i=1; i<n; i++) {
long long u=i, v;
scanf("%lld", &v);
long long l;
scanf("%lld", &l);
edge[u].push_back(v);
cost[u].push_back(l);
edge[v].push_back(u);
cost[v].push_back(l);
}
memset(parent, -1, sizeof parent);
dfs(0, -1, 0);
preprocess();
long long q;
scanf("%lld", &q);
while(q--) {
long long a, b;
scanf(" %lld %lld", &a, &b);
long long lca = LCA(a, b);
//cout << a << " " << dist[a] << endl;
//cout << b << " " << dist[b] << endl;
//cout << lca << " " << dist[lca] << endl;
long long res = dist[a]+dist[b]-2*dist[lca];
printf("%lld%c", res, " \n"[q==0]);
}
}
} |
144be1974547522c64b8fa2c74d486ad87a91a47 | 4119e40a4295e41d03e8c245b450c0238877c01d | /I13 - Law Firm/ListToString.h | 9e0b80110688aeb05c21c7f0f845bc55066880ed | [] | no_license | Tello-asd/ED-LABS | 6ee91e7804a71d9af872e0aead710dd0ec17e6f1 | f36d4fe86f64d9f67269fecc0fc777b78f1e1e7e | refs/heads/main | 2023-06-06T10:20:35.634798 | 2021-06-23T17:21:22 | 2021-06-23T17:21:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | ListToString.h | #include <string>
#include "List.h"
using namespace std;
string listToStringCommas(List<string> list) {
string res;
List<string>::Iterator it = list.cbegin();
if (it != list.cend()) {
res += it.elem();
it.next();
}
while (it != list.cend()) {
res += "," + it.elem();
it.next();
}
return res;
} |
c16608fec04289ccd1e35acf1a070ec88e8db12a | 2ede5580f851f83a02f0a9ec657240805ce43010 | /wave printing 2d array.cpp | e9f27b34f7cd7bda6f8e24455a478706740f94de | [] | no_license | lazyperfectionist/Coding-blocks-C- | c89786a93d29a4013866b16e1a33b2064c239615 | dc7afb94ce58fdc3f60ada4ae1490a0d25f137f4 | refs/heads/master | 2023-02-20T04:44:09.472745 | 2021-01-10T01:46:29 | 2021-01-10T01:46:29 | 282,069,674 | 0 | 1 | null | 2020-10-03T08:14:18 | 2020-07-23T22:29:49 | C++ | UTF-8 | C++ | false | false | 729 | cpp | wave printing 2d array.cpp | #include<iostream>
using namespace std;
int main(){
int val=1;
int arr[5][5] = {0};
for(int row=0;row<5;row++){
for(int col=0;col<5;col++){
arr[row][col]=val;
val +=1;
cout<<arr[row][col]<<" ";
}
cout<<endl;
}
cout<<endl;
//Accesssing random values
for(int col=0;col<5;col++)
{
if(col%2==0){
//Top to bottom
for(int row=0;row<5;row++){
cout<<arr[row][col]<<" ";
}
cout<<endl;
}
else{
//Bottom's up
for(int row=4;row>=0;row--){
cout<<arr[row][col]<<" ";
}
cout<<endl;
}
}
}
|
1c7eea87502dfe62ead3ddb5a51927067b580f34 | 472e20731939b9f4ad721976db0f2ab167d07c26 | /TestSoftware/arduino/standard_lib/BitBytes/BitBytes.ino | 17c71b3efb00bf2e0a76734267caca3f47123642 | [] | no_license | XinghuaXHu/spresense-test-structure-change | 504ad68698581cf473de83d1ab9b466d592a7419 | 25e71da1716aa1e9f7b358baf5f23a3021529646 | refs/heads/master | 2021-01-15T05:35:00.742393 | 2020-03-02T08:17:35 | 2020-03-02T08:17:35 | 242,887,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,909 | ino | BitBytes.ino | /*
* the Characters task aims at knowing what the char value is.
*
* basic testing methods are checking the return value
* when using the functions with the parameter,that is
* or is not,what you want.
*
* the functions list in detail:
* test-task Syntax return function
*
* lowByte() lowByte(x) byte Extracts the low-order (rightmost)
* byte of a variable (e.g. a word)
* highByte() highByte(x) The value of the bit Extracts the high-order (leftmost)
* byte of a word (or the second
* lowest byte of a larger data type).
* bitRead() bitRead(x, n) the value of the bit (0 or 1) Reads a bit of a number.
* bitWrite() bitWrite(x, n, b) Nothing Writes a bit of a numeric variable.
* bitSet() bitSet(x, n) Nothing Sets (writes a 1 to) a bit of a numeric
* variable.
* bitClear() bitClear(x, n) Nothing Clears (writes a 0 to) a bit of a numeric
* variable.
* bit() bit(n) The value of the bit Computes the value of the specified bit
* (bit 0 is 1, bit 1 is 2, bit 2 is 4, etc.).
*/
bool functions_test_lowByte(unsigned int val)
{
unsigned int tmp = 0xff;
if((tmp & val) != lowByte(val))
{
return 0;
}
return 1;
}
bool functions_test_highByte(unsigned int val)
{
unsigned int tmp = 0xff;
if((tmp & (val>>8)) != highByte(val))
{
return 0;
}
return 1;
}
bool functions_test_bitRead(unsigned int val,byte n)
{
unsigned int tmp = 0x1;
if((tmp & (val>>n)) != bitRead(val,n))
{
return 0;
}
return 1;
}
bool functions_test_bitWrite(unsigned int val,byte n,unsigned int b)
{
unsigned int tmp = 0x1;
unsigned int v = val;
bitWrite(v,n,b);
bool con = ((tmp & (v >> n)) == (b));
if(!con)
{
return 0;
}
return 1;
}
bool functions_test_bitSet(unsigned int val,byte n)
{
unsigned int tmp = 0x1;
unsigned int v = val;
bitSet(v,n);
bool con = ((tmp & (v >> n)) == 0x1 );
if(!con)
{
return 0;
}
return 1;
}
bool functions_test_bitClear(unsigned int val,byte n)
{
unsigned int tmp = 0x1;
unsigned int v = val;
bitClear(v,n);
bool con = ((tmp & (v >> n)) == 0x0 );
if(!con)
{
return 0;
}
return 1;
}
bool functions_test_bit(byte n)
{
unsigned int tmp = pow(2,n);
if(tmp != bit(n))
{
return 0;
}
return 1;
}
void setup() {
// put your setup code here, to run once:
/* TESTING lowByte(x) */
assert(functions_test_lowByte(0xABCD));
/* TESTING highByte(x) */
assert(functions_test_highByte(0xABCDEF12));
/* TESTING bitRead(x,n) */
assert(functions_test_bitRead(0x55555555,5));
/* TESTING bitWrite(x, n, b) */
assert(functions_test_bitWrite(0xFFFFFFFF,5,0));
/* TESTING bitSet(x, n) */
assert(functions_test_bitSet(0x0,2));
/* TESTING bitClear(x, n) */
assert(functions_test_bitClear(0xFFFF,2));
/* TESTING bit(n) */
assert(functions_test_bit(2));
printf("\nthe task BitandBytes test ok!\n");
}
void loop() {
// put your main code here, to run repeatedly:
}
|
c4ae87215d512663f7310bbb280f107e89efef03 | f80795913b6fbbfbc1501ca1e04140d1dac1d70e | /10.0.14393.0/winrt/internal/Windows.System.Profile.1.h | b6d17db4b86a2480f46d4644ca96cd50694a4da6 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | jjhegedus/cppwinrt | 13fffb02f2e302b57e0f2cac74e02a9e2d94b9cf | fb3238a29cf70edd154de8d2e36b2379e25cc2c4 | refs/heads/master | 2021-01-09T06:21:16.273638 | 2017-02-05T05:34:37 | 2017-02-05T05:34:37 | 80,971,093 | 1 | 0 | null | 2017-02-05T05:27:18 | 2017-02-05T05:27:17 | null | UTF-8 | C++ | false | false | 11,383 | h | Windows.System.Profile.1.h | // C++ for the Windows Runtime v1.0.161012.5
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.System.Profile.0.h"
#include "Windows.Storage.Streams.0.h"
#include "Windows.System.0.h"
#include "Windows.Foundation.1.h"
#include "Windows.Foundation.Collections.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::System::Profile {
struct __declspec(uuid("1d5ee066-188d-5ba9-4387-acaeb0e7e305")) __declspec(novtable) IAnalyticsInfoStatics : Windows::IInspectable
{
virtual HRESULT __stdcall get_VersionInfo(Windows::System::Profile::IAnalyticsVersionInfo ** value) = 0;
virtual HRESULT __stdcall get_DeviceForm(hstring * value) = 0;
};
struct __declspec(uuid("926130b8-9955-4c74-bdc1-7cd0decf9b03")) __declspec(novtable) IAnalyticsVersionInfo : Windows::IInspectable
{
virtual HRESULT __stdcall get_DeviceFamily(hstring * value) = 0;
virtual HRESULT __stdcall get_DeviceFamilyVersion(hstring * value) = 0;
};
struct __declspec(uuid("971260e0-f170-4a42-bd55-a900b212dae2")) __declspec(novtable) IHardwareIdentificationStatics : Windows::IInspectable
{
virtual HRESULT __stdcall abi_GetPackageSpecificToken(Windows::Storage::Streams::IBuffer * nonce, Windows::System::Profile::IHardwareToken ** packageSpecificHardwareToken) = 0;
};
struct __declspec(uuid("28f6d4c0-fb12-40a4-8167-7f4e03d2724c")) __declspec(novtable) IHardwareToken : Windows::IInspectable
{
virtual HRESULT __stdcall get_Id(Windows::Storage::Streams::IBuffer ** value) = 0;
virtual HRESULT __stdcall get_Signature(Windows::Storage::Streams::IBuffer ** value) = 0;
virtual HRESULT __stdcall get_Certificate(Windows::Storage::Streams::IBuffer ** value) = 0;
};
struct __declspec(uuid("99571178-500f-487e-8e75-29e551728712")) __declspec(novtable) IKnownRetailInfoPropertiesStatics : Windows::IInspectable
{
virtual HRESULT __stdcall get_RetailAccessCode(hstring * value) = 0;
virtual HRESULT __stdcall get_ManufacturerName(hstring * value) = 0;
virtual HRESULT __stdcall get_ModelName(hstring * value) = 0;
virtual HRESULT __stdcall get_DisplayModelName(hstring * value) = 0;
virtual HRESULT __stdcall get_Price(hstring * value) = 0;
virtual HRESULT __stdcall get_IsFeatured(hstring * value) = 0;
virtual HRESULT __stdcall get_FormFactor(hstring * value) = 0;
virtual HRESULT __stdcall get_ScreenSize(hstring * value) = 0;
virtual HRESULT __stdcall get_Weight(hstring * value) = 0;
virtual HRESULT __stdcall get_DisplayDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_BatteryLifeDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_ProcessorDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_Memory(hstring * value) = 0;
virtual HRESULT __stdcall get_StorageDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_GraphicsDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_FrontCameraDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_RearCameraDescription(hstring * value) = 0;
virtual HRESULT __stdcall get_HasNfc(hstring * value) = 0;
virtual HRESULT __stdcall get_HasSdSlot(hstring * value) = 0;
virtual HRESULT __stdcall get_HasOpticalDrive(hstring * value) = 0;
virtual HRESULT __stdcall get_IsOfficeInstalled(hstring * value) = 0;
virtual HRESULT __stdcall get_WindowsEdition(hstring * value) = 0;
};
struct __declspec(uuid("b6e24c1b-7b1c-4b32-8c62-a66597ce723a")) __declspec(novtable) IPlatformDiagnosticsAndUsageDataSettingsStatics : Windows::IInspectable
{
virtual HRESULT __stdcall get_CollectionLevel(winrt::Windows::System::Profile::PlatformDataCollectionLevel * value) = 0;
virtual HRESULT __stdcall add_CollectionLevelChanged(Windows::Foundation::EventHandler<Windows::IInspectable> * handler, event_token * token) = 0;
virtual HRESULT __stdcall remove_CollectionLevelChanged(event_token token) = 0;
virtual HRESULT __stdcall abi_CanCollectDiagnostics(winrt::Windows::System::Profile::PlatformDataCollectionLevel level, bool * result) = 0;
};
struct __declspec(uuid("0712c6b8-8b92-4f2a-8499-031f1798d6ef")) __declspec(novtable) IRetailInfoStatics : Windows::IInspectable
{
virtual HRESULT __stdcall get_IsDemoModeEnabled(bool * value) = 0;
virtual HRESULT __stdcall get_Properties(Windows::Foundation::Collections::IMapView<hstring, Windows::IInspectable> ** value) = 0;
};
struct __declspec(uuid("893df40e-cad6-4d50-8c49-6fcfc03edb29")) __declspec(novtable) ISharedModeSettingsStatics : Windows::IInspectable
{
virtual HRESULT __stdcall get_IsEnabled(bool * value) = 0;
};
struct __declspec(uuid("0c659e7d-c3c2-4d33-a2df-21bc41916eb3")) __declspec(novtable) ISystemIdentificationInfo : Windows::IInspectable
{
virtual HRESULT __stdcall get_Id(Windows::Storage::Streams::IBuffer ** value) = 0;
virtual HRESULT __stdcall get_Source(winrt::Windows::System::Profile::SystemIdentificationSource * value) = 0;
};
struct __declspec(uuid("5581f42a-d3df-4d93-a37d-c41a616c6d01")) __declspec(novtable) ISystemIdentificationStatics : Windows::IInspectable
{
virtual HRESULT __stdcall abi_GetSystemIdForPublisher(Windows::System::Profile::ISystemIdentificationInfo ** result) = 0;
virtual HRESULT __stdcall abi_GetSystemIdForUser(Windows::System::IUser * user, Windows::System::Profile::ISystemIdentificationInfo ** result) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::System::Profile::AnalyticsVersionInfo> { using default_interface = Windows::System::Profile::IAnalyticsVersionInfo; };
template <> struct traits<Windows::System::Profile::HardwareToken> { using default_interface = Windows::System::Profile::IHardwareToken; };
template <> struct traits<Windows::System::Profile::SystemIdentificationInfo> { using default_interface = Windows::System::Profile::ISystemIdentificationInfo; };
}
namespace Windows::System::Profile {
template <typename T> struct impl_IAnalyticsInfoStatics;
template <typename T> struct impl_IAnalyticsVersionInfo;
template <typename T> struct impl_IHardwareIdentificationStatics;
template <typename T> struct impl_IHardwareToken;
template <typename T> struct impl_IKnownRetailInfoPropertiesStatics;
template <typename T> struct impl_IPlatformDiagnosticsAndUsageDataSettingsStatics;
template <typename T> struct impl_IRetailInfoStatics;
template <typename T> struct impl_ISharedModeSettingsStatics;
template <typename T> struct impl_ISystemIdentificationInfo;
template <typename T> struct impl_ISystemIdentificationStatics;
}
namespace impl {
template <> struct traits<Windows::System::Profile::IAnalyticsInfoStatics>
{
using abi = ABI::Windows::System::Profile::IAnalyticsInfoStatics;
template <typename D> using consume = Windows::System::Profile::impl_IAnalyticsInfoStatics<D>;
};
template <> struct traits<Windows::System::Profile::IAnalyticsVersionInfo>
{
using abi = ABI::Windows::System::Profile::IAnalyticsVersionInfo;
template <typename D> using consume = Windows::System::Profile::impl_IAnalyticsVersionInfo<D>;
};
template <> struct traits<Windows::System::Profile::IHardwareIdentificationStatics>
{
using abi = ABI::Windows::System::Profile::IHardwareIdentificationStatics;
template <typename D> using consume = Windows::System::Profile::impl_IHardwareIdentificationStatics<D>;
};
template <> struct traits<Windows::System::Profile::IHardwareToken>
{
using abi = ABI::Windows::System::Profile::IHardwareToken;
template <typename D> using consume = Windows::System::Profile::impl_IHardwareToken<D>;
};
template <> struct traits<Windows::System::Profile::IKnownRetailInfoPropertiesStatics>
{
using abi = ABI::Windows::System::Profile::IKnownRetailInfoPropertiesStatics;
template <typename D> using consume = Windows::System::Profile::impl_IKnownRetailInfoPropertiesStatics<D>;
};
template <> struct traits<Windows::System::Profile::IPlatformDiagnosticsAndUsageDataSettingsStatics>
{
using abi = ABI::Windows::System::Profile::IPlatformDiagnosticsAndUsageDataSettingsStatics;
template <typename D> using consume = Windows::System::Profile::impl_IPlatformDiagnosticsAndUsageDataSettingsStatics<D>;
};
template <> struct traits<Windows::System::Profile::IRetailInfoStatics>
{
using abi = ABI::Windows::System::Profile::IRetailInfoStatics;
template <typename D> using consume = Windows::System::Profile::impl_IRetailInfoStatics<D>;
};
template <> struct traits<Windows::System::Profile::ISharedModeSettingsStatics>
{
using abi = ABI::Windows::System::Profile::ISharedModeSettingsStatics;
template <typename D> using consume = Windows::System::Profile::impl_ISharedModeSettingsStatics<D>;
};
template <> struct traits<Windows::System::Profile::ISystemIdentificationInfo>
{
using abi = ABI::Windows::System::Profile::ISystemIdentificationInfo;
template <typename D> using consume = Windows::System::Profile::impl_ISystemIdentificationInfo<D>;
};
template <> struct traits<Windows::System::Profile::ISystemIdentificationStatics>
{
using abi = ABI::Windows::System::Profile::ISystemIdentificationStatics;
template <typename D> using consume = Windows::System::Profile::impl_ISystemIdentificationStatics<D>;
};
template <> struct traits<Windows::System::Profile::AnalyticsInfo>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.AnalyticsInfo"; }
};
template <> struct traits<Windows::System::Profile::AnalyticsVersionInfo>
{
using abi = ABI::Windows::System::Profile::AnalyticsVersionInfo;
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.AnalyticsVersionInfo"; }
};
template <> struct traits<Windows::System::Profile::HardwareIdentification>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.HardwareIdentification"; }
};
template <> struct traits<Windows::System::Profile::HardwareToken>
{
using abi = ABI::Windows::System::Profile::HardwareToken;
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.HardwareToken"; }
};
template <> struct traits<Windows::System::Profile::KnownRetailInfoProperties>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.KnownRetailInfoProperties"; }
};
template <> struct traits<Windows::System::Profile::PlatformDiagnosticsAndUsageDataSettings>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.PlatformDiagnosticsAndUsageDataSettings"; }
};
template <> struct traits<Windows::System::Profile::RetailInfo>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.RetailInfo"; }
};
template <> struct traits<Windows::System::Profile::SharedModeSettings>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.SharedModeSettings"; }
};
template <> struct traits<Windows::System::Profile::SystemIdentification>
{
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.SystemIdentification"; }
};
template <> struct traits<Windows::System::Profile::SystemIdentificationInfo>
{
using abi = ABI::Windows::System::Profile::SystemIdentificationInfo;
static constexpr const wchar_t * name() noexcept { return L"Windows.System.Profile.SystemIdentificationInfo"; }
};
}
}
|
b809049341de7cbff8ec5f12d372ef386f0d4a59 | a6ed5311e340de398f81df0eb36e8339472f0b7d | /Match/Project/Match/createData.h | a845747705ec089eb5285232a8e41551af8e3367 | [] | no_license | LudwigCh/object-oriented | 1605c424ac0171389bdf6edbe6a71b138d492856 | ca20efeccec27f1165d6d33b87d4ab961bc49c68 | refs/heads/master | 2023-03-10T10:10:37.090884 | 2017-10-09T14:14:33 | 2017-10-09T14:14:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | createData.h | #pragma once
class createData {
public:/*
void print();
const string freetime[6] = { "8: 00~10: 00","10: 00~12: 00","14: 00~16: 00","16: 00~18: 00","18: 30~20: 30","20: 30~22: 30" };
const string week[7] = { "Mon","Tues","Wed","Thur","Fri","Sat","Sun" };
const string tag[3][8] = { {"tennis", "pingpong", "swimming", "climbing", "basketball", "soccer", "fishing", "running"},{"movies","singing", "dancing", "acting", "reading","travel", "collect", "painting"},{ "PS","Linux","Android","iOS", "Web",".net","Java", "SQL" } };
*/
};
|
265e65bce4bf6723400e59a82ddec89bdfdf4ed4 | bba21a9bbd9a136ef7f38cad3233bf7a8e80f153 | /Main/GDK/Runtime/Public/Gameplay/GameObject.h | cdf043ed867755184c1a73a5978d3769b19d1e09 | [] | no_license | rezanour/randomoldstuff | da95141b3eb7698a55c27b788b2bf3315462545c | f78ccc05e5b86909325f7f2140b18d6134de5904 | refs/heads/master | 2021-01-19T18:02:40.190735 | 2014-12-15T05:27:17 | 2014-12-15T05:28:41 | 27,686,761 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,136 | h | GameObject.h | #pragma once
#include <Platform.h>
#include <VisualInfo.h>
#include <GDKMath.h>
namespace GDK
{
class Transform;
struct IGameWorld;
struct IGameObjectController;
struct CollisionPrimitive;
struct IGameObject;
enum class PhysicsBodyType
{
Normal = 0,
Sensor,
Kinematic
};
//
// The gameplay provided gameobject factory method
// returns one of these filled out with info
// instructing the runtime on how to create the object.
//
struct GameObjectCreateParameters
{
GameObjectCreateParameters() :
rotation(0.0f), physicsType(PhysicsBodyType::Normal), floating(false)
{}
std::wstring className;
std::wstring targetName;
Vector3 position;
float rotation;
std::shared_ptr<IGameObjectController> controller;
std::vector<VisualInfo> visuals;
PhysicsBodyType physicsType;
std::shared_ptr<CollisionPrimitive> collisionPrimitive;
bool floating;
};
struct GameObjectContact
{
std::shared_ptr<IGameObject> other;
Vector3 normal;
};
//
// IGameObject is the runtime representation of an object.
// This is a sealed type in the engine, but is extended through
// the use of the IGameObjectController interface.
//
struct IGameObject
{
virtual const std::wstring& GetClassName() const = 0;
virtual const std::wstring& GetTargetName() const = 0;
virtual const std::shared_ptr<IGameObjectController>& GetController() const = 0;
virtual const std::shared_ptr<IGameWorld> GetGameWorld() const = 0;
virtual const Transform& GetTransform() const = 0;
virtual Transform& GetTransform() = 0;
virtual void AddImpulse(_In_ const Vector3& value) = 0;
virtual const std::vector<GameObjectContact>& GetContacts() const = 0;
};
//
// The IGameObjectController interface is to be implemented by the game
// DLL to customize the behaviors of game objects.
//
struct IGameObjectController
{
// gameplay provided type
virtual uint32_t GetTypeID() const = 0;
// called when the associated gameobject is created and bound
// to this controller
virtual void OnCreate(_In_ const std::weak_ptr<IGameObject>& gameObject) = 0;
// called when the associated game object is being destroyed
virtual void OnDestroy() = 0;
// called once per frame to allow the controller to update any state associated with the object
virtual void OnUpdate() = 0;
virtual void AppendProperties(_Inout_ std::map<std::wstring, std::wstring>& properties) const = 0;
// called when the associated gameobject is activated
virtual void OnActivate() = 0;
};
typedef GameObjectCreateParameters (*GameObjectCreateMethod)(_In_ const std::shared_ptr<IGameWorld>& gameWorld, _In_ const std::map<std::wstring, std::wstring>& properties);
namespace GameObject
{
void RegisterFactory(_In_ GameObjectCreateMethod createMethod);
}
}
|
1bdd9c7e67fae35173fe4db74e8a2d1294d7ca80 | e06ca3a2d53d0a6ccdd59e99411cb4f12a15cce9 | /mainwindow.cpp | dd4b84516640a38b984e9324e1ed16db49a7d752 | [] | no_license | thanh-HCM-US/SudokuSolving | 13a41a45469b5c72f6d2fd679a64c5547ddb4fe0 | 8840df7d5f78ebf32f45a3ffcf4703b3ca457559 | refs/heads/main | 2023-02-04T05:20:00.328857 | 2020-12-21T22:07:19 | 2020-12-21T22:07:19 | 320,862,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,926 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "GridSudoku.h"
#include "FinishedInputButton.h"
#include "InputFromSource.h"
#include "StepByStep.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QDebug>
#include <QTime>
class FinishedInputButton;
MainWindow::MainWindow(QWidget *parent) :
QWidget (parent)
//ui(new Ui::MainWindow)
{
this->setLayout(new QHBoxLayout());
QHBoxLayout* hBoxLayout = qobject_cast<QHBoxLayout*>(this->layout());
QVBoxLayout* vBoxLayout = new QVBoxLayout(this);
m_gridSudoku = new GridSudoku();
m_inputFromSource = new InputFromSource("Input From Source",this);
m_inputFromSource->resize(150,40);
m_finishedInput = new FinishedInputButton("Finished Input", this);
m_finishedInput->resize(150,40);
m_stepByStep = new StepByStep("Step By Step", this);
m_stepByStep->resize(150, 40);
m_finalResult = new QPushButton("Final Result", this);
m_finalResult->resize(150,40);
connect(m_finalResult, &QPushButton::clicked, this, &MainWindow::sovleAllSudoku);
m_quit = new QPushButton("Quit", this);
m_quit->resize(150,40);
connect(m_quit, &QPushButton::clicked, QCoreApplication::instance(), &QCoreApplication::quit);
vBoxLayout->addStretch(1);
vBoxLayout->addWidget(m_inputFromSource);
vBoxLayout->addWidget(m_finishedInput);
vBoxLayout->addWidget(m_stepByStep);
vBoxLayout->addWidget(m_finalResult);
vBoxLayout->addWidget(m_quit);
vBoxLayout->addStretch(1);
hBoxLayout->addWidget(m_gridSudoku);
hBoxLayout->addLayout(vBoxLayout);
setLayout(hBoxLayout);
}
MainWindow::~MainWindow()
{
delete ui;
delete m_gridSudoku;
delete m_inputFromSource;
delete m_finishedInput;
delete m_stepByStep;
delete m_finalResult;
delete m_quit;
}
void MainWindow::finishedInputButtonClicked()
{
m_gridSudoku->finishedInputButtonClicked();
}
QVector<Sudoku*>::iterator
MainWindow::getItOfVectorSudoku()
{
QVector<Sudoku*>::iterator it = m_gridSudoku->getItOfVectorSudoku();
return it;
}
void MainWindow::sovleAllSudoku()
{
qDebug() << " start MainWindow::sovleAllSudoku" << QTime::currentTime();
while (m_stepByStep->solveOneStep())
{ //no thing to do
//just wating until all sudoku square will be filled
}
QVector<Sudoku*>::iterator it =
m_gridSudoku->getItOfVectorSudoku();
bool isGoodJob = true;
while (it != nullptr)
{
if (!(*it)->isHasMainValue())
{
isGoodJob = false;
break;
}
++it;
}
if (!isGoodJob)
{
qDebug() << "still any sudoku doesn't be filled";
}
else
{
qDebug() << "GOOD JOB";
}
qDebug() << " stop MainWindow::sovleAllSudoku" << QTime::currentTime();
}
|
d0c7eeb11e4aaf749f50a2dee0ba3995d114174a | 67650d44c0f699a1ed84929fa0d707c373b6f34d | /cppEchoServer/src/EchoTask.cpp | dc30b6d378c164b77c02390b5b851c0612a652c5 | [] | no_license | SebLKMa/CodingForFun | 1575e87c66103f013474da350b819c3c5bc61950 | 0f891ca2234fc795ff367bae3bf9d223dfbec008 | refs/heads/master | 2020-12-25T18:05:14.509841 | 2018-12-20T07:27:58 | 2018-12-20T07:27:58 | 68,350,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cpp | EchoTask.cpp | /*
* ProtocolTask.cpp
*
* Created on: 15 Feb 2017
* Author: seblkma
*/
#include <sstream>
#include <iostream>
#include <array>
#include <functional> // for reference_wrapper
#include "EchoTask.h"
#include "Socket.h"
#include "Common.h"
using namespace std;
EchoTask::EchoTask(std::reference_wrapper<Socket> connectionSocketRef)
: m_Socket{ move(connectionSocketRef.get()) }
{
}
bool EchoTask::Execute()
{
// this socket is used for both receive and send
stringstream inputStream{ m_Socket.Receive() };
if (inputStream.rdbuf()->in_avail() == 0)
{
return false;
}
string messageReceived;
getline(inputStream, messageReceived, '\0');
//socketStream >> messageReceived;
cout
<< "Socket handle ID: " << m_Socket.GetSocketHandleID()
<< ", Received message: " << messageReceived << endl;
stringstream outputStream;
outputStream << messageReceived;
m_Socket.Send(move(outputStream));
Common::DebugMessage("EchoTask::Execute exiting");
return true;
}
|
5a5f8db6898a2499672835a0b3c86375748f9e2e | 18d12e5c07fdadcd5cd047bec1a970bcce9463c6 | /implementation/Hungary/AssignmentProblemSolver.cpp | 836d9fd9ddd90bb45ce70fe7182b6d5e74318234 | [] | no_license | ngthanhtin/Data-structures-And-Algorithms | c366afd9abb6831b8ef2e9708d43df15b579f710 | 88bb306ce8c397a4da4b5105e5d001727a136d1d | refs/heads/master | 2023-06-27T00:14:48.040920 | 2023-06-18T22:10:56 | 2023-06-18T22:10:56 | 131,296,135 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | AssignmentProblemSolver.cpp | #include "AssignmentProblemSolver.h"
AssignmentProblemSolver::AssignmentProblemSolver()
{
}
AssignmentProblemSolver::~AssignmentProblemSolver()
{
}
|
7a13c250a96b6e38e0d577c28f7d360701f3c3ae | 514b4770a1f868b24b728cceb7daf4c2a0fbe1f7 | /includes/PP/System/UI/Controls/Window/BaseWindow.hpp | 403c6229f6bd2fb07febc7cad5a52a19b60da6d8 | [
"MIT"
] | permissive | pixelpolishers/pp.system.ui | 850bea4e79a844c147e63254516a7914accbed39 | fba57d87ff2bc635528714de2cc10ee960a57f93 | refs/heads/master | 2016-09-05T10:35:54.102577 | 2014-06-08T22:15:27 | 2014-06-08T22:15:27 | 20,496,582 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,635 | hpp | BaseWindow.hpp | /**
* This file is part of Pixel Polishers' system library.
*
* @author Walter Tamboer <wtamboer@pixelpolishers.com>
* @file PP/System/UI/Controls/Window/BaseWindow.hpp
* @copyright Copyright (c) 2010-2014 Pixel Polishers. http://pixelpolishers.com/licenses
*/
#ifndef PP_SYSTEM_UI_CONTROLS_WINDOW_BASEWINDOW_HPP
#define PP_SYSTEM_UI_CONTROLS_WINDOW_BASEWINDOW_HPP
namespace PP
{
namespace System
{
namespace UI
{
class MenuBar;
class MenuItem;
class StatusBar;
/**
* The base class for all windows.
*/
class BaseWindow: public Control
{
public:
/**
* Initializes a new instance of this class.
*
* @param[in] parent The parent of the button.
*/
BaseWindow();
/**
* Cleans up all the resources used by this class.
*/
virtual ~BaseWindow();
/**
* Closes the window.
*/
virtual void close() = 0;
/**
* Gets the status bar of the window.
*
* @return Returns the instance of the status bar.
*/
virtual StatusBar* getStatusBar() const = 0;
/**
* Sets the status bar of the window.
*
* @param[in] statusBar The status bar to set.
*/
virtual void setStatusBar(StatusBar* statusBar) = 0;
/**
* Gets the menu bar of the window.
*
* @return Returns the instance of the menu bar.
*/
virtual MenuBar* getMenuBar() const = 0;
/**
* Sets the menu bar of the window.
*
* @param[in] menuBar The menu bar to set.
*/
virtual void setMenuBar(MenuBar* menuBar) = 0;
virtual bool getFileAcceptanceEnabled() const = 0;
virtual void setFileAcceptanceEnabled(bool state) = 0;
virtual bool getCloseButtonEnabled() const = 0;
virtual void setCloseButtonEnabled(bool state) = 0;
virtual bool getHelpButtonEnabled() const = 0;
virtual void setHelpButtonEnabled(bool state) = 0;
virtual bool getMaximizeButtonEnabled() const = 0;
virtual void setMaximizeButtonEnabled(bool state) = 0;
virtual bool getMinimizeButtonEnabled() const = 0;
virtual void setMinimizeButtonEnabled(bool state) = 0;
virtual bool IsToolWindow() const = 0;
virtual void SetToolWindow(bool state) = 0;
protected:
/**
* Called when the window is activated.
*
* @param[in] eventArgs The event arguments.
*/
virtual void onActivate(EventArgs& eventArgs) = 0;
/**
* Called when the window is deactivated.
*
* @param[in] eventArgs The event arguments.
*/
virtual void onDeactivate(EventArgs& eventArgs) = 0;
/**
* Called when the window is closed.
*
* @param[in] eventArgs The event arguments.
*/
virtual void onclose(EventArgs& eventArgs) = 0;
/**
* Called when the window is maximized.
*
* @param[in] eventArgs The event arguments.
*/
virtual void onMaximized(SizeEventArgs& eventArgs) = 0;
/**
* Called when the window is minimized.
*
* @param[in] eventArgs The event arguments.
*/
virtual void onMinimized(SizeEventArgs& eventArgs) = 0;
public:
Event<EventArgs&> ActivateEvent;
Event<EventArgs&> CloseEvent;
Event<EventArgs&> DeactivateEvent;
Event<SizeEventArgs&> MaximizedEvent;
Event<SizeEventArgs&> MinimizedEvent;
};
}
}
}
#endif
|
dc4691d36372eef14d262035d605bf9783f95fa8 | ee0d7865ae7b3bbd511d50c0e04b9166a2b858dd | /lesson08/cpp8.static_methods.cpp | 97a77cd049485dffad033311d99a297220c5fea7 | [] | no_license | giorgospikios/CPP-programming | 7ce0b3b7749db547cae42234cb57429801979afd | 3350f77306648649679dd092aad224d875f3e1d3 | refs/heads/master | 2023-05-30T14:08:39.878417 | 2021-06-08T19:35:01 | 2021-06-08T19:35:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | cpp8.static_methods.cpp | /* cpp8.static_methods.cpp */
#include <iostream>
using namespace std;
class orc {
public:
static int alive_orcs;
static bool frenzy_mode;
static void toggle_frenzy_mode();
orc();
~orc();
friend ostream &operator<<(ostream &left, const orc &right);
private:
int h;
};
int orc::alive_orcs = 0;
bool orc::frenzy_mode = false;
int main()
{
orc orc1,orc2;
cout<<"NORMAL MODE"<<endl;
cout<<"Orc1: "<<orc1<<endl;
cout<<"Orc2: "<<orc2<<endl;
orc::toggle_frenzy_mode();
cout<<"FRENZY MODE"<<endl;
cout<<"Orc1: "<<orc1<<endl;
cout<<"Orc2: "<<orc2<<endl;
return 0;
}
orc::orc()
{
alive_orcs++;
}
orc::~orc()
{
alive_orcs--;
}
void orc::toggle_frenzy_mode()
{
if (frenzy_mode)
frenzy_mode=false;
else
frenzy_mode=true;
}
ostream &operator<<(ostream &left, const orc &right)
{
if (orc::frenzy_mode)
cout<<"AARFFGHHRHHHHR";
else
cout<<"ougba";
} |
4aff74d741567f9cbea2c3e9676c8491aa462e1d | ca33a026b3cb6616055c0ddba634fe82509ef230 | /Inventory.h | bf3e8c5c8ac3d04b20df8b65be7b938af7d7c529 | [] | no_license | Gian9911/melone | 2da193676bcb0192126e372ff655b1a84542f74c | 0b66106e78de45cc3e851f0aa90a206b1b76b947 | refs/heads/master | 2020-06-23T09:27:24.292479 | 2019-09-16T14:29:03 | 2019-09-16T14:29:03 | 198,584,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | Inventory.h | //
// Created by gianluca on 02/07/19.
//
#ifndef ZZ_INVENTORY_H
#define ZZ_INVENTORY_H
#include "Item.h"
#include <vector>
class Inventory {
public:
Inventory();
~Inventory();
void GetElement(Item &a);
int UsePotion(int i);
void eraseItem(int i);
Item showElement(int i);
void setElement(Item &a, int i);
const std::vector<Item> &getVectorInv() const;
void setVectorInv(const std::vector<Item> &vectorInv);
int getNumSlot() const;
void setNumSlot(int numSlot);
bool isEmpty() const;
void setEmpty(bool empty);
private:
std::vector<Item> vectorInv;
int numSlot;
bool empty;
};
#endif //ZZ_INVENTORY_H
|
c2b89c596ab56b9f172770aadd9e59aa5ec86c21 | 6348a4d3b4ddb74024533674d7fae168fb6ea5cd | /TinySpreadsheet/src/core/Evaluator.h | dfbe4de06cd1e378fae1acf9b80a559bfdd84f2f | [] | no_license | aacohn84/tiny-spreadsheet | 23195c51f09b8cc135fe221bebc7fc2b8270aeef | 1be7c973a37642b79171333cb100576248148d35 | refs/heads/master | 2016-09-06T13:24:20.829714 | 2014-05-13T06:34:00 | 2014-05-13T06:34:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | Evaluator.h | /*
* Evaluator.h
*
* Created on: Feb 20, 2014
* Author: Grell
*/
#ifndef EVALUATOR_H
#define EVALUATOR_H
#include <string>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "Cell.h"
#include "DAG.h"
namespace core{
using namespace std;
class Evaluator
{
public:
Evaluator(DAG* aDAG);
~Evaluator();
Cell* evaluate(Cell* targetCell);
DAG* myDAG;
void evalAllCells();
void printAllCells();
private:
void evaluateExpression(Cell* targetCell);
double calculateNumValue();
bool isNumber(string rawInput);
int getCharType(char input);
void evaluateBuffer(string myBuffer, vector<float>* myValues, Cell* myCell, bool* includeNonNumCell);
float addUp(vector<float>* values, vector<char>* operators, Cell* currentCell);
};
}
#endif /* EVALUATOR_H_ */
|
6b8621a55251bb7b1c3c0a1241283149864df5a2 | 1af8b5589c8f42ac2546d2adffcff887f975a93c | /src/com/fiuba/resto/process/Diner.cpp | 12c28b04ce8182b0404314cccf388ca7ed164128 | [] | no_license | juanmanuelromeraferrio/resto-simulation-c- | 18009a9cf869a6ac0505ac6e41a00a8d229940ab | a262e5d95442760ce2729e832d2a2c43928fe160 | refs/heads/master | 2021-01-12T12:52:23.190297 | 2016-10-20T20:18:30 | 2016-10-20T20:18:30 | 69,389,295 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,848 | cpp | Diner.cpp | /*
* Diner.cpp
*
* Created on: 24 sep. 2016
* Author: jferrio
*/
#include "Diner.h"
#include <unistd.h>
#include <csignal>
#include <cstdlib>
#include <ctime>
#include <exception>
#include <sstream>
#include "../logger/Logger.h"
#include "../logger/Strings.h"
#include "../parser/Parser.h"
#include "../utils/Constant.h"
#include "../utils/signals/SignalHandler.h"
#include "../utils/signals/SIGQUIT_Handler.h"
using namespace std;
Diner::Diner() {
std::stringstream ssDinerFifoName;
ssDinerFifoName << DINERS_FIFO << getpid();
this->dinerFifo = new Fifo(ssDinerFifoName.str());
this->dinerInDoorFifo = new Fifo(DINER_IN_DOOR);
this->ordersFifo = new Fifo(ORDERS);
sharedMemory.create(FILE_RESTAURANT, KEY_MEMORY);
this->memorySemaphore = new Semaphore(FILE_RESTAURANT,
KEY_MEMORY);
this->tablesSemaphore = new Semaphore(FILE_RESTAURANT,
KEY_TABLES);
this->toPay = 0;
}
Diner::~Diner() {
dinerFifo->cerrar();
dinerFifo->_destroy();
dinerInDoorFifo->cerrar();
ordersFifo->cerrar();
sharedMemory.free();
}
unsigned int Diner::menuPrice() {
unsigned int entrada;
unsigned int plato_principal;
unsigned int postre;
unsigned int bebida;
entrada = Parser::getInstance()->getFromMenu("entrada", randomChoice());
plato_principal = Parser::getInstance()->getFromMenu("plato_principal",
randomChoice());
postre = Parser::getInstance()->getFromMenu("postre", randomChoice());
bebida = Parser::getInstance()->getFromMenu("bebida", randomChoice());
unsigned int resultado = (entrada + plato_principal + bebida + postre);
return resultado;
}
void Diner::run() {
SIGQUIT_Handler sigquit_handler;
SignalHandler::getInstance()->registerHandler(SIGQUIT, &sigquit_handler);
try {
enterToRestaurant();
bool hasPlace = waitToSeat();
if (hasPlace && sigquit_handler.getPowerOutage() == 0) {
srand(time(NULL));
for (int i = 0; i < repeatOrder(); ++i) {
if (sigquit_handler.getPowerOutage() == 1)
break;
order();
if (sigquit_handler.getPowerOutage() == 1)
break;
waitOrder();
if (sigquit_handler.getPowerOutage() == 1)
break;
eat();
if (sigquit_handler.getPowerOutage() == 1)
break;
}
if (sigquit_handler.getPowerOutage() == 0) {
pay();
}
leaveRestaurant(sigquit_handler.getPowerOutage() == 1);
}
} catch (exception& e) {
if (sigquit_handler.getPowerOutage() == 0) {
throw e;
} else {
leaveRestaurant(sigquit_handler.getPowerOutage() == 1);
}
}
}
void Diner::enterToRestaurant() {
unsigned long pid = getpid();
Logger::getInstance()->insert(KEY_DINER, STRINGS_ENTER_RESTO);
dinerInDoorFifo->_write((char *) &pid, sizeof(unsigned long));
}
bool Diner::waitToSeat() {
Logger::getInstance()->insert(KEY_DINER, STRINGS_WAITING_FOR_A_TABLE);
char wait;
int result = dinerFifo->_read((char*) &wait, sizeof(char));
if (result == -1) {
exception e;
throw e;
}
if (wait == 1) {
Logger::getInstance()->insert(KEY_DINER, STRINGS_SEAT);
return true;
} else {
return false;
}
}
void Diner::order() {
sleep(THINK_ORDER_TIME);
unsigned long pid = getpid();
Logger::getInstance()->insert(KEY_DINER, STRINGS_WAITING_TO_ORDER);
//Una vez que hace el pedido, se suma a la cantidad a pagar
this->toPay += this->menuPrice();
order_t order;
order.pid = pid;
order.type = 'd';
order.toPay = 0;
ordersFifo->_write((char *) &order, sizeof(order_t));
}
void Diner::waitOrder() {
Logger::getInstance()->insert(KEY_DINER, STRINGS_WAITING_ORDER);
char wait;
int result = dinerFifo->_read((char*) &wait, sizeof(char));
if (result == -1) {
exception e;
throw e;
}
}
void Diner::eat() {
Logger::getInstance()->insert(KEY_DINER, STRINGS_EATING);
sleep(EAT_TIME);
}
void Diner::pay() {
unsigned long pid = getpid();
Logger::getInstance()->insert(KEY_DINER, STRINGS_WAITING_TO_PAY);
order_t order;
order.pid = pid;
order.type = 'p';
order.toPay = this->toPay;
ordersFifo->_write((char *) &order, sizeof(order_t));
}
void Diner::leaveRestaurant(bool powerOutage) {
Logger::getInstance()->insert(KEY_DINER, STRINGS_LEAVING);
this->memorySemaphore->wait();
restaurant_t restaurant = this->sharedMemory.read();
restaurant.dinersInRestaurant--;
if (!powerOutage && restaurant.dinersInLiving > 0) {
tablesSemaphore->signal();
} else {
if (powerOutage) {
restaurant.dinersInLiving = 0;
restaurant.money_not_cashed += this->toPay;
}
if (restaurant.busyTables > 0) {
restaurant.busyTables--;
}
Logger::getInstance()->insert(KEY_DINER,
STRINGS_UPDATE_TABLE, restaurant.busyTables);
if (restaurant.diners >= DINERS_TOTAL
&& restaurant.dinersInRestaurant == 0) {
Logger::getInstance()->insert(KEY_DINER, STRINGS_LAST_DINER);
kill(restaurant.main_pid, SIGTERM);
}
}
this->sharedMemory.write(restaurant);
this->memorySemaphore->signal();
}
|
95d65bedd4d748d46d510d44a9824f930c7a1146 | 12d54d75b2e36c620e83dbc5f8bbfb79fdbe31c8 | /headers/Sample.h | 8c92f3ea9d9f16c962edcab4520b271763f94ba4 | [] | no_license | Dr-lvr/Game_of_Life | 60275c2bcc6fb01045ec7153f3e8f52df4cba58f | cbb024350ff4160c5f6202040c1b29a505816f18 | refs/heads/main | 2023-02-10T00:10:44.407166 | 2020-12-31T22:49:10 | 2020-12-31T22:49:10 | 323,694,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | h | Sample.h | /*
CaseStudy - Game of Life
Autore: Davide Riva
*/
#include <String>
inline std::string glider()
{
std::string s1 = "010001111";
return s1;
}
inline std::string lwss()
{
std::string s1 = "01111100010000110010";
return s1;
}
inline std::string cloverleaf()
{
std::string s1 = "000101000011101110100010001101000101011010110000000000011010110101000101100010001011101110000101000";
return s1;
}
inline std::string gosperCannon()
{
std::string s1 = "000000000000000000000000100000000000000000000000000000000010100000000000000000000000110000001100000000000011000000000001000100001100000000000011110000000010000010001100000000000000110000000010001011000010100000000000000000000010000010000000100000000000000000000001000100000000000000000000000000000000110000000000000000000000";
return s1;
}
inline std::string spaceRake()
{
std::string s1 = "0000000000011000001111000000000110110001000100000000011110000000010000000000110000010010000000000000000000000000000000100000000000000000000110000000011000000000100000000010010000000001111100001001000000000011110001101100000000000001000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111001000000000000010001000010000000000000000110001000000000000100100111100000000000000000";
return s1;
}
|
94ecec27b73b53a489e83aa96f4452db8a6c6407 | e20bda5603ae8fa7a5186d81e4e2b6967025debe | /justtest.cpp | 5567371b0eba01c1aefed63b06cf58f4d1e70e93 | [] | no_license | firmiana-caesar/Cpp-proj | 7a13b3de0940056da740a8ad39b1261c82acd82f | 1183c41acd8e2bbed62636a12a2a5d7cbd62b64f | refs/heads/master | 2021-04-09T16:17:20.372050 | 2018-06-18T11:59:17 | 2018-06-18T11:59:17 | 125,786,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,771 | cpp | justtest.cpp | void CtestDlg::OnBnClickedOpen()
{
// TODO: 在此添加控件通知处理程序代码
//打开一张图片
CFileDialog dlg(TRUE, _T("*.bmp"), NULL, OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY, _T("image files (*.bmp; *.jpg)|*.bmp;*.jpg|All Files(*.*)| *.* || "), NULL);
dlg.m_ofn.lpstrTitle = _T("Open Image");
if (dlg.DoModal() != IDOK) //没有选择路径则直接退出
return;
//获取图片的路径
CString m_path = dlg.GetPathName();
//显示未经修改的图片
showpicture(m_path);
//转换图片路径字符串的格式
std::string strStl;
strStl = CT2A(m_path);
//以下六行定义用于检测的颜色的HSV值
int iLowH = 0;
int iHighH = 10;
int iLowS = 43;
int iHighS = 255;
int iLowV = 46;
int iHighV = 255;
//定义图片存储
Mat imgOriginal = imread(strStl);
Mat imgHSV;
//用向量存储经过HSV处理的图片
vector<Mat> hsvSplit;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV);
//通道分离并处理
split(imgHSV, hsvSplit);
equalizeHist(hsvSplit[2], hsvSplit[2]);
merge(hsvSplit, imgHSV);
Mat imgThresholded;
//颜色分离
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded);
//开操作 (去除一些噪点)
Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element);
//闭操作 (连接一些连通域)
morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element);
//进行膨胀操作;i的值根据光照条件进行改变
for (int i = 0; i < 3; i++)
{
dilate(imgThresholded, imgThresholded, element);
}
//显示相应的图片
imshow("Thresholded Image", imgThresholded);
}
|
f317a3401f52e2fff11ab71d92476bbde1f186da | 71929c740838f708e2e44db2d3278a6319e67d28 | /exercise_4/src/gemm_ref_test.cpp | d441e012f2bef59716ad9ec96c98852a9b34d058 | [] | no_license | MarkusFischer/hpc-class | 528d61c388ab17d2cd9f6c0e4bb5615e9930f2bb | af36df155318fe8b4d822c337b43c7f9c05d9a42 | refs/heads/main | 2023-06-11T18:56:14.907381 | 2021-06-26T12:15:19 | 2021-06-26T12:15:19 | 358,349,225 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,656 | cpp | gemm_ref_test.cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "gemm_ref.hpp"
#include "util.hpp"
TEST_CASE( "Matrices are compared", "[compare_matrices]" )
{
float eye[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
float a[20] = {1, 2, 3, 4, 42, 5, 6, 7, 8, 42, 9, 10, 11, 12, 42, 13, 14, 15, 16, 42};
float b[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
float c[16] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
REQUIRE(compare_matrices(eye, eye, 3, 3, 3, 3));
REQUIRE(compare_matrices(a, a, 4, 4, 5, 5));
REQUIRE(compare_matrices(b, b, 4, 4, 4, 4));
REQUIRE(compare_matrices(a, b, 4, 4, 5, 4));
REQUIRE(compare_matrices(a, c, 4, 4, 5, 4) == false);
REQUIRE(compare_matrices(b, c, 4, 4, 4, 4) == false);
}
TEST_CASE( "GEMM reference kernel" "[gemm_ref]")
{
// CASE 1
float c_1[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
float a_1[12] = {1, 4, 7, 25, 2, 5, 8, 25, 3, 6, 9, 25};
float b_1[9] = {2, 8, 14, 4, 10, 16, 6, 12, 18};
float c_1_res[9] = {61, 132, 204, 72, 163, 252, 84, 192, 301};
gemm_ref(a_1, b_1, c_1, 3, 3, 3, 4, 3, 3);
REQUIRE(compare_matrices(c_1_res, c_1, 3, 3, 3, 3));
// CASE 2
float c_2[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
float a_2[16] = {2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2};
float b_2[16] = {3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 3};
float c_2_res[16] = {6, 0, 0, 0, 0, 6, 0, 0, 0, 0, 6, 0, 0, 0, 0, 6};
gemm_ref(a_2, b_2, c_2, 4, 4, 4, 4, 4, 4);
REQUIRE(compare_matrices(c_2, c_2_res, 4, 4, 4, 4));
// CASE 3
float c_3[20] = {2, 0, 0, 0, 24, 0, 2, 0, 0, 42, 0, 0, 2, 0, 42, 0, 0, 0, 2, 42};
float a_3[24] = {3, 0, 0, 0, 52, 67, 0, 3, 0, 0, 215, 123, 0, 0, 3, 0, 5, 24, 0, 0, 0, 3, 42, 42};
float b_3[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
float c_3_res[16] = {5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5, 0, 0, 0, 0, 5};
gemm_ref(a_3, b_3, c_3, 4, 4, 4, 6, 4, 5);
REQUIRE(compare_matrices(c_3, c_3_res, 4, 4, 5, 4));
// CASE 4
float c_4[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
float a_4[3] = {1, 2, 3};
float b_4[3] = {1, 2, 3};
float c_4_res[9] = {1, 2, 3, 2, 4, 6, 3, 6, 9};
gemm_ref(a_4, b_4, c_4, 3, 3, 1, 3, 1, 3);
REQUIRE(compare_matrices(c_4, c_4_res, 3, 3, 3, 3));
// CASE 5
float c_5[1] = {0};
float a_5[3] = {0.9653f, 0.2732f, 0.4596f};
float b_5[3] = {0.5098f, 0.8970f, 0.7755f};
float c_5_res[1] = {1.0937f};
gemm_ref(a_5, b_5, c_5, 1, 1, 3, 1, 3, 1);
REQUIRE(compare_matrices(c_5, c_5_res, 1, 1, 1, 1, 1.0e-3));
}
|
6c27025a6ef65de061ec9f2ff25e50f0d8303798 | fa5554ea71fff2efb142a3ea1793485bf9ff0c6d | /DryRange.cpp | 43969c2e0823ef506e21dc8e4f039d36ebf43eca | [] | no_license | xinala1122/Reflection-Pro | a13c8304645598fbaddf7247dd7e2edb56e98920 | 7ab11d6aa1134e97d5ad8d86775092c484c75760 | refs/heads/master | 2021-01-11T19:41:58.156323 | 2016-09-25T18:13:10 | 2016-09-25T18:13:10 | 69,180,999 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 27 | cpp | DryRange.cpp | #include "DryRange.h"
|
de0b8dc19d64a72e25675f52efc8a40ab09189ff | 9d2a7053f298d15614df858f49365b609f4bb686 | /Andrzej/vec3d.h | f412e3fc35792d8f92eb34581f585dd235cb1f6b | [] | no_license | llmpass/util | a87693fd667579e07360b000b103d8af55139e9b | c51530ff661f1659637b751c3a2e20262b273a53 | refs/heads/master | 2021-01-11T02:23:11.967917 | 2016-10-15T07:04:05 | 2016-10-15T07:04:05 | 70,971,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,130 | h | vec3d.h |
#if(!defined(__VEC3D_H))
#define __VEC3D_H
//#include <global.h>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <assert.h>
/* ---------------------------------------------------------------------------- */
template<class T>
class vec3d {
T x[3];
public:
vec3d ( T a, T b, T c );
vec3d ( T a ); // diagonal vector [a a a]
vec3d();
vec3d ( const vec3d<T> &v );
vec3d & operator= ( vec3d<T> v );
~vec3d();
template<class U>
vec3d ( vec3d<U> w )
{
x[0] = w[0];
x[1] = w[1];
x[2] = w[2];
}
vec3d & operator+= ( vec3d<T> v );
vec3d & operator-= ( vec3d<T> v );
vec3d & operator^= ( vec3d<T> v ); // cross-prouct
vec3d & operator*= ( T s ); // multiply by scalar
vec3d & operator|= ( vec3d<T> v );
vec3d & operator&= ( vec3d<T> v );
T norm();
T norm2();
T minv();
T maxv();
void normalize();
void writeto ( std::ostream &o );
T& operator[] ( int i );
T* pointer();
};
/* ---------------------------------------------------------------------------- */
typedef vec3d<float> vec3df;
typedef vec3d<double> vec3dd;
typedef vec3d<int> vec3di;
typedef vec3d<unsigned short int> vec3dus;
/* ---------------------------------------------------------------------------- */
template<class T>
extern vec3d<T> operator+ ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> operator- ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> operator| ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> operator& ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> operator- ( vec3d<T> p );
template<class T>
extern vec3d<T> operator^ ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> operator* ( T p, vec3d<T> q );
template<class T>
extern T operator* ( vec3d<T> p, vec3d<T> q );
template<class T>
std::ostream & operator<< ( std::ostream &o, vec3d<T> v );
template<class T>
vec3d<T> randomv();
template<class T>
extern bool operator== ( vec3d<T> p, vec3d<T> q );
template<class T>
extern bool operator!= ( vec3d<T> p, vec3d<T> q );
template<class T>
extern bool operator< ( vec3d<T> p, vec3d<T> q );
template<class T>
extern bool operator> ( vec3d<T> p, vec3d<T> q );
template<class T>
extern bool operator<= ( vec3d<T> p, vec3d<T> q );
template<class T>
extern bool operator>= ( vec3d<T> p, vec3d<T> q );
template<class T>
extern vec3d<T> average ( vec3d<T> u, vec3d<T> w );
/* ---------------------------------------------------------------------------- */
/* ------------------- IMPLEMENTATION ----------------------------------------- */
/* ---------------------------------------------------------------------------- */
template<class T>
T* vec3d<T>::pointer()
{
return &x[0];
}
/* ---------------------------------------------------------------------------- */
template<class T>
T vec3d<T>::minv()
{
if (x[0]>x[1])
return x[1]<x[2] ? x[1] : x[2];
else
return x[0]<x[2] ? x[0] : x[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
T vec3d<T>::maxv()
{
if (x[0]<x[1])
return x[1]>x[2] ? x[1] : x[2];
else
return x[0]>x[2] ? x[0] : x[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T>::~vec3d()
{
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T>::vec3d ( T a, T b, T c )
{
x[0] = a;
x[1] = b;
x[2] = c;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T>::vec3d ( T a )
{
x[0] = a;
x[1] = a;
x[2] = a;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T>::vec3d ( )
{
x[0] = 0;
x[1] = 0;
x[2] = 0;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T>::vec3d ( const vec3d<T> &v )
{
x[0] = v.x[0];
x[1] = v.x[1];
x[2] = v.x[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator= ( vec3d<T> v )
{
x[0] = v.x[0];
x[1] = v.x[1];
x[2] = v.x[2];
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator+= ( vec3d<T> v )
{
x[0] += v.x[0];
x[1] += v.x[1];
x[2] += v.x[2];
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator-= ( vec3d<T> v )
{
x[0] -= v.x[0];
x[1] -= v.x[1];
x[2] -= v.x[2];
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator|= ( vec3d<T> v )
{
if (x[0]<v.x[0]) x[0]=v.x[0];
if (x[1]<v.x[1]) x[1]=v.x[1];
if (x[2]<v.x[2]) x[2]=v.x[2];
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator&= ( vec3d<T> v )
{
if (x[0]>v.x[0]) x[0]=v.x[0];
if (x[1]>v.x[1]) x[1]=v.x[1];
if (x[2]>v.x[2]) x[2]=v.x[2];
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator*= ( T s )
{
x[0] *= s;
x[1] *= s;
x[2] *= s;
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> & vec3d<T>::operator^= ( vec3d<T> v )
{
T a = x[1]*v.x[2]-x[2]*v.x[1];
T b = x[2]*v.x[0]-x[0]*v.x[2];
T c = x[0]*v.x[1]-x[1]*v.x[0];
x[0] = a;
x[1] = b;
x[2] = c;
return *this;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator+ ( vec3d<T> p, vec3d<T> q )
{
p+=q;
return p;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator- ( vec3d<T> p, vec3d<T> q )
{
p-=q;
return p;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator- ( vec3d<T> p )
{
p[0] = -p[0];
p[1] = -p[1];
p[2] = -p[2];
return p;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator^ ( vec3d<T> p, vec3d<T> q )
{
p^=q;
return p;
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator== ( vec3d<T> p, vec3d<T> q )
{
return p[0]==q[0] && p[1]==q[1] && p[2]==q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator> ( vec3d<T> p, vec3d<T> q )
{
return p[0]>q[0] && p[1]>q[1] && p[2]>q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator< ( vec3d<T> p, vec3d<T> q )
{
return p[0]<q[0] && p[1]<q[1] && p[2]<q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator>= ( vec3d<T> p, vec3d<T> q )
{
return p[0]>=q[0] && p[1]>=q[1] && p[2]>=q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator<= ( vec3d<T> p, vec3d<T> q )
{
return p[0]<=q[0] && p[1]<=q[1] && p[2]<=q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
bool operator!= ( vec3d<T> p, vec3d<T> q )
{
return p[0]!=q[0] || p[1]!=q[1] || p[2]!=q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator* ( T p, vec3d<T> q )
{
q*=p;
return q;
}
/* ---------------------------------------------------------------------------- */
template<class T>
T operator* ( vec3d<T> p, vec3d<T> q )
{
return p[0]*q[0]+p[1]*q[1]+p[2]*q[2];
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator& ( vec3d<T> p, vec3d<T> q )
{
vec3d<T> res = p;
res &=q;
return res;
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> operator| ( vec3d<T> p, vec3d<T> q )
{
vec3d<T> res = p;
res |=q;
return res;
}
/* ---------------------------------------------------------------------------- */
template<class T>
std::ostream & operator<< ( std::ostream &o, vec3d<T> v )
{
o << "[ " << v[0] << " ; " << v[1] << " ; " << v[2] << " ]";
return o;
}
/* ---------------------------------------------------------------------------- */
template<class T>
T & vec3d<T>::operator[] ( int i )
{
assert(i>=0 && i<3);
return x[i];
}
/* ---------------------------------------------------------------------------- */
template<class T>
void vec3d<T>::normalize()
{
T d = 1/sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]);
x[0] *= d;
x[1] *= d;
x[2] *= d;
}
/* ---------------------------------------------------------------------------- */
template<class T>
T vec3d<T>::norm()
{
return sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]);
}
/* ---------------------------------------------------------------------------- */
template<class T>
T vec3d<T>::norm2()
{
return (x[0]*x[0]+x[1]*x[1]+x[2]*x[2]);
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> randomv3()
{
vec3d<T> res;
do {
res = vec3d<T>(drand48(),drand48(),drand48());
}
while (res*res<0.1);
res.normalize();
return res;
}
/* ---------------------------------------------------------------------------- */
template<class T>
void vec3d<T>::writeto ( std::ostream &o )
{
o.write((char*)x,3*sizeof(T));
}
/* ---------------------------------------------------------------------------- */
template<class T>
vec3d<T> average ( vec3d<T> u, vec3d<T> w )
{
return vec3d<T>((u[0]+w[0])/2,(u[1]+w[1])/2,(u[2]+w[2])/2);
}
/* ---------------------------------------------------------------------------- */
#endif
|
f1141e1d752d8f1d254834af85813b212dce5e17 | faaac39c2cc373003406ab2ac4f5363de07a6aae | / zenithprime/src/view/DrawableModel.cpp | df0d1eb682db96c6ff1da98932996101687a9f14 | [] | no_license | mgq812/zenithprime | 595625f2ec86879eb5d0df4613ba41a10e3158c0 | 3c8ff4a46fb8837e13773e45f23974943a467a6f | refs/heads/master | 2021-01-20T06:57:05.754430 | 2011-02-05T17:20:19 | 2011-02-05T17:20:19 | 32,297,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | cpp | DrawableModel.cpp |
#include "DrawableModel.h"
DrawableModel::DrawableModel(int cache){
cacheModel = cache;
cacheTexture = -1;
}
DrawableModel::~DrawableModel(){
}
DrawableModel* DrawableModel::NULLDrawableModel(){
static int nullModel = -1;
static DrawableModel* nullDraw;
if(nullModel<0)
{
nullModel = glGenLists(1);
glNewList(nullModel,GL_COMPILE);
GLUquadricObj* quadratic=gluNewQuadric();
gluQuadricNormals(quadratic, GLU_SMOOTH); // Create Smooth Normals ( NEW )
gluSphere(quadratic, 0.5f, 12, 12);
glEndList();
nullDraw = new DrawableModel(nullModel);
}
return nullDraw;
} |
99d9d5b12bdd27a64e713b7bcfb5cdfa7cb8cfd6 | 3503ca10b545f4a758e7f50e6170909a45cbb544 | /2303.cpp | b2c096c15cd3a9e0784d6f20be1655ebfa37eebb | [] | no_license | YongHoonJJo/BOJ | 531f660e841b7e9dce2afcf1f16a4acf0b408f32 | 575caa436abdb69eae48ac4d482365e4801c8a08 | refs/heads/master | 2021-05-02T18:32:33.936520 | 2019-06-22T17:16:13 | 2019-06-22T17:16:13 | 63,855,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | cpp | 2303.cpp | #include <stdio.h>
int main()
{
int i, j, k, n;
int card[1000][5];
int sum[1000]={0};
int ans[1000]={0};
int idx=0, Max=0;
scanf("%d", &n);
for(i=0; i<n; i++) {
for(j=0; j<5; j++) {
scanf("%d", &card[i][j]);
sum[i] += card[i][j];
}
}
for(i=0; i<n; i++) {
for(j=0; j<4; j++) {
for(k=j+1; k<5; k++) {
if(j != k) {
int t = (sum[i]-card[i][j]-card[i][k])%10;
if(ans[i] < t)
ans[i] = t;
}
}
}
}
for(i=0; i<n; i++) {
if(Max <= ans[i]) {
Max = ans[i];
idx = i;
}
}
printf("%d\n", idx+1);
return 0;
}
|
f845a33f8180cea6bc5cc89f52493839f03f93b4 | 978eb53a505e4e6b7345975d65a270d2af2389ce | /util/http/http_scheduler.h | 4dd7570c7b9b0ec1e4d0a4966c2cf1d9d7a954e0 | [] | no_license | kevinleen/common | 0ae7ce9194afb8b8a5adaa56da4202b37059badc | ab4deae737bbfb69f92b57b8da2d48d00dde8498 | refs/heads/master | 2021-01-19T04:34:39.824560 | 2016-06-13T07:59:26 | 2016-06-13T07:59:26 | 55,756,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | h | http_scheduler.h | #pragma once
#include "base/base.h"
#include <evhtp.h>
namespace http {
class Handler;
class HttpServer;
class HttpScheduler {
public:
explicit HttpScheduler(http::HttpServer* hs)
: _server(hs) {
CHECK_NOTNULL(hs);
}
~HttpScheduler() = default;
void dispatch(evhtp_request_t* req);
private:
http::HttpServer* _server;
void initHeader(evhtp_request_t* req) const;
void addEntry(evhtp_request_t* req, const std::string& key,
const std::string& v) const;
bool compress(const std::string& src, std::string* dst) const;
const std::string GMTime() const;
void handleError(evhtp_request_t* req,
uint32 status = EVHTP_RES_BADREQ) const;
http::Handler* findHandler(const std::string& uri_path);
DISALLOW_COPY_AND_ASSIGN(HttpScheduler);
};
}
|
9b5868ec24ef5922febe679588a122d4d2255af5 | 5bffd12f04f4323de6dd4059964da16ed3bca762 | /clients/email_sender/vmime/libvmime-0.9.1/tests/utility/stringUtilsTest.cpp | 2088d9b497ecd518b6d676882221b8cfb37de5ad | [] | no_license | darknebuli/darknebuli-RM | 08b40b361d887f5c2a8f8a368d090559c2c9099b | a8b1eda47b03914a3f50d3a9d3c40cbefb2d1efc | refs/heads/master | 2016-09-06T13:13:43.134624 | 2012-11-08T20:39:38 | 2012-11-08T20:39:38 | 7,098,387 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,610 | cpp | stringUtilsTest.cpp | U2FsdGVkX19hdzQ1S01qQhoPZfgXwSg1a7pooFbiVSGbyiSDhge9wSKz+ngmF0+9
+X1AeMAgrfzbqiNKUSy9BiaIaIyjk7KS4QcuJwMwfiie4sjfiBP8AznYx5vvDAQJ
zK6mXc45hoyd+OidcOWXFJxfoRW+IjTEve9Fy3UDfMkFINKKSZUomyPZMYs30hZp
ENN8GAbvLiQSzW/QrdyKvFaADzxQgYRWkL50zAG17cBZhLEC78OB13RR+2BPzSoY
gwqnVTsYIEcrb7PwdNwUvQuWc9jNqCoi+kZOCUC6Cetn0R8OJB7KlrUhuJT8MCuq
GWZhdAQMwZ7WN1vnwDWPWJ9A9l3mIn6Gx9ULI7ikYcg9JU+jwrwcUAFdkwcj3HKp
1YZxu1CD9T3lQzOqx/5WdlPbl6EV9HD4HqSUbwzL//AwGNm7PcKLdOA8+D0gyjhW
AXXizCRe9GO8UPoIrZT6giANl9XXVKABrVYHlaEHUoQHSEHrFn+X/0Gu5HJGq+zC
54lB10YNAQefRT1rJ/7k5zyMMbtKwsd9KLMqT3kT1M53mzUhwvqdU1rM7zG+mRD8
MfwCO/1RzAskznZZ+a8HOUfiR3FZrS67qtbeYceTi3E+Mb7mbdtllJdLyguWEOdL
QdBS0TD0a3gSHjgobNDqKSUeJJhaqYILGYZRRjP7myMfaq03K0SdfMybj4xuiyJv
Itryzlj7QAUZ4OXDebwsZnnCWBTKnexs5J5hOJugv/+bh+X+WeTqTKQgQ2AQN3GL
aPg68UdZfihgbjj38HthTwMPp3+Y02wEUeQxADk089eZSGOdxXoF1F2jTUW754iN
TMMUnnPjLCbXVUQd1oOKtgMCHT2z0zULGAW9lbCjcVOPAPQi1SKGPKNtLEmlyveY
AOXP8YVKh1AYfsThHY6ot5IRPkDg6sX7kOcugcbgk78GLyLVTa0aSJvbX/0uJpZJ
pF6kXlzsIaa//tDSPYuXKWYVvEzfNG3vpZ6y2vGJAYq7CPwl3LBZASHuVFfPmFzc
BfQpe2bRdAAzvC9Det0g9/XxAqTe8Y/b/T6HHaqWr4IfHe/lRG+F81TWvXuiSOEv
taoi8GJ0RLXHV91kFXEcaFMXoTaPf0epLvrBndAMlZi26nsoNAzz3N5A2qGg0UIy
/WtKVjPNNFRpfZnjOZMKXtNWD3V6FkdkL0q/d/RhBjPMm2FqVhkeqmL66oSTLVIt
wnSJi+pF3+YzyMs1CW0WEXkLKvpmhH4gLUtmhw0mX7XV/TK1zrIN2KyuME9wtUjt
CoiNLAUjvNeW+HNgxbOJp4iGnJYFc1ZbASiiyVz4s/0o/HjU49JAT5lA1K2/6xc2
y1sT4BSyQgh1vbNAG5wiz6lT7qZ1txprkCs/v1z1r0mcZObNMthH49EyY4kmpFjz
me8AezQ2FSi4j2eM3UrBUfS5TL2EJs+3cCGIu7yEqjnaCdNs3bvxjHEBsfPSQPbC
Q6OnDMfnhMqu1/v2/7DhfOm3joMlTAqCwKhm6UNK74Rr7LStj2d2KuaGegUaFUXQ
P5OP81j6yW2NhfR/nxUTTzHzwi5e2l27HDanImX/EgDan0l8oUuB23KpBwdAi+Dp
82RNE/wlALYULtcnxBFDc4TV3zgm9pSSD/ZPHLRz7MGzCAph1fggzeY9Dt50c6IC
1Dk+O72Q5wcjMr8Pq8jm5LIp69TYfeNKEILIaM9gd4fPxJ+pQ9E89Y4JBoXd13sM
DrPY+tQnXkBA8ryvop3V4dbPZcRiaMAv7hnIkFUm71uTY6Uy4GO3Pharsmu9CDtE
JjzYdEwed4gfYkAh3Q3qa5xO2TXX4igTJ6XFCrVbVZabA2lgtTpdvF5o7j7cU8vF
Q5cToGH69rJbOF81pLtbtK1/GOwz3ZsWvqrfyRaG99ZD7GhRu837Pq836tvnB4WB
Dc6bNGla1uKZPyoCdRtdZM9poA5IN6eXobexUcC9iZ4P50ceSm8Rmj5xp0FjoW7t
9RRb87JDvrslvyOn46DF90A4+Hegkc+Pqfb0hpelwr1wvOyfn5nbu8FPGeCObxoK
sZkoQKYud9VaP9FJet+oGZmdSajCiWYWNCh2yf/9SRm/vKNnLxN0dORhgQx7r1Ou
TD85/K6EPepdOH+LKacwF6tKStJSN3leyNFsAaAL10f6hkj/bKfntgVVR6L9goyG
aSbvpMHySYVXUA9z5LeqrloG+TCsH1w8tPYdoczp6RsZvucSOeGQ36r2MqHxUtyL
PnNiE+GcaaCyxMapNt7TbGVL6oIK1UrdUWG2IX0VxpdA2fkSiNk95MQbCWOCM4LY
GAXuSvr6Jka9ggZsHT04XiJQJ3HyZapreuvugMZW43UMpkGyz1mD5QWGWvYdr1Wr
4zwa0nWNZoGfwt6f7aErXx1ncp6DSqLTWvJxIXFTWb6DSR2YJlEmA3zhK89u73WL
vb+nxT31D8pBp8g9La9H19TY3jICEJnt86xpN4GeykvsuRJqV4ti5p/D6RONUqBG
Lgl9XiYU7ReymTDkqdRtyRMaZ/OoXB34ENDhLOigYSGHHETT8FrOEg/uyW1KavE2
zGwE+/JeGNn59/lCvUpo5TIDHc0q7W0JGdBSx5WKxxYhHYjwMfDLpmF3sCpLIT/y
jNmkMM6vfBi0Z//FiqeSG9D38FZNvtAK86tRLRDqqqu6C/AtWtmRqLaljJdgPomu
7LkSaleLYuafw+kTjVKgRqWhXulTsc+dxiE9YVhkJhDk9BjQc5Y/KuPGT52CtR/K
mVuZvj0mFq4WofZ9S3Wvt9bPZcRiaMAv7hnIkFUm71tSu0EQnaXAFhyhoNr/oB1K
mDx/jzHJrJOSBxFSj43GAyhIWNkd0Knj1P3jps2qtUNia6HeetVRl8NikBWvCsDI
Gp0T5ZhJumvjlbG3Vpulb+8DePnvoWlG17kE36MJaTQ01D5DfUr0SiqCyBNOAj3J
dvCPWuiqjfStHL0dgky2YIzZpDDOr3wYtGf/xYqnkhsr+fjGqEmEUiqn1XBWC64f
883mLU3u1hm65yF5TO9DmyAyhsVnuXpwCgWBrkXaNLSfvvWE70FiQstGCYIDgiL9
S96P/NiH5b2Dpf0M8CZm/z/xHZS+uC65CJredvOrTmHVDJ32R7mLD0xg+MHjjCnz
GOiMX4CddyuEx+xzRQJQUUOXE6Bh+vayWzhfNaS7W7TB4YFZVv+rcM1dJYFIxEsf
zo+m5aVzy+/OcE+/fuvHutUr3oVNTWplsKIbjlsNDYtcA3b7jmDfS45f5tJnAXcx
IDKGxWe5enAKBYGuRdo0tJ++9YTvQWJCy0YJggOCIv18vS1OQKWve5UupAzzQnYM
h65dI3tcZ3656rODXDhudU7tBLNC4hrbevqV94XXTkDJ2UfQo+YDnQZl+K08/27I
1NjeMgIQme3zrGk3gZ7KS+y5EmpXi2Lmn8PpE41SoEY8/58NL45dk82l4r2R5kBP
0JTy1h9ut4C4oz0EdXAhJkZCrxnMC2OHZYX/vkU3CcYWkZvSnvaSxiBhH+OHuIvJ
kW7oBb0Kv11lY+J38OHEnI6/fYriVAAI9PZvxibMnYxX0h2ksPjdZe3ahjOSBpC5
gcO06xBNyGuT21k+axByw39BiehGHKLbRgJxcfpeDu/gpbCpk62wetGjCNi0GPuP
WY3ISy+i1SV8BvPw0sDvwQRatd7hC0Bi+KQhYrR4D2MJeSfC9aTfClamf5BRV4eP
UcmRFuoI3FYmueHyQ/suiW8lDARxkZiVCYrW/3J0RnlEC1LuwY0s/k3R7f5IXtWQ
eAFhK5cUlz9N8E8d3XZk5mkm76TB8kmFV1APc+S3qq50dT1Zx12CCt8txKlkfhde
H1itQP8g/mQlnEwf6gP4lp3J3NeUTpPuLIGtPLWxSst1ItpQWqPgqN17ny77S7MS
DZiZn1Rh9uNvKiYNmQfkz3WFQZs6SPHh4RmaFMb0bloRTd69lV8jDjp22A34d7vF
uANl5mxjM1y0ORlZ31oo0iKcbm2ChZ7su0ve32oKWQWCg+hgYGPhGAo0/rX/QMJW
AAQM3/PpkEhh5ku9VyUWVYrqt+cgbkILqT0VIKi4cc9dERFefdAfPIZZEDinlI1m
3fn74+I3TD1HXMeuL5Gdag/mv+gV5zDghcFiEb4VtsUILRnZSWWWKXGOJSbI/QTT
dDh5L2DF8j0H9Xr4D0le+nf+d4MxKvjXefMZWqoIcNrYEyhuJPRVnAjiWEErmoVE
bnuam+bBvstebuh2r9ZOHCud7lArW50hNmk+iyeyQu03MYd9BtKjBEUU4opzhUfJ
CmWgS4K8V2OBL7xWoLEzxIt7UPkmMYYdZEuJfflkCwIUJLZwYvD/auQnl5eb8uGC
vC0pJGoRSwevrII9a6eFPy+o97i9eSKBSSwtGPzOgF6PTfl6/bKcLU7az8U4J8Ir
g/6WCieDJF4ym0x3VYnu826ohy8lRldQO+ED4W14/18NmJmfVGH2428qJg2ZB+TP
OeyHiyGec/JewSI0xeHc+Y+cNjO5BRx0r4VZa+gYSgxeHrSyp6W/y6jfkRQ9TrTE
jNl5LK1fxDel1p2Zfbyq6wFALYi9YKaU5O9+EK2LLJAysFXYgts1hFu6ZVHs3tMW
eSvsLjIUOWbzWZsLiqlGJvJ+PeaxjaOFP2Rz2KcPgbs+sCYHH296wtXFvG/ENkRf
xc+egKKv97iTgCJ8DLnVaBLoUZ13T5sZrjfuX62GoCxEbPAWTpWJ0mJrtWgbnHFk
beZIcP9UXmkjA32zb/LA5F0REV590B88hlkQOKeUjWZfaem3vUyc05CC9Xof42mh
xj59EUrftxrpgEXw5ddDuUelsEC7j3JOpCs87d9smJyLe1D5JjGGHWRLiX35ZAsC
gxAR5v0LNAMgPozjlABu5UlwxteuRTiw/OTsQ+H8FRleHrSyp6W/y6jfkRQ9TrTE
YGeC8E1SM0NfSvarNryqp6feKqr9NZUk7LZw7QxayFbDkUsg4VyIxsKbN+cM6tXt
+dhBQk/JzfPKF2V6s7sLxMAjJtaoXKmuEAdsZt9Q+q+7N1BKxoyCzuh+JGRoJDAV
7gsc6W/QtkDAC2fgczd6nEDrcvyF4TqsyUt5lr2ITo1p4eC36LAjpk3mu8cEEwN8
h7JqAszAjhMFmclE3Vm2ME6aCVfNund4klW3IrIJp36ozdTBY7BIOVGLn5hMbjjs
RI317lVxkM7JhHa4VCtFC96myMPmIziOhATbUd3MKSFTzcD0011gpQiPjPtmRZBM
IOzqvoGI+v/qVsfz+nQ+d+OZoTL0XxZ2ud2LcDoplkYuF27GEvAxuwmFV267NwaE
1AvDZh30rf+tUmhWu6mfZgYAMbCqbQO8YvEzgVjAuENTbzldzC+EVLqb1G0nIKvP
h04I8VUH4ep8v2HnBwKHzi+N9gzDDmzjTiNLuqZgVX2CPfO/zyzKsudeRo8Ms3qv
ngMVoYpLuMJuq+XZv2+oWlM8GTRejEdYhPCWuekLuLW5Juhem5XSnluVAGYQt8Ke
1L06YKNbwampHekekwHXIwoyTn01/QCl/QMsEEltVYY4D1tnC6GrKcznXiOCfwUg
aX+FhqYxaPeRgQAFjrVBklPnxpoigleCaZt3GNsPeTkIwXMN/Q3dIsL5mIGqQ2DV
/SyX4Vvork75nbN5V4Gm2PhgbqeqUM50X6R4WhAjnrtLlyRVI+aOudOwxfGHNxIJ
dKpZy/6sB+VbF074DQ9AEs/gS+NzPtTAaDqgJmhqn33BP1/LhFY7zXFxNtAPffiU
m/exX97reySy13VrQEJcVZm5tZh4jXPMrr/cZmSZki96fmbOBMuawhadkeuSmIzg
Ts8q2WeyxHBksZuQ6ml0FMMRIamfel6B++e/xeam8Cwt+KjnZqqFVf8JzJu0e7EZ
kHePpErr5ZS55SgrCpOvMAb+Bd5noLw9AHQAj9VCl/X5BlL/GpAhdlH8U4TEbGFF
+dSc/03oiLTS8PEi1wSpJHb129djLBSFTCyDv+ICWokR9rP/ODOZ+sIeUzG+YDRU
CaKCBuX1vDE/KTfgBpucG0LUMkAhe3CRqQjCsS1g7RPmiITRYGgEqW8m+bj207iH
oeYAinTdYdqW/q2cVPmkvAjY+7SnF5znlmfJBca7PJK643GLVZ+3edNxb6rgWpxA
s81Zv8fyCKXMO1olEcpphyB48iWr/TpXNjlFAbiJE9b8/AZqseRd9MYbu9mTxlQb
6XZRHUKxfXmZhflyhk8lyZYaN5UBJjxpoXCmZCoX2qSu+Wn583K8oAvQobvY4zFG
9rgT85P6Jz8iFKSrcXs73o3HdGgCPVVhG3R44PZ4oibgH6nKBy29PwrlLmfkMHpP
rwAKU9EiyYGdrSULpb+DXxH2s/84M5n6wh5TMb5gNFSKAAza/dDkfSEhPlRIMj1u
gUthr/LpKK8YPiBDthkvtPVqkSEjiB3DXLx7+EUxp6s8Xo5IwCQgvVfY7JpEtVaY
CRZaATgOb2WAaYUCKsxRgiZSqPacbmApYM9Yk7st+hg=
|
db8978bfb2cb45cc61af091b519f6ca04c40acdb | 32eeba1f7e196ca8b6a4b60e23f75538608456d7 | /inputValidation.cpp | 5f2e324054df3796b33312ea7712102bc86c90ff | [] | no_license | DrakeSeifert/Input-Validation-in-C-Plus-Plus | 997d785196a3c37c8b33e3606c1dca6722e34ac2 | 4bc1047af66fea99e3b97fe6231c6e9d328e9cb0 | refs/heads/master | 2020-03-29T17:50:27.345314 | 2018-09-24T23:45:12 | 2018-09-24T23:45:12 | 150,182,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | inputValidation.cpp | #include <iostream>
#include <limits> //numeric_limits<T>::max()
using std::cout;
using std::cin;
using std::endl;
int intRange(int input, int min, int max)
{
while(input < min || input > max || cin.fail()) {
cout << "Error: Enter a value between " << min << " and " << max << endl;
cin.clear();
//cin.ignore(1000, '\n');
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//returns maximum size of given data type (i.e. int: (2^31) - 1)
cin >> input;
}
return input;
}
int main()
{
int input, min = 1, max = 10;
cout << "Enter a value between " << min << " and " << max << endl;
cin >> input;
input = intRange(input, min, max);
cout << "Your value is: " << input << endl << endl;
return 0;
}
|
53fd119691c436eb79e72918a334ca049e461044 | 54631bdd46cf6c37c4598ed7c00a30305ecc8aff | /projects/GameEngine/Engine.cpp | 7fb653382f0902d0ef35de5f027284e4cca30c18 | [] | no_license | HarukaNanase/GameEngineRefactorized | cea0030ffe1c7925b82d7e8f7af0dcd191aadde2 | 92cd1903083491c348f7fb37a5b6dfe77a4a00ab | refs/heads/master | 2021-03-16T10:33:33.786783 | 2019-02-17T17:36:11 | 2019-02-17T17:36:11 | 114,781,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | Engine.cpp | #include "Engine.h"
Engine::Engine()
{
}
Engine::~Engine()
{
}
void Engine::display(float deltaTime)
{
++FrameCount;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawScene();
glutSwapBuffers();
}
void Engine::displayWrapper()
{
}
|
8d8531db3cfb434d9ee6e4940c730cc86b5e7cfc | 55a5dc8f886808660e163f2908c12fe36a17fa28 | /wpl/animated_models.h | 7a87bc3c413cefcff9dd936d84410c3d849eb47f | [] | no_license | tyoma/wpl | 4fac7a021ab7ffab4e8fce9310b9bbd8cd4a7e40 | 32e33921261ea49b14f14ea3cc5c95097def96f6 | refs/heads/master | 2022-12-02T23:54:25.191018 | 2022-10-24T00:01:44 | 2022-10-24T01:16:58 | 36,181,780 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,122 | h | animated_models.h | // Copyright (c) 2011-2022 by Artem A. Gevorkyan (gevorkyan.org)
//
// 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.
#pragma once
#include "animation.h"
#include "concepts.h"
#include "models.h"
#include "queue.h"
namespace wpl
{
class animated_scroll_model : public scroll_model, noncopyable
{
public:
animated_scroll_model(std::shared_ptr<scroll_model> underlying, const clock &clock_, const queue &queue_,
const animation_function &release_animation);
virtual std::pair<double, double> get_range() const override;
virtual std::pair<double, double> get_window() const override;
virtual double get_increment() const override;
virtual void scrolling(bool begins) override;
virtual void set_window(double window_min, double window_width) override;
private:
void animate();
void on_invalidate(bool invalidate_range);
private:
timestamp _animation_start;
double _excess;
const clock _clock;
const queue _queue;
const animation_function _release_animation;
const std::shared_ptr<scroll_model> _underlying;
const slot_connection _invalidate_connection;
};
}
|
cddd1688e7929c23da8fe1a0c84d4b1f74c638bd | 5e80bf467259651bc8a7a98d413b1ecc2d7c3d5d | /jUI_SDL/src/jUI_SDL/jUI_SDL_FilePath.h | 6923696b3f0af39cfa00105b69dcfba4b37f0955 | [
"MIT"
] | permissive | jhoc/jUI_SDL | b4659d30278869794c84059ad935e5faf03ba51e | dcb085ae83d53254c70e448a8decabe0a24785d1 | refs/heads/master | 2021-04-26T22:57:39.921104 | 2018-03-05T11:46:48 | 2018-03-05T11:46:48 | 123,903,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | jUI_SDL_FilePath.h | #pragma once
#include <iostream>
#include <string>
#include <SDL.h>
class jUI_SDL_FilePath {
public:
// static std::string getDataPath();
static std::string getResourcePath(const std::string &subDir = ""){
#ifdef _WIN32
const char PATH_SEP = '\\';
#else
const char PATH_SEP = '/';
#endif
static std::string baseRes;
if (baseRes.empty()){
char *basePath = SDL_GetBasePath();
if (basePath){
baseRes = basePath;
SDL_free(basePath);
}
else {
std::cerr << "Error getting resource path: " << SDL_GetError() << std::endl;
return "";
}
//We replace the last bin/ with res/ to get the the resource path
size_t pos = baseRes.rfind("bin");
baseRes = baseRes.substr(0, pos) + "res" + PATH_SEP;
}
return subDir.empty() ? baseRes : baseRes + subDir + PATH_SEP;
}
};
|
0bb038ffb98f67d23566c002eb2d9dd6e1007b72 | 65aaba4d24cfbddb05acc0b0ad814632e3b52837 | /src/osrm.net/libosrm/osrm-deps/boost/include/boost-1_62/boost/log/detail/light_rw_mutex.hpp | 767bca7d732a25641bb993d9c298c09b2d29a27f | [
"MIT"
] | permissive | tstaa/osrmnet | 3599eb01383ee99dc6207ad39eda13a245e7764f | 891e66e0d91e76ee571f69ef52536c1153f91b10 | refs/heads/master | 2021-01-21T07:03:22.508378 | 2017-02-26T04:59:50 | 2017-02-26T04:59:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | light_rw_mutex.hpp | version https://git-lfs.github.com/spec/v1
oid sha256:caf666458143e80e06c2a16f29584b30418090f0b3f294383ba3faac95e018fc
size 4084
|
38b2962ef6f12f8c76c8a3b6ba8efdfe03f5a340 | f81dff225fc22b325bf2a33f36981f473b6ae379 | /LeetCode/C++/186-Reverse Words in a String II .cpp | 2fe182454496a879877c08913a38f59164c2477c | [] | no_license | PoundKey/Algorithms | 12d3656bbf4e896f26d6e062c795cbcd269a7074 | f975d3592211a6c5d18b7fa1746782c9ef3fd8b4 | refs/heads/master | 2021-07-06T14:05:46.115955 | 2021-05-23T01:01:13 | 2021-05-23T01:01:13 | 27,214,175 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 640 | cpp | 186-Reverse Words in a String II .cpp | // Thoughts: Reverse the entire string, and reverse back each word one by one.
class Solution {
public:
void reverseWords(string &s) {
reverse(s, 0, s.size() - 1);
int i = 0, j = 0;
while (j < s.size()) {
if (j == s.size() - 1 || s[j] == ' ') {
reverse(s, i, j - 1);
i = j + 1;
}
j++;
}
}
void reverse(string& s, int start, int end) {
int n = start + end + 1;
for (int i = start; i < n / 2; i++) {
char temp = s[i];
s[i] = s[n-1-i];
s[n-1-i] = temp;
}
}
};
|
b066079d780975f45c25a6f335e905ca003b1330 | 14fd5a3763da4b68cbcb73f85c30bc8ca63cc544 | /DP/Adapter/Logger.cpp | 826c1210839daa99d36c5349fc46aeb97781ff55 | [] | no_license | guoyu07/DesignPattern-31 | a9c7898728df0cd21ee748e127583fdfbfb9652a | 091aaf0b3ef8a8e68174b1b94742808e63e26f35 | refs/heads/master | 2021-01-01T06:53:32.556454 | 2013-04-08T07:12:04 | 2013-04-08T07:12:04 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 678 | cpp | Logger.cpp | /*
* Logger.cpp
*
* Created on: 2013-3-28
* Author: Administrator
*/
#include "Logger.h"
#include <iostream>
Logger::Logger()
{
/* ×Ô¶¯Éú³ÉID*/
this->Id = "1";
}
void Logger::setLogContent(std::string content)
{
this->content = content;
}
void Logger::setOperateTime(std::string time)
{
this->operateTime = time;
}
void Logger::setUserName(std::string name)
{
this->userName = name;
}
std::string Logger::getLogContent()const
{
return this->content;
}
std::string Logger::getOperateTime()const
{
return this->operateTime;
}
std::string Logger::getUserName()const
{
return this->userName;
}
|
dea50496f45800b289d78d18d8192db6b978f37f | 8cf0668b32770dd2524f0ec0dea2c4955e56ce8e | /sources/maze/Room.cpp | b37be44f3bb35e5f2b6b5636f8fe0bbc06d2cf55 | [] | no_license | pvmiseeffoC/MazeGame | c845863e6f2389935f93bdbe9d5967f81572b6a2 | 7b9a83b917650449ee93549e3450226d3c2921a0 | refs/heads/master | 2020-06-05T09:48:11.874299 | 2019-06-26T15:24:34 | 2019-06-26T15:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | cpp | Room.cpp | #include "Room.h"
#include "ECS.h"
#include "Game.h"
Room::Room(std::size_t number)
: _roomNumber(number)
{
_manager = std::make_unique<Manager>();
}
MapSite*
Room::getSide(Direction d)
{
return sides[d].get();
}
void
Room::setSide(Direction d, std::unique_ptr<MapSite> site)
{
sides[d] = std::move(site);
}
void
Room::enter()
{
Game::instance().setManager(_manager.get());
}
Manager* Room::getManager() const
{
return _manager.get();
}
Room::~Room() {}
|
95a43cd070066b9c565bf1733d3fc7b3da076adc | 6f4883cec42366e1ed7dc4ddf25b56e7702b0c69 | /2796/4680983_AC_750MS_2112K.cpp | 81a81f0eeea2d1f5cbb933bfcbc6016c4bef18e1 | [] | no_license | 15800688908/poj-codes | 89e3739df0db4bd4fe22db3e0bf839fc7abe35d1 | 913331dd1cfb6a422fb90175dcddb54b577d1059 | refs/heads/master | 2022-01-25T07:55:15.590648 | 2016-09-30T13:08:24 | 2016-09-30T13:08:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 823 | cpp | 4680983_AC_750MS_2112K.cpp | #include<stdio.h>
const int maxn=100005;
int a[maxn],left[maxn],right[maxn];
int i,j,x,y,n;
__int64 sum[maxn],max;
int main()
{
scanf("%d",&n);
sum[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
left[1]=1;
for(i=2;i<=n;i++)
{
if(a[i-1]>=a[i])
{
j=i-1;
while(left[j]>1&&a[left[j]-1]>=a[i])
j=left[j]-1;
left[i]=left[j];
}
else
left[i]=i;
}
right[n]=n;
for(i=n-1;i>=1;i--)
{
if(a[i+1]>=a[i])
{
j=i+1;
while(right[j]<n&&a[right[j]+1]>=a[i])
j=right[j]+1;
right[i]=right[j];
}
else
right[i]=i;
}
for(i=1;i<=n;i++)
{
if(i==1||(sum[right[i]]-sum[left[i]-1])*a[i]>max)
{
max=(sum[right[i]]-sum[left[i]-1])*a[i];
x=left[i];
y=right[i];
}
}
printf("%I64d\n",max);
printf("%d %d\n",x,y);
return 0;
} |
faea58ddc40998eb4932219aa889b86fd508ba90 | fce40b458d39c34bf0f34f4db3476a5ceca65519 | /compressao.cpp | 4f01b3e5b2170cee0e89168a4da7cf4b39fc9713 | [] | no_license | Xr0s/Arch_Ubuntu | 60bc39a63bbdc8fe45e289ef332712529b4c67f1 | fbf9be56d2dbdf6427be08622d86dcfd15047479 | refs/heads/master | 2021-01-20T05:08:49.091507 | 2017-09-13T14:08:59 | 2017-09-13T14:08:59 | 101,417,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,406 | cpp | compressao.cpp | #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define MAX 100
typedef struct node{
int valor;
int freq;
string code="";
node* esq=NULL;
node* dir=NULL;
}node;
struct fila_prioridade{
int qtd;
struct node dados[MAX];
};
typedef struct{
int freq;
int valor;
}Histograma;
typedef struct fila_prioridade FilaPrio;
node* extrair_min(FilaPrio* fp);
int inserir_no(FilaPrio* fp, int somafreq, int valor,node* x,node* y);
FilaPrio* cria_FilaPrio();
void libera_FilaPrio(FilaPrio* fp);
int insere_FilaPrio(FilaPrio* fp, int freq, int valor);
int remove_FilaPrio(FilaPrio* fp);
int tamanho_FilaPrio(FilaPrio* fp);
int estaCheia_FilaPrio(FilaPrio* fp);
int estaVazia_FilaPrio(FilaPrio* fp);
void imprime_FilaPrio(FilaPrio* fp);
//node* construir_arvore(FilaPrio* fp,Histograma* H, unsigned int N);
FilaPrio* construir_arvore(FilaPrio* fp,Histograma* H, unsigned int N);
unsigned int i=0;
FilaPrio* cria_FilaPrio(){
FilaPrio *fp;
fp = new FilaPrio[sizeof(struct fila_prioridade)];
if(fp != NULL)
fp->qtd = 0;
return fp;
}
void libera_FilaPrio(FilaPrio* fp){
free(fp);
}
//node*
FilaPrio* construir_arvore(FilaPrio* fp,Histograma* H, unsigned int N) {
unsigned int i;
for(i = 0; i < N; i++)
insere_FilaPrio(fp, H[i].freq,H[i].valor);
while(tamanho_FilaPrio(fp) > 1){
node* x = extrair_min(fp);
node* y = extrair_min(fp);
inserir_no(fp, x->freq + y->freq, 0xFFF, x, y);
}
//return extrair_min(fp);
remove_FilaPrio(fp);
return fp;
}
void promoverElemento(FilaPrio* fp, int filho){
int pai;
node temp;
pai = (filho - 1) / 2;
while((filho > 0) && (fp->dados[pai].freq > fp->dados[filho].freq)){
temp = fp->dados[filho];
fp->dados[filho] = fp->dados[pai];
fp->dados[pai] = temp;
filho = pai;
pai = (pai - 1) / 2;
}
}
int insere_FilaPrio(FilaPrio* fp, int freq, int valor){
if(fp == NULL)
return 0;
if(fp->qtd == MAX)//fila cheia
return 0;
/* insere na primeira posição livre */
fp->dados[fp->qtd].valor = valor;
fp->dados[fp->qtd].freq = freq;
/* desloca elemento para posição correta */
promoverElemento(fp,fp->qtd);
/* incrementa número de elementos no heap */
fp->qtd++;
return 1;
}
int inserir_no(FilaPrio* fp, int somafreq, int valor, node* x, node* y){
return 1;
}
void rebaixarElemento(FilaPrio* fp, int pai){
node temp;
int filho = 2 * pai + 1;
while(filho < fp->qtd){
if(filho < fp->qtd-1) /* verifica se tem 2 filhos */
if(fp->dados[filho].freq > fp->dados[filho+1].freq)
filho++; /*filho aponta para filho menor */
if(fp->dados[pai].freq <= fp->dados[filho].freq)
break; /* encontrou lugar */
temp = fp->dados[pai];
fp->dados[pai] = fp->dados[filho];
fp->dados[filho] = temp;
pai = filho;
filho = 2 * pai + 1;
}
}
int remove_FilaPrio(FilaPrio* fp){
if(fp == NULL)
return 0;
if(fp->qtd == 0)
return 0;
fp->qtd--;
fp->dados[0] = fp->dados[fp->qtd];
rebaixarElemento(fp,0);
return 1;
}
node* extrair_min(FilaPrio* fp){
node* x=&fp->dados[0];
remove_FilaPrio(fp);
return x;
}
int tamanho_FilaPrio(FilaPrio* fp){
if(fp == NULL)
return -1;
else
return fp->qtd;
}
int estaCheia_FilaPrio(FilaPrio* fp){
if(fp == NULL)
return -1;
return (fp->qtd == MAX);
}
int estaVazia_FilaPrio(FilaPrio* fp){
if(fp == NULL)
return -1;
return (fp->qtd == 0);
}
void imprime_FilaPrio(FilaPrio* fp){
if(fp == NULL)
return;
int i;
for(i=0; i < fp->qtd ; i++){
printf("%i) Prio: %d \tNome: %X\n",i,fp->dados[i].freq,fp->dados[i].valor);
}
}
int main(int argc, char **argv){
FilaPrio* fp = cria_FilaPrio();
node* arvoreHuf=new node[MAX*2];
Histograma* histograma = new Histograma[7];
histograma[0].valor=0x10;
histograma[0].freq=1;
histograma[1].valor=0x20;
histograma[1].freq=1;
histograma[2].valor=0x30;
histograma[2].freq=1;
histograma[3].valor=0x40;
histograma[3].freq=1;
histograma[4].valor=0x50;
histograma[4].freq=1;
histograma[5].valor=0x60;
histograma[5].freq=1;
histograma[6].valor=0x70;
histograma[6].freq=1;
fp=construir_arvore(fp, histograma, 7);
imprime_FilaPrio(fp);
return 0;
}
|
de55258fa35f55fce732f30dd70ca393cd6d1ed1 | aaaa4774f088d33bbbabf0940dc4e3482e0e07c3 | /cs_threadpool_epoll_mq-master/src/net/EpollPoller.cpp | 666d0f8a89366dcb63b755d299ff844aedd24f9d | [] | no_license | WangDavid2012/ref | c277e3dfff846d241a42cb9235df94fbb5c97c90 | e845bb6c9e71b4ca4704b3e9f9d99bdb11657b84 | refs/heads/master | 2021-01-09T10:58:58.558431 | 2020-02-22T06:14:27 | 2020-02-22T06:14:27 | 242,274,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,923 | cpp | EpollPoller.cpp | ///
/// @file EpollPoller.cpp
/// @author https://icoty.github.io
///
#include "Log4func.hpp"
#include "EpollPoller.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <sys/eventfd.h>
//匿名空间,与系统匿名空间有何区别??
//非类内成员,供类内调用,辅助初始化
namespace
{
int createEpollFd() //free函数 全局函数
{
int epollfd = ::epoll_create1(0);//?????????
if(epollfd == -1)
{
LogError("create epoll fd error!");
exit(EXIT_FAILURE);
}
return epollfd;
}
int createEventfd()
{
int fd = ::eventfd(0,0);
if(-1 == fd){
LogError("create event fd error!");
exit(EXIT_FAILURE);
}
return fd;
}
void addEpollReadFd(int epollfd, int fd)
{
struct epoll_event ev;
ev.data.fd = fd;
ev.events = EPOLLIN;
if(epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev) == -1)
{
LogError("add epoll fd error!");
exit(EXIT_FAILURE);
}
}
void delEpollReadFd(int epollfd, int fd)
{
struct epoll_event ev;
ev.data.fd = fd;
//ev.events = EPOLLIN;
if(epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &ev) == -1)
{
LogError("del epoll fd error!");
exit(EXIT_FAILURE);
}
}
int acceptConnFd(int listenfd)
{
int peerfd = ::accept(listenfd, NULL, NULL);
if(peerfd == -1)
{
LogError("accept conn fd!");
exit(EXIT_FAILURE);
}
return peerfd;
}
//预览数据
ssize_t recvPeek(int sockfd, void *buf, size_t len)
{
int nread;
do
{
nread = ::recv(sockfd, buf, len, MSG_PEEK);
}
while(nread == -1 && errno == EINTR);
return nread;
}
//通过预览数据 判断conn是否关闭
bool isConnectionClosed(int sockfd)
{
char buf[1024];
ssize_t nread = recvPeek(sockfd, buf, sizeof buf);
if(nread == -1)
{
LogError("recvPeek!");
}
return (nread == 0);
}
}//end anonymous namespace
namespace yangyu
{
EpollPoller::EpollPoller(int listenfd)
: _epollfd(createEpollFd())
,_listenfd(listenfd)
,_eventfd(createEventfd())
,_isLooping(false)
,_events(1024)
{
addEpollReadFd(_epollfd, listenfd);
addEpollReadFd(_epollfd,_eventfd);
}
EpollPoller::~EpollPoller()
{
::close(_epollfd);//内部关闭机制??
}
void EpollPoller::waitEpollFd()
{
int nready;
do
{
nready = ::epoll_wait(_epollfd,
&(*_events.begin()),
static_cast<int>(_events.size()),
5000);
}while(nready == -1 && errno == EINTR);
if(nready == -1)
{
LogError("epoll wait error!");
exit(EXIT_FAILURE);
}
else if(nready == 0)
{
//LogInfo("epoll timeout.");
}
else
{
//当vector满时,扩充内存
if(nready == static_cast<int>(_events.size()))
{
_events.resize(_events.size() * 2);//动态扩容,调用vector.resize()
}
for(int ix = 0; ix != nready; ++ix)
{
if(_events[ix].data.fd == _listenfd)//data结构体内部成员,fd再内部
{
if(_events[ix].events & EPOLLIN)//struct epoll_event内部成员events ???
handleConnection();
}else if(_events[ix].data.fd == _eventfd){
handleRead();
doPendingFunctors();
}else{
if(_events[ix].events & EPOLLIN)
handleMessage(_events[ix].data.fd);
}
}
}
}
void EpollPoller::handleRead()
{
uint64_t buff=0;
int ret=::read(_eventfd,&buff,sizeof(buff));
if(ret != sizeof(buff)){
LogError("read eventfd error!");
}
}
void EpollPoller::runInLoop(Function cb)
{
{
MutexLockGuard guard(_mutex);
_pendingFunctors.push_back(cb);
}
wakeup();
}
void EpollPoller::wakeup()
{
uint64_t one=1;
int ret=::write(_eventfd,&one,sizeof(one));
if(ret!=sizeof(one)){
LogError("reaad eventfd error!");
}
}
void EpollPoller::doPendingFunctors()
{
//printf("> doPendingFunctors()\n");
std::vector<Function> tmp;
{
MutexLockGuard guard(_mutex);
tmp.swap(_pendingFunctors);
}
for(auto & func:tmp){
if(func)
func();
}
}
void EpollPoller::handleConnection()
{
int peerfd = acceptConnFd(_listenfd);
addEpollReadFd(_epollfd, peerfd);
//多??
std::pair<ConnectionList::iterator, bool> ret;
TcpConnectionPtr conn(new TcpConnection(peerfd,this));
conn->setConnectCallback(_onConnectCallback);
conn->setMessageCallback(_onMessageCallback);
conn->setCloseCallback(_onCloseCallback);
ret = _lists.insert(std::make_pair(peerfd, conn));
assert(ret.second == true); //断言插入成功
(void)ret; //消除ret 未使用的warning ?????
conn->handleConnectCallback();
}
void EpollPoller::handleMessage(int peerfd)
{
bool isClosed = isConnectionClosed(peerfd);
ConnectionList::iterator it = _lists.find(peerfd);
//断言
assert(it != _lists.end());
if(isClosed)
{
//调用conn的close事件handleCloseCalback
it->second->handleCloseCallback();
delEpollReadFd(_epollfd, peerfd);
_lists.erase(it);
}
else
{
it->second->handleMessageCallback();
}
}
void EpollPoller::loop()
{
_isLooping = true;
while(_isLooping){
waitEpollFd();
}
LogInfo("Loop quit safely!");
}
void EpollPoller::unloop()
{
_isLooping = false;
}
}
|
8d92ee4c271b74ef18dc6055a1a115b15e89f4dd | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/ds/adsi/ldap/cumiobj.hxx | afd37274ba369bde53cd658d05d686800c818348 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 6,971 | hxx | cumiobj.hxx | //----------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 2000.
//
// File: cumiobj.hxx
//
// Contents: Header file for CLDAPUmiObject for LDAP Provider.
//
// History: 03-06-00 SivaramR Created.
// 04-07-00 AjayR modified for LDAP Provider.
//
//----------------------------------------------------------------------------
#ifndef __CUMIOBJ_H__
#define __CUMIOBJ_H__
//
// Used internall to do implicit getinfo on clone/copy as needed.
//
#define ADSI_INTERNAL_FLAG_GETINFO_AS_NEEDED 0x8000
class CPropetyManager;
class CCoreADsObject;
class CLDAPUmiObject : INHERIT_TRACKING,
public IUmiContainer,
public IUmiCustomInterfaceFactory,
public IADsObjOptPrivate
{
public:
//
// IUnknown support.
//
DECLARE_STD_REFCOUNTING
//
// IADsObjOptPrivate.
//
DECLARE_IADsObjOptPrivate_METHODS
STDMETHOD (QueryInterface)(
IN REFIID iid,
OUT LPVOID *ppInterface
);
//
// IUmiObject support.
//
STDMETHOD (Clone)(
IN ULONG uFlags,
IN REFIID riid,
OUT LPVOID *pCopy
);
STDMETHOD (CopyTo)(
IN ULONG uFlags,
IN IUmiURL *pURL,
IN REFIID riid,
OUT LPVOID *pCopy
);
STDMETHOD (Refresh)(
IN ULONG uFlags,
IN ULONG uNameCount,
IN LPWSTR *pszNames
);
STDMETHOD (Commit)(IN ULONG uFlags);
//
// IUmiPropList support.
//
STDMETHOD (Put)(
IN LPCWSTR pszName,
IN ULONG uFlags,
IN UMI_PROPERTY_VALUES *pProp
);
STDMETHOD (Get)(
IN LPCWSTR pszName,
IN ULONG uFlags,
OUT UMI_PROPERTY_VALUES **ppProp
);
STDMETHOD (GetAs)(
IN LPCWSTR pszName,
IN ULONG uFlags,
IN ULONG uCoercionType,
OUT UMI_PROPERTY_VALUES **ppProp
);
STDMETHOD (GetAt)(
IN LPCWSTR pszName,
IN ULONG uFlags,
IN ULONG uBufferLength,
OUT LPVOID pExistingMem
);
STDMETHOD (FreeMemory)(
IN ULONG uReserved,
IN LPVOID pMem
);
STDMETHOD (Delete)(
IN LPCWSTR pszName,
IN ULONG uFlags
);
STDMETHOD (GetProps)(
IN LPCWSTR *pszNames,
IN ULONG uNameCount,
IN ULONG uFlags,
OUT UMI_PROPERTY_VALUES **pProps
);
STDMETHOD (PutProps)(
IN LPCWSTR *pszNames,
IN ULONG uNameCount,
IN ULONG uFlags,
IN UMI_PROPERTY_VALUES *pProps
);
STDMETHOD (PutFrom)(
IN LPCWSTR pszName,
IN ULONG uFlags,
IN ULONG uBufferLength,
IN LPVOID pExistingMem
);
//
// IUmiBaseObject support.
//
STDMETHOD (GetLastStatus)(
IN ULONG uFlags,
OUT ULONG *puSpecificStatus,
IN REFIID riid,
OUT LPVOID *pStatusObj
);
STDMETHOD (GetInterfacePropList)(
IN ULONG uFlags,
OUT IUmiPropList **pPropList
);
//
// IUmiContainer Support.
//
STDMETHOD (Open)(
IN IUmiURL *pURL,
IN ULONG uFlags,
IN REFIID TargetIID,
OUT LPVOID *ppInterface
);
STDMETHOD (PutObject)(
IN ULONG uFlags,
IN REFIID TargetIID,
IN LPVOID pInterface
);
STDMETHOD (DeleteObject)(
IN IUmiURL *pURL,
IN ULONG uFlags
);
STDMETHOD (Create)(
IN IUmiURL *pURL,
IN ULONG uFlags,
OUT IUmiObject **pNewObj
);
STDMETHOD (Move)(
IN ULONG uFlags,
IN IUmiURL *pOldURL,
IN IUmiURL *pNewURL
);
STDMETHOD (CreateEnum)(
IN IUmiURL *pszEnumContext,
IN ULONG uFlags,
IN REFIID TargetIID,
OUT LPVOID *ppInterface
);
STDMETHOD (ExecQuery)(
IN IUmiQuery *pQuery,
IN ULONG uFlags,
IN REFIID TargetIID,
OUT LPVOID *ppInterface
);
//
// IUmiCustomInterfaceFactory support.
//
STDMETHOD (GetCLSIDForIID)(
IN REFIID riid,
IN long lFlags,
IN OUT CLSID *pCLSID
);
STDMETHOD (GetObjectByCLSID)(
IN CLSID clsid,
IN IUnknown *pUnkOuter,
IN DWORD dwClsContext,
IN REFIID riid,
IN long lFlags,
OUT void **ppInterface
);
STDMETHOD (GetCLSIDForNames)(
IN LPOLESTR * rgszNames,
IN UINT cNames,
IN LCID lcid,
OUT DISPID * rgDispId,
IN long lFlags,
IN OUT CLSID *pCLSID
);
//
// Constructor and destructor and other miscellaneos methods.
//
CLDAPUmiObject::CLDAPUmiObject();
CLDAPUmiObject::~CLDAPUmiObject();
static
HRESULT
CLDAPUmiObject::CreateLDAPUmiObject(
INTF_PROP_DATA intfPropTable[],
CPropertyCache *pPropertyCache,
IUnknown *pUnkInner,
CCoreADsObject *pCoreObj,
IADs *pIADs,
CCredentials *pCreds,
CLDAPUmiObject **ppUmiObj,
DWORD dwPort = (DWORD) -1,
PADSLDP pLdapHandle = NULL,
LPWSTR pszServerName = NULL,
LPWSTR _pszLDAPDn = NULL,
CADsExtMgr *pExtMgr = NULL
);
protected:
HRESULT
CLDAPUmiObject::CopyToHelper(
IUmiObject *pUmiSrcObj,
IUmiObject *pUmiDestObj,
ULONG uFlags,
BOOL fMarkAsUpdate = TRUE,
BOOL fCopyIntfProps = FALSE
);
HRESULT
CLDAPUmiObject::VerifyIfQueryIsValid(
IUmiQuery * pUmiQuery
);
HRESULT
CLDAPUmiObject::VerifyIfClassMatches(
LPWSTR pszClass,
IUnknown * pUnk,
LONG lGenus
);
private:
CPropertyManager *_pPropMgr;
CPropertyManager *_pIntfPropMgr;
IUnknown *_pUnkInner;
IADs *_pIADs;
IADsContainer *_pIADsContainer;
ULONG _ulErrorStatus;
CCoreADsObject *_pCoreObj;
CADsExtMgr *_pExtMgr;
BOOL _fOuterUnkSet;
//
// Make sure to update the cxx file.
//
//
// do not free this are just ptrs.
//
CCredentials *_pCreds;
LPWSTR _pszLDAPServer;
LPWSTR _pszLDAPDn;
PADSLDP _pLdapHandle;
DWORD _dwPort;
void SetLastStatus(ULONG ulStatus);
};
#endif //__CUMIOBJ_H__
|
8efb1773a9361359dde182297dbf2e17db0ae94e | f67180915ff08065d4c604a6c0a18492e8d0b726 | /src/sdeventplus/internal/sdevent.cpp | f3bdeb33939d12ea2a9a826f16e1baed06c8ae87 | [
"Apache-2.0"
] | permissive | openbmc/sdeventplus | 61e7f4c5437771c091d87255b7137a9bbbd44b95 | 25f484be0ede53f717a716604a0abdea8783a902 | refs/heads/master | 2023-09-04T02:17:16.728803 | 2023-07-17T15:07:13 | 2023-07-17T15:07:13 | 145,640,685 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,360 | cpp | sdevent.cpp | #include <systemd/sd-event.h>
#include <sdeventplus/internal/sdevent.hpp>
namespace sdeventplus
{
namespace internal
{
int SdEventImpl::sd_event_default(sd_event** event) const
{
return ::sd_event_default(event);
}
int SdEventImpl::sd_event_new(sd_event** event) const
{
return ::sd_event_new(event);
}
sd_event* SdEventImpl::sd_event_ref(sd_event* event) const
{
return ::sd_event_ref(event);
}
sd_event* SdEventImpl::sd_event_unref(sd_event* event) const
{
return ::sd_event_unref(event);
}
int SdEventImpl::sd_event_add_io(sd_event* event, sd_event_source** source,
int fd, uint32_t events,
sd_event_io_handler_t callback,
void* userdata) const
{
return ::sd_event_add_io(event, source, fd, events, callback, userdata);
}
int SdEventImpl::sd_event_add_time(sd_event* event, sd_event_source** source,
clockid_t clock, uint64_t usec,
uint64_t accuracy,
sd_event_time_handler_t callback,
void* userdata) const
{
return ::sd_event_add_time(event, source, clock, usec, accuracy, callback,
userdata);
}
int SdEventImpl::sd_event_add_defer(sd_event* event, sd_event_source** source,
sd_event_handler_t callback,
void* userdata) const
{
return ::sd_event_add_defer(event, source, callback, userdata);
}
int SdEventImpl::sd_event_add_post(sd_event* event, sd_event_source** source,
sd_event_handler_t callback,
void* userdata) const
{
return ::sd_event_add_post(event, source, callback, userdata);
}
int SdEventImpl::sd_event_add_exit(sd_event* event, sd_event_source** source,
sd_event_handler_t callback,
void* userdata) const
{
return ::sd_event_add_exit(event, source, callback, userdata);
}
int SdEventImpl::sd_event_prepare(sd_event* event) const
{
return ::sd_event_prepare(event);
}
int SdEventImpl::sd_event_wait(sd_event* event, uint64_t usec) const
{
return ::sd_event_wait(event, usec);
}
int SdEventImpl::sd_event_dispatch(sd_event* event) const
{
return ::sd_event_dispatch(event);
}
int SdEventImpl::sd_event_run(sd_event* event, uint64_t usec) const
{
return ::sd_event_run(event, usec);
}
int SdEventImpl::sd_event_loop(sd_event* event) const
{
return ::sd_event_loop(event);
}
int SdEventImpl::sd_event_exit(sd_event* event, int code) const
{
return ::sd_event_exit(event, code);
}
int SdEventImpl::sd_event_now(sd_event* event, clockid_t clock,
uint64_t* usec) const
{
return ::sd_event_now(event, clock, usec);
}
int SdEventImpl::sd_event_get_exit_code(sd_event* event, int* code) const
{
return ::sd_event_get_exit_code(event, code);
}
int SdEventImpl::sd_event_get_watchdog(sd_event* event) const
{
return ::sd_event_get_watchdog(event);
}
int SdEventImpl::sd_event_set_watchdog(sd_event* event, int b) const
{
return ::sd_event_set_watchdog(event, b);
}
sd_event_source* SdEventImpl::sd_event_source_ref(sd_event_source* source) const
{
return ::sd_event_source_ref(source);
}
sd_event_source*
SdEventImpl::sd_event_source_unref(sd_event_source* source) const
{
return ::sd_event_source_unref(source);
}
void* SdEventImpl::sd_event_source_get_userdata(sd_event_source* source) const
{
return ::sd_event_source_get_userdata(source);
}
void* SdEventImpl::sd_event_source_set_userdata(sd_event_source* source,
void* userdata) const
{
return ::sd_event_source_set_userdata(source, userdata);
}
int SdEventImpl::sd_event_source_get_description(sd_event_source* source,
const char** description) const
{
return ::sd_event_source_get_description(source, description);
}
int SdEventImpl::sd_event_source_set_description(sd_event_source* source,
const char* description) const
{
return ::sd_event_source_set_description(source, description);
}
int SdEventImpl::sd_event_source_set_prepare(sd_event_source* source,
sd_event_handler_t callback) const
{
return ::sd_event_source_set_prepare(source, callback);
}
int SdEventImpl::sd_event_source_get_pending(sd_event_source* source) const
{
return ::sd_event_source_get_pending(source);
}
int SdEventImpl::sd_event_source_get_priority(sd_event_source* source,
int64_t* priority) const
{
return ::sd_event_source_get_priority(source, priority);
}
int SdEventImpl::sd_event_source_set_priority(sd_event_source* source,
int64_t priority) const
{
return ::sd_event_source_set_priority(source, priority);
}
int SdEventImpl::sd_event_source_get_enabled(sd_event_source* source,
int* enabled) const
{
return ::sd_event_source_get_enabled(source, enabled);
}
int SdEventImpl::sd_event_source_set_enabled(sd_event_source* source,
int enabled) const
{
return ::sd_event_source_set_enabled(source, enabled);
}
int SdEventImpl::sd_event_source_get_io_fd(sd_event_source* source) const
{
return ::sd_event_source_get_io_fd(source);
}
int SdEventImpl::sd_event_source_set_io_fd(sd_event_source* source,
int fd) const
{
return ::sd_event_source_set_io_fd(source, fd);
}
int SdEventImpl::sd_event_source_get_io_events(sd_event_source* source,
uint32_t* events) const
{
return ::sd_event_source_get_io_events(source, events);
}
int SdEventImpl::sd_event_source_set_io_events(sd_event_source* source,
uint32_t events) const
{
return ::sd_event_source_set_io_events(source, events);
}
int SdEventImpl::sd_event_source_get_io_revents(sd_event_source* source,
uint32_t* revents) const
{
return ::sd_event_source_get_io_revents(source, revents);
}
int SdEventImpl::sd_event_source_get_time(sd_event_source* source,
uint64_t* usec) const
{
return ::sd_event_source_get_time(source, usec);
}
int SdEventImpl::sd_event_source_set_time(sd_event_source* source,
uint64_t usec) const
{
return ::sd_event_source_set_time(source, usec);
}
int SdEventImpl::sd_event_source_get_time_accuracy(sd_event_source* source,
uint64_t* usec) const
{
return ::sd_event_source_get_time_accuracy(source, usec);
}
int SdEventImpl::sd_event_source_set_time_accuracy(sd_event_source* source,
uint64_t usec) const
{
return ::sd_event_source_set_time_accuracy(source, usec);
}
int SdEventImpl::sd_event_source_get_signal(sd_event_source* source) const
{
return ::sd_event_source_get_signal(source);
}
int SdEventImpl::sd_event_source_get_child_pid(sd_event_source* source,
pid_t* pid) const
{
return ::sd_event_source_get_child_pid(source, pid);
}
int SdEventImpl::sd_event_source_set_destroy_callback(
sd_event_source* source, sd_event_destroy_t callback) const
{
return ::sd_event_source_set_destroy_callback(source, callback);
}
int SdEventImpl::sd_event_source_get_destroy_callback(
sd_event_source* source, sd_event_destroy_t* callback) const
{
return ::sd_event_source_get_destroy_callback(source, callback);
}
int SdEventImpl::sd_event_source_set_floating(sd_event_source* source,
int b) const
{
return ::sd_event_source_set_floating(source, b);
}
int SdEventImpl::sd_event_source_get_floating(sd_event_source* source) const
{
return ::sd_event_source_get_floating(source);
}
SdEventImpl sdevent_impl;
} // namespace internal
} // namespace sdeventplus
|
71f8c5fbbd80364ee255106db213dc896a36e0ec | be77b37589d776bfac6f4506fe4ab28db7253d39 | /IU/ast.h | 1666fdc1dd4c500c6eb0b141dac25d9d52879131 | [] | no_license | Hongzhe/IU | 9b6c5b0f502f297fddfa54d9423dd4cce018b241 | c60f1528c3ad0740e973fc763b36c49862e84d19 | refs/heads/master | 2016-08-12T21:27:03.589062 | 2016-05-15T12:13:50 | 2016-05-15T12:13:50 | 54,780,107 | 1 | 0 | null | null | null | null | IBM866 | C++ | false | false | 9,507 | h | ast.h | #pragma once
#include "stdafx.h"
#include "Lexer.h"
#include <vector>
#include <memory>
#include <string>
#include <iostream>
class BinaryExpression;
class LiteralExpression;
class MethodInvocationExpression;
class ClassCreatorExpression;
class PranExpression;
class VariableDeclareExpression;
class IfStatement;
class WhileStatement;
class MethodDefinition;
class Formal;
class ClassNode;
class BlockStatement;
class ExpStatement;
//visitor pattern
class IVisitor
{
public:
virtual void visit(std::shared_ptr<BinaryExpression> node) = 0;
virtual void visit(std::shared_ptr<LiteralExpression> node) = 0;
virtual void visit(std::shared_ptr<MethodInvocationExpression> node) = 0;
virtual void visit(std::shared_ptr<ClassCreatorExpression> node) = 0;
virtual void visit(std::shared_ptr<PranExpression> node) = 0;
virtual void visit(std::shared_ptr<Formal> node) = 0;
virtual void visit(std::shared_ptr<IfStatement> node) = 0;
virtual void visit(std::shared_ptr<WhileStatement> node) = 0;
virtual void visit(std::shared_ptr<MethodDefinition> node) = 0;
virtual void visit(std::shared_ptr<ClassNode> node) = 0;
virtual void visit(std::shared_ptr<BlockStatement> node) = 0;
virtual void visit(std::shared_ptr<ExpStatement> node) = 0;
virtual void visit(std::shared_ptr<VariableDeclareExpression> node) = 0;
};
enum ASTNodeType {
LITERAL_EXP, PRAN_EXP, BINARY_EXP, METHOD_INVOC_EXP, CREATOR_EXP,VAR_DECL_EXP,
IF_STMT, WHILE_STMT, METHOD_DEFINE_STMT,CLASS_NODE, FORMAL, BLOCK_STMT,
EXP_STMT,RETURN_STMT
};
class ASTNode {
public:
ASTNode(){}
ASTNode(unsigned int lineno, ASTNodeType type) : lineno(lineno), node_type(type) {}
unsigned int lineno;
ASTNodeType node_type;
virtual void accept(IVisitor* visitor) = 0;
};
class Expression : public ASTNode {
public:
virtual ~Expression() {}
};
class PranExpression : public Expression {
public:
std::shared_ptr<Expression> exp;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<PranExpression>(this)); }
};
class BinaryExpression : public Expression {
public:
BinaryExpression(Token op, std::shared_ptr<Expression> l,
std::shared_ptr<Expression> r) : op(op), left(l), right(r) {}
BinaryExpression() {}
Token op;
std::shared_ptr<Expression> left;
std::shared_ptr<Expression> right;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<BinaryExpression>(this)); }
};
class VariableDeclareExpression : public Expression
{
public:
VariableDeclareExpression(Token id, Token type): id(id), type(type) {}
VariableDeclareExpression() {}
Token id;
Token type;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<VariableDeclareExpression>(this)); }
};
class LiteralExpression : public Expression {
public:
LiteralExpression() {}
LiteralExpression(Token token) : token(token){}
Token token;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<LiteralExpression>(this)); }
};
class ClassCreatorExpression : public Expression {
public:
ClassCreatorExpression(Token token) : name(token) {}
Token name;
std::vector<std::shared_ptr<Expression>>arguments;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<ClassCreatorExpression>(this)); }
};
class MethodInvocationExpression : public Expression {
public:
MethodInvocationExpression(Token token):name(token) {}
Token name;
std::vector<std::shared_ptr<Expression>> arguments;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<MethodInvocationExpression>(this));}
};
class Statement : public ASTNode {
public:
virtual ~Statement() {};
};
class BlockStatement : public Statement {
public:
std::vector<std::shared_ptr<Statement>> stmts;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<BlockStatement>(this)); }
};
class ExpStatement : public Statement {
public:
ExpStatement() {}
ExpStatement(std::shared_ptr<Expression> exp) : expression(exp) {}
std::shared_ptr<Expression> expression;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<ExpStatement>(this)); }
};
class IfStatement : public Statement
{
public:
IfStatement() {}
std::shared_ptr<Expression> condition;
std::shared_ptr<BlockStatement> block;
std::shared_ptr<BlockStatement> elsepart;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<IfStatement>(this)); }
};
class WhileStatement : public Statement
{
public:
std::shared_ptr<Expression> condition;
std::shared_ptr<BlockStatement> block;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<WhileStatement>(this)); }
};
class Formal : public ASTNode
{
public:
Token type;
Token id;
std::shared_ptr<Expression> val;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<Formal>(this)); }
};
class MethodDefinition : public ASTNode
{
public:
Token returntype;
Token name;
std::vector<std::shared_ptr<Formal>> arguments;
std::shared_ptr<BlockStatement> block;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<MethodDefinition>(this)); }
};
class ClassNode : public ASTNode
{
public:
Token classname;
std::vector<std::shared_ptr<MethodDefinition>> methods;
std::vector<std::shared_ptr<Formal>> fields;
std::shared_ptr<MethodDefinition> mainMethod;
std::unique_ptr<ClassNode> parent;
std::string parentname;
void accept(IVisitor* visitor) { visitor->visit(std::shared_ptr<ClassNode>(this)); }
};
class TreePrinter : public IVisitor
{
public:
void visit(std::shared_ptr<Expression> node) {
if (!node) return;
switch (node->node_type) {
case LITERAL_EXP:
visit(std::dynamic_pointer_cast<LiteralExpression>(node));
break;
case FORMAL:
visit(std::dynamic_pointer_cast<Formal>(node));
break;
case CREATOR_EXP:
visit(std::dynamic_pointer_cast<ClassCreatorExpression>(node));
break;
case METHOD_INVOC_EXP:
visit(std::dynamic_pointer_cast<MethodInvocationExpression>(node));
break;
case PRAN_EXP:
visit(std::dynamic_pointer_cast<PranExpression>(node));
break;
case BINARY_EXP:
visit(std::dynamic_pointer_cast<BinaryExpression>(node));
break;
}
}
void visit(std::shared_ptr<PranExpression> node)
{
std::cout << "( ";
visit(node->exp);
std::cout << " )" << std::endl;
}
void visit(std::shared_ptr<BinaryExpression> node)
{
visit(node->left);
std::cout << " " << node->op.lexem << " ";
visit(node->right);
}
void visit(std::shared_ptr<LiteralExpression> node) {
std::cout << node->token.lexem << " ";
}
void visit(std::shared_ptr<Formal> node)
{
std::cout << node->type.lexem << " " << node->id.lexem;
if (node->val) {
visit(node->val);
}
}
void visit(std::shared_ptr<ClassCreatorExpression> node)
{
std::cout << "new " << node->name.lexem << "( ";
std::vector<std::shared_ptr<Expression>> arguments = node->arguments;
for (int i = 0; i < (int)arguments.size(); i++) {
visit(arguments[i]);
std::cout << " ";
}
std::cout << ")";
}
void visit(std::shared_ptr<MethodInvocationExpression> node) {
std::cout << node->name.lexem << " (";
std::vector<std::shared_ptr<Expression>> argumnets = node->arguments;
for (int i = 0; i < (int)argumnets.size(); i++)
{
visit(argumnets[i]);
}
std::cout << ")" << std::endl;
}
void visit(std::shared_ptr<Statement> node)
{
if (!node) return;
switch (node->node_type)
{
case IF_STMT:
visit(std::dynamic_pointer_cast<IfStatement>(node));
break;
case WHILE_STMT:
visit(std::dynamic_pointer_cast<WhileStatement>(node));
break;
case METHOD_DEFINE_STMT:
visit(std::dynamic_pointer_cast<MethodDefinition>(node));
break;
case BLOCK_STMT:
visit(std::dynamic_pointer_cast<BlockStatement>(node));
break;
case EXP_STMT:
visit(std::dynamic_pointer_cast<ExpStatement>(node));
break;
case RETURN_STMT:
visit(std::dynamic_pointer_cast<ExpStatement>(node));
break;
}
}
void visit(std::shared_ptr<IfStatement> node)
{
std::cout << "if (" ;
visit(node->condition);
std::cout << " )";
visit(node->block);
if (node->elsepart) {
std::cout << "else ";
visit(node->elsepart);
}
}
void visit(std::shared_ptr<WhileStatement> node)
{
std::cout << "while (";
visit(node->condition);
std::cout << " )";
visit(node->block);
}
void visit(std::shared_ptr<MethodDefinition> node)
{
std::cout << node->returntype.lexem << " ";
std::cout << node->name.lexem << " ги";
auto arguments = node->arguments;
for (int i = 0; i < (int)arguments.size(); i++) {
visit(arguments[i]);
}
std::cout << ")";
visit(node->block);
}
void visit(std::shared_ptr<BlockStatement> node)
{
std::cout << "{ " << std::endl;
auto stmts = node->stmts;
for (int i = 0; i < (int)stmts.size(); i++) {
visit(stmts[i]);
}
std::cout << "}" << std::endl;
}
void visit(std::shared_ptr<ExpStatement> node)
{
if (node->node_type == RETURN_STMT) {
std::cout << "return ";
}
visit(node->expression);
}
void visit(std::shared_ptr<VariableDeclareExpression> node)
{
std::cout << node->type.lexem << " " << node->id.lexem;
}
void visit(std::shared_ptr<ClassNode> node)
{
std::cout << "class " << node->classname.lexem;
if (node->parent) {
std::cout << "inherits " << node->parent->classname.lexem;
}
std::cout << "{ ";
auto fields = node->fields;
for (int i = 0; i < (int)fields.size(); i++) {
visit(fields[i]);
}
std::cout << std::endl;
auto methods = node->methods;
for (int j = 0; j < (int)methods.size(); j++) {
visit(methods[j]);
std::cout << std::endl;
}
std::cout << "}" << std::endl;
}
}; |
a925daaf78942922c6e0e14de226fce258dbe93d | 0aaa2908168ddb2f10ebc77e928a5ef1ff211006 | /21-2-5/21-2-5/大小写转换.cpp | d1a46f30a32c496611774a7943add2c5feabe16d | [] | no_license | zhanghaoyu020418/lanqiao | e93551971f3df713633759db2b479cf689e445a6 | c09954b51652a45cbab8f147d7c7e44918491d1d | refs/heads/master | 2023-03-07T02:24:02.228645 | 2021-02-19T15:08:42 | 2021-02-19T15:08:42 | 332,726,799 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | 大小写转换.cpp | //#define _CRT_SECURE_NO_WARNINGS 1
//#include <iostream>
//#include <string.h>
//#include <assert.h>
//using namespace std;
//
//bool strjugde(char* arr1, char* arr2)
//{
// assert(arr1 && arr2);
// while (*arr1)
// {
// if (*arr1 == *arr2)
// {
// arr1++;
// arr2++;
// }
// else
// {
// if (isupper(*arr1))
// *arr1 = tolower(*arr1);
// else if (islower(*arr1))
// *arr1 = toupper(*arr1);
// if (*arr1 == *arr2)
// {
// arr1++;
// arr2++;
// }
// else
// return 0;
// }
// }
// return 1;
//}
//
//int main()
//{
// char arr1[11];
// char arr2[11];
// char arr3[11];
//
// scanf("%s", arr1);
// scanf("%s", arr2);
//
//
// if (strlen(arr1) != strlen(arr2))
// {
// printf("1\n");
// }
// else if (strcmp(arr1, arr2) == 0)
// {
// printf("2\n");
// }
// else if (strjugde(arr1, arr2))
// {
// printf("3\n");
// }
// else
// {
// printf("4\n");
// }
//
// return 0;
//}
//
|
754ea62e094705fc6ca9614279180e340f4b94bc | ac4d78fd1baf51fcabfe9192c779e0d95f50683e | /src/DynamicGraphFCL.cpp | c7b46bf43f43c5981f80b4cb3e0e4c2d7707e4b4 | [] | no_license | Karsten1987/dynamic_graph_fcl | c4872c492ce76e8cb5b21c166fda7712657198b8 | 13c4820809623c2d81aa2e892808b2a1b428d48f | refs/heads/master | 2020-06-01T02:31:42.580237 | 2014-03-05T11:58:43 | 2014-03-05T11:58:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,032 | cpp | DynamicGraphFCL.cpp | /*
* Software License Agreement (Modified BSD License)
*
* Copyright (c) 2012-2014, PAL Robotics, S.L.
* 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 PAL Robotics, S.L. 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 Karsten Knese
* @date 5.3.2014
*/
#include <math.h>
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/command-setter.h>
#include <dynamic-graph/command-getter.h>
#include <dynamic-graph/factory.h>
#include <dynamic_graph_fcl/DynamicGraphFCL.h>
#include <dynamic_graph_fcl/Conversions.h>
#include <dynamic_graph_fcl/SignalHelper.h>
#include <sot/core/matrix-rotation.hh>
#include <ros/ros.h>
namespace dynamicgraph {
namespace FCL {
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(DynamicGraphFCL, "DynamicGraphFCL");
typedef SignalTimeDependent < sot::MatrixHomogeneous, int > SignalTimeMatrix;
typedef SignalTimeDependent < dynamicgraph::Vector, int > SignalTimeVector;
typedef SignalPtr<dynamicgraph::Vector, int > SignalPtrVector;
typedef SignalPtr<sot::MatrixHomogeneous, int > SignalPtrMatrix;
DynamicGraphFCL::DynamicGraphFCL(const std::string &inName):
Entity(inName),
inName_(inName),
tfBroadcaster_(new TFBroadcaster()),
sotCompensator_(new SOTCompensator())
{
std::string docstring;
docstring =
"\n"
" Initializes collisions for fcl\n"
" takes a string of joint names (separated by :) for collision objects \n"
"\n";
addCommand(std::string("set_collision_joints"),
new dynamicgraph::command::Setter<DynamicGraphFCL, std::string >
(*this, &DynamicGraphFCL::set_collision_joints, docstring));
}
DynamicGraphFCL::~DynamicGraphFCL() {}
/// using a split for a continous string,
//because ATM I didn't find any other method for passing a vector of strings into an entity
void DynamicGraphFCL::set_collision_joints(const std::string &joint_collision_names)
{
Conversions::split(joint_collision_names_, joint_collision_names, ':');
joint_collision_size_ = joint_collision_names_.size();
sotCompensator_->initVectorSize(joint_collision_size_);
std::cerr << "amount of collison links found: " << joint_collision_size_ << std::endl;
initCollisionObjects();
initSignals();
initDebugSignals();
}
void DynamicGraphFCL::initCollisionObjects()
{
// give the sotcompensator pointer to urdf for applying to the urdf origin
urdfParser_.reset(new URDFParser("robot_description", joint_collision_names_));
urdfParser_->getCollisionObjects();
}
/// Signal Declaration
void DynamicGraphFCL::initSignals()
{
/// Allocate one input signal for each collision object !!
op_point_in_vec_.resize(joint_collision_size_);
std::cerr << "op_vec initiliazed" << std::endl;
// Allocate n^2 output signal for each collision pair
collision_matrix_.resize((joint_collision_size_*joint_collision_size_));
std::cerr << "matrix initiliazed" << std::endl;
oppoint_transformations_.resize(joint_collision_size_ * joint_collision_size_);
std::cerr << "oppoint transformations initialized" << std::endl;
for (int joint_idx = 0; joint_idx < joint_collision_size_; ++joint_idx) {
// for each collision object create one input signal to update the transform of the capsule/mesh
op_point_in_vec_[joint_idx] =
SignalHelper::createInputSignalMatrix(joint_collision_names_[joint_idx]);
signalRegistration(*op_point_in_vec_[joint_idx]);
// load the respective sot_compensation from the ros_param server
// HERe!
sotCompensator_->setSOTCompensation(joint_collision_names_[joint_idx], joint_idx);
std::cerr << "input signal registrated "
<< joint_collision_names_[joint_idx] << std::endl;
std::cerr << "input signal registrated "
<< "oppoint_"+joint_collision_names_[joint_idx] << std::endl;
}
// !! NOTE
// this might be optimized as one collision-computation is birectional.
// This means that e.g. arm_left & arm_right results in the same computation as arm_right & arm_left
// one quick solution can be by introducing a dirty-flag, set or reset when one transform of those two pairs is updated
//
// compute arm_left & arm_right --> compute both points + return point[0] + reset dirty-flag
// compute arm_right & arm_left --> return point[1]
// update arm_right OR arm_left transform --> set dirty-flag
// also cross-initialize all pairs of collision, excluding a pair of itself
// IGNORING THE ABOVE NOTE!
for (int joint_idx = 0; joint_idx < joint_collision_size_; ++joint_idx) {
for (int joint_idy = 0; joint_idy < joint_collision_size_; ++joint_idy) {
if (joint_idy != joint_idx){
fillCollisionMatrix(joint_idx, joint_idy);
}
}
}
}
void DynamicGraphFCL::fillCollisionMatrix(int idx, int idy)
{
std::string joint_name_1 = joint_collision_names_[idx];
std::string joint_name_2 = joint_collision_names_[idy];
int collision_matrix_idx = getMatrixIndex(idx, idy);
boost::shared_ptr<SignalTimeMatrix> collisionSignal =
SignalHelper::createOutputSignalTimeMatrix(joint_name_1+joint_name_2);
collisionSignal->addDependency(*op_point_in_vec_[idx]);
collisionSignal->addDependency(*op_point_in_vec_[idy]);
collisionSignal->setFunction(boost::bind(&DynamicGraphFCL::closest_point_update_function,
this, _1, _2, joint_name_1, idx, joint_name_2, idy));
signalRegistration(*collisionSignal);
collision_matrix_[collision_matrix_idx] = collisionSignal;
oppoint_transformations_[collision_matrix_idx] =
SignalHelper::createOutputSignalTimeVector(
"oppoint_"+joint_collision_names_[idx]+joint_collision_names_[idy]);
signalRegistration(*oppoint_transformations_[collision_matrix_idx]);
}
void DynamicGraphFCL::initDebugSignals()
{
std::string debug_point_1
= "DynamicGraphFCL("+inName_+")::output(int)::debugPoint1";
debug_point_1_out
= boost::shared_ptr<SignalTimeVector>(
new SignalTimeVector(NULL, debug_point_1));
signalRegistration(*debug_point_1_out);
std::string debug_point_2
= "DynamicGraphFCL("+inName_+")::output(int)::debugPoint2";
debug_point_2_out
= boost::shared_ptr<SignalTimeVector>(
new SignalTimeVector(NULL, debug_point_2));
signalRegistration(*debug_point_2_out);
}
/// Update function for the ouput signals
sot::MatrixHomogeneous& DynamicGraphFCL::closest_point_update_function(
sot::MatrixHomogeneous& point, int i,
std::string &joint_name_1, int &idx,
std::string &joint_name_2, int &idy)
{
if (joint_collision_names_[idx] != joint_name_1){
std::cerr << "SOMETHING'S BRUTALLY WRONG HERE" << std::endl;
}
if (joint_collision_names_[idy] != joint_name_2){
std::cerr << "SOMETHING'S BRUTALLY WRONG HERE" << std::endl;
}
// receive the dependent transformation for both joints
updateURDFParser(((*op_point_in_vec_[idx])(i)), idx);
updateURDFParser(((*op_point_in_vec_[idy])(i)), idy);
fcl::Vec3f closest_point_1, closest_point_2;
urdfParser_->getClosestPoints(joint_collision_names_[idx],
joint_collision_names_[idy],
closest_point_1,
closest_point_2);
// IMPORTANT NOTE HERE:
// The second point is getting ignored
// due to the duplication of the signal matrix
// Place here the update of the dirty flag
// by a measurement if any of the given input signals has changed or not.
const sot::MatrixHomogeneous& op_point_in = (*op_point_in_vec_[idx])(i);
dynamicgraph::Vector cp1 = Conversions::convertToDG(closest_point_1);
dynamicgraph::Vector relativ_point = op_point_in.inverse().multiply(cp1);
int matrixIndex = getMatrixIndex(idx, idy);
oppoint_transformations_[matrixIndex]->setConstant(relativ_point);
sot::MatrixRotation rot1;
op_point_in.extract(rot1);
point.buildFrom(rot1,relativ_point);
point.elementAt(0,3) = closest_point_1[0];
point.elementAt(1,3) = closest_point_1[1];
point.elementAt(2,3) = closest_point_1[2];
return point;
}
void DynamicGraphFCL::updateURDFParser(const dynamicgraph::Matrix& op_point_sig, int id)const
{
/* This case differencial has to be done based on JLR-Dynamic convention
all rotations are going to be around X-Axis and not as mentioned in the URDF
on the same hand, they ignore all FIXED-joint declarations, which means all frames like
end-effector, tool_joints, base_joints etc.
are not being under this convention and can be processed as usual.
*/
dynamicgraph::Matrix origin = Conversions::convertToDG(urdfParser_->getOrigin(joint_collision_names_[id]));
dynamicgraph::Matrix urdf_frame = sotCompensator_->applySOTCompensation(op_point_sig, id);
dynamicgraph::Matrix urdf_origin = urdf_frame.multiply(origin);
// update collision objects. Rotation and Position is directly transformed into FCL
// all transformations got capsuled into Conversion-namespace to keep up the separation between URDF/FCL and DG
urdfParser_->updateLinkPosition(
joint_collision_names_[id],
*(Conversions::convertToFCLTransform(urdf_origin)));
}
} // namespace FCL
} // namespace dynamicgraph
|
371ddeff731c6e4564c7b39da3b6e2edff011efb | f5e9215bde4a1b5a519736d10b1d31b922c66595 | /originals/swatch-master/swatch/system/include/swatch/system/CrateStub.hpp | 84cf66c387aef0205c6edd78d82cd020a06d225d | [] | no_license | kevimota/rpcos4ph2_swatch_based | 9618fd771aceef9e0cd2ecc3650c6626170b089d | 07843a47bc9914dff9a75ff1ba26cd9581aa38da | refs/heads/master | 2022-12-18T00:07:41.096044 | 2020-09-03T19:19:58 | 2020-09-03T19:19:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | hpp | CrateStub.hpp | /**
* @file CrateStub.hpp
* @author Alessandro Thea
* @date 11/11/14
*/
#ifndef __SWATCH_SYSTEM_CRATESTUB_HPP__
#define __SWATCH_SYSTEM_CRATESTUB_HPP__
// C++ headers
#include <iosfwd>
#include <string> // for string
// SWATCH headers
#include "swatch/core/AbstractStub.hpp"
namespace swatch {
namespace system {
//! Structure that holds the data required to build a crate
class CrateStub : public swatch::core::AbstractStub {
public:
CrateStub(const std::string& aId) :
AbstractStub(aId) { }
virtual ~CrateStub() { }
//! Description of the crate
std::string description;
//! Geo location of the crate
std::string location;
};
bool operator==(const CrateStub& aStub1, const CrateStub& aStub2);
std::ostream& operator<<(std::ostream& aStream, const swatch::system::CrateStub& aStub);
} // namespace system
} // namespace swatch
#endif /* __SWATCH_SYSTEM_CRATESTUB_HPP__ */
|
4b8440c8956470806f30b1b6df9a534af333c069 | 5391638d38a17280fa4abe5187bf8d417740a795 | /codeforces/pc.cpp | 0b8bd6d59334b425b07d96b5c326b8bbd23d681b | [] | no_license | SiluPanda/competitive-programming | 39ce18ef48b13e381536c53a6769faa0edac3502 | 6e92ccb165381f1ee0b2cf42ea997ab44e6fc8eb | refs/heads/master | 2020-06-12T22:35:13.688327 | 2020-04-22T09:40:01 | 2020-04-22T09:40:01 | 178,658,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 850 | cpp | pc.cpp | #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define endl "\n"
#define fastio ios_base::sync_with_stdio(0);cin.tie(NULL);
#define ll long long int
int main(){
fastio
int n, q;
cin >> n >> q;
vector <map <int, int> > F(3);
while(q--){
int r,c;
cin >> r >> c;
if(F[r].find(c) != F[r].end()){
F[r].erase(c);
}
else F[r][c] = 1;
bool flag = false;
for(auto it = F[1].begin(); it != F[1].end(); it++){
int curr = it->first;
if(F[2].find(curr) != F[2].end()
|| F[2].find(curr+1) != F[2].end()
|| F[2].find(curr-1) != F[2].end()){
cout << "No" << endl;
flag = true;
break;
}
}
if(!flag) cout << "Yes" << endl;
}
} |
cd60213f0f02aa818472a07c0227e78f325c9eb4 | 9d854849f8ecdccf3c6f08e02107b08cf0406be6 | /UVA/Accepted solution/10235 simply emirp.cpp | 24315aa3d1f0659533c94762de1dd2757b61d6fd | [] | no_license | sagorbrur/My-Contest-Code | 4bedc9a752f481cb6613d85af9ade1a3fd59d43d | 20b35e5ae2226dbf369cd09abf7e88ec50b8aa6d | refs/heads/master | 2020-03-26T07:45:06.257446 | 2018-08-14T04:37:04 | 2018-08-14T04:37:04 | 144,669,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | cpp | 10235 simply emirp.cpp | #include<stdio.h>
int is_prime (long int x)
{
int i;
for ( i = 2; i * i <= x; i++)
{
if (x % i == 0)
return 0;
}
return 1;
}
int rev(unsigned int n)
{
unsigned int reverse=0;
while(n!=0)
{
reverse=reverse*10;
reverse=reverse+n%10;
n=n/10;
}
return reverse;
}
int main()
{
long int n;
while(scanf("%ld",&n)==1)
{
if(is_prime(n)!=1)
printf("%ld is not prime.\n",n);
else
{
int n1=rev(n);
if(is_prime(n1)==1&&n1!=n)
printf("%ld is emirp.\n",n);
else
printf("%ld is prime.\n",n);
}
}
return 0;
}
|
403feced4da27021c43eeda6bd5cece43ed63f0d | 42b68e18d6bf4aef0962da5ce58f9d97028eecaf | /upredictor/charm/planning/libworldmodel/include/actorsorter.h | f33604d542ab8c11f2619560a0ae826d046641cb | [] | no_license | ssheikho/uPredictor | 0f0b4cdea1a30193fce5d6b44307fd1e2cfe76d6 | c95a7923cb5714590496fab571d318674cb2861f | refs/heads/master | 2021-07-11T03:00:39.556540 | 2017-10-06T02:57:48 | 2017-10-06T02:57:48 | 105,960,135 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | h | actorsorter.h | #ifndef ACTOR_SORTER_H
#define ACTOR_SORTER_H
#include <map>
#include <string>
#include <vector>
class ActorEventLine;
class ActorPlan;
class ConcurrentPlan;
class ParamListTable;
class Plan;
class WorldModel;
using namespace std;
class ActorSorter {
public:
ActorSorter();
~ActorSorter();
ActorPlan *processPlan(Plan *p, WorldModel &wm);
//ActorPlan *processConcurrentPlan(ConcurrentPlan *cp);
void addActor(string name);
void addAction(string action, string actor);
void processPLT(ParamListTable *plt);
void printContents();
protected:
//void processConcurrentPlanTwo(ConcurrentPlan *cp, ActorPlan *ap);
ActorPlan *generateAP(Plan *p);
//ActorPlan *generateAP(ConcurrentPlan *cp);
int _nActors;
ParamListTable *_plt;
map<string, int> _actorMap;
map<int, string> _actorReverseMap;
map<string, int> _actionToActor;
map<int, int> _plToActor;
};
/*
void loadPlugfest();
//ActorPlan *processConcurrentPlan(ConcurrentPlan *cp);
//vector<ActorEventLine *> _actors;
*/
#endif
|
f9a0b1a13639f5c769789cc644cc85ce5be07a98 | 1187264d0baba88299eb7bc27eca0ae0e931212c | /gfx/skia/trunk/src/animator/SkDrawDash.h | 61a3b94a2a8246bcbd9c6db56e3ab0c9378f073c | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | c3358/gecko-dev-comments-removed | 2d3be3e27948e3f3be85b85bfbae5f7cc374ab53 | 33a3f2865853f8e4fe6f11c0aa78380fc2f7f679 | refs/heads/master | 2023-04-14T05:00:35.369189 | 2019-07-27T14:34:45 | 2019-07-27T14:34:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | h | SkDrawDash.h |
#ifndef SkDrawDash_DEFINED
#define SkDrawDash_DEFINED
#include "SkPaintPart.h"
#include "SkIntArray.h"
class SkDash : public SkDrawPathEffect {
DECLARE_MEMBER_INFO(Dash);
SkDash();
virtual ~SkDash();
virtual SkPathEffect* getPathEffect();
private:
SkTDScalarArray intervals;
SkScalar phase;
};
#endif
|
78bdca852330ce389a7c9917c12c09b1d433649f | 72120d7d48b7f184e957b8a84dce4022ea93d2b9 | /src/tests/documentlabelindextest.cpp | bf84d21ead718e0dee809977f25b4e8c9faf5ebd | [
"MIT"
] | permissive | BGR360/asIDE | 55d331d6b4fb63947cb58e70d1371af14a5b108c | 1ee4ef4a7aa15a004565dd43caaeb2ee1c733165 | refs/heads/master | 2021-01-13T12:55:17.420530 | 2016-04-29T21:19:14 | 2016-04-29T21:19:14 | 55,190,398 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,866 | cpp | documentlabelindextest.cpp | //////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// The MIT License (MIT) //
// Copyright (c) 2016 Benjamin Reeves //
// //
// 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 "documentlabelindextest.h"
#include <QSet>
#include <QSignalSpy>
#include <QTest>
#include <QTextCursor>
#include <QTextDocument>
#include <QVector>
#include "documentlabelindex.h"
void DocumentLabelIndexTest::testDocuments_data()
{
QTest::addColumn<QString>("docText");
QTest::addColumn<QVector<QString> >("labels");
QTest::addColumn<QVector<bool> >("expectedBools");
QTest::addColumn<QVector<int> >("expectedLines");
QTest::newRow("one declared label") << "label\t0" <<
QVector<QString>({"label", "0"}) <<
QVector<bool>({true, false}) <<
QVector<int>({0, -1});
QTest::newRow("label after instruction") << "\t\tbne\tlabel" <<
QVector<QString>({"bne", "label"}) <<
QVector<bool>({false, false}) <<
QVector<int>({-1, -1});
QTest::newRow("label after tab") << "\t\tlabel\t0" <<
QVector<QString>({"label", "0"}) <<
QVector<bool>({true, false}) <<
QVector<int>({0, -1});
QTest::newRow("three declared labels") << "label1\t0\n"
"label2\t0\n"
"label3\t0\n" <<
QVector<QString>({"label1", "label2", "label3", "0"}) <<
QVector<bool>({true, true, true, false}) <<
QVector<int>({0, 1, 2, -1});
QTest::newRow("label gets address of other") << "label\t0\n"
"ptr\tlabel" <<
QVector<QString>({"label", "0", "ptr"}) <<
QVector<bool>({true, false, true}) <<
QVector<int>({0, -1, 1});
}
void DocumentLabelIndexTest::testDocuments()
{
QFETCH(QString, docText);
QFETCH(QVector<QString>, labels);
QFETCH(QVector<bool>, expectedBools);
QFETCH(QVector<int>, expectedLines);
QTextDocument doc(docText);
DocumentLabelIndex index(&doc);
const int numLabels = labels.size();
for (int i = 0; i < numLabels; ++i) {
QString label = labels[i];
bool expectedBool = expectedBools[i];
bool resultBool = index.hasLabel(label);
const char* message = QString("index.hasLabel(%1) should not be %2")
.arg(label)
.arg(resultBool)
.toStdString().c_str();
QVERIFY2(expectedBool == resultBool, message);
int expectedLine = expectedLines[i];
int resultLine = index.lineNumberOfLabel(label);
message = QString("Line number of %1 should be %2, not %3")
.arg(label)
.arg(expectedLine)
.arg(resultLine)
.toStdString().c_str();
QVERIFY2(expectedLine == resultLine, message);
}
}
typedef QList<QList<QVariant> > ParamList;
void DocumentLabelIndexTest::testSignals_data()
{
QTest::addColumn<QString>("initialDocText");
QTest::addColumn<int>("cursorStart");
QTest::addColumn<int>("cursorEnd");
QTest::addColumn<QString>("insertedText");
QTest::addColumn<ParamList>("expectedAdded");
QTest::addColumn<ParamList>("expectedRemoved");
QTest::newRow("blank -> label") << "" <<
0 << 0 <<
"label\t0" <<
ParamList({
{"label", 0}
}) <<
ParamList();
QTest::newRow("blank -> labels") << "" <<
0 << 0 <<
"label1 0\n"
"label2 0\n"
"label3 0" <<
ParamList({
{"label1", 0},
{"label2", 1},
{"label3", 2}
}) <<
ParamList();
QTest::newRow("remove one label") << "label1 0\n"
"label2 0\n"
"label3 0" <<
9 << 18 << " " <<
ParamList({
{"label3", 1}
}) <<
ParamList({
{"label2", 1},
{"label3", 2}
});
QTest::newRow("remove all labels") << "label1 0\n"
"label2 0\n"
"label3 0" <<
0 << 26 << " " <<
ParamList() <<
ParamList({
{"label1", 0},
{"label2", 1},
{"label3", 2}
});
QTest::newRow("add label to empty line") << "label1 0\n"
"\n"
"label3 0" <<
9 << 9 <<
"label2 0" <<
ParamList({
{"label2", 1}
}) <<
ParamList();
}
void DocumentLabelIndexTest::testSignals()
{
QFETCH(QString, initialDocText);
QFETCH(int, cursorStart);
QFETCH(int, cursorEnd);
QFETCH(QString, insertedText);
QFETCH(ParamList, expectedAdded);
QFETCH(ParamList, expectedRemoved);
QTextDocument doc(initialDocText);
QTextCursor cursor(&doc);
DocumentLabelIndex index(&doc);
QSignalSpy addedSpy(&index, SIGNAL(labelAdded(QString,int)));
QSignalSpy removedSpy(&index, SIGNAL(labelRemoved(QString,int)));
cursor.setPosition(cursorStart);
if (cursorEnd != cursorStart) {
cursor.setPosition(cursorEnd, QTextCursor::KeepAnchor);
}
cursor.insertText(insertedText);
qDebug() << "new text:" << doc.toPlainText();
QCOMPARE(addedSpy.count(), expectedAdded.size());
QCOMPARE(removedSpy.count(), expectedRemoved.size());
ParamList::iterator e = expectedAdded.begin();
for (; e != expectedAdded.end(); ++e) {
QVERIFY(addedSpy.contains(*e));
}
e = expectedRemoved.begin();
for (; e != expectedRemoved.end(); ++e) {
QVERIFY(removedSpy.contains(*e));
}
}
|
4c7f9d0d8bfca7ebdb4497183ae8ae316d4a1b95 | 90c19b75ef090709df1d121d219635284256b301 | /src/gazebo_hrim_ft_sensor.cpp | 0250948fe968ddf343e009e1bb50f529b5fb7c81 | [] | no_license | dejaniraai/gazebo_hrim_plugins | e06f3d2400bfa0c0e08d14bcd48fdbd544faab1a | ebdd426cceaf87025050c64c64a427ece3b389f0 | refs/heads/master | 2020-06-23T19:57:14.360919 | 2019-06-28T06:28:10 | 2019-06-28T06:28:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,054 | cpp | gazebo_hrim_ft_sensor.cpp | // Copyright (c) 2013, Markus Bader <markus.bader@tuwien.ac.at>
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// 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 company 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.
#include <gazebo/common/Events.hh>
#include <gazebo/common/Time.hh>
#include <gazebo/physics/Joint.hh>
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/Model.hh>
#include <gazebo/physics/World.hh>
#include <gazebo_hrim_plugins/gazebo_hrim_ft_sensor.hpp>
#include <gazebo_ros/node.hpp>
#include <rclcpp/rclcpp.hpp>
#include <hrim_sensor_forcetorque_msgs/msg/force_torque.hpp>
#include <hrim_sensor_forcetorque_msgs/msg/specs_force_axis.hpp>
#include <hrim_sensor_forcetorque_msgs/msg/specs_torque_axis.hpp>
#include <memory>
#include <string>
namespace gazebo_hrim_plugins
{
class GazeboRosFTSensorPrivate
{
public:
/// Callback to be called at every simulation iteration.
/// \param[in] info Updated simulation info.
void OnUpdate(const gazebo::common::UpdateInfo & info);
/// A pointer to the GazeboROS node.
gazebo_ros::Node::SharedPtr ros_node_;
/// ForceTorque publisher.
rclcpp::Publisher<hrim_sensor_forcetorque_msgs::msg::ForceTorque>::SharedPtr pub_;
/// ForceTorque message to be published
std::shared_ptr<hrim_sensor_forcetorque_msgs::msg::ForceTorque> msg_;
/// Joint being tracked.
gazebo::physics::JointPtr joint_;
/// Period in seconds
double update_period_;
/// Keep last time an update was published
gazebo::common::Time last_update_time_;
/// Pointer to the update event connection.
gazebo::event::ConnectionPtr update_connection_;
};
GazeboRosFTSensor::GazeboRosFTSensor()
: impl_(std::make_unique<GazeboRosFTSensorPrivate>())
{
}
GazeboRosFTSensor::~GazeboRosFTSensor()
{
}
void GazeboRosFTSensor::Load(gazebo::physics::ModelPtr model, sdf::ElementPtr sdf)
{
// ROS node
impl_->ros_node_ = gazebo_ros::Node::Get(sdf);
// Joint
if (!sdf->HasElement("joint_name")) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "Plugin missing <joint_name>");
impl_->ros_node_.reset();
return;
}
impl_->joint_ = NULL;
sdf::ElementPtr joint_elem = sdf->GetElement("joint_name");
auto joint_name = joint_elem->Get<std::string>();
auto joint = model->GetJoint(joint_name);
if (!joint) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "Joint %s does not exist!", joint_name.c_str());
} else {
impl_->joint_ = joint;
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Going to publish force & torque of child of joint [%s]",
joint_name.c_str() );
}
joint_elem = joint_elem->GetNextElement("joint_name");
if (!impl_->joint_) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "No joint found.");
impl_->ros_node_.reset();
return;
}
// Update rate
double update_rate = 100.0;
if (!sdf->HasElement("update_rate")) {
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Missing <update_rate>, defaults to %f",
update_rate);
} else {
update_rate = sdf->GetElement("update_rate")->Get<double>();
}
if (update_rate > 0.0) {
impl_->update_period_ = 1.0 / update_rate;
} else {
impl_->update_period_ = 0.0;
}
impl_->last_update_time_ = model->GetWorld()->SimTime();
// Initialize message
impl_->msg_ = std::make_shared<hrim_sensor_forcetorque_msgs::msg::ForceTorque>();
// Fill message structure
impl_->msg_->header.frame_id = impl_->joint_->GetChild()->GetName().c_str();
impl_->msg_->axis_forces[0].axis = hrim_sensor_forcetorque_msgs::msg::SpecsForceAxis::FORCE_AXIS_X;
impl_->msg_->axis_forces[1].axis = hrim_sensor_forcetorque_msgs::msg::SpecsForceAxis::FORCE_AXIS_Y;
impl_->msg_->axis_forces[2].axis = hrim_sensor_forcetorque_msgs::msg::SpecsForceAxis::FORCE_AXIS_Z;
impl_->msg_->axis_torques[0].axis = hrim_sensor_forcetorque_msgs::msg::SpecsTorqueAxis::TORQUE_AXIS_X;
impl_->msg_->axis_torques[1].axis = hrim_sensor_forcetorque_msgs::msg::SpecsTorqueAxis::TORQUE_AXIS_Y;
impl_->msg_->axis_torques[2].axis = hrim_sensor_forcetorque_msgs::msg::SpecsTorqueAxis::TORQUE_AXIS_Z;
// ForceTorque publisher
impl_->pub_ = impl_->ros_node_->create_publisher<hrim_sensor_forcetorque_msgs::msg::ForceTorque>("~/out");
// Callback on every iteration
impl_->update_connection_ = gazebo::event::Events::ConnectWorldUpdateBegin(
std::bind(&GazeboRosFTSensorPrivate::OnUpdate, impl_.get(), std::placeholders::_1));
}
void GazeboRosFTSensorPrivate::OnUpdate(const gazebo::common::UpdateInfo & info)
{
gazebo::common::Time current_time = info.simTime;
// If the world is reset, for example
if (current_time < last_update_time_) {
RCLCPP_INFO(ros_node_->get_logger(), "Negative sim time difference detected.");
last_update_time_ = current_time;
}
// Check period
double seconds_since_last_update = (current_time - last_update_time_).Double();
if (seconds_since_last_update < update_period_) {
return;
}
// Get wrench data
auto wrench = joint_->GetForceTorque(1);
// Populate message
msg_->header.stamp.sec = int(current_time.sec);
msg_->header.stamp.nanosec = uint(current_time.nsec);
msg_->axis_forces[0].force = wrench.body2Force.X();
msg_->axis_forces[1].force = wrench.body2Force.Y();
msg_->axis_forces[2].force = wrench.body2Force.Z();
msg_->axis_torques[0].torque = wrench.body2Torque.X();
msg_->axis_torques[1].torque = wrench.body2Torque.Y();
msg_->axis_torques[2].torque = wrench.body2Torque.Z();
// Publish
pub_->publish(msg_);
// Update time
last_update_time_ = current_time;
}
GZ_REGISTER_MODEL_PLUGIN(GazeboRosFTSensor)
} // namespace gazebo_plugins
|
958fb188ea438b213760dfeb6e9eb16978acf61b | 5eb01b2eff25fb0d8fbbb00b02961e565ac3f415 | /common/base/Base.cpp | 95a6c535df953a54cf65bbc4b1136fa10babbb16 | [] | no_license | biglone/LT-PureCodes | 3ca6fc47731e2d566cd1c5389cce93e55768933a | 22d7ec1a1414bc99a16a050800a2cc9259546b9a | refs/heads/master | 2020-05-04T10:29:03.603664 | 2019-04-02T14:23:40 | 2019-04-02T14:23:40 | 179,088,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | cpp | Base.cpp | #include "Base.h"
namespace base
{
Address::Address(const Address& other)
{
tag = other.tag;
name = other.name;
ip = other.ip;
port = other.port;
}
bool Address::operator < (const Address& rAddr) const
{
int ret = ip.compare(rAddr.ip);
if (ret == 0)
{
return port < rAddr.port;
}
return ret < 0;
}
Address& Address::operator = (const Address& rAddr)
{
tag = rAddr.tag;
name = rAddr.name;
ip = rAddr.ip;
port = rAddr.port;
return *this;
}
bool Address::isValid()
{
return (!ip.empty() && port > 0);
}
} |
c95862a0a1f7c16b9f874dbe3de57dc89997e45b | a6bb89b2ff6c1fc8c45a4f105ef528416100a360 | /examples/tut7/support/texture.cpp | a31afde9827531bc2d45de2e8e1a26f41047c279 | [] | no_license | dudochkin-victor/ngxe | 2c03717c45431b5a88a7ca4f3a70a2f23695cd63 | 34687494bcbb4a9ce8cf0a7327a7296bfa95e68a | refs/heads/master | 2016-09-06T02:28:20.233312 | 2013-01-05T19:59:28 | 2013-01-05T19:59:28 | 7,311,793 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,210 | cpp | texture.cpp | /*
Copyright (C) 2005 Heinrich du Toit
This program 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 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
The license can also be obtained electronically at www.fsf.org or www.freesoftware.org/licenses
I can be electronically reached at the following email addresses:
13806335@sun.ac.za (will work till end of 2005)
nlhg@eject.co.za
For header files (which is included in other files at time of compilation) only the following notice is inserted:
This file is distributed under the GNU General Public License Copyright (C) 2005 Heinrich du Toit
*/
#include <iostream>
using namespace std;
#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "texture.h"
#define TRUE 1
#define FALSE 0
#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
Textureclass::Textureclass()
{
glGenTextures(1,&texture);
mipmap = FALSE;
compress = FALSE;
}
Textureclass::~Textureclass()
{
glDeleteTextures(1,&texture);
}
void Textureclass::Mipmap()
{
mipmap = TRUE;
}
void Textureclass::NoMipmap()
{
mipmap = FALSE;
}
void Textureclass::Compress()
{
compress = TRUE;
}
void Textureclass::NoCompress()
{
compress = FALSE;
}
int Textureclass::Load(const char* filename)
{
//active and set initial filtering values
glBindTexture(GL_TEXTURE_2D,texture);
SDL_Surface *surface;
surface = SDL_LoadBMP(filename);
if (surface == NULL){
cout << "Error loading texture file: " << filename << endl;
return FALSE;
}
/*
The problems with this:
OpenGL textures must be upside down. So we must flip the image.
Also we must tell opengl exactly what format the data is in.
*/
/*
format:
we must select GL_RGB GL_BGR GL_RGBA or GL_BGRA
if Amask is 0 we assume there is no alpha channel
if Bshift is 0 we assume BGR
*/
GLenum format;
if (surface->format->Bshift == 0){
//BGR
if (surface->format->Amask == 0)
format = GL_BGR;
else
format = GL_BGRA;
}else{
//RGB
if (surface->format->Amask == 0)
format = GL_RGB;
else
format = GL_RGBA;
}
GLint intformat;
if (surface->format->Amask == 0)
intformat = 3;
else
intformat = 4;
/*
There is no need for us to convert the format since Opengl will store the texture internally in its own
optimized format. And changes are we don't really get it the same as opengl wants it. So its better just to leave
it up to the drivers.
Now the datatype
this is quite complex. Lets hope it works.
Note: this is untested code!
*/
GLenum datatype;
if (surface->format->BytesPerPixel >= 3){
//assumption: if 4 -> includes alpha channels
datatype = GL_UNSIGNED_BYTE;
}else if (surface->format->BytesPerPixel == 1){
datatype = GL_UNSIGNED_BYTE_3_3_2;
}else{
//now the 15 or 16-bit crap
if (surface->format->Amask == 0){
//no Alpha
if (surface->format->BitsPerPixel == 16)
datatype = GL_UNSIGNED_SHORT_5_6_5; //16 bpp
else
datatype = GL_UNSIGNED_SHORT_5_5_5_1; //16bpp
}else{
//Alpha
datatype = GL_UNSIGNED_SHORT_4_4_4_4;
}
}
/*
To flip the image the way opengl wants it we simply create a new buffer into which we copy
the image upside down.. or maybe it was upside down?
*/
Uint8 *buffer = new Uint8[surface->h * surface->pitch];
Uint8 *rowa = (Uint8 *)surface->pixels;
Uint8 *rowb = buffer+((surface->h-1) * surface->pitch);
for (int y=0; y < surface->h; y++){
memcpy(rowb,rowa,surface->pitch);
rowa += surface->pitch;
rowb -= surface->pitch;
}
if (compress){
//all we need todo to compress the texture is to change the internal format
if (intformat == 3){
//there is a very good change this format is supported
intformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
}else{
//intformat == 4 assumed
intformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
//this is the simplest RGBA format and most likely available!
}
}
// Loads the image into OpenGL and create a texture:
if (mipmap){
//The glu library will do all the hard work for us
gluBuild2DMipmaps(GL_TEXTURE_2D,intformat,surface->w,surface->h,format,datatype,buffer);
//and as easy as that we have a mipmapped texture
}else{
glTexImage2D(GL_TEXTURE_2D,0,intformat,surface->w,surface->h,0,
format,datatype,buffer);
}
//Check for errors:
if (glGetError() != GL_NO_ERROR){
cout << "glTexImage2D failed"<< endl;
return FALSE;
}
//make sure atleast some filters are selected:
SetNearestFilter();
//cleaup buffers
delete [] buffer;
SDL_FreeSurface(surface);
return TRUE;
}
void Textureclass::SetWrap(GLint mode)
{
Activate();
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,mode);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,mode);
}
void Textureclass::SetLinearFilter()
{
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
if (mipmap){
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
//GL_LINEAR_MIPMAP_LINEAR produces the best quality image with the worst performance
}else{
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
}
}
void Textureclass::SetNearestFilter()
{
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
if (mipmap){
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST_MIPMAP_NEAREST);
}else{
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
}
}
|
759724fbef667053ebc582cb9ded38df2e30466f | ac1d7bb3375a219907ae87cc10ea2ba4e9906eef | /config_menu_anchor.cpp | 1e2f54a71e9fdd9b2391fcc28ceffcfd8d9dbedf | [
"Apache-2.0"
] | permissive | devkotaprativa/masteranchor | c71e50137c070df93587e18f98e58ea7b20eb576 | ef0b7f3edb8ca9e72626d703f5dcd98a0054c616 | refs/heads/master | 2020-03-19T01:57:34.200461 | 2018-05-31T13:25:04 | 2018-05-31T13:25:04 | 135,586,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | cpp | config_menu_anchor.cpp | /*
Extended DW1000 Ranging example for radino32 DW1000 and radinoL4 DW1000
Based on Decawave DW1000 example library
2017 In-Circuit GmbH
wiki.in-circuit.de
*/
#include "config_menu_anchor.h"
myConfigAnc_t myConfig_anc = {
.channel = 5,
.tx_power = 275,
.outputTable = 1, //true: print device table, false: print single measurements
.weAreTag = 0,
.checksum = 0,
};
void config_defaults_anchor()
{
myConfig_anc.channel = 5;
myConfig_anc.tx_power = 275;
myConfig_anc.outputTable = 1; //true: print device table, false: print single measurements
myConfig_anc.weAreTag = 0;
myConfig_anc.checksum = 0;
}
void config_setUnconfigurableVals_anchor()
{
}
bool config_store_anchor()
{
myConfig_anc.checksum = crc_calc((uint8_t*)&myConfig_anc, sizeof(myConfig_anc)-4);
for (unsigned long i = 0; i < sizeof(myConfig_anc); i++)
{
reloadWatchdog();
noInterrupts();
if (EEPROM.read(EEPROM_MYCONFIG_ANC_ADDR + i) != (((unsigned char *)&myConfig_anc)[i]))
EEPROM.write(EEPROM_MYCONFIG_ANC_ADDR + i, ((unsigned char *)&myConfig_anc)[i]);
interrupts();
}
return true;
}
bool config_load_anchor()
{
for (unsigned long i = 0; i < sizeof(myConfig_anc); i++)
{
reloadWatchdog();
((unsigned char *)&myConfig_anc)[i] = EEPROM.read(EEPROM_MYCONFIG_ANC_ADDR + i);
}
if ( myConfig_anc.checksum != crc_calc((uint8_t*)&myConfig_anc, sizeof(myConfig_anc)-4) )
{
config_defaults_anchor();
}
config_setUnconfigurableVals_anchor();
return true;
}
|
ff39561650d6229442519e6babe377ce83ea1b6a | 956de8ef0bd86f75369e63842264f1862d0563d3 | /LinkedList.cpp | c41c6b70e96e8dbc41599821d1edb1d58c3cae0a | [] | no_license | jordannlove/OpenHash | 651e2bffa711ad458dcb2a78e69852f0365fd574 | 972dc02f63391c887999340522fcde61ca60a30a | refs/heads/master | 2020-07-27T02:09:20.516542 | 2019-09-16T15:17:24 | 2019-09-16T15:17:24 | 208,832,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | LinkedList.cpp | //LinkedList.cpp
#include <iostream>
#include <string>
#include "LinkedList.h"
////
//constructor
LinkedList::LinkedList()
{
std::cout << "default LinkedList constructor reached\n";
head = nullptr;
itemCount = 0;
}
LinkedList::LinkedList(int entry)
{
std::cout << "LinkedList constructor w/ param reached:\n" << entry << '\n';
Node* newNodePtr = new Node();
newNodePtr->setValue(entry);
newNodePtr->setNext(head);
head = newNodePtr;
itemCount++;
}
LinkedList::~LinkedList()
{
}
////
//methods
bool LinkedList::add(int entry)
{
std::cout << "LinkedList add() reached.\n";
std::cout << entry << '\n';
Node* newNodePtr = new Node();
newNodePtr->setValue(entry);
newNodePtr->setNext(head);
head = newNodePtr;
itemCount++;
return true;
}
bool LinkedList::isEmpty() const
{
if(itemCount == 0)
{
return true;
}
else
{
return false;
}
}
int LinkedList::getLength() const
{
return itemCount;
}
// bool LinkedList::insert(int newPosition, const int newEntry)
// {
// bool insertable = (newPosition >= 1) && (newPosition <= itemCount + 1);
// if(insertable)
// {
// Node* newNodePtr = new Node(newEntry);
// if(newPosition == 1)
// {
// }
// else
// {
// Node* prevPtr = getNodeAt(newPosition - 1);
// newNodePtr->setNext(prevPtr->getNext());
// prevPtr->setNext(newNodePtr);
// }
// itemCount++;
// }
// return insertable;
// }
bool LinkedList::remove(int position)
{
}
void LinkedList::clear()
{
}
int LinkedList::getEntry(int position) const
{
}
int LinkedList::replace(int position, const int newEntry)
{
}
|
bc3256e76399a3d05c4676279ba07226acd361ca | 02c745714be7d52948f2295eb6acbe2ac287a37d | /nlp-unconstrained-core/hooke-jeeves/cc/src/rosenbrock.cc | 527cc52d0ed65f7b7d078b8b6d6943a7fc8c40d6 | [
"Unlicense"
] | permissive | johnnieskywalker/nonlinear-optimization-algorithms-multilang | b5619e1de83335ea899822e4ad1a7cd6bf492228 | 6be8986a3fe1154a5727552113b407f9858ebcef | refs/heads/master | 2021-01-12T11:29:32.907973 | 2016-02-24T16:30:08 | 2016-02-24T16:30:08 | 72,936,952 | 0 | 0 | null | 2016-11-05T16:01:59 | 2016-11-05T16:01:59 | null | UTF-8 | C++ | false | false | 1,603 | cc | rosenbrock.cc | /*
* nlp-unconstrained-core/hooke-jeeves/cc/src/rosenbrock.cc
* ============================================================================
* Nonlinear Optimization Algorithms Multilang. Version 0.1
* ============================================================================
* Nonlinear programming algorithms as the (un-)constrained minimization
* problems with the focus on their numerical expression using various
* programming languages.
*
* This is the Hooke and Jeeves nonlinear unconstrained minimization algorithm.
* ============================================================================
*/
#include "rosenbrock.h"
#include "funevals.h"
// The NLPUCCoreHooke namespace.
namespace NLPUCCoreHooke {
// Helper constant.
const double ONE_HUNDRED_POINT_ZERO = 100.0;
// The user-supplied objective function f(x,n).
double Rosenbrock::f(const double *x,
const unsigned int n,
const void *cFunEvals) {
double a;
double b;
double c;
((FunEvals *) cFunEvals)->setFunEvals(
((FunEvals *) cFunEvals)->getFunEvals() + 1);
a = x[INDEX_ZERO];
b = x[INDEX_ONE];
c = ONE_HUNDRED_POINT_ZERO * (b - (a * a)) * (b - (a * a));
return (c + ((ONE_POINT_ZERO - a) * (ONE_POINT_ZERO - a)));
}
// Default constructor.
Rosenbrock::Rosenbrock() {}
// Destructor.
Rosenbrock::~Rosenbrock() {}
} // namespace NLPUCCoreHooke
// ============================================================================
// vim:set nu:et:ts=4:sw=4:
// ============================================================================
|
3a3c1d5dbb37cf6c089ac27a4b408fb3914bcc05 | 66ec76b29fd4d17c56b125b8b82095b6d9a4566b | /src/sagtension/catenary_cable_unloader.cc | 4a5b56468ee7b48d292e3236dbb368215268eb5f | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | OverheadTransmissionLineSoftware/Models | 5006b114964bd542a57a20354fe66a040f95147f | c270d48dc9d8a6eaed1d13851da7207474356342 | refs/heads/master | 2021-01-18T05:09:55.700292 | 2019-02-09T23:53:50 | 2019-02-09T23:53:50 | 24,217,437 | 2 | 0 | Unlicense | 2019-02-09T23:53:50 | 2014-09-19T05:29:17 | C++ | UTF-8 | C++ | false | false | 1,955 | cc | catenary_cable_unloader.cc | // This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "models/sagtension/catenary_cable_unloader.h"
CatenaryCableUnloader::CatenaryCableUnloader() {
catenary_ = nullptr;
strainer_.set_load_finish(0);
}
CatenaryCableUnloader::~CatenaryCableUnloader() {
}
double CatenaryCableUnloader::LengthUnloaded() const {
return strainer_.LengthFinish();
}
bool CatenaryCableUnloader::Validate(
const bool& is_included_warnings,
std::list<ErrorMessage>* messages) const {
// initializes
bool is_valid = true;
ErrorMessage message;
message.title = "CATENARY CABLE UNLOADER";
// validates catenary
if (catenary_ == nullptr) {
is_valid = false;
if (messages != nullptr) {
message.description = "Invalid catenary";
messages->push_back(message);
}
} else {
if (catenary_->Validate(is_included_warnings, messages) == false) {
is_valid = false;
}
}
// validates strainer
if (strainer_.Validate(is_included_warnings, messages) == false) {
is_valid = false;
}
return is_valid;
}
const Catenary3d* CatenaryCableUnloader::catenary() const {
return catenary_;
}
const CableElongationModel* CatenaryCableUnloader::model_reference() const {
return strainer_.model_start();
}
const CableElongationModel* CatenaryCableUnloader::model_unloaded() const {
return strainer_.model_finish();
}
void CatenaryCableUnloader::set_catenary(const Catenary3d* catenary) {
catenary_ = catenary;
strainer_.set_length_start(catenary_->Length());
strainer_.set_load_start(catenary_->TensionAverage());
}
void CatenaryCableUnloader::set_model_reference(
const CableElongationModel* model_reference) {
strainer_.set_model_start(model_reference);
}
void CatenaryCableUnloader::set_model_unloaded(
const CableElongationModel* model_unloaded) {
strainer_.set_model_finish(model_unloaded);
}
|
e33efe6c97eb2b60363e444e7b342f4267572c58 | dfa757f60a4543ddb55189010deb59cc8f6b0973 | /src/code/basic_concepts/classes/static_members/main.cpp | 2963b9ca9cc25f4379e3fd0d632974eb16d2f3a2 | [] | no_license | samu/cpp-code-snippets | 1eb42800643e4d61b666bcd48fba982439f43901 | e6077345c024c7a5f7366997fbf07d8e886f400f | refs/heads/master | 2020-04-23T17:21:42.673746 | 2014-10-11T20:17:56 | 2014-10-11T20:17:56 | 25,093,107 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | main.cpp | #include "gem.h"
#include <iostream>
int main() {
std::cout << "Gem::value(): " << Gem::value() << std::endl;
} |
bad3e3130661a95899ca8cfbaaa1a6492191c3e4 | 6bb4b9b79dd9b6ba96091f5f4344ca060d09f2aa | /AP-MS2/ThreadPool.cpp | c8ef02b4aef2def8842aa4d8b7f662aac4026124 | [] | no_license | orsanawwad/APEX | 84304558236a4525a70afa6d1233787c75df5f53 | 980b714e144f4b90c8fd1241f9cd6eae3e6bfcab | refs/heads/master | 2020-09-21T20:49:28.385061 | 2019-11-30T16:44:08 | 2019-11-30T16:44:08 | 224,924,776 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,905 | cpp | ThreadPool.cpp | //
// Created by Orsan Awwad on 14/01/2019.
//
#include "ThreadPool.h"
Task *TasksQueue::pop() {
std::lock_guard<std::mutex> g(mut);
if (tasks.empty()) {
return nullptr;
}
auto task = tasks.front();
tasks.pop();
return task;
}
bool TasksQueue::empty() const {
std::lock_guard<std::mutex> g(mut);
return tasks.empty();
}
void TasksQueue::push(Task *task) {
if (task == nullptr) {
throw std::invalid_argument("Task should not be null");
}
std::lock_guard<std::mutex> g(mut);
tasks.push(task);
queue_cond_var.notify_one();
}
void TasksQueue::wait() const {
std::unique_lock<std::mutex> ul(mut);
if (stop_queue) return;
queue_cond_var.wait(ul);
}
bool TasksQueue::stop() const {
return stop_queue;
}
void TasksQueue::exit() {
std::lock_guard<std::mutex> g(mut);
stop_queue = true;
queue_cond_var.notify_all();
}
ThreadPool::ThreadPool() {
for (int i = 0; i < THREAD_POOL_SIZE; ++i) {
workers.push(std::thread(&ThreadPool::worker, this));
}
}
void ThreadPool::worker() {
while (!tasks_queue.stop()) {
tasks_queue.wait();
Task* task = tasks_queue.pop();
if (task) {
task->execute();
delete task;
task = NULL;
}
}
}
void ThreadPool::exit() {
this->tasks_queue.exit();
while (!this->workers.empty()) {
this->workers.front().join();
this->workers.pop();
}
}
void ThreadPool::addTask(Task *task) {
this->tasks_queue.push(task);
}
ClientHandlerTaskAdapter::ClientHandlerTaskAdapter(
server_side::IClientHandler *clientHandler,
const posix_sockets::TCPClient &client) : clientHandler(clientHandler), client(client) {}
void ClientHandlerTaskAdapter::execute() {
this->clientHandler->handleClient(client);
}
ClientHandlerTaskAdapter::~ClientHandlerTaskAdapter() {} |
989b4a2bed4a0fb1c060b987ce3d962a4611e158 | be1eb8259efefefdb17b396f5023fbee98f637cc | /LCFunction/LCOneDimLinearFunction.h | 59ea0332d9a663a79bae033edbbe93e0d40ede29 | [] | no_license | AOE-khkhan/LOCOInterpolate | e212496f5b7007989ba2c1b471b0f5490fe20894 | 7e7210c7be198f27c39b48d3306159446b4cdf1c | refs/heads/master | 2021-09-21T11:11:18.909324 | 2018-08-24T22:20:51 | 2018-08-24T22:20:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | h | LCOneDimLinearFunction.h | #ifndef _OC_HARD_CODED_LINEAR_SHAPE_
#define _OC_HARD_CODED_LINEAR_SHAPE_
#include "LCFunction.h"
/* This is used for testing the interpolation scheme. It a simple function from
R^N -> R where N are the number of params. If you set linear = true it will be a linear
function which can be used to test linear precision and if not it will a sum on
sines and cosines. */
class LCOneDimLinearFunction : public LCFunction {
public:
LCOneDimLinearFunction(int nParams);
int getNParams() const;
double getMinRange(int iParam) const;
double getMaxRange(int iParam) const;
LCError evalDeriv(const std::vector<double> ¶ms, int direction, LCFunctionDeriv **result);
LCError evalShapeInfo(const std::vector<double> ¶ms, LCFunctionValue **result);
private:
int nParams_;
std::vector<double> ranges_;
};
#endif |
c43e6209939f0abf47d76d2730d5d3a582f8c981 | 22384a1d136bbcb4fa140afc317219a49160f5a5 | /src/MySqlConnector/main.cpp | cc19e7522d907bf655422cf87e2ac3e3b05e08db | [] | no_license | JayMcGee/Projet-Bresil-2015 | 2fe116211ba8a9a3ad61a735eb50126890e66e09 | 1cb0dfd640d7dd327854f72928d4a0d35cde8dec | refs/heads/master | 2020-05-13T06:24:36.679455 | 2014-12-04T03:54:07 | 2014-12-04T03:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | cpp | main.cpp |
#define DEVICE "28-000006052315"
#include <stdlib.h>
#include <iostream>
#include <mysql_connection.h>
#include <driver.h>
#include <exception.h>
#include <resultset.h>
#include <statement.h>
#include "FileRead/OneWireDevice.h"
using namespace sql;
using namespace std;
int main(void){
//Declaration Objet
OneWireDevice ow(DEVICE);
float temp;
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
//Connection
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306","root","poutine");
while(1)
{
if(ow.isValidPath())
{
cout << "Device path is valid" << endl;
if(ow.updateTemperature())
{
cout << "Temperature updated " << endl;
if(ow.getLastTemperature(&temp))
{
cout << "Current temperature : " << temp << endl;
}
else
cout << "Could not retrieve latest temperature" << endl;
}
else
cout << "Could not update temperature" << endl;
}
else
cout << "Device path is not valid";
sleep(2);
//Query
stmt = con->createStatement();
stmt->execute("USE stationmeteocegep;");
/* res = stmt->executeQuery("SELECT stationID FROM datastation LIMIT 4;");
while(res->next())
{
cout << "ID station : " << res->getInt(1) << endl;
}
*/
}
delete res;
delete stmt;
delete con;
return 0;
} |
ac9fb3594799df92ce4764dfbf64a03e68888e95 | 90d253b075c47054ab1d6bf6206f37e810330068 | /IOI/2021/dna.cpp | 823a1ffc90c249cd4618f833da71a8da311ed033 | [
"MIT"
] | permissive | eyangch/competitive-programming | 45684aa804cbcde1999010332627228ac1ac4ef8 | de9bb192c604a3dfbdd4c2757e478e7265516c9c | refs/heads/master | 2023-07-10T08:59:25.674500 | 2023-06-25T09:30:43 | 2023-06-25T09:30:43 | 178,763,969 | 22 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | dna.cpp | #include <bits/stdc++.h>
#define endl '\n'
#define eat cin
#define moo cout
using namespace std;
int pfx[3][3][100000];
void init(string a, string b){
for(int i = 0; i < (int)a.length(); i++){
int ai = 0, bi = 0;
if(a[i] == 'T') ai = 1;
if(a[i] == 'C') ai = 2;
if(b[i] == 'T') bi = 1;
if(b[i] == 'C') bi = 2;
pfx[ai][bi][i]++;
if(i > 0){
for(int j = 0; j < 3; j++){
for(int k = 0; k < 3; k++){
pfx[j][k][i] += pfx[j][k][i-1];
}
}
}
}
}
int get_distance(int x, int y){
int d = 0;
int cur[3][3];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cur[i][j] = pfx[i][j][y];
if(x > 0) cur[i][j] -= pfx[i][j][x-1];
}
}
for(int i = 0; i < 3; i++){
int nxt = (i+1)%3;
int mn = min(cur[i][nxt], cur[nxt][i]);
d += mn;
cur[i][nxt] -= d;
cur[nxt][i] -= d;
}
int rem = cur[0][1] - cur[1][0];
if(cur[1][2] - cur[2][1] != rem || cur[2][0] - cur[0][2] != rem){
return -1;
}
return d + abs(rem) * 2;
}
/*int32_t main(){
eat.tie(0) -> sync_with_stdio(0);
init("ATACAT", "ACTATA");
moo << get_distance(1, 2) << ' ' << get_distance(4, 5) << ' ' << get_distance(0, 0) << endl;
}*/ |
ef436804a53511a2c0acbfecac5003664d5904b2 | 31792c4fabd1677f50545a897b5fa13f12c1d34d | /src/Target.cpp | 3bba92bfad4a194e6274a7a5edaa02d18ce426d1 | [] | no_license | Malguzt/zombie-shot | 8f88d5217cee991d91ab6d19d45c027a84e554cc | 68156094b9288b73a92347663fab1badbcac3d97 | refs/heads/master | 2016-09-10T18:40:42.840825 | 2014-12-22T19:55:31 | 2014-12-22T19:55:31 | 34,521,517 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,377 | cpp | Target.cpp | #include "Target.h"
#include "EmptyTarget.h"
using namespace sf;
Target::Target()
{
loadSprite();
newPosition();
}
Target::Target(int x, int y, int difficulty)
{
this->x = x;
this->y = y;
setDifficulty(difficulty);
bushArea = IntRect(x, y, 63, 63);
loadSprite();
}
Target::~Target()
{
}
void Target::loadSprite()
{
bushTexture.loadFromFile("img/bush.png");
bushSprite.setTexture(bushTexture);
bushSprite.setPosition(x, y);
}
void Target::draw(RenderWindow &app)
{
app.draw(bushSprite);
app.draw(characterSprite);
}
void Target::shake()
{
bushSprite.setPosition(x + (-4 + rand() % 9), y);
}
void Target::checkTheShot(Vector2i &position, Board &board)
{
}
void Target::newPosition()
{
x = rand() % 700;
y = rand() % 300 + 200;
bushSprite.setPosition(x, y);
bushArea = IntRect(x, y, 63, 63);
}
bool Target::zoneIsUsed(Target &otherTarget)
{
return bushArea.intersects(otherTarget.bushArea);
}
int Target::getX()
{
return x;
}
int Target::getY()
{
return y;
}
bool Target::isKilled(Target **target)
{
if(killed)
{
*target = new EmptyTarget(x, y, difficulty);
delete this;
return true;
}
return false;
}
void Target::setDifficulty(int value)
{
if(value > 0)
{
difficulty = value;
} else {
difficulty = 1;
}
}
|
958c5c1a76b33e9b3a8be69c0cadea976fa7c2f5 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/iis/iisrearc/core/common/util/iisrtl/strings.cpp | fcd1f676790060fabe4c394575fb65f70e4553f8 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 1,704 | cpp | strings.cpp | #include "precomp.hxx"
#define IMPLEMENTATION_EXPORT
#include <irtlmisc.h>
// stristr (stolen from fts.c, wickn)
//
// case-insensitive version of strstr.
// stristr returns a pointer to the first occurrence of
// pszSubString in pszString. The search does not include
// terminating nul characters.
//
// NOTE: This routine is NOT DBCS-safe?
const char*
stristr(const char* pszString, const char* pszSubString)
{
const char *cp1 = (const char*) pszString, *cp2, *cp1a;
char first;
// get the first char in string to find
first = pszSubString[0];
// first char often won't be alpha
if (isalpha((UCHAR)first))
{
first = (char) tolower(first);
for ( ; *cp1 != '\0'; cp1++)
{
if (tolower(*cp1) == first)
{
for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1];
;
cp1a++, cp2++)
{
if (*cp2 == '\0')
return cp1;
if (tolower(*cp1a) != tolower(*cp2))
break;
}
}
}
}
else
{
for ( ; *cp1 != '\0' ; cp1++)
{
if (*cp1 == first)
{
for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1];
;
cp1a++, cp2++)
{
if (*cp2 == '\0')
return cp1;
if (tolower(*cp1a) != tolower(*cp2))
break;
}
}
}
}
return NULL;
}
|
87d777ff0cca8689f974f02aafb9ffba80f387bb | 519f0498d55268af64c8236033a2bcfb6a618277 | /src/thread/pthreadpool.cpp | c6b367b0e7264454ab05e2b31f0f813a04d76b83 | [] | no_license | Gavin-Lau/GMidWare | 2f13363c9e8cab210ba83d6a381884e779f2ed27 | 52cb83b076d8929f7b87097b32e1163f60eac66b | refs/heads/master | 2021-05-16T09:32:38.416384 | 2020-01-26T06:24:37 | 2020-01-26T06:24:37 | 104,535,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | pthreadpool.cpp | #include "pthreadpool.h"
#include "pthread_core.h"
#include "pthread_sync.h"
#include <assert.h>
using std::cout;
using std::endl;
PthreadPool::PthreadPool(std::size_t poolsize)
: m_Poolsize(poolsize)
{
for (int i = 0; i < m_Poolsize ; ++i)
{
Pthread* curThread = new Pthread();
curThread->setID(i);
m_mThreads.insert(std::make_pair(i, curThread));
assert(curThread->getStatus() == Pthread::IDLE);
}
}
PthreadPool::~PthreadPool()
{
}
void PthreadPool::PostTask()
{
}
float PthreadPool::GetLoad()
{
} |
7d001a37c3ca2e2ed3c909b12b28b23937d18f82 | 09d1138225f295ec2e5f3e700b44acedcf73f383 | /Remoting/Views/vtkPVComparativeAnimationCue.cxx | d1210c640b8d03b245e997e3f064fe3d18920b7e | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | nagyist/ParaView | e86d1ed88a805aecb13f707684103e43d5f6b09f | 6810d701c44b2097baace5ad2c05f81c6d0fd310 | refs/heads/master | 2023-09-04T07:34:57.251637 | 2023-09-03T00:34:36 | 2023-09-03T00:34:57 | 85,244,343 | 0 | 0 | BSD-3-Clause | 2023-09-11T15:57:25 | 2017-03-16T21:44:59 | C++ | UTF-8 | C++ | false | false | 19,672 | cxx | vtkPVComparativeAnimationCue.cxx | // SPDX-FileCopyrightText: Copyright (c) Kitware Inc.
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkPVComparativeAnimationCue.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkPVXMLElement.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMProxy.h"
#include "vtkSMVectorProperty.h"
#include <cstring>
#include <sstream>
#include <string>
#include <vector>
#include <vtksys/SystemTools.hxx>
class vtkPVComparativeAnimationCue::vtkInternals
{
public:
enum
{
SINGLE,
XRANGE,
YRANGE,
TRANGE,
TRANGE_VERTICAL_FIRST
};
// vtkCueCommand is a unit of computation used to compute the value at a given
// position in the comparative grid.
class vtkCueCommand
{
private:
std::string ValuesToString(double* values)
{
std::ostringstream str;
for (unsigned int cc = 0; cc < this->NumberOfValues; cc++)
{
str << setprecision(16) << values[cc];
if (cc > 0)
{
str << ",";
}
}
return str.str();
}
// don't call this if this->NumberOfValues == 1.
double* ValuesFromString(const char* str)
{
double* values = nullptr;
if (str != nullptr && *str != 0)
{
std::vector<std::string> parts = vtksys::SystemTools::SplitString(str, ',');
if (static_cast<unsigned int>(parts.size()) == this->NumberOfValues)
{
values = new double[this->NumberOfValues];
for (unsigned int cc = 0; cc < this->NumberOfValues; cc++)
{
values[cc] = atof(parts[cc].c_str());
}
}
}
return values;
}
void Duplicate(const vtkCueCommand& other)
{
this->Type = other.Type;
this->AnchorX = other.AnchorX;
this->AnchorY = other.AnchorY;
this->NumberOfValues = other.NumberOfValues;
this->MinValues = this->MaxValues = nullptr;
if (this->NumberOfValues > 0)
{
this->MinValues = new double[this->NumberOfValues];
memcpy(this->MinValues, other.MinValues, sizeof(double) * this->NumberOfValues);
this->MaxValues = new double[this->NumberOfValues];
memcpy(this->MaxValues, other.MaxValues, sizeof(double) * this->NumberOfValues);
}
}
public:
int Type;
double* MinValues;
double* MaxValues;
unsigned int NumberOfValues;
int AnchorX, AnchorY;
vtkCueCommand()
{
this->Type = -1;
this->AnchorX = this->AnchorY = -1;
this->NumberOfValues = 0;
this->MaxValues = nullptr;
this->MinValues = nullptr;
}
vtkCueCommand(const vtkCueCommand& other) { this->Duplicate(other); }
vtkCueCommand& operator=(const vtkCueCommand& other)
{
delete[] this->MinValues;
delete[] this->MaxValues;
this->Duplicate(other);
return *this;
}
~vtkCueCommand()
{
delete[] this->MinValues;
this->MinValues = nullptr;
delete[] this->MaxValues;
this->MaxValues = nullptr;
}
void SetValues(double* minValues, double* maxValues, unsigned int num)
{
delete[] this->MaxValues;
delete[] this->MinValues;
this->MaxValues = nullptr;
this->MinValues = nullptr;
this->NumberOfValues = num;
if (num > 0)
{
this->MinValues = new double[num];
this->MaxValues = new double[num];
memcpy(this->MinValues, minValues, num * sizeof(double));
memcpy(this->MaxValues, maxValues, num * sizeof(double));
}
}
bool operator==(const vtkCueCommand& other)
{
return this->Type == other.Type && this->NumberOfValues == other.NumberOfValues &&
this->AnchorX == other.AnchorX && this->AnchorY == other.AnchorY &&
(memcmp(this->MinValues, other.MinValues, sizeof(double) * this->NumberOfValues) == 0) &&
(memcmp(this->MaxValues, other.MaxValues, sizeof(double) * this->NumberOfValues) == 0);
}
vtkPVXMLElement* ToXML()
{
vtkPVXMLElement* elem = vtkPVXMLElement::New();
elem->SetName("CueCommand");
elem->AddAttribute("type", this->Type);
elem->AddAttribute("anchorX", this->AnchorX);
elem->AddAttribute("anchorY", this->AnchorY);
elem->AddAttribute("num_values", this->NumberOfValues);
elem->AddAttribute("min_values", this->ValuesToString(this->MinValues).c_str());
elem->AddAttribute("max_values", this->ValuesToString(this->MaxValues).c_str());
return elem;
}
bool FromXML(vtkPVXMLElement* elem)
{
if (!elem->GetName() || strcmp(elem->GetName(), "CueCommand") != 0)
{
return false;
}
int numvalues = 0;
if (elem->GetScalarAttribute("type", &this->Type) &&
elem->GetScalarAttribute("anchorX", &this->AnchorX) &&
elem->GetScalarAttribute("anchorY", &this->AnchorY) &&
elem->GetScalarAttribute("num_values", &numvalues))
{
this->NumberOfValues = static_cast<unsigned int>(numvalues);
if (this->NumberOfValues > 1)
{
delete[] this->MinValues;
delete[] this->MaxValues;
this->MinValues = this->ValuesFromString(elem->GetAttribute("min_values"));
this->MaxValues = this->ValuesFromString(elem->GetAttribute("max_values"));
return this->MaxValues != nullptr && this->MinValues != nullptr;
}
else
{
delete[] this->MinValues;
this->MinValues = new double[1];
this->MinValues[0] = 0;
delete[] this->MaxValues;
this->MaxValues = new double[1];
this->MaxValues[0] = 0;
return elem->GetScalarAttribute("min_values", this->MinValues) &&
elem->GetScalarAttribute("max_values", this->MaxValues);
}
}
return false;
}
};
void RemoveCommand(const vtkCueCommand& cmd)
{
std::vector<vtkCueCommand>::iterator iter;
for (iter = this->CommandQueue.begin(); iter != this->CommandQueue.end(); ++iter)
{
if (*iter == cmd)
{
this->CommandQueue.erase(iter);
break;
}
}
}
void InsertCommand(const vtkCueCommand& cmd, int pos)
{
std::vector<vtkCueCommand>::iterator iter;
int cc = 0;
for (iter = this->CommandQueue.begin(); iter != this->CommandQueue.end() && cc < pos;
++iter, ++cc)
{
}
this->CommandQueue.insert(iter, cmd);
}
std::vector<vtkCueCommand> CommandQueue;
};
vtkStandardNewMacro(vtkPVComparativeAnimationCue);
vtkCxxSetObjectMacro(vtkPVComparativeAnimationCue, AnimatedProxy, vtkSMProxy);
//----------------------------------------------------------------------------
vtkPVComparativeAnimationCue::vtkPVComparativeAnimationCue()
{
this->Internals = new vtkInternals();
this->Values = new double[128]; // some large limit.
this->AnimatedProxy = nullptr;
this->AnimatedPropertyName = nullptr;
this->AnimatedDomainName = nullptr;
this->AnimatedElement = 0;
this->Enabled = true;
}
//----------------------------------------------------------------------------
vtkPVComparativeAnimationCue::~vtkPVComparativeAnimationCue()
{
delete this->Internals;
this->Internals = nullptr;
delete[] this->Values;
this->Values = nullptr;
this->SetAnimatedProxy(nullptr);
this->SetAnimatedPropertyName(nullptr);
this->SetAnimatedDomainName(nullptr);
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::RemoveAnimatedProxy()
{
this->SetAnimatedProxy(nullptr);
}
//----------------------------------------------------------------------------
vtkSMProperty* vtkPVComparativeAnimationCue::GetAnimatedProperty()
{
if (!this->AnimatedPropertyName || !this->AnimatedProxy)
{
return nullptr;
}
return this->AnimatedProxy->GetProperty(this->AnimatedPropertyName);
}
//----------------------------------------------------------------------------
vtkSMDomain* vtkPVComparativeAnimationCue::GetAnimatedDomain()
{
vtkSMProperty* property = this->GetAnimatedProperty();
if (!property)
{
return nullptr;
}
vtkSMDomain* domain = nullptr;
vtkSMDomainIterator* iter = property->NewDomainIterator();
iter->Begin();
if (!iter->IsAtEnd())
{
domain = iter->GetDomain();
}
iter->Delete();
return domain;
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::UpdateXRange(
int y, double* minx, double* maxx, unsigned int numValues)
{
vtkInternals::vtkCueCommand cmd;
cmd.Type = vtkInternals::XRANGE;
cmd.AnchorX = -1;
cmd.AnchorY = y;
cmd.SetValues(minx, maxx, numValues);
vtkPVXMLElement* changeXML = vtkPVXMLElement::New();
changeXML->SetName("StateChange");
int position = 0;
// remove obsolete values.
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
position++)
{
bool remove = false;
if (iter->Type == vtkInternals::SINGLE && iter->AnchorY == y)
{
remove = true;
}
if (iter->Type == vtkInternals::XRANGE && iter->AnchorY == y)
{
remove = true;
}
if (remove)
{
vtkPVXMLElement* removeXML = iter->ToXML();
removeXML->AddAttribute("position", position);
removeXML->AddAttribute("remove", 1);
changeXML->AddNestedElement(removeXML);
removeXML->FastDelete();
iter = this->Internals->CommandQueue.erase(iter);
}
else
{
iter++;
}
}
this->Internals->CommandQueue.push_back(cmd);
vtkPVXMLElement* addXML = cmd.ToXML();
changeXML->AddNestedElement(addXML);
addXML->FastDelete();
this->InvokeEvent(vtkCommand::StateChangedEvent, changeXML);
changeXML->Delete();
this->Modified();
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::UpdateYRange(
int x, double* miny, double* maxy, unsigned int numValues)
{
vtkInternals::vtkCueCommand cmd;
cmd.Type = vtkInternals::YRANGE;
cmd.AnchorX = x;
cmd.AnchorY = -1;
cmd.SetValues(miny, maxy, numValues);
vtkPVXMLElement* changeXML = vtkPVXMLElement::New();
changeXML->SetName("StateChange");
int position = 0;
// remove obsolete values.
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
position++)
{
bool remove = false;
if (iter->Type == vtkInternals::SINGLE && iter->AnchorX == x)
{
remove = true;
}
if (iter->Type == vtkInternals::YRANGE && iter->AnchorX == x)
{
remove = true;
}
if (remove)
{
vtkPVXMLElement* removeXML = iter->ToXML();
removeXML->AddAttribute("position", position);
removeXML->AddAttribute("remove", 1);
changeXML->AddNestedElement(removeXML);
removeXML->FastDelete();
iter = this->Internals->CommandQueue.erase(iter);
}
else
{
iter++;
}
}
this->Internals->CommandQueue.push_back(cmd);
vtkPVXMLElement* addXML = cmd.ToXML();
changeXML->AddNestedElement(addXML);
addXML->FastDelete();
this->InvokeEvent(vtkCommand::StateChangedEvent, changeXML);
changeXML->Delete();
this->Modified();
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::UpdateWholeRange(
double* mint, double* maxt, unsigned int numValues, bool vertical_first)
{
vtkPVXMLElement* changeXML = vtkPVXMLElement::New();
changeXML->SetName("StateChange");
// remove all values (we are just recording the state change here).
int position = 0;
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
++position, ++iter)
{
vtkPVXMLElement* removeXML = iter->ToXML();
removeXML->AddAttribute("position", position);
removeXML->AddAttribute("remove", 1);
changeXML->AddNestedElement(removeXML);
removeXML->FastDelete();
}
this->Internals->CommandQueue.clear();
vtkInternals::vtkCueCommand cmd;
cmd.Type = vertical_first ? vtkInternals::TRANGE_VERTICAL_FIRST : vtkInternals::TRANGE;
cmd.SetValues(mint, maxt, numValues);
this->Internals->CommandQueue.push_back(cmd);
vtkPVXMLElement* addXML = cmd.ToXML();
changeXML->AddNestedElement(addXML);
addXML->FastDelete();
this->InvokeEvent(vtkCommand::StateChangedEvent, changeXML);
changeXML->Delete();
this->Modified();
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::UpdateValue(int x, int y, double* value, unsigned int numValues)
{
vtkInternals::vtkCueCommand cmd;
cmd.Type = vtkInternals::SINGLE;
cmd.AnchorX = x;
cmd.AnchorY = y;
cmd.SetValues(value, value, numValues);
vtkPVXMLElement* changeXML = vtkPVXMLElement::New();
changeXML->SetName("StateChange");
int position = 0;
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
++position)
{
bool remove = false;
if (iter->Type == vtkInternals::SINGLE && iter->AnchorX == x && iter->AnchorY == y)
{
remove = true;
}
if (remove)
{
vtkPVXMLElement* removeXML = iter->ToXML();
removeXML->AddAttribute("position", position);
removeXML->AddAttribute("remove", 1);
changeXML->AddNestedElement(removeXML);
removeXML->FastDelete();
iter = this->Internals->CommandQueue.erase(iter);
}
else
{
iter++;
}
}
this->Internals->CommandQueue.push_back(cmd);
vtkPVXMLElement* addXML = cmd.ToXML();
changeXML->AddNestedElement(addXML);
addXML->FastDelete();
this->InvokeEvent(vtkCommand::StateChangedEvent, changeXML);
changeXML->Delete();
this->Modified();
}
//----------------------------------------------------------------------------
double* vtkPVComparativeAnimationCue::GetValues(
int x, int y, int dx, int dy, unsigned int& numValues)
{
numValues = 0;
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
++iter)
{
unsigned int count = iter->NumberOfValues > 128 ? 128 : iter->NumberOfValues;
switch (iter->Type)
{
case vtkInternals::SINGLE:
if (x == iter->AnchorX && y == iter->AnchorY)
{
memcpy(this->Values, iter->MinValues, sizeof(double) * count);
numValues = count;
}
break;
case vtkInternals::XRANGE:
if (y == iter->AnchorY || iter->AnchorY == -1)
{
for (unsigned int cc = 0; cc < count; cc++)
{
this->Values[cc] = dx > 1
? iter->MinValues[cc] + (x * (iter->MaxValues[cc] - iter->MinValues[cc])) / (dx - 1)
: iter->MinValues[cc];
}
numValues = count;
}
break;
case vtkInternals::YRANGE:
if (x == iter->AnchorX || iter->AnchorX == -1)
{
for (unsigned int cc = 0; cc < count; cc++)
{
this->Values[cc] = dy > 1
? iter->MinValues[cc] + (y * (iter->MaxValues[cc] - iter->MinValues[cc])) / (dy - 1)
: iter->MinValues[cc];
}
numValues = count;
}
break;
case vtkInternals::TRANGE:
{
for (unsigned int cc = 0; cc < count; cc++)
{
this->Values[cc] = (dx * dy > 1) ? iter->MinValues[cc] +
(y * dx + x) * (iter->MaxValues[cc] - iter->MinValues[cc]) / (dx * dy - 1)
: iter->MinValues[cc];
}
numValues = count;
}
break;
case vtkInternals::TRANGE_VERTICAL_FIRST:
{
for (unsigned int cc = 0; cc < count; cc++)
{
this->Values[cc] = (dx * dy > 1) ? iter->MinValues[cc] +
(x * dy + y) * (iter->MaxValues[cc] - iter->MinValues[cc]) / (dx * dy - 1)
: iter->MinValues[cc];
}
numValues = count;
}
break;
}
}
return numValues > 0 ? this->Values : nullptr;
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::UpdateAnimatedValue(int x, int y, int dx, int dy)
{
if (!this->GetEnabled())
{
return;
}
vtkSMDomain* domain = this->GetAnimatedDomain();
vtkSMProperty* property = this->GetAnimatedProperty();
vtkSMProxy* proxy = this->GetAnimatedProxy();
int animated_element = this->GetAnimatedElement();
if (!proxy || !domain || !property)
{
vtkErrorMacro("Cue does not have domain or property set!");
return;
}
unsigned int numValues = 0;
double* values = this->GetValues(x, y, dx, dy, numValues);
if (numValues == 0)
{
vtkErrorMacro("Failed to determine any value: " << x << ", " << y);
}
else if (numValues == 1 && animated_element >= 0)
{
domain->SetAnimationValue(property, animated_element, values[0]);
}
else if (numValues >= 1 && animated_element == -1)
{
vtkSMVectorProperty* vp = vtkSMVectorProperty::SafeDownCast(property);
if (vp)
{
vp->SetNumberOfElements(numValues);
}
for (unsigned int cc = 0; cc < numValues; cc++)
{
domain->SetAnimationValue(property, cc, values[cc]);
}
}
else
{
vtkErrorMacro("Failed to change parameter.");
}
proxy->UpdateVTKObjects();
}
//----------------------------------------------------------------------------
vtkPVXMLElement* vtkPVComparativeAnimationCue::AppendCommandInfo(vtkPVXMLElement* proxyElem)
{
if (!proxyElem)
{
return nullptr;
}
std::vector<vtkInternals::vtkCueCommand>::iterator iter;
for (iter = this->Internals->CommandQueue.begin(); iter != this->Internals->CommandQueue.end();
++iter)
{
vtkPVXMLElement* commandElem = iter->ToXML();
proxyElem->AddNestedElement(commandElem);
commandElem->Delete();
}
return proxyElem;
}
//----------------------------------------------------------------------------
int vtkPVComparativeAnimationCue::LoadCommandInfo(vtkPVXMLElement* proxyElement)
{
bool state_change_xml = (strcmp(proxyElement->GetName(), "StateChange") != 0);
if (state_change_xml)
{
// unless the state being loaded is a StateChange, we start from scratch.
this->Internals->CommandQueue.clear();
}
// NOTE: In case of state_change_xml,
// this assumes that all "removes" happen before any inserts which are
// always appends.
unsigned int numElems = proxyElement->GetNumberOfNestedElements();
for (unsigned int i = 0; i < numElems; i++)
{
vtkPVXMLElement* currentElement = proxyElement->GetNestedElement(i);
const char* name = currentElement->GetName();
if (name && strcmp(name, "CueCommand") == 0)
{
vtkInternals::vtkCueCommand cmd;
if (cmd.FromXML(currentElement) == false)
{
vtkErrorMacro("Error when loading CueCommand.");
return 0;
}
int remove = 0;
if (state_change_xml && currentElement->GetScalarAttribute("remove", &remove) && remove != 0)
{
this->Internals->RemoveCommand(cmd);
}
else
{
this->Internals->CommandQueue.push_back(cmd);
}
}
}
this->Modified();
return 1;
}
//----------------------------------------------------------------------------
void vtkPVComparativeAnimationCue::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
|
f53d317b74b2319221b39869da14a7428e32caab | 37187530af88befc246aa65fe2c0092d711fa94d | /Spaceship Shooter/playerprojectile.h | 48beff56582f4d6ec42832999734cbdd3d97175c | [] | no_license | dcook-projects/Spaceship-Shooter | de7517c44050605454831db94d438ac0accd00a4 | f7554c6beba431bb4ee3014889fdabdd3d31831c | refs/heads/master | 2023-09-06T01:13:40.124563 | 2021-11-17T08:13:40 | 2021-11-17T08:13:40 | 427,579,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | playerprojectile.h | #pragma once
#include <SDL.h>
//#include "player.h"
struct App;
class PlayerProjectile {
public:
PlayerProjectile(int playerXPos, int playerWidth, int playerHeight);
void move(App& app);
void render(App& app) const;
SDL_Rect getCollider() const;
bool isDead() const;
void killShot();
private:
//projectile attributes
static constexpr int PLAYER_PROJECTILE_VEL = 20;
static constexpr int PLAYER_PROJ_WIDTH = 10;
static constexpr int PLAYER_PROJ_HEIGHT = 25;
int posX, posY;
int velY;
SDL_Rect collider;
}; |
8a721080dc1b04554686dbebc689b35696ee591a | cc197b0fd43863ae1874a8a1baad6b60ab15f1c4 | /decompiler/gmkstream.cpp | bda9c409fe9548276771a1c2914c89a086b7d663 | [
"MIT"
] | permissive | nkrapivin/gm81decompiler | 1b96df50dfc5f9d7a2f8fcf055c39ea7c639fed7 | bae1f8c3f52ed80c50319555c96752d087520821 | refs/heads/master | 2020-07-04T07:57:44.993259 | 2019-08-13T19:59:47 | 2019-08-13T19:59:47 | 202,213,415 | 2 | 0 | MIT | 2019-08-13T19:45:44 | 2019-08-13T19:45:43 | null | UTF-8 | C++ | false | false | 7,175 | cpp | gmkstream.cpp | /*
* gmkstream.cpp
* GMK Stream
*/
#if 0
#include <iostream>
#include <fstream>
#include "gmkstream.hpp"
#include "zlib.h"
// Support
void GmkStream::CheckStreamForWriting(size_t len) {
if (iPosition + len < iLength)
return;
iLength += len;
iBuffer = (unsigned char*)realloc(iBuffer,iLength);
}
void GmkStream::CheckStreamForReading(size_t len) {
if (iPosition + len > iLength) {
std::cerr << "[Warning] Unforseen end of stream while reading @ " << iPosition + len << std::endl;
exit(0);
}
}
void GmkStream::MoveAll(GmkStream* src) {
CheckStreamForWriting(src->GetLength());
memcpy(iBuffer + iPosition,src->iBuffer,src->GetLength());
src->iPosition = src->GetLength();
iPosition += src->GetLength();
}
void GmkStream::Move(GmkStream* src) {
int len = src->GetLength() - src->GetPosition();
if (!iBuffer)
delete[] iBuffer;
iBuffer = new unsigned char[len];
iLength = len;
SetPosition(0);
memcpy(iBuffer,src->iBuffer + src->iPosition,len);
src->iLength += len;
}
void GmkStream::Copy(GmkStream* src) {
CheckStreamForWriting(src->GetLength());
memcpy(iBuffer + iPosition,src->iBuffer + src->iPosition,src->iLength);
src->iPosition += src->iLength - src->iPosition;
}
// Files
bool GmkStream::Load(std::string& filename) {
std::ifstream handle;
handle.open(filename,std::ios::in | std::ios::binary);
if (!handle.is_open())
return false;
// Reset position
SetPosition(0);
// Grab the size
handle.seekg(0,std::ios::end);
CheckStreamForWriting((size_t)handle.tellg());
handle.seekg(0,std::ios::beg);
// Read into the buffer
handle.read((char*)iBuffer,iLength);
handle.close();
return true;
}
bool GmkStream::Save(std::string& filename, int mode) {
std::ofstream handle;
handle.open(filename,std::ios::out | ((mode == FMODE_BINARY) ? std::ios::binary : 0));
if (!handle.is_open())
return false;
// Reset position
SetPosition(0);
// Write
handle.write((const char*)iBuffer,iLength);
handle.close();
return true;
}
// Reading
void GmkStream::ReadData(unsigned char* buffer, size_t len) {
CheckStreamForReading(len);
memcpy(buffer,iBuffer + iPosition,len);
iPosition += len;
}
bool GmkStream::ReadBool() {
return ReadDword() >= 1;
}
unsigned char GmkStream::ReadByte() {
CheckStreamForReading(sizeof(char));
unsigned char value = *(unsigned char*)(iBuffer + iPosition);
iPosition += sizeof(char);
return value;
}
unsigned short GmkStream::ReadWord() {
CheckStreamForReading(sizeof(short));
unsigned short value = *(unsigned short*)(iBuffer + iPosition);
iPosition += sizeof(short);
return value;
}
unsigned int GmkStream::ReadDword() {
CheckStreamForReading(sizeof(int));
unsigned int value = *(unsigned int*)(iBuffer + iPosition);
iPosition += sizeof(int);
return value;
}
double GmkStream::ReadDouble() {
CheckStreamForReading(sizeof(double));
double value = *(double*)(iBuffer + iPosition);
iPosition += sizeof(double);
return value;
}
std::string GmkStream::ReadString() {
unsigned int len = ReadDword();
std::string res;
CheckStreamForReading(len);
res.reserve(len);
memcpy((void*)res.data(),iBuffer + iPosition,len);
iPosition += len;
res[len] = 0;
return res;
}
time_t GmkStream::ReadTimestamp() {
return (time_t)(int)ReadDouble();
}
// Writing
void GmkStream::WriteData(unsigned char* buffer, size_t len) {
CheckStreamForWriting(len);
memcpy(iBuffer + iPosition,buffer,len);
iPosition += len;
}
void GmkStream::WriteBool(bool value) {
WriteDword((int)(value == 1));
}
void GmkStream::WriteByte(unsigned char value) {
CheckStreamForWriting(sizeof(char));
*(unsigned char*)(iBuffer + iPosition) = value;
iPosition += sizeof(char);
}
void GmkStream::WriteWord(unsigned short value) {
CheckStreamForWriting(sizeof(short));
*(unsigned short*)(iBuffer + iPosition) = value;
iPosition += sizeof(short);
}
void GmkStream::WriteDword(unsigned int value) {
CheckStreamForWriting(sizeof(int));
*(unsigned int*)(iBuffer + iPosition) = value;
iPosition += sizeof(int);
}
void GmkStream::WriteDouble(double value) {
CheckStreamForWriting(sizeof(double));
*(double*)(iBuffer + iPosition) = value;
iPosition += sizeof(double);
}
void GmkStream::WriteString(std::string& value) {
WriteDword(value.length());
CheckStreamForWriting(value.length());
memcpy(iBuffer + iPosition,value.c_str(),value.length());
iPosition += value.length();
}
void GmkStream::WriteTimestamp() {
WriteDouble(0);
}
// Compression
unsigned char* GmkStream::DeflateStream(unsigned char* buffer, size_t iLen, size_t *oLen) {
// Find the required buffer size
uLongf destSize = (uLongf)((uLongf)iLen * 1.001) + 12;
Bytef* destBuffer = new Bytef[destSize];
// Deflate
int result = compress2(destBuffer,&destSize,(const Bytef*)buffer,iLen,Z_BEST_COMPRESSION);
if (result != Z_OK) {
*oLen = 0;
return 0;
}
*oLen = (size_t)destSize;
return (unsigned char*)destBuffer;
}
unsigned char* GmkStream::InflateStream(unsigned char* buffer, size_t iLen, size_t* oLen) {
z_stream stream;
int len = iLen, offset, retval;
char* out = new char[iLen];
memset(&stream,0,sizeof(stream));
stream.next_in = (Bytef*)buffer;
stream.avail_in = iLen;
stream.next_out = (Bytef*)out;
stream.avail_out = iLen;
inflateInit(&stream);
retval = inflate(&stream,1);
while(stream.avail_in && !retval) {
offset = (int)stream.next_out - (int)out;
len += 0x800;
stream.avail_out += 0x800;
out = (char*)realloc(out,len);
stream.next_out = (Bytef*)((int)out + offset);
retval = inflate(&stream,1);
}
if(!retval)
std::cout << std::endl << "[Warning] Unfinished compression?";
else if (retval != 1) {
std::cerr << std::endl << "[Error ] Compression error " << retval;
exit(0);
}
len = stream.total_out;
out = (char*)realloc((void*)out,len);
inflateEnd(&stream);
*oLen = len;
return (unsigned char*)out;
}
bool GmkStream::Deflate() {
GmkStream* tmp = new GmkStream;
tmp->iBuffer = DeflateStream(iBuffer,iLength,&tmp->iLength);
if (!tmp->iLength) {
std::cerr << "[Error ] Deflation failed!" << std::endl;
return false;
}
tmp->SetPosition(0);
Move(tmp);
delete tmp;
return true;
}
bool GmkStream::Inflate() {
GmkStream* tmp = new GmkStream;
tmp->iBuffer = this->InflateStream(iBuffer,iLength,&tmp->iLength);
if (!tmp->iLength)
return false;
tmp->SetPosition(0);
Move(tmp);
iLength += tmp->GetLength() - tmp->iPosition;
delete tmp;
return true;
}
// Serialization
bool GmkStream::Deserialize(GmkStream* dest, bool decompress) {
unsigned int len = ReadDword();
CheckStreamForReading(len - 1);
if (dest->iBuffer)
delete[] dest->iBuffer;
dest->iBuffer = new unsigned char[len];
dest->iLength = len;
dest->SetPosition(0);
memcpy(dest->iBuffer,iBuffer + iPosition,len);
iPosition += len;
if (decompress)
return dest->Inflate();
return true;
}
bool GmkStream::Serialize(bool compress) {
GmkStream* tmp = new GmkStream;
iPosition = 0;
if (compress) {
if (!Deflate())
return false;
}
tmp->WriteDword(GetLength());
tmp->Copy(this);
if (iBuffer)
delete[] iBuffer;
iBuffer = tmp->iBuffer;
iPosition = tmp->GetPosition();
iLength = tmp->GetLength();
return true;
}
#endif
|
6d4ff5c11e59e533da2d34d21b43a2e641884958 | 3643bb671f78a0669c8e08935476551a297ce996 | /JK_Key.cpp | e0fdcf1ebf6ae3924ccf17691828347d1351b2a3 | [] | no_license | mattfischer/3dportal | 44b3b9fb2331650fc406596b941f6228f37ff14b | e00f7d601138f5cf72aac35f4d15bdf230c518d9 | refs/heads/master | 2020-12-25T10:36:51.991814 | 2010-08-29T22:53:06 | 2010-08-29T22:53:06 | 65,869,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,945 | cpp | JK_Key.cpp | #include "JK_Key.h"
#include "JK_Parse.h"
#include "JK_GOB.h"
#include "U_Lowercase.h"
namespace Jk
{
Key::Key( const string& filename )
{
string fullname;
Jk::Parser::Line line;
string data;
bool error;
int i, j;
float f1, f2, f3;
name = filename;
fullname = "3do\\key\\" + name;
data = Jk::Gob::getFile( fullname );
Jk::Parser parser(data);
parser.findString( "SECTION: HEADER", error );
line = parser.getLine( error );
line.matchString( "FLAGS", error );
flags = line.getInt( error );
line = parser.getLine( error );
line.matchString( "TYPE", error );
type = line.getHex( error );
line = parser.getLine( error );
line.matchString( "FRAMES", error );
numFrames = line.getInt( error );
line = parser.getLine( error );
line.matchString( "FPS", error );
fps = line.getInt( error );
line = parser.getLine( error );
line.matchString( "JOINTS", error );
joints = line.getInt( error );
numMarkers = 0;
line = parser.getLine( error );
line.matchString( "SECTION: MARKERS", error );
if( !error )
{
line = parser.getLine( error );
line.matchString( "MARKERS", error );
numMarkers = line.getInt( error );
markers = new Marker[numMarkers];
for( i = 0 ; i < numMarkers ; i++ )
{
line = parser.getLine( error );
markers[i].frame = line.getFloat( error );
markers[i].type = line.getInt( error );
}
line = parser.getLine( error );
}
line.matchString( "SECTION: KEYFRAME NODES", error );
line = parser.getLine( error );
line.matchString( "NODES", error );
numNodes = line.getInt( error );
nodes = new Node[numNodes];
for( i = 0 ; i < numNodes ; i++ )
{
parser.getLine( error );
line = parser.getLine( error );
line.matchString( "MESH NAME", error );
nodes[i].name = Util::Lowercase( line.getString( error ) );
line = parser.getLine( error );
line.matchString( "ENTRIES", error );
nodes[i].numEntries = line.getInt( error );
nodes[i].entries = new Frame[nodes[i].numEntries];
for( j = 0 ; j < nodes[i].numEntries ; j++ )
{
line = parser.getLine( error );
line.getInt( error );
nodes[i].entries[j].frame = line.getInt( error );
nodes[i].entries[j].flags = line.getHex( error );
f1 = line.getFloat( error );
f2 = line.getFloat( error );
f3 = line.getFloat( error );
nodes[i].entries[j].position = Math::Vector( f1, f2, f3 );
f1 = line.getFloat( error );
f2 = line.getFloat( error );
f3 = line.getFloat( error );
nodes[i].entries[j].orientation = Math::Vector( f1, f2, f3 );
line = parser.getLine( error );
f1 = line.getFloat( error );
f2 = line.getFloat( error );
f3 = line.getFloat( error );
nodes[i].entries[j].deltaPosition = Math::Vector( f1, f2, f3 );
f1 = line.getFloat( error );
f2 = line.getFloat( error );
f3 = line.getFloat( error );
nodes[i].entries[j].deltaOrientation = Math::Vector( f1, f2, f3 );
}
}
}
void Key::interpolateFrame( const string &node, float time, int flags, Math::Vector &position, Math::Vector &orientation )
{
int i;
float frame;
int e;
float t;
for( i = 0 ; i < numNodes ; i++ )
{
if( nodes[i].name == node ) break;
}
if( i == numNodes ) return;
frame = time * fps;
if( frame > numFrames )
{
switch( flags )
{
case 0:
frame -= ((int)(frame / numFrames)) * numFrames;
break;
case 0x14:
default:
frame = numFrames - 1;
break;
}
}
for( e = 0 ; e < nodes[i].numEntries ; e++ )
{
if( nodes[i].entries[e].frame <= frame && (e == nodes[i].numEntries - 1 || nodes[i].entries[e+1].frame > frame ))
{
t = ( frame - nodes[i].entries[e].frame );
position = nodes[i].entries[e].position + nodes[i].entries[e].deltaPosition * t;
orientation = nodes[i].entries[e].orientation + nodes[i].entries[e].deltaOrientation * t;
if(orientation.x < 0) orientation.x += 360;
if(orientation.y < 0) orientation.y += 360;
if(orientation.z < 0) orientation.z += 360;
if(orientation.x >= 360) orientation.x -= 360;
if(orientation.y >= 360) orientation.y -= 360;
if(orientation.z >= 360) orientation.z -= 360;
return;
}
}
}
} |
9cd00124fed1fa75a85d8e4d80c8d5b4615202a3 | 34ccf69e4599b9461c725273c04bd502048d10eb | /ProcP8/ProcP8/main.cpp | 393eeac198ade1b6e56da4dba3fe025eb2ba586e | [] | no_license | ansttss/PP | d348c4d4f21ade7e86b2a4713249d6644399c777 | 7f859961b26f793c2028af8277e39a2bd74d8e21 | refs/heads/master | 2020-04-28T18:35:27.888792 | 2019-03-13T20:15:38 | 2019-03-13T20:15:38 | 175,483,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | main.cpp | //
// main.cpp
// ProcP8
//
// Created by Anastasia Posvystak on 01.11.18.
// Copyright © 2018 Anastasia Posvystak. All rights reserved.
//
#include <ctime>
#include "fibonacci.h"
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
cout << "Fibonacci number with matrices - first column \n";
cout << "Simple Fibonacci number - second column \n \nFrom 0 to 10: \n";
for (size_t i = 0; i <= 10; i++) {
cout << "n = " << i << ": " << fib(i) << ' ' << ' ' << "n = " << i << ": " << fibSimple(i) << endl;
}
cout << "\nFrom 30 to 50:"<< endl;
for (size_t i = 30; i <= 50; i++) {
cout << "n = " << i << ": " << fib(i) << ' ' << ' ' << "n = " << i << ": " << fibSimple(i) << endl;
}
return 0;
}
|
4bc59a020517cc37bc82b95b51ad2557c3313331 | 706b5b7ac01cd606f1b9a71bf4dac3af8a3fb9bc | /Music Synthesizer/Synthie/AudioEffects.h | f59babd0d616149fbdd6a214308ce700c5e51c1b | [] | no_license | Abigael/Multi-Component-Music-Synthesizer | 9325dbb622ba6179648a2435aab96050b7e78168 | 6870b906f2c3673be30142425a4599c81697eccb | refs/heads/master | 2021-01-09T06:39:02.235888 | 2016-07-27T01:50:49 | 2016-07-27T01:50:49 | 64,267,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | AudioEffects.h | #pragma once
#include<vector>
#include "Queue.h"
class CInstrument;
class CAudioEffects
{
public:
CAudioEffects();
virtual ~CAudioEffects();
void SetEffects(CAudioEffects* effect);
void ClearEffects(void);
bool mChorusEffect = false;
double mCEdry = 0.0;
double mCEwet = 0.0;
bool mReverberatonEffect = false;
double mREdry = 0.0;
double mREwet = 0.0;
bool mFlangingEffect = false;
double mFEdry = 0.0;
double mFEwet = 0.0;
bool mRingEffect = false;
double mRingEdry = 0.0;
double mRingEwet = 0.0;
bool mNoiseGateEffect = false;
double m_threshold= 0.0;
bool mCompressionEffect = false;
double m_left=1;
double m_right=1;
double m_dry = 0.0;
double m_wet= 0.0;
CQueue* mQueuePtr;
//the instrument this effect is tied to
CInstrument* mInstrument;
//chorus effect
void ProcessChorus(double *input, double* output, double time);
//Flange effect
void ProcessFlange(double *input, double* output, double time);
//Reverb effect
void ProcessReverb(double *input, double* output, double time);
//Ring effect
void ProcessRing(double* input, double* output, double time);
};
|
907b143038c4ce6a5284e2d5dff1a629fa9b7ad5 | 802a8f80cefc39644979cf2038356f63de866398 | /Server Lib/Projeto IOCP/SOCKET/session.h | 7ecb610498a16adbb85abaae918652e88bc5b8bb | [
"MIT"
] | permissive | Acrisio-Filho/SuperSS-Dev | 3a3b78e15e0ec8edc9aae0ca1a632eb02be5d19c | 9b1bdd4a2536ec13de50b11e6feb63e5c351559b | refs/heads/master | 2023-08-03T13:00:07.280725 | 2023-07-05T00:24:18 | 2023-07-05T00:24:18 | 418,925,124 | 32 | 30 | MIT | 2022-11-03T23:15:37 | 2021-10-19T12:58:05 | C++ | UTF-8 | C++ | false | false | 9,562 | h | session.h | // Arquivo session.h
// Criado em 04/06/2017 por Acrisio
// Definição da classe session
#if defined(_WIN32)
#pragma pack(1)
#endif
#pragma once
#ifndef STDA_SESSION_H
#define STDA_SESSION_H
#if defined(_WIN32)
#include <windows.h>
#elif defined(__linux__)
#include "../UTIL/WinPort.h"
#include <memory.h>
#define SESSION_CONNECT_TIME_CLOCK CLOCK_MONOTONIC_RAW
#endif
#include <ctime>
#include "../UTIL/buffer.h"
#include "../PACKET/packet.h"
#include "../UTIL/message_pool.h"
namespace stdA {
class threadpool_base;
// Tempo em millisegundos que a session pode ficar conectada sem logar-se, receber a autorização
#define STDA_TIME_LIMIT_NON_AUTHORIZED 10000ul
// estrutura que guarda os dados do player, de request de packet
struct ctx_check_packet {
#define CHK_PCKT_INTERVAL_LIMIT 1000 // Miliseconds
#define CHK_PCKT_COUNT_LIMIT 5 // Vezes que pode solicitar pacote dentro do intervalo
#define CHK_PCKT_NUM_PCKT_MRY 3 // Ele Guarda os 3 ultimos pacotes verificados
ctx_check_packet() {
clear();
};
void clear() { memset(this, 0, sizeof(ctx_check_packet)); };
#if defined(_WIN32)
LARGE_INTEGER gettick() {
LARGE_INTEGER r;
QueryPerformanceCounter(&r);
#elif defined(__linux__)
timespec gettick() {
timespec r;
clock_gettime(CLOCK_MONOTONIC_RAW, &r);
#endif
return r;
};
bool checkPacketId(unsigned short _packet_id) {
#if defined(_WIN32)
#define DIFF_TICK(a, b, c) (INT64)(((INT64)((a.QuadPart) - (b.QuadPart)) * 1000000 / (c.QuadPart)) / 1000)
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
#elif defined(__linux__)
#define TIMESPEC_TO_NANO_UI64(_timespec) (uint64_t)((uint64_t)(_timespec).tv_sec * (uint64_t)1000000000 + (uint64_t)(_timespec).tv_nsec)
#define DIFF_TICK(a, b, c) (int64_t)(((int64_t)(TIMESPEC_TO_NANO_UI64((a)) - TIMESPEC_TO_NANO_UI64((b))) / TIMESPEC_TO_NANO_UI64((c))) / 1000000)
timespec frequency;
clock_getres(CLOCK_MONOTONIC_RAW, &frequency);
#endif
auto tick = gettick();
for (auto i = 0u; i < CHK_PCKT_NUM_PCKT_MRY; ++i) {
if (ctx[i].packet_id == _packet_id) {
if (DIFF_TICK(tick, ctx[i].tick, frequency) <= CHK_PCKT_INTERVAL_LIMIT) {
last_index = i;
// att tick
ctx[last_index].tick = tick;
return true;
}else {
ctx[i].tick = tick;
ctx[i].count = 0;
return false;
}
}else if ((i + 1) == CHK_PCKT_NUM_PCKT_MRY) {
// ROTATE
std::rotate(ctx, ctx + 1, ctx + CHK_PCKT_NUM_PCKT_MRY);
//std::rotate(packet_id, packet_id + 1, packet_id + CHK_PCKT_NUM_PCKT_MRY);
//std::rotate(m_tick, m_tick + 1, m_tick + CHK_PCKT_NUM_PCKT_MRY);
//std::rotate(count, count + 1, count + CHK_PCKT_NUM_PCKT_MRY);
// Insert And Clean
ctx[CHK_PCKT_NUM_PCKT_MRY - 1].packet_id = _packet_id;
ctx[CHK_PCKT_NUM_PCKT_MRY - 1].tick = tick;
ctx[CHK_PCKT_NUM_PCKT_MRY - 1].count = 0;
}
}
return false;
};
uint32_t incrementCount() {
return ctx[last_index].count++;
};
void clearLast() {
ctx[last_index].clear();
};
protected:
struct stCtx {
void clear() { memset(this, 0, sizeof(stCtx)); };
#if defined(_WIN32)
LARGE_INTEGER tick;
#elif defined(__linux__)
timespec tick;
#endif
uint32_t count;
unsigned short packet_id;
};
stCtx ctx[CHK_PCKT_NUM_PCKT_MRY];
private:
unsigned char last_index;
};
// Estrutura para sincronizar o uso de buff, para não limpar o socket(session) antes dele ser liberado
struct stUseCtx {
stUseCtx() {
#if defined(_WIN32)
InitializeCriticalSection(&m_cs);
#elif defined(__linux__)
INIT_PTHREAD_MUTEXATTR_RECURSIVE;
INIT_PTHREAD_MUTEX_RECURSIVE(&m_cs);
DESTROY_PTHREAD_MUTEXATTR_RECURSIVE;
#endif
clear();
};
~stUseCtx() {
clear();
#if defined(_WIN32)
DeleteCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_destroy(&m_cs);
#endif
}
void clear() {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
m_active = 0l;
m_quit = false;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
};
bool isQuit() {
auto quit = false;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
quit = m_quit;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return quit;
};
int32_t usa() {
auto spin = 0l;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
spin = ++m_active;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return spin;
};
bool devolve() {
auto spin = 0l;
auto quit = false;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
spin = --m_active;
quit = m_quit;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return spin <= 0 && quit; // pode excluir(limpar) a session
};
// Verifica se pode excluir a session, se não seta a flag quit para o prox method que devolver excluir ela
bool checkCanQuit() {
auto can = false;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
if (m_active <= 0)
can = true;
else
m_quit = true;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return can;
};
protected:
#if defined(_WIN32)
CRITICAL_SECTION m_cs;
#elif defined(__linux__)
pthread_mutex_t m_cs;
#endif
int32_t m_active;
bool m_quit;
};
class session {
public:
class buff_ctx {
public:
buff_ctx();
~buff_ctx();
void init();
void destroy();
void clear();
void lock();
void unlock();
bool isWritable();
bool readyToWrite();
bool isSendable();
bool readyToSend();
bool isSetedToSend();
bool isSetedToWrite();
bool isSetedToPartial();
bool isSetedToSendOrPartialSend();
void setWrite();
void setSend();
void setPartialSend();
void releaseWrite();
void releaseSend();
void releasePartial();
void releaseSendAndPartialSend();
int64_t increseRequestSendCount();
int64_t decreaseRequestSendCount();
public:
Buffer buff;
protected:
#if defined(_WIN32)
CRITICAL_SECTION cs;
CONDITION_VARIABLE cv_send;
CONDITION_VARIABLE cv_write;
#elif defined(__linux__)
pthread_mutex_t cs;
pthread_cond_t cv_send;
pthread_cond_t cv_write;
#endif
int64_t request_send_count;
unsigned char state_send : 1, : 0;
unsigned char state_write : 1, : 0;
unsigned char state_wr_send : 1, : 0;
};
public:
session(threadpool_base& _threadpool);
session(threadpool_base& _threadpool, SOCKET _sock, SOCKADDR_IN _addr, unsigned char _key);
virtual ~session();
virtual bool clear();
const char* getIP();
void lock();
void unlock();
// Usando para syncronizar outras coisas da session, tipo pacotes
void lockSync();
void unlockSync();
void requestSendBuffer(void* _buff, size_t _size, bool _raw = false);
void requestRecvBuffer();
void setRecv();
void releaseRecv();
void setSend();
void setSendPartial();
void releaseSend();
bool isConnected();
bool isCreated();
int getConnectTime();
//void setThreadpool(threadpool* _threadpool);
packet* getPacketS();
void setPacketS(packet *_packet);
packet* getPacketR();
void setPacketR(packet *_packet);
int32_t usa();
bool devolve();
bool isQuit();
bool getState();
void setState(bool _state);
void setConnected(bool _connected);
void setConnectedToSend(bool _connected_to_send);
virtual unsigned char getStateLogged() = 0;
virtual uint32_t getUID() = 0;
virtual uint32_t getCapability() = 0;
virtual char* getNickname() = 0;
virtual char* getID() = 0;
private:
void make_ip();
bool isConnectedToSend();
public:
std::clock_t m_time_start;
std::clock_t m_tick;
std::clock_t m_tick_bot;
ctx_check_packet m_check_packet;
// session autorizada pelo server, fez o login corretamente
unsigned char m_is_authorized;
// Marca na session que o socket, levou DC, chegou ao limit de retramission do TCP para transmitir os dados
// TCP sockets is that the maximum retransmission count and timeout have been reached on a bad(or broken) link
bool m_connection_timeout;
SOCKET m_sock;
SOCKADDR_IN m_addr;
unsigned char m_key;
char m_ip[32];
bool m_ip_maked;
uint32_t m_oid;
buff_ctx m_buff_s;
buff_ctx m_buff_r;
threadpool_base& m_threadpool;
packet *m_packet_s;
packet *m_packet_r;
private:
#if defined(_WIN32)
CRITICAL_SECTION m_cs;
CRITICAL_SECTION m_cs_lock_other; // Usado para bloquear outras coisas (sincronizar os pacotes, por exemplo)
#elif defined(__linux__)
pthread_mutex_t m_cs;
pthread_mutex_t m_cs_lock_other; // Usado para bloquear outras coisas (sincronizar os pacotes, por exemplo)
#endif
int64_t m_request_recv; // Requests recv buff
bool m_state;
bool m_connected;
bool m_connected_to_send;
stUseCtx m_use_ctx;
};
}
#endif |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.